News.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820
  1. <?php
  2. namespace app\models;
  3. use app\helpers\Transliterator;
  4. use app\models\base\Comments;
  5. use app\models\base\Gallery;
  6. use app\models\base\Image;
  7. use app\models\base\OldNews;
  8. use DOMDocument;
  9. use yii\db\ActiveQuery;
  10. use yii\helpers\ArrayHelper;
  11. use yii\helpers\Inflector;
  12. use yii;
  13. use app\components\behaviors\CachedBehavior;
  14. use yii\helpers\Url;
  15. /**
  16. * @property string $url
  17. * @property $mainPic
  18. * @property Image $preview
  19. * @property Image $image
  20. * @property OldNews $old
  21. * @property string $publishedAt
  22. * @property Comments[] $commentsAll
  23. * @property Gallery[] $galleries
  24. */
  25. class News extends \app\models\base\News
  26. {
  27. /*
  28. * Ключи кэширования для авто сброса
  29. */
  30. public static $keysCache=[
  31. 'MainPageBlock' => 120,
  32. 'main_page_lenta' =>120,
  33. 'main-page-main-view-glob' => 60, //600
  34. 'main-page-main-view' => 60,
  35. 'topic-news-##' => 3600
  36. ];
  37. private static function processPersons(string $body)
  38. {
  39. $re = '/<a.*class=[\'"](person|person-inject)[\'"].*href=[\'"]\/person\/(.+)[\'"].*>(\W+)<\/a>/m';
  40. $res = preg_replace_callback($re,function (array $matches): string
  41. {
  42. $person = Person::find()->andWhere(['alias'=>ArrayHelper::getValue($matches,'2')])->one();
  43. if($person instanceof Person){
  44. switch (ArrayHelper::getValue($matches,'1')) {
  45. case "person-inject":
  46. return \Yii::$app->view->render("/news/view/inject-person-as-widget", ["person" => $person]);
  47. break;
  48. default:
  49. return \Yii::$app->view->render("/news/view/inject-person-as-link", ["person" => $person]);
  50. }
  51. }
  52. return ArrayHelper::getValue($matches,0);
  53. }, $body);
  54. return $res;
  55. }
  56. private static function processBody($body,$model)
  57. {
  58. $counter = 0;
  59. $re = '/<(?:p|h2).*>(.*)<\/(?:p|h2)>/msU';
  60. $res = preg_replace_callback($re,function (array $matches) use(&$counter,$model): string
  61. {
  62. $counter++;
  63. if($counter==2 && Yii::$app->deviceDetect->isMobile() && !$model->inTopic(158)) return $matches[0].Yii::$app->controller->renderPartial("@app/views/_etc/banners/adfinityInContent");
  64. if($counter==3 && !Yii::$app->deviceDetect->isMobile() && !$model->inTopic(158)) return $matches[0].Yii::$app->controller->renderPartial("@app/views/_etc/banners/desktopInContent");
  65. return $matches[0];
  66. },$body);
  67. return $res;
  68. }
  69. private static function processGalleriesInjects(string $body, News $post)
  70. {
  71. $re = '/<p>(##_gallery-(\d+)##)<\/p>/mU';
  72. $body = preg_replace( $re, '\1', $body );
  73. $re = '/##_gallery-(\d+)##/mU';
  74. $res = preg_replace_callback($re,function (array $matches) use($post): string
  75. {
  76. $gallery = \app\models\front\Gallery::findOne(['id'=>ArrayHelper::getValue($matches,1)]);
  77. if($gallery instanceof \app\models\front\Gallery) {
  78. return \Yii::$app->view->render("/news/view/inject-gallery-x",["gallery"=>$gallery, "model"=>$post]);
  79. } else {
  80. return "";
  81. }
  82. },$body);
  83. return $res;
  84. }
  85. public function getUrl($full = false):string
  86. {
  87. if(count($this->topics)>0){
  88. $topic = Transliterator::toUrl($this->topics[0]->title)."/";
  89. } else{
  90. $topic = "";
  91. }
  92. switch ($this->type){
  93. // case 6:
  94. // return "https://old.amic.ru/long/{$this->id}/";
  95. // break;
  96. default:
  97. $base = Url::base('https');
  98. $alias = trim( $this->alias );
  99. if( $alias == '' ){
  100. $alias = Transliterator::toUrl($this->title);
  101. }
  102. if( isset( $this->dt_pub ) && strtotime( $this->dt_pub ) > strtotime('2023-01-27 15:00:00') ){
  103. return ($full ? $base : "")."/news/".$alias."-".$this->id;
  104. }
  105. return ($full ? $base : "")."/news/".$topic.$alias."-".$this->id;
  106. }
  107. }
  108. public function getMainPic(){
  109. }
  110. /**
  111. * @return Image
  112. */
  113. public function getPreview($type="webp"):Image{
  114. return Image::findOne($this->id,$type,$this->photo_name);
  115. }
  116. public function getOld():ActiveQuery
  117. {
  118. return $this->hasOne(OldNews::class,['alias'=>'alias']);
  119. }
  120. /**
  121. * @return ActiveQuery
  122. */
  123. public function getCommentsAll(): ActiveQuery
  124. {
  125. if($this->comments=="Y"){
  126. return $this->hasMany(Comments::class,['news_id'=>"id"])->andWhere(['visible'=>'Y']);
  127. }
  128. return $this->hasMany(Comments::class,['news_id'=>"id"])->andWhere(0);
  129. }
  130. public static function getMainView(){
  131. return self::find()->joinWith("topics t")->andWhere(["t.id"=>[33,]]);
  132. }
  133. public static function getNH(){
  134. return self::find()->andWhere(['active'=>'Y', 'NH'=>['Y','F']])->andWhere(['between', 'dt_pub', date("Y-m-d H:i:00",time()-2678400*3 ) , date("Y-m-d H:i:00")])->orderBy(["NH"=>SORT_DESC,"dt_pub"=>SORT_DESC])->limit(1);
  135. }
  136. public static function getPartnersNews(){
  137. return self::find()->joinWith("topics t")->andWhere(["t.id"=>[34,]]);
  138. }
  139. public static function getMainOfWeek(){
  140. return self::find()->joinWith("topics t")->andWhere(["t.id"=>[35,]]);
  141. }
  142. public function getDatePub(){
  143. return $this->dt_pub;
  144. }
  145. public function getPublishedAt(){
  146. if($this->dt_pub<date("Y-m-d H:i:s",strtotime("-1 day"))){
  147. return
  148. date("d",strtotime($this->dt_pub))." ".mb_strtolower(Transliterator::month(date("n",strtotime($this->dt_pub))))
  149. .date(" Y, H:i", strtotime($this->dt_pub))
  150. ;
  151. } else {
  152. $diff = ceil((time() - strtotime($this->dt_pub))/60); //В минутах
  153. if($diff<=60){
  154. return Transliterator::plural($diff,['минуту','минуты', 'минут'],true,'только что','минуту')." назад";
  155. } else {
  156. $diff = (int)floor($diff/60);
  157. return Transliterator::plural($diff,['час','часа', 'часов'],true,'только что','час')." назад";
  158. }
  159. }
  160. }
  161. public function getPublishedNorm(){
  162. return
  163. date("d",strtotime($this->dt_pub))." ".mb_strtolower(Transliterator::month(date("n",strtotime($this->dt_pub))))
  164. .date(" Y, H:i", strtotime($this->dt_pub))
  165. ;
  166. }
  167. public function isPhotosOnNews( $dt_pub = null )
  168. {
  169. if( $this->inscription) return true;
  170. if( isset( $this->photo_title ) && stripos($this->photo_title, 'amic.ru') !== false ) return true;
  171. if( $dt_pub ){
  172. $dt_pub = strtotime($dt_pub);
  173. }else{
  174. $dt_pub = strtotime($this->dt_pub);
  175. }
  176. if( $dt_pub >= strtotime(Yii::$app->params['delPhotoB']) && $dt_pub < strtotime(Yii::$app->params['delPhotoE']) ) return false;
  177. return true;
  178. }
  179. public function renderBody()
  180. {
  181. $post = $this;
  182. $device = Yii::$app->deviceDetect->isMobile()?"mobile":"desktop";
  183. return \Yii::$app->cache->getOrSet("post-body8-".$this->id."-".$device,function () use ($post){
  184. $body = $post->text;
  185. //Нужно воткнуть рекламу после второго абзаца
  186. $body = self::processBody($body,$this);
  187. // $body = self::processSingleImg($body);
  188. $body = $this->DateDelImg($body);
  189. $body = self::processTextImg($body);
  190. $body = self::processInjects($body);
  191. $body = self::processAudio($body);
  192. if( $this->isPhotosOnNews($post->getDatePub() ) ){
  193. $body = self::processSlider($body, $post); //old slider
  194. $body = self::processGalleriesInjects($body, $post);
  195. }
  196. $body = self::processYoutube($body);
  197. $body = self::processIframe($body);
  198. $body = self::processSpecialFormats($body);
  199. $body = self::processPersons($body);
  200. $body = self::processTest($body);
  201. $body = self::processApiImg($body);
  202. $body = self::ShowPollsWidget($body);
  203. $body = self::ShowPreportWidget($body);
  204. if( $post->inscription == 0 ) $body = self::processAhref($body); // кроме комерческих
  205. return $body;
  206. },YII_ENV_DEV?1:60);
  207. }
  208. public static function processApiImg($text)
  209. {
  210. return str_replace( 'https://api.amic.ru', '', $text);
  211. }
  212. public static function processTest($text)
  213. {
  214. $text = str_replace("\xc2\xa0", ' ', $text);
  215. $text = str_replace(['<p>&nbsp;</p>','<p> </p>'], "\c", $text);
  216. $text = trim( $text );
  217. $text = str_replace( "\c", "<p></p>", $text);
  218. $text = str_replace( 'href="http://tel=', 'href="tel:', $text );
  219. return $text;
  220. }
  221. public static function processSpecialFormats($text)
  222. {
  223. if( stripos($text, 'class="juxtapose"') !== false ){
  224. $str = '
  225. <script src="/js/juxtapose/juxtapose.min.js"></script>
  226. <link rel="stylesheet" href="/js/juxtapose/juxtapose.css">
  227. ';
  228. return $text.$str;
  229. }
  230. return $text;
  231. }
  232. /*
  233. * Парсинг для старых слайдеров (очень старых)
  234. */
  235. public static function processSlider($text, $obj)
  236. {
  237. if( $obj->uid == '' ) return $text;
  238. $dir = '/images/items/'.$obj->uid;
  239. $files1 = @scandir(Yii::getAlias('@webroot').$dir.'/thumbnails/',0);
  240. $old_title = ( trim($obj->old_gallery_title) != '' )?''.trim($obj->old_gallery_title).'':'';
  241. if( $files1 == false || count( $files1 ) < 4){
  242. $files1 = @scandir(Yii::getAlias('@webroot').$dir.'/images/thumbnails/', 0);
  243. if( $files1 === false || count( $files1 ) == 0){
  244. return $text;
  245. }else{
  246. $i=1;
  247. ob_start();
  248. foreach( $files1 as $file ){
  249. if( preg_match('/^.*\.(gif|jpe?g|png)/i', $file ) ){
  250. $str = @file_get_contents( Yii::getAlias('@webroot').$dir.'/info/'.$file.'.json' );
  251. if( $str == false ){
  252. $str='{"title":"","copyrate":""}';
  253. }
  254. $js_title = json_decode( $str );
  255. $str_title = ( $js_title->title == '' )?$old_title:$js_title->title;//iconv('UTF-8','cp1251',$js_title->title);
  256. $str_title .= ( $js_title->copyrate == '' )?'':'<br><span class="style8">'.$js_title->copyrate.'</span>';
  257. $add_cap = ($str_title != '')?", caption: '".$str_title."'":'';
  258. ?>
  259. {img: '<?=$dir?>/images/<?=$file?>', thumb: '<?=$dir?>/images/thumbnails/<?=$file?>' <?=$add_cap?>},
  260. <?
  261. }
  262. }
  263. $ltext = ob_get_contents();
  264. ob_end_clean();
  265. }
  266. }else{
  267. $i=1;
  268. ob_start();
  269. foreach( $files1 as $file ){
  270. if( preg_match('/^.*\.(gif|jpe?g|png)/i', $file ) ){
  271. ?>
  272. {img: '<?=$dir?>/big/<?=$file?>', thumb: '<?=$dir?>/thumbnails/<?=$file?>'},
  273. <?
  274. }
  275. }
  276. $ltext = ob_get_contents();
  277. ob_end_clean();
  278. }
  279. ob_start();
  280. if( isset( $ltext ) ){
  281. if( strstr( $text, 'id="mycarousel"') === false ){
  282. echo '<div id="mycarousel"></div>';
  283. }
  284. ?>
  285. <!-- Fotorama -->
  286. <?
  287. $c = Yii::$app->acache;
  288. $c->set('fotorama', true);
  289. ?>
  290. <!-- <div class="fotorama" data-width="700" data-ratio="700/467" data-max-width="100%"></div>-->
  291. <script type="text/javascript">
  292. window.addEventListener("DOMContentLoaded",function () {
  293. $('#mycarousel').fotorama({ width:'100%',maxwidth:780,thumbheight:70,thumbwidth:94, captions: true,nav:'thumbs', caption: 'overlay', allowfullscreen:'native', data: [ <?=$ltext?> ] });
  294. });
  295. </script>
  296. <?
  297. }
  298. $ltext = ob_get_clean();
  299. return $ltext.$text;
  300. }
  301. public static function processAudio($text)
  302. {
  303. $re = '/<a([^>]+)href=\"([^>]*\/files\/)(.+)\.mp3\"([^>]*)>([^<]*)<\/a>/i';
  304. $res = preg_replace_callback($re,function (array $matches): string
  305. {
  306. $title = isset($matches[5])?$matches[5]:'';
  307. if( !strstr( $matches[1], "download") ) {
  308. $url = $matches[2];
  309. $audio = '<source src="'.$url.$matches[3].'.mp3" type="audio/mpeg">'."\n";
  310. if( file_exists( $_SERVER['DOCUMENT_ROOT'].''.$matches[2].$matches[3].'.mp3.ogg' ) ){
  311. $audio .= '<source src="'.$url.$matches[3].'.mp3.ogg" type="audio/ogg; codecs=vorbis">'."\n";
  312. }
  313. return \Yii::$app->view->render("/news/view/audio",["audio"=>$audio, "title"=>$title]);
  314. } else {
  315. return ArrayHelper::getValue($matches,0);
  316. }
  317. },$text);
  318. return $res;
  319. }
  320. /*
  321. * Спрятать внешнии ссылки от поисковиков
  322. * Псевдо SEO
  323. *
  324. */
  325. public static function processAhref($text)
  326. {
  327. $re = '/<a[^>]+href=\"(https?:\/\/[^"]*)\".*>/Ui';
  328. $res = preg_replace_callback($re,function (array $matches): string
  329. {
  330. $mydomain = \Yii::$app->params['mydomain'];
  331. foreach( $mydomain as $find ){
  332. if( stripos( $matches[1], $find) !== false ) return $matches[0];
  333. }
  334. $ret = str_replace( $matches[1], "/go/?u=".urlencode($matches[1]), $matches[0] );
  335. return $ret;
  336. },$text);
  337. return $res;
  338. }
  339. public static function processInjects($text)
  340. {
  341. $re = '/##news_(.*)##/mU';
  342. $res = preg_replace_callback($re,function (array $matches): string
  343. {
  344. $post = News::findOne(['uid'=>ArrayHelper::getValue($matches,1)]);
  345. if($post instanceof News) {
  346. return \Yii::$app->view->render("/news/view/inject",["post"=>$post]);
  347. } else {
  348. return "";
  349. }
  350. },$text);
  351. if( strlen($res) != strlen($text) ) return $res;
  352. $re = "|<div[^>]+>.[^<]*</div>|U";
  353. $res = preg_replace_callback($re,function (array $matches): string
  354. {
  355. @$xml = simplexml_load_string( str_replace( '&nbsp;', '', ArrayHelper::getValue($matches,0) ), 'SimpleXMLElement', LIBXML_NOCDATA );
  356. if( $xml ){
  357. $attributes =$xml->attributes();
  358. if( $attributes['class'] == 'insinject' || $attributes['id'] == "inject" ){
  359. $r = preg_match( "/^https?:\/\/(.*)\/(.*)\/(\d+)\/$/i", $attributes['url'], $aa );
  360. $id = 0;
  361. if( $r && ($aa[1] == 'www.amic.ru' || $aa[1] == Yii::$app->request->serverName) && $aa[3]*1 > 0 ){
  362. // old style inject
  363. $id = $aa[3]*1;
  364. }
  365. $r = preg_match( "/^https?:\/\/(.*)\/.*(\d+)\/?$/Ui", $attributes['url'], $aa );
  366. if( $r && ($aa[1] == Yii::$app->request->serverName || $aa[1] == 'www.amic.ru')&& $aa[2]*1 > 0 ){
  367. // new style inject
  368. $id = $aa[2]*1;
  369. }
  370. $r = preg_match( '/^https?:\/\/(.*)\/person\/(.*)\/?$/Ui', $attributes['url'], $aa );
  371. if( $r && ($aa[1] == Yii::$app->request->serverName || $aa[1] == 'www.amic.ru')&& $aa[2] != '' ){
  372. $person = \app\models\Person::findOne(['alias'=>$aa[2]]);
  373. if( ( !$person instanceof Person ) || $person->show == 'N' ){
  374. return "";
  375. }
  376. return \Yii::$app->view->render("/news/view/injectp",["post"=>$person]);
  377. }
  378. if( $id ){
  379. //$attributes['type'] to do
  380. $post = News::findOne(['id'=>$id]);
  381. if($post instanceof News) {
  382. if( $attributes['type'] == 1 ){
  383. return \Yii::$app->view->render("/news/view/inject1",["post"=>$post]);
  384. }else if( $attributes['type'] == 2 ){
  385. return \Yii::$app->view->render("/news/view/inject2",["post"=>$post]);
  386. }else{
  387. return \Yii::$app->view->render("/news/view/inject",["post"=>$post]);
  388. }
  389. } else {
  390. return "Битый инжект";
  391. }
  392. }
  393. }
  394. }
  395. return ArrayHelper::getValue($matches,0);
  396. },$text);
  397. return $res;
  398. }
  399. public static function processIframe($text) //https://youtu.be/sfzX5fMaSj4 -> https://www.youtube.com/embed/sfzX5fMaSj4
  400. {
  401. $re = '/(<iframe[^>]*>).*(<\/iframe>)/Ui';
  402. $text = preg_replace_callback($re,function (array $mt): string
  403. {
  404. //print_r($mt);
  405. // libxml_use_internal_errors(true);
  406. $content = $mt[0];
  407. $content = str_replace( '&', '#-#', $content);
  408. $HXML='<?xml version="1.0" encoding="UTF-8"?>';
  409. $doc = new DOMDocument('1.0','UTF-8'); // нормализация xml
  410. @$doc->loadHTML($HXML.$content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD | LIBXML_NOCDATA);
  411. // $doc->encoding = 'UTF-8';
  412. $doc->normalizeDocument();
  413. $content = $doc->saveXML($doc->documentElement);
  414. $content = html_entity_decode($content);
  415. $content = str_replace( '<?xml version="1.0" standalone="yes"?>', '', $content);
  416. $content = str_replace( '<?xml version="1.0" encoding="UTF-8"??>', '', $content);
  417. $content = str_replace( '<?xml version="1.0" encoding="UTF-8"?>', '', $content);
  418. $xml = simplexml_load_string( $content, 'SimpleXMLElement',LIBXML_HTML_NODEFDTD | LIBXML_NOXMLDECL |LIBXML_HTML_NOIMPLIED );
  419. if( $xml ){
  420. $attrs = $attributes =$xml->attributes();
  421. //print_r( $attrs );
  422. $xmlo = simplexml_load_string( $HXML.'<iframe loading="lazy"> </iframe>', 'SimpleXMLElement', LIBXML_NOCDATA );
  423. // var_dump($attrs);
  424. if( !Yii::$app->deviceDetect->isMobile() ){
  425. if( $attrs['src'] && strpos( $attrs['src'], 'vk.com' ) !== false ) $fixedRatio = '16/9';
  426. }
  427. foreach( $attrs as $key=>$attr ){
  428. if( $key == 'height'){
  429. $height = preg_replace('/[\D]/', '', $attr);
  430. if( $height == 0 ) $height = 0.1;
  431. $attr = 'auto';
  432. }
  433. if( $key == 'width'){
  434. $width = preg_replace('/[\D]/', '', $attr);
  435. if( strpos($attr, '%') !== false ){
  436. $width = $width*720/100;
  437. }
  438. $attr = '100%';
  439. }
  440. if( isset($height) && isset($width) ){
  441. if( isset( $fixedRatio ) ){
  442. $ratio = $fixedRatio;
  443. }else{
  444. $ratio = round( $width/$height, 2 );
  445. }
  446. if( !isset($xmlo->attributes()->style) ){
  447. $xmlo->addAttribute('style', 'width:100%; aspect-ratio:'.$ratio);
  448. }else{
  449. $xmlo->attributes()->style = $xmlo->attributes()->style.'width:100%; aspect-ratio:'.$ratio;
  450. }
  451. unset($height);
  452. unset($width);
  453. }
  454. @$xmlo->addAttribute($key, $attr);
  455. }
  456. return str_replace( '#-#', '&', preg_replace('|^\<\?xml version="1.0" encoding="UTF-8"\?\>\n|i', '',$xmlo->asXML()) );
  457. }
  458. return $mt[0];
  459. }, $text);
  460. return $text;
  461. }
  462. /*
  463. * Парсинг короткой ссылки ютуба
  464. *
  465. */
  466. public static function processYoutube($text) //https://youtu.be/sfzX5fMaSj4 -> https://www.youtube.com/embed/sfzX5fMaSj4
  467. {
  468. return str_replace( 'https://youtu.be/', 'https://www.youtube.com/embed/', $text );
  469. }
  470. public static function processSingleImg($text)
  471. {
  472. $re = '/(<[p|a][^>]*>)(<img.*>)(<\/[p|a]>)/i';
  473. $res = preg_replace_callback($re,function (array $matches): string
  474. {
  475. $img = ArrayHelper::getValue($matches,2);
  476. $a = array();
  477. $title = '';
  478. if( preg_match( '/title="(.*)"/mU', $img, $a) ){
  479. $title = '<div class="image-title" style="margin-top: 20px;">'.$a[1].'</div>';
  480. }
  481. if( $title && preg_match( '/rel-credit="(.*)"/mU', $img, $a) ){
  482. if( trim( $a[1] ) != '' ){
  483. $title = str_replace('</div>', ' фото: '.$a[1].'</div>', $title);
  484. }
  485. }
  486. if( $title && preg_match( '/longdesc="(.*)"/mU', $img, $a) ){
  487. $title = str_replace('</div>', ' <a href="'.$a[1].'">'.$a[1].'</a></div>', $title);
  488. }
  489. $style = '';
  490. $a = array();
  491. if( preg_match( '/style="(.*)"/mU', $img, $a) ){
  492. $style = $a[1];
  493. $style = str_replace('height', 'data-height', $style);
  494. $img = str_replace('margin', 'margin-block', $img);
  495. }
  496. //class='picture-cont-16x9'
  497. $pic= "<div style='{$style}' class=\"pic\">
  498. <picture class='w-100'>
  499. {$img}
  500. </picture>
  501. {$title}
  502. </div>
  503. ";
  504. return str_replace('<p','<div',ArrayHelper::getValue($matches,1)).$pic.str_replace('p>','div>',ArrayHelper::getValue($matches,3));
  505. },$text);
  506. return $res;
  507. }
  508. public function DateDelImg($text)
  509. {
  510. $obj = $this;
  511. $re = '/(<img[^>]*>)/i';
  512. $text = preg_replace_callback($re,function (array $mt) use($obj): string
  513. {
  514. /*
  515. После этой даты не выводить фото до подтверждения юриста
  516. */
  517. if( !$this->isPhotosOnNews( $obj->getDatePub() ) ){
  518. $bad = '/images/default.jpg';
  519. return '<span><picture class="w-100"><img src="'.$bad.'" width="100%"/></picture></span>';
  520. };
  521. return $mt[0];
  522. }, $text);
  523. return $text;
  524. }
  525. public static function processTextImg($text)
  526. {
  527. $text = str_replace('src="http://', 'src="https://', $text); //в качестве бреда
  528. $text = str_replace( 'publib/gimage.php?image=/', '', $text ); // очень очень старый движ
  529. $re = '/(<img[^>]*>)/i';
  530. $text = preg_replace_callback($re,function (array $mt): string
  531. {
  532. //print_r($mt);
  533. libxml_use_internal_errors(true);
  534. $staic = false;
  535. $content = $mt[0];
  536. $content = str_replace('&','$%$',$content);
  537. $HXML='<?xml version="1.0" encoding="UTF-8"?>';
  538. $doc = new DOMDocument('1.0','UTF-8'); // нормализация xml
  539. $doc->loadHTML($HXML.$content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD | LIBXML_NOCDATA);
  540. // $doc->encoding = 'UTF-8';
  541. $doc->normalizeDocument();
  542. $content = $doc->saveXML($doc->documentElement);
  543. $content = html_entity_decode($content);
  544. $content = str_replace( '<?xml version="1.0" standalone="yes"?>', '', $content);
  545. $content = str_replace( '<?xml version="1.0" encoding="UTF-8"??>', '', $content);
  546. $content = str_replace( '<?xml version="1.0" encoding="UTF-8"?>', '', $content);
  547. $xml = simplexml_load_string( $content, 'SimpleXMLElement',LIBXML_HTML_NODEFDTD | LIBXML_NOXMLDECL |LIBXML_HTML_NOIMPLIED );
  548. if( $xml ){
  549. $attrs = $attributes =$xml->attributes();
  550. //print_r( $attrs );
  551. $xmlo = simplexml_load_string( $HXML.'<span><picture class="w-100"><img /></picture></span>', 'SimpleXMLElement', LIBXML_NOCDATA );
  552. // var_dump($attrs);
  553. $url = isset($attrs->longdesc)?$attrs->longdesc:'';
  554. foreach( $attrs as $key=>$attr ){
  555. if( $key == 'height'){
  556. $xmlo->addAttribute('data-height', $attr);
  557. continue;
  558. }
  559. if( $key == 'style'){
  560. $attr = trim( $attr, " ;\r\n" );
  561. //$attr = str_replace(' ', '', $attr);
  562. $css = explode( ";", $attr );
  563. $stylesd = array();
  564. $stylesi = array();
  565. foreach( $css as $attrx ){
  566. list($key1, $value) = explode( ":", $attrx );
  567. $key1 = trim($key1);
  568. if( $key1 == 'height' || $key1 == '' ){
  569. continue;
  570. }elseif( stristr( 'margin', $key1 ) !== false ){
  571. $stylesd[] = "{$key1}:{$value}";
  572. }elseif( $key1 == 'float' ){
  573. $stylesd[] = "{$key1}:{$value}";
  574. }elseif( $key1 == 'width' ){
  575. //$value = preg_replace("/[^0-9\-.]/", '', $value);
  576. if( preg_replace("/[^0-9\-.]/", '', $value) > 720-150 ){
  577. $value = '100%';
  578. }
  579. $stylesd[] = "{$key1}:{$value}";
  580. $stylesi[] = "{$key1}:100%";
  581. $stylesd[] = "display:block";
  582. }elseif( $key1 && $value){
  583. $stylesd[] = "{$key1}:{$value}";
  584. if( $key1 == 'margin-right' || $key1 == 'margin-left' ) $value = 0;
  585. if( $key1 != 'margin' ) {
  586. $stylesi[] = "{$key1}:{$value}";
  587. }
  588. }
  589. }
  590. $attr = implode('; ', $stylesd);
  591. $xmlo->addAttribute($key, $attr);
  592. $attr = implode('; ', $stylesi);
  593. $xmlo->picture->img->addAttribute($key, $attr);
  594. }
  595. if( $key == 'class'){
  596. if( $attr == 'staic' ){
  597. $staic = true;
  598. }
  599. }
  600. $title = '';
  601. if( $key == 'title'){
  602. $title = str_replace( '"', "'", trim($attr));
  603. $xmlo->picture->img->addAttribute($key, $title);
  604. /*
  605. if( isset( $attrs['rel-credit'] ) && trim($attrs->rel-credit) != ''){
  606. $attr = trim($attrs->{rel-credit})?$attrs->rel-credit:'';
  607. $title .= ' фото: '.$attr;
  608. }
  609. */
  610. }else{
  611. if( $xmlo->picture->img->$key && trim($key) != ''){
  612. $xmlo->picture->img->$key = $attr;
  613. }else{
  614. if( trim($key) != '' ) @$xmlo->picture->img->addAttribute($key, $attr);
  615. }
  616. }
  617. if( $title ){
  618. $e = $xmlo->addChild('span', $title); // class="image-title" style="margin-top: 20px;"
  619. $e->addAttribute('class',"image-title image-title-fix");
  620. //$e->addAttribute('style',"margin-top: 20px;");
  621. if( $url ){
  622. $e1 = $e->addChild('a', $url);
  623. $e1->addAttribute('href', $url);
  624. }
  625. }
  626. }
  627. if( isset( $xmlo->attributes()->style ) ){
  628. $s = $xmlo->attributes()->style .= ';overflow: hidden;';
  629. unset($xmlo->attributes()->style);
  630. $xmlo->addAttribute('style',$s );
  631. }else{
  632. $xmlo->addAttribute('style', 'overflow: hidden;');
  633. }
  634. $str = str_replace('$%$','&',preg_replace('|^\<\?xml version="1.0" encoding="UTF-8"\?\>\n|i', '',$xmlo->asXML()));
  635. if( $staic ){
  636. $str = str_replace( '100%', 'auto', $str);
  637. }
  638. return $str;
  639. }
  640. return $mt[0];
  641. }, $text);
  642. return $text;
  643. }
  644. public function behaviors()
  645. {
  646. $keys = array_keys(self::$keysCache);
  647. return [
  648. 'CachedBehavior' => [
  649. 'class' => CachedBehavior::class,
  650. 'cache_key' => $keys,
  651. ]
  652. ];
  653. }
  654. public static function find0()
  655. {
  656. return parent::find();
  657. }
  658. public static function find()
  659. {
  660. return parent::find()->orderBy(["dt_pub"=>SORT_DESC]);
  661. }
  662. /**
  663. * @return ActiveQuery
  664. */
  665. public function getGalleries()
  666. {
  667. return $this->hasMany(Gallery::class,['post_id'=>'id']);
  668. }
  669. public function getYoutubeEmbedLink(){
  670. $data = parse_url($this->embed_url);
  671. if(is_array($data)){
  672. switch (ArrayHelper::getValue($data,'host')){
  673. case "vk.com":
  674. $path = preg_split( '/[-_]/', ArrayHelper::getValue($data,'path') );
  675. if( isset($path[1]) && isset($path[2]) && is_numeric($path[1]) && is_numeric($path[2]) ){
  676. return "https://vk.com/video_ext.php?oid=-{$path[1]}&id={$path[2]}";
  677. }
  678. return '';
  679. break;
  680. default:
  681. switch (ArrayHelper::getValue($data,'path')){
  682. case "/watch":
  683. $re = '/v=(.*)/m';
  684. preg_match_all($re, ArrayHelper::getValue($data,'query'), $matches, PREG_SET_ORDER, 0);
  685. $video_id = '/'.ArrayHelper::getValue($matches,'0.1');
  686. break;
  687. default:
  688. $video_id = ArrayHelper::getValue($data,'path','');
  689. }
  690. }
  691. return "https://www.youtube.com/embed".$video_id;
  692. }
  693. return "";
  694. }
  695. public function inTopic(int $topic_id): bool
  696. {
  697. return (bool)$this->getTopicRelations()->andWhere(['topic_id'=>$topic_id])->count();
  698. }
  699. public static function ShowPollsWidget( $str ){
  700. preg_match_all( "|<div[^>]+>.[^<]*</div>|U", $str, $a, PREG_SET_ORDER );
  701. foreach ( $a as $item ){
  702. $xml = @simplexml_load_string( str_replace( '&nbsp;', '', $item[0] ), 'SimpleXMLElement', LIBXML_NOCDATA );
  703. if( $xml ){
  704. $attributes =$xml->attributes();
  705. if( $attributes['id'] == 'widgetpolls' ){
  706. // старый стиль url
  707. $r = preg_match( "/^https?:\/\/(.*)\/(.*)\/widget\/(\d+)\/$/i", trim($attributes['url']), $aa );
  708. if( $r && $aa[3]*1 > 0 ){
  709. if( $aa[2] == 'polls' ){
  710. $str = str_replace( $item[0], self::ShowPollsHtml( str_replace( ['http://www.amic.ru'],[''],$attributes['url']), $attributes['type'] ), $str );
  711. }
  712. }else{
  713. $r = preg_match( "/^https?:\/\/(.*)\/inquirer\/(\d+)$/i", trim($attributes['url']), $aa );
  714. if( $r && $aa[2]*1 > 0 ){
  715. $str = str_replace( $item[0], self::ShowPollsHtml( "/polls/widget/".$aa[2]*1, $attributes['type'] ), $str );
  716. }
  717. }
  718. }
  719. }
  720. }
  721. return $str;
  722. }
  723. public static function ShowPollsHtml( $url, $type ){
  724. static $i = 0;
  725. $url = trim($url);
  726. ob_start();
  727. ?>
  728. <script type="text/javascript">
  729. function AdjustIframeHeightOnLoad() { document.getElementById("form-iframe").style.height = document.getElementById("form-iframe").contentWindow.document.body.scrollHeight + "px"; }
  730. function AdjustIframeHeight(i) { document.getElementById("form-iframe").style.height = parseInt(i) + "px"; }
  731. </script>
  732. <div class="shadow p-2 mb-4 rounded" style="width:100%">
  733. <div class="header"></div>
  734. <iframe id="form-iframe" onload="AdjustIframeHeightOnLoad()" scrolling="no" src="<?=$url.'?widget='.$type?>" style="margin:0; width:100%; height:400px; border:none; overflow:hidden;"></iframe></div>
  735. <?
  736. $i++;
  737. return ob_get_clean();
  738. }
  739. public static function ShowPreportWidget( $str ){
  740. preg_match_all( "|<div[^>]+>.[^<]*</div>|U", $str, $a, PREG_SET_ORDER );
  741. foreach ( $a as $item ){
  742. $xml = @simplexml_load_string( str_replace( '&nbsp;', '', $item[0] ), 'SimpleXMLElement', LIBXML_NOCDATA );
  743. if( $xml ){
  744. $attributes =$xml->attributes();
  745. if( $attributes['id'] == 'widgetgallery' ){
  746. // старый стиль url
  747. $r = preg_match( "/^https?:\/\/(.*)\/(.*)\/(\d+)\/$/i", trim($attributes['url']), $aa );
  748. if( $r && $aa[3]*1 > 0 ){
  749. if( $aa[2] == 'photo' ){
  750. $str = str_replace( $item[0], self::ShowPreportHtml( "/photo/widget/".$aa[3]*1, $attributes['type'] ), $str );
  751. $c = Yii::$app->acache;
  752. $c->set('fotorama', true);
  753. }
  754. }
  755. }
  756. }
  757. }
  758. return $str;
  759. }
  760. public static function ShowPreportHtml( $url, $type ){
  761. static $i = 0;
  762. ob_start();
  763. ?>
  764. <div id='galleryID<?=$i?>'></div>
  765. <script>window.addEventListener("DOMContentLoaded",function () {$( '#galleryID<?=$i?>' ).load( '<?=$url?>'+'?widget=<?=$type?>');});</script>
  766. <?
  767. $i++;
  768. return ob_get_clean();
  769. }
  770. }