News.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  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 = '/##_gallery-(\d+)##/mU';
  72. $res = preg_replace_callback($re,function (array $matches): string
  73. {
  74. $gallery = \app\models\front\Gallery::findOne(['id'=>ArrayHelper::getValue($matches,1)]);
  75. if($gallery instanceof \app\models\front\Gallery) {
  76. return \Yii::$app->view->render("/news/view/inject-gallery",["gallery"=>$gallery]);
  77. } else {
  78. return "";
  79. }
  80. },$body);
  81. return $res;
  82. }
  83. public function getUrl($full = false):string
  84. {
  85. if(count($this->topics)>0){
  86. $topic = Transliterator::toUrl($this->topics[0]->title)."/";
  87. } else{
  88. $topic = "";
  89. }
  90. switch ($this->type){
  91. // case 6:
  92. // return "https://old.amic.ru/long/{$this->id}/";
  93. // break;
  94. default:
  95. $base = Url::base('https');
  96. $alias = trim( $this->alias );
  97. if( $alias == '' ){
  98. $alias = Transliterator::toUrl($this->title);
  99. }
  100. if( isset( $this->dt_pub ) && strtotime( $this->dt_pub ) > strtotime('2023-01-27 15:00:00') ){
  101. return ($full ? $base : "")."/news/".$alias."-".$this->id;
  102. }
  103. return ($full ? $base : "")."/news/".$topic.$alias."-".$this->id;
  104. }
  105. }
  106. public function getMainPic(){
  107. }
  108. /**
  109. * @return Image
  110. */
  111. public function getPreview($type="webp"):Image{
  112. return Image::findOne($this->id,$type,$this->photo_name);
  113. }
  114. public function getOld():ActiveQuery
  115. {
  116. return $this->hasOne(OldNews::class,['alias'=>'alias']);
  117. }
  118. /**
  119. * @return ActiveQuery
  120. */
  121. public function getCommentsAll(): ActiveQuery
  122. {
  123. if($this->comments=="Y"){
  124. return $this->hasMany(Comments::class,['news_id'=>"id"])->andWhere(['visible'=>'Y']);
  125. }
  126. return $this->hasMany(Comments::class,['news_id'=>"id"])->andWhere(0);
  127. }
  128. public static function getMainView(){
  129. return self::find()->joinWith("topics t")->andWhere(["t.id"=>[33,]]);
  130. }
  131. public static function getNH(){
  132. 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);
  133. }
  134. public static function getPartnersNews(){
  135. return self::find()->joinWith("topics t")->andWhere(["t.id"=>[34,]]);
  136. }
  137. public static function getMainOfWeek(){
  138. return self::find()->joinWith("topics t")->andWhere(["t.id"=>[35,]]);
  139. }
  140. public function getPublishedAt(){
  141. if($this->dt_pub<date("Y-m-d H:i:s",strtotime("-1 day"))){
  142. return
  143. date("d",strtotime($this->dt_pub))." ".mb_strtolower(Transliterator::month(date("n",strtotime($this->dt_pub))))
  144. .date(" Y, H:i", strtotime($this->dt_pub))
  145. ;
  146. } else {
  147. $diff = ceil((time() - strtotime($this->dt_pub))/60); //В минутах
  148. if($diff<=60){
  149. return Transliterator::plural($diff,['минуту','минуты', 'минут'],true,'только что','минуту')." назад";
  150. } else {
  151. $diff = (int)floor($diff/60);
  152. return Transliterator::plural($diff,['час','часа', 'часов'],true,'только что','час')." назад";
  153. }
  154. }
  155. }
  156. public function getPublishedNorm(){
  157. return
  158. date("d",strtotime($this->dt_pub))." ".mb_strtolower(Transliterator::month(date("n",strtotime($this->dt_pub))))
  159. .date(" Y, H:i", strtotime($this->dt_pub))
  160. ;
  161. }
  162. public function renderBody()
  163. {
  164. $post = $this;
  165. $device = Yii::$app->deviceDetect->isMobile()?"mobile":"desktop";
  166. return \Yii::$app->cache->getOrSet("post-body8-".$this->id."-".$device,function () use ($post){
  167. $body = $post->text;
  168. //Нужно воткнуть рекламу после второго абзаца
  169. $body = self::processBody($body,$this);
  170. // $body = self::processSingleImg($body);
  171. $body = self::processTextImg($body);
  172. $body = self::processInjects($body);
  173. $body = self::processAudio($body);
  174. $body = self::processSlider($body, $post); //old slider
  175. $body = self::processGalleriesInjects($body, $post);
  176. $body = self::processYoutube($body);
  177. $body = self::processIframe($body);
  178. $body = self::processSpecialFormats($body);
  179. $body = self::processPersons($body);
  180. $body = self::processTest($body);
  181. if( $post->inscription == 0 ) $body = self::processAhref($body); // кроме комерческих
  182. return $body;
  183. },YII_ENV_DEV?1:60);
  184. }
  185. public static function processTest($text)
  186. {
  187. $text = str_replace("\xc2\xa0", ' ', $text);
  188. $text = str_replace(['<p>&nbsp;</p>','<p> </p>'], "\c", $text);
  189. $text = trim( $text );
  190. $text = str_replace( "\c", "<p></p>", $text);
  191. return $text;
  192. }
  193. public static function processSpecialFormats($text)
  194. {
  195. if( stripos($text, 'class="juxtapose"') !== false ){
  196. $str = '
  197. <script src="/js/juxtapose/juxtapose.min.js"></script>
  198. <link rel="stylesheet" href="/js/juxtapose/juxtapose.css">
  199. ';
  200. return $text.$str;
  201. }
  202. return $text;
  203. }
  204. /*
  205. * Парсинг для старых слайдеров (очень старых)
  206. */
  207. public static function processSlider($text, $obj)
  208. {
  209. if( $obj->uid == '' ) return $text;
  210. $dir = '/images/items/'.$obj->uid;
  211. $files1 = @scandir(Yii::getAlias('@webroot').$dir.'/thumbnails/',0);
  212. $old_title = ( trim($obj->old_gallery_title) != '' )?''.trim($obj->old_gallery_title).'':'';
  213. if( $files1 == false || count( $files1 ) < 4){
  214. $files1 = @scandir(Yii::getAlias('@webroot').$dir.'/images/thumbnails/', 0);
  215. if( $files1 === false || count( $files1 ) == 0){
  216. return $text;
  217. }else{
  218. $i=1;
  219. ob_start();
  220. foreach( $files1 as $file ){
  221. if( preg_match('/^.*\.(gif|jpe?g|png)/i', $file ) ){
  222. $str = @file_get_contents( Yii::getAlias('@webroot').$dir.'/info/'.$file.'.json' );
  223. if( $str == false ){
  224. $str='{"title":"","copyrate":""}';
  225. }
  226. $js_title = json_decode( $str );
  227. $str_title = ( $js_title->title == '' )?$old_title:$js_title->title;//iconv('UTF-8','cp1251',$js_title->title);
  228. $str_title .= ( $js_title->copyrate == '' )?'':'<br><span class="style8">'.$js_title->copyrate.'</span>';
  229. $add_cap = ($str_title != '')?", caption: '".$str_title."'":'';
  230. ?>
  231. {img: '<?=$dir?>/images/<?=$file?>', thumb: '<?=$dir?>/images/thumbnails/<?=$file?>' <?=$add_cap?>},
  232. <?
  233. }
  234. }
  235. $ltext = ob_get_contents();
  236. ob_end_clean();
  237. }
  238. }else{
  239. $i=1;
  240. ob_start();
  241. foreach( $files1 as $file ){
  242. if( preg_match('/^.*\.(gif|jpe?g|png)/i', $file ) ){
  243. ?>
  244. {img: '<?=$dir?>/big/<?=$file?>', thumb: '<?=$dir?>/thumbnails/<?=$file?>'},
  245. <?
  246. }
  247. }
  248. $ltext = ob_get_contents();
  249. ob_end_clean();
  250. }
  251. ob_start();
  252. if( isset( $ltext ) ){
  253. if( strstr( $text, 'id="mycarousel"') === false ){
  254. echo '<div id="mycarousel"></div>';
  255. }
  256. ?>
  257. <!-- Fotorama -->
  258. <link href="/js/fotorama/fotorama.css" rel="stylesheet">
  259. <script src="/js/fotorama/fotorama.js" defer></script>
  260. <!-- <div class="fotorama" data-width="700" data-ratio="700/467" data-max-width="100%"></div>-->
  261. <script type="text/javascript">
  262. window.addEventListener("DOMContentLoaded",function () {
  263. $('#mycarousel').fotorama({ width:'100%',maxwidth:780,thumbheight:70,thumbwidth:94, captions: true,nav:'thumbs', caption: 'overlay', allowfullscreen:'native', data: [ <?=$ltext?> ] });
  264. });
  265. </script>
  266. <?
  267. }
  268. $ltext = ob_get_clean();
  269. return $ltext.$text;
  270. }
  271. public static function processAudio($text)
  272. {
  273. $re = '/<a([^>]+)href=\"([^>]*\/files\/)(.+)\.mp3\"([^>]*)>([^<]*)<\/a>/i';
  274. $res = preg_replace_callback($re,function (array $matches): string
  275. {
  276. $title = isset($matches[5])?$matches[5]:'';
  277. if( !strstr( $matches[1], "download") ) {
  278. $url = $matches[2];
  279. $audio = '<source src="'.$url.$matches[3].'.mp3" type="audio/mpeg">'."\n";
  280. if( file_exists( $_SERVER['DOCUMENT_ROOT'].''.$matches[2].$matches[3].'.mp3.ogg' ) ){
  281. $audio .= '<source src="'.$url.$matches[3].'.mp3.ogg" type="audio/ogg; codecs=vorbis">'."\n";
  282. }
  283. return \Yii::$app->view->render("/news/view/audio",["audio"=>$audio, "title"=>$title]);
  284. } else {
  285. return ArrayHelper::getValue($matches,0);
  286. }
  287. },$text);
  288. return $res;
  289. }
  290. /*
  291. * Спрятать внешнии ссылки от поисковиков
  292. * Псевдо SEO
  293. *
  294. */
  295. public static function processAhref($text)
  296. {
  297. $re = '/<a[^>]+href=\"(https?:\/\/[^"]*)\".*>/Ui';
  298. $res = preg_replace_callback($re,function (array $matches): string
  299. {
  300. $mydomain = \Yii::$app->params['mydomain'];
  301. foreach( $mydomain as $find ){
  302. if( stripos( $matches[1], $find) !== false ) return $matches[0];
  303. }
  304. $ret = str_replace( $matches[1], "/go/?u=".urlencode($matches[1]), $matches[0] );
  305. return $ret;
  306. },$text);
  307. return $res;
  308. }
  309. public static function processInjects($text)
  310. {
  311. $re = '/##news_(.*)##/mU';
  312. $res = preg_replace_callback($re,function (array $matches): string
  313. {
  314. $post = News::findOne(['uid'=>ArrayHelper::getValue($matches,1)]);
  315. if($post instanceof News) {
  316. return \Yii::$app->view->render("/news/view/inject",["post"=>$post]);
  317. } else {
  318. return "";
  319. }
  320. },$text);
  321. if( strlen($res) != strlen($text) ) return $res;
  322. $re = "|<div[^>]+>.[^<]*</div>|U";
  323. $res = preg_replace_callback($re,function (array $matches): string
  324. {
  325. @$xml = simplexml_load_string( str_replace( '&nbsp;', '', ArrayHelper::getValue($matches,0) ), 'SimpleXMLElement', LIBXML_NOCDATA );
  326. if( $xml ){
  327. $attributes =$xml->attributes();
  328. if( $attributes['class'] == 'insinject' || $attributes['id'] == "inject" ){
  329. $r = preg_match( "/^https?:\/\/(.*)\/(.*)\/(\d+)\/$/i", $attributes['url'], $aa );
  330. $id = 0;
  331. if( $r && ($aa[1] == 'www.amic.ru' || $aa[1] == Yii::$app->request->serverName) && $aa[3]*1 > 0 ){
  332. // old style inject
  333. $id = $aa[3]*1;
  334. }
  335. $r = preg_match( "/^https?:\/\/(.*)\/.*(\d+)\/?$/Ui", $attributes['url'], $aa );
  336. if( $r && ($aa[1] == Yii::$app->request->serverName || $aa[1] == 'www.amic.ru')&& $aa[2]*1 > 0 ){
  337. // new style inject
  338. $id = $aa[2]*1;
  339. }
  340. $r = preg_match( '/^https?:\/\/(.*)\/person\/(.*)\/?$/Ui', $attributes['url'], $aa );
  341. if( $r && ($aa[1] == Yii::$app->request->serverName || $aa[1] == 'www.amic.ru')&& $aa[2] != '' ){
  342. $person = \app\models\Person::findOne(['alias'=>$aa[2]]);
  343. if( ( !$person instanceof Person ) || $person->show == 'N' ){
  344. return "";
  345. }
  346. return \Yii::$app->view->render("/news/view/injectp",["post"=>$person]);
  347. }
  348. if( $id ){
  349. //$attributes['type'] to do
  350. $post = News::findOne(['id'=>$id]);
  351. if($post instanceof News) {
  352. if( $attributes['type'] == 1 ){
  353. return \Yii::$app->view->render("/news/view/inject1",["post"=>$post]);
  354. }else if( $attributes['type'] == 2 ){
  355. return \Yii::$app->view->render("/news/view/inject2",["post"=>$post]);
  356. }else{
  357. return \Yii::$app->view->render("/news/view/inject",["post"=>$post]);
  358. }
  359. } else {
  360. return "Битый инжект";
  361. }
  362. }
  363. }
  364. }
  365. return ArrayHelper::getValue($matches,0);
  366. },$text);
  367. return $res;
  368. }
  369. public static function processIframe($text) //https://youtu.be/sfzX5fMaSj4 -> https://www.youtube.com/embed/sfzX5fMaSj4
  370. {
  371. $re = '/(<iframe[^>]*>).*(<\/iframe>)/Ui';
  372. $text = preg_replace_callback($re,function (array $mt): string
  373. {
  374. //print_r($mt);
  375. // libxml_use_internal_errors(true);
  376. $content = $mt[0];
  377. $content = str_replace( '&', '#-#', $content);
  378. $HXML='<?xml version="1.0" encoding="UTF-8"?>';
  379. $doc = new DOMDocument('1.0','UTF-8'); // нормализация xml
  380. @$doc->loadHTML($HXML.$content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD | LIBXML_NOCDATA);
  381. // $doc->encoding = 'UTF-8';
  382. $doc->normalizeDocument();
  383. $content = $doc->saveXML($doc->documentElement);
  384. $content = html_entity_decode($content);
  385. $content = str_replace( '<?xml version="1.0" standalone="yes"?>', '', $content);
  386. $content = str_replace( '<?xml version="1.0" encoding="UTF-8"??>', '', $content);
  387. $content = str_replace( '<?xml version="1.0" encoding="UTF-8"?>', '', $content);
  388. $xml = simplexml_load_string( $content, 'SimpleXMLElement',LIBXML_HTML_NODEFDTD | LIBXML_NOXMLDECL |LIBXML_HTML_NOIMPLIED );
  389. if( $xml ){
  390. $attrs = $attributes =$xml->attributes();
  391. //print_r( $attrs );
  392. $xmlo = simplexml_load_string( $HXML.'<iframe loading="lazy"> </iframe>', 'SimpleXMLElement', LIBXML_NOCDATA );
  393. // var_dump($attrs);
  394. if( $attrs['src'] && strpos( $attrs['src'], 'vk.com' ) !== false ) $fixedRatio = '3/2';
  395. foreach( $attrs as $key=>$attr ){
  396. if( $key == 'height'){
  397. $height = preg_replace('/[\D]/', '', $attr);
  398. if( $height == 0 ) $height = 0.1;
  399. $attr = 'auto';
  400. }
  401. if( $key == 'width'){
  402. $width = preg_replace('/[\D]/', '', $attr);
  403. if( strpos($attr, '%') !== false ){
  404. $width = $width*720/100;
  405. }
  406. $attr = '100%';
  407. }
  408. if( isset($height) && isset($width) ){
  409. if( isset( $fixedRatio ) ){
  410. $ratio = $fixedRatio;
  411. }else{
  412. $ratio = round( $width/$height, 2 );
  413. }
  414. if( !isset($xmlo->attributes()->style) ){
  415. $xmlo->addAttribute('style', 'width:100%; aspect-ratio:'.$ratio);
  416. }else{
  417. $xmlo->attributes()->style = $xmlo->attributes()->style.'width:100%; aspect-ratio:'.$ratio;
  418. }
  419. unset($height);
  420. unset($width);
  421. }
  422. @$xmlo->addAttribute($key, $attr);
  423. }
  424. return str_replace( '#-#', '&', preg_replace('|^\<\?xml version="1.0" encoding="UTF-8"\?\>\n|i', '',$xmlo->asXML()) );
  425. }
  426. return $mt[0];
  427. }, $text);
  428. return $text;
  429. }
  430. /*
  431. * Парсинг короткой ссылки ютуба
  432. *
  433. */
  434. public static function processYoutube($text) //https://youtu.be/sfzX5fMaSj4 -> https://www.youtube.com/embed/sfzX5fMaSj4
  435. {
  436. return str_replace( 'https://youtu.be/', 'https://www.youtube.com/embed/', $text );
  437. }
  438. public static function processSingleImg($text)
  439. {
  440. $re = '/(<[p|a][^>]*>)(<img.*>)(<\/[p|a]>)/i';
  441. $res = preg_replace_callback($re,function (array $matches): string
  442. {
  443. $img = ArrayHelper::getValue($matches,2);
  444. $a = array();
  445. $title = '';
  446. if( preg_match( '/title="(.*)"/mU', $img, $a) ){
  447. $title = '<div class="image-title" style="margin-top: 20px;">'.$a[1].'</div>';
  448. }
  449. if( $title && preg_match( '/rel-credit="(.*)"/mU', $img, $a) ){
  450. if( trim( $a[1] ) != '' ){
  451. $title = str_replace('</div>', ' фото: '.$a[1].'</div>', $title);
  452. }
  453. }
  454. if( $title && preg_match( '/longdesc="(.*)"/mU', $img, $a) ){
  455. $title = str_replace('</div>', ' <a href="'.$a[1].'">'.$a[1].'</a></div>', $title);
  456. }
  457. $style = '';
  458. $a = array();
  459. if( preg_match( '/style="(.*)"/mU', $img, $a) ){
  460. $style = $a[1];
  461. $style = str_replace('height', 'data-height', $style);
  462. $img = str_replace('margin', 'margin-block', $img);
  463. }
  464. //class='picture-cont-16x9'
  465. $pic= "<div style='{$style}' class=\"pic\">
  466. <picture class='w-100'>
  467. {$img}
  468. </picture>
  469. {$title}
  470. </div>
  471. ";
  472. return str_replace('<p','<div',ArrayHelper::getValue($matches,1)).$pic.str_replace('p>','div>',ArrayHelper::getValue($matches,3));
  473. },$text);
  474. return $res;
  475. }
  476. public static function processTextImg($text)
  477. {
  478. $text = str_replace('src="http://', 'src="https://', $text); //в качестве бреда
  479. $text = str_replace( 'publib/gimage.php?image=/', '', $text ); // очень очень старый движ
  480. $re = '/(<img[^>]*>)/i';
  481. $text = preg_replace_callback($re,function (array $mt): string
  482. {
  483. //print_r($mt);
  484. libxml_use_internal_errors(true);
  485. $content = $mt[0];
  486. $content = str_replace('&','$%$',$content);
  487. $HXML='<?xml version="1.0" encoding="UTF-8"?>';
  488. $doc = new DOMDocument('1.0','UTF-8'); // нормализация xml
  489. $doc->loadHTML($HXML.$content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD | LIBXML_NOCDATA);
  490. // $doc->encoding = 'UTF-8';
  491. $doc->normalizeDocument();
  492. $content = $doc->saveXML($doc->documentElement);
  493. $content = html_entity_decode($content);
  494. $content = str_replace( '<?xml version="1.0" standalone="yes"?>', '', $content);
  495. $content = str_replace( '<?xml version="1.0" encoding="UTF-8"??>', '', $content);
  496. $content = str_replace( '<?xml version="1.0" encoding="UTF-8"?>', '', $content);
  497. $xml = simplexml_load_string( $content, 'SimpleXMLElement',LIBXML_HTML_NODEFDTD | LIBXML_NOXMLDECL |LIBXML_HTML_NOIMPLIED );
  498. if( $xml ){
  499. $attrs = $attributes =$xml->attributes();
  500. //print_r( $attrs );
  501. $xmlo = simplexml_load_string( $HXML.'<span><picture class="w-100"><img /></picture></span>', 'SimpleXMLElement', LIBXML_NOCDATA );
  502. // var_dump($attrs);
  503. $url = isset($attrs->longdesc)?$attrs->longdesc:'';
  504. foreach( $attrs as $key=>$attr ){
  505. if( $key == 'height'){
  506. $xmlo->addAttribute('data-height', $attr);
  507. continue;
  508. }
  509. if( $key == 'style'){
  510. $attr = trim( $attr, " ;\r\n" );
  511. //$attr = str_replace(' ', '', $attr);
  512. $css = explode( ";", $attr );
  513. $stylesd = array();
  514. $stylesi = array();
  515. foreach( $css as $attrx ){
  516. list($key1, $value) = explode( ":", $attrx );
  517. $key1 = trim($key1);
  518. if( $key1 == 'height' || $key1 == '' ){
  519. continue;
  520. }elseif( stristr( 'margin', $key1 ) !== false ){
  521. $stylesd[] = "{$key1}:{$value}";
  522. }elseif( $key1 == 'float' ){
  523. $stylesd[] = "{$key1}:{$value}";
  524. }elseif( $key1 == 'width' ){
  525. //$value = preg_replace("/[^0-9\-.]/", '', $value);
  526. if( preg_replace("/[^0-9\-.]/", '', $value) > 720-150 ){
  527. $value = '100%';
  528. }
  529. $stylesd[] = "{$key1}:{$value}";
  530. $stylesi[] = "{$key1}:100%";
  531. $stylesd[] = "display:block";
  532. }elseif( $key1 && $value){
  533. $stylesd[] = "{$key1}:{$value}";
  534. if( $key1 == 'margin-right' || $key1 == 'margin-left' ) $value = 0;
  535. if( $key1 != 'margin' ) {
  536. $stylesi[] = "{$key1}:{$value}";
  537. }
  538. }
  539. }
  540. $attr = implode('; ', $stylesd);
  541. $xmlo->addAttribute($key, $attr);
  542. $attr = implode('; ', $stylesi);
  543. $xmlo->picture->img->addAttribute($key, $attr);
  544. }
  545. $title = '';
  546. if( $key == 'title'){
  547. $title = str_replace( '"', "'", trim($attr));
  548. $xmlo->picture->img->addAttribute($key, $title);
  549. /*
  550. if( isset( $attrs['rel-credit'] ) && trim($attrs->rel-credit) != ''){
  551. $attr = trim($attrs->{rel-credit})?$attrs->rel-credit:'';
  552. $title .= ' фото: '.$attr;
  553. }
  554. */
  555. }else{
  556. if( $xmlo->picture->img->$key && trim($key) != ''){
  557. $xmlo->picture->img->$key = $attr;
  558. }else{
  559. if( trim($key) != '' ) @$xmlo->picture->img->addAttribute($key, $attr);
  560. }
  561. }
  562. if( $title ){
  563. $e = $xmlo->addChild('span', $title); // class="image-title" style="margin-top: 20px;"
  564. $e->addAttribute('class',"image-title image-title-fix");
  565. //$e->addAttribute('style',"margin-top: 20px;");
  566. if( $url ){
  567. $e1 = $e->addChild('a', $url);
  568. $e1->addAttribute('href', $url);
  569. }
  570. }
  571. }
  572. if( isset( $xmlo->attributes()->style ) ){
  573. $s = $xmlo->attributes()->style .= ';overflow: hidden;';
  574. unset($xmlo->attributes()->style);
  575. $xmlo->addAttribute('style',$s );
  576. }else{
  577. $xmlo->addAttribute('style', 'overflow: hidden;');
  578. }
  579. return str_replace('$%$','&',preg_replace('|^\<\?xml version="1.0" encoding="UTF-8"\?\>\n|i', '',$xmlo->asXML()));
  580. }
  581. return $mt[0];
  582. }, $text);
  583. return $text;
  584. }
  585. public function behaviors()
  586. {
  587. $keys = array_keys(self::$keysCache);
  588. return [
  589. 'CachedBehavior' => [
  590. 'class' => CachedBehavior::class,
  591. 'cache_key' => $keys,
  592. ]
  593. ];
  594. }
  595. public static function find0()
  596. {
  597. return parent::find();
  598. }
  599. public static function find()
  600. {
  601. return parent::find()->orderBy(["dt_pub"=>SORT_DESC]);
  602. }
  603. /**
  604. * @return ActiveQuery
  605. */
  606. public function getGalleries()
  607. {
  608. return $this->hasMany(Gallery::class,['post_id'=>'id']);
  609. }
  610. public function getYoutubeEmbedLink(){
  611. $data = parse_url($this->embed_url);
  612. if(is_array($data)){
  613. switch (ArrayHelper::getValue($data,'path')){
  614. case "/watch":
  615. $re = '/v=(.*)/m';
  616. preg_match_all($re, ArrayHelper::getValue($data,'query'), $matches, PREG_SET_ORDER, 0);
  617. $video_id = '/'.ArrayHelper::getValue($matches,'0.1');
  618. break;
  619. default:
  620. $video_id = ArrayHelper::getValue($data,'path','');
  621. }
  622. return "https://www.youtube.com/embed".$video_id;
  623. }
  624. return "";
  625. }
  626. public function inTopic(int $topic_id): bool
  627. {
  628. return (bool)$this->getTopicRelations()->andWhere(['topic_id'=>$topic_id])->count();
  629. }
  630. }