News.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721
  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. $body = self::ShowPollsWidget($body);
  182. if( $post->inscription == 0 ) $body = self::processAhref($body); // кроме комерческих
  183. return $body;
  184. },YII_ENV_DEV?1:60);
  185. }
  186. public static function processTest($text)
  187. {
  188. $text = str_replace("\xc2\xa0", ' ', $text);
  189. $text = str_replace(['<p>&nbsp;</p>','<p> </p>'], "\c", $text);
  190. $text = trim( $text );
  191. $text = str_replace( "\c", "<p></p>", $text);
  192. return $text;
  193. }
  194. public static function processSpecialFormats($text)
  195. {
  196. if( stripos($text, 'class="juxtapose"') !== false ){
  197. $str = '
  198. <script src="/js/juxtapose/juxtapose.min.js"></script>
  199. <link rel="stylesheet" href="/js/juxtapose/juxtapose.css">
  200. ';
  201. return $text.$str;
  202. }
  203. return $text;
  204. }
  205. /*
  206. * Парсинг для старых слайдеров (очень старых)
  207. */
  208. public static function processSlider($text, $obj)
  209. {
  210. if( $obj->uid == '' ) return $text;
  211. $dir = '/images/items/'.$obj->uid;
  212. $files1 = @scandir(Yii::getAlias('@webroot').$dir.'/thumbnails/',0);
  213. $old_title = ( trim($obj->old_gallery_title) != '' )?''.trim($obj->old_gallery_title).'':'';
  214. if( $files1 == false || count( $files1 ) < 4){
  215. $files1 = @scandir(Yii::getAlias('@webroot').$dir.'/images/thumbnails/', 0);
  216. if( $files1 === false || count( $files1 ) == 0){
  217. return $text;
  218. }else{
  219. $i=1;
  220. ob_start();
  221. foreach( $files1 as $file ){
  222. if( preg_match('/^.*\.(gif|jpe?g|png)/i', $file ) ){
  223. $str = @file_get_contents( Yii::getAlias('@webroot').$dir.'/info/'.$file.'.json' );
  224. if( $str == false ){
  225. $str='{"title":"","copyrate":""}';
  226. }
  227. $js_title = json_decode( $str );
  228. $str_title = ( $js_title->title == '' )?$old_title:$js_title->title;//iconv('UTF-8','cp1251',$js_title->title);
  229. $str_title .= ( $js_title->copyrate == '' )?'':'<br><span class="style8">'.$js_title->copyrate.'</span>';
  230. $add_cap = ($str_title != '')?", caption: '".$str_title."'":'';
  231. ?>
  232. {img: '<?=$dir?>/images/<?=$file?>', thumb: '<?=$dir?>/images/thumbnails/<?=$file?>' <?=$add_cap?>},
  233. <?
  234. }
  235. }
  236. $ltext = ob_get_contents();
  237. ob_end_clean();
  238. }
  239. }else{
  240. $i=1;
  241. ob_start();
  242. foreach( $files1 as $file ){
  243. if( preg_match('/^.*\.(gif|jpe?g|png)/i', $file ) ){
  244. ?>
  245. {img: '<?=$dir?>/big/<?=$file?>', thumb: '<?=$dir?>/thumbnails/<?=$file?>'},
  246. <?
  247. }
  248. }
  249. $ltext = ob_get_contents();
  250. ob_end_clean();
  251. }
  252. ob_start();
  253. if( isset( $ltext ) ){
  254. if( strstr( $text, 'id="mycarousel"') === false ){
  255. echo '<div id="mycarousel"></div>';
  256. }
  257. ?>
  258. <!-- Fotorama -->
  259. <link href="/js/fotorama/fotorama.css" rel="stylesheet">
  260. <script src="/js/fotorama/fotorama.js" defer></script>
  261. <!-- <div class="fotorama" data-width="700" data-ratio="700/467" data-max-width="100%"></div>-->
  262. <script type="text/javascript">
  263. window.addEventListener("DOMContentLoaded",function () {
  264. $('#mycarousel').fotorama({ width:'100%',maxwidth:780,thumbheight:70,thumbwidth:94, captions: true,nav:'thumbs', caption: 'overlay', allowfullscreen:'native', data: [ <?=$ltext?> ] });
  265. });
  266. </script>
  267. <?
  268. }
  269. $ltext = ob_get_clean();
  270. return $ltext.$text;
  271. }
  272. public static function processAudio($text)
  273. {
  274. $re = '/<a([^>]+)href=\"([^>]*\/files\/)(.+)\.mp3\"([^>]*)>([^<]*)<\/a>/i';
  275. $res = preg_replace_callback($re,function (array $matches): string
  276. {
  277. $title = isset($matches[5])?$matches[5]:'';
  278. if( !strstr( $matches[1], "download") ) {
  279. $url = $matches[2];
  280. $audio = '<source src="'.$url.$matches[3].'.mp3" type="audio/mpeg">'."\n";
  281. if( file_exists( $_SERVER['DOCUMENT_ROOT'].''.$matches[2].$matches[3].'.mp3.ogg' ) ){
  282. $audio .= '<source src="'.$url.$matches[3].'.mp3.ogg" type="audio/ogg; codecs=vorbis">'."\n";
  283. }
  284. return \Yii::$app->view->render("/news/view/audio",["audio"=>$audio, "title"=>$title]);
  285. } else {
  286. return ArrayHelper::getValue($matches,0);
  287. }
  288. },$text);
  289. return $res;
  290. }
  291. /*
  292. * Спрятать внешнии ссылки от поисковиков
  293. * Псевдо SEO
  294. *
  295. */
  296. public static function processAhref($text)
  297. {
  298. $re = '/<a[^>]+href=\"(https?:\/\/[^"]*)\".*>/Ui';
  299. $res = preg_replace_callback($re,function (array $matches): string
  300. {
  301. $mydomain = \Yii::$app->params['mydomain'];
  302. foreach( $mydomain as $find ){
  303. if( stripos( $matches[1], $find) !== false ) return $matches[0];
  304. }
  305. $ret = str_replace( $matches[1], "/go/?u=".urlencode($matches[1]), $matches[0] );
  306. return $ret;
  307. },$text);
  308. return $res;
  309. }
  310. public static function processInjects($text)
  311. {
  312. $re = '/##news_(.*)##/mU';
  313. $res = preg_replace_callback($re,function (array $matches): string
  314. {
  315. $post = News::findOne(['uid'=>ArrayHelper::getValue($matches,1)]);
  316. if($post instanceof News) {
  317. return \Yii::$app->view->render("/news/view/inject",["post"=>$post]);
  318. } else {
  319. return "";
  320. }
  321. },$text);
  322. if( strlen($res) != strlen($text) ) return $res;
  323. $re = "|<div[^>]+>.[^<]*</div>|U";
  324. $res = preg_replace_callback($re,function (array $matches): string
  325. {
  326. @$xml = simplexml_load_string( str_replace( '&nbsp;', '', ArrayHelper::getValue($matches,0) ), 'SimpleXMLElement', LIBXML_NOCDATA );
  327. if( $xml ){
  328. $attributes =$xml->attributes();
  329. if( $attributes['class'] == 'insinject' || $attributes['id'] == "inject" ){
  330. $r = preg_match( "/^https?:\/\/(.*)\/(.*)\/(\d+)\/$/i", $attributes['url'], $aa );
  331. $id = 0;
  332. if( $r && ($aa[1] == 'www.amic.ru' || $aa[1] == Yii::$app->request->serverName) && $aa[3]*1 > 0 ){
  333. // old style inject
  334. $id = $aa[3]*1;
  335. }
  336. $r = preg_match( "/^https?:\/\/(.*)\/.*(\d+)\/?$/Ui", $attributes['url'], $aa );
  337. if( $r && ($aa[1] == Yii::$app->request->serverName || $aa[1] == 'www.amic.ru')&& $aa[2]*1 > 0 ){
  338. // new style inject
  339. $id = $aa[2]*1;
  340. }
  341. $r = preg_match( '/^https?:\/\/(.*)\/person\/(.*)\/?$/Ui', $attributes['url'], $aa );
  342. if( $r && ($aa[1] == Yii::$app->request->serverName || $aa[1] == 'www.amic.ru')&& $aa[2] != '' ){
  343. $person = \app\models\Person::findOne(['alias'=>$aa[2]]);
  344. if( ( !$person instanceof Person ) || $person->show == 'N' ){
  345. return "";
  346. }
  347. return \Yii::$app->view->render("/news/view/injectp",["post"=>$person]);
  348. }
  349. if( $id ){
  350. //$attributes['type'] to do
  351. $post = News::findOne(['id'=>$id]);
  352. if($post instanceof News) {
  353. if( $attributes['type'] == 1 ){
  354. return \Yii::$app->view->render("/news/view/inject1",["post"=>$post]);
  355. }else if( $attributes['type'] == 2 ){
  356. return \Yii::$app->view->render("/news/view/inject2",["post"=>$post]);
  357. }else{
  358. return \Yii::$app->view->render("/news/view/inject",["post"=>$post]);
  359. }
  360. } else {
  361. return "Битый инжект";
  362. }
  363. }
  364. }
  365. }
  366. return ArrayHelper::getValue($matches,0);
  367. },$text);
  368. return $res;
  369. }
  370. public static function processIframe($text) //https://youtu.be/sfzX5fMaSj4 -> https://www.youtube.com/embed/sfzX5fMaSj4
  371. {
  372. $re = '/(<iframe[^>]*>).*(<\/iframe>)/Ui';
  373. $text = preg_replace_callback($re,function (array $mt): string
  374. {
  375. //print_r($mt);
  376. // libxml_use_internal_errors(true);
  377. $content = $mt[0];
  378. $content = str_replace( '&', '#-#', $content);
  379. $HXML='<?xml version="1.0" encoding="UTF-8"?>';
  380. $doc = new DOMDocument('1.0','UTF-8'); // нормализация xml
  381. @$doc->loadHTML($HXML.$content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD | LIBXML_NOCDATA);
  382. // $doc->encoding = 'UTF-8';
  383. $doc->normalizeDocument();
  384. $content = $doc->saveXML($doc->documentElement);
  385. $content = html_entity_decode($content);
  386. $content = str_replace( '<?xml version="1.0" standalone="yes"?>', '', $content);
  387. $content = str_replace( '<?xml version="1.0" encoding="UTF-8"??>', '', $content);
  388. $content = str_replace( '<?xml version="1.0" encoding="UTF-8"?>', '', $content);
  389. $xml = simplexml_load_string( $content, 'SimpleXMLElement',LIBXML_HTML_NODEFDTD | LIBXML_NOXMLDECL |LIBXML_HTML_NOIMPLIED );
  390. if( $xml ){
  391. $attrs = $attributes =$xml->attributes();
  392. //print_r( $attrs );
  393. $xmlo = simplexml_load_string( $HXML.'<iframe loading="lazy"> </iframe>', 'SimpleXMLElement', LIBXML_NOCDATA );
  394. // var_dump($attrs);
  395. if( $attrs['src'] && strpos( $attrs['src'], 'vk.com' ) !== false ) $fixedRatio = '3/2';
  396. foreach( $attrs as $key=>$attr ){
  397. if( $key == 'height'){
  398. $height = preg_replace('/[\D]/', '', $attr);
  399. if( $height == 0 ) $height = 0.1;
  400. $attr = 'auto';
  401. }
  402. if( $key == 'width'){
  403. $width = preg_replace('/[\D]/', '', $attr);
  404. if( strpos($attr, '%') !== false ){
  405. $width = $width*720/100;
  406. }
  407. $attr = '100%';
  408. }
  409. if( isset($height) && isset($width) ){
  410. if( isset( $fixedRatio ) ){
  411. $ratio = $fixedRatio;
  412. }else{
  413. $ratio = round( $width/$height, 2 );
  414. }
  415. if( !isset($xmlo->attributes()->style) ){
  416. $xmlo->addAttribute('style', 'width:100%; aspect-ratio:'.$ratio);
  417. }else{
  418. $xmlo->attributes()->style = $xmlo->attributes()->style.'width:100%; aspect-ratio:'.$ratio;
  419. }
  420. unset($height);
  421. unset($width);
  422. }
  423. @$xmlo->addAttribute($key, $attr);
  424. }
  425. return str_replace( '#-#', '&', preg_replace('|^\<\?xml version="1.0" encoding="UTF-8"\?\>\n|i', '',$xmlo->asXML()) );
  426. }
  427. return $mt[0];
  428. }, $text);
  429. return $text;
  430. }
  431. /*
  432. * Парсинг короткой ссылки ютуба
  433. *
  434. */
  435. public static function processYoutube($text) //https://youtu.be/sfzX5fMaSj4 -> https://www.youtube.com/embed/sfzX5fMaSj4
  436. {
  437. return str_replace( 'https://youtu.be/', 'https://www.youtube.com/embed/', $text );
  438. }
  439. public static function processSingleImg($text)
  440. {
  441. $re = '/(<[p|a][^>]*>)(<img.*>)(<\/[p|a]>)/i';
  442. $res = preg_replace_callback($re,function (array $matches): string
  443. {
  444. $img = ArrayHelper::getValue($matches,2);
  445. $a = array();
  446. $title = '';
  447. if( preg_match( '/title="(.*)"/mU', $img, $a) ){
  448. $title = '<div class="image-title" style="margin-top: 20px;">'.$a[1].'</div>';
  449. }
  450. if( $title && preg_match( '/rel-credit="(.*)"/mU', $img, $a) ){
  451. if( trim( $a[1] ) != '' ){
  452. $title = str_replace('</div>', ' фото: '.$a[1].'</div>', $title);
  453. }
  454. }
  455. if( $title && preg_match( '/longdesc="(.*)"/mU', $img, $a) ){
  456. $title = str_replace('</div>', ' <a href="'.$a[1].'">'.$a[1].'</a></div>', $title);
  457. }
  458. $style = '';
  459. $a = array();
  460. if( preg_match( '/style="(.*)"/mU', $img, $a) ){
  461. $style = $a[1];
  462. $style = str_replace('height', 'data-height', $style);
  463. $img = str_replace('margin', 'margin-block', $img);
  464. }
  465. //class='picture-cont-16x9'
  466. $pic= "<div style='{$style}' class=\"pic\">
  467. <picture class='w-100'>
  468. {$img}
  469. </picture>
  470. {$title}
  471. </div>
  472. ";
  473. return str_replace('<p','<div',ArrayHelper::getValue($matches,1)).$pic.str_replace('p>','div>',ArrayHelper::getValue($matches,3));
  474. },$text);
  475. return $res;
  476. }
  477. public static function processTextImg($text)
  478. {
  479. $text = str_replace('src="http://', 'src="https://', $text); //в качестве бреда
  480. $text = str_replace( 'publib/gimage.php?image=/', '', $text ); // очень очень старый движ
  481. $re = '/(<img[^>]*>)/i';
  482. $text = preg_replace_callback($re,function (array $mt): string
  483. {
  484. //print_r($mt);
  485. libxml_use_internal_errors(true);
  486. $content = $mt[0];
  487. $content = str_replace('&','$%$',$content);
  488. $HXML='<?xml version="1.0" encoding="UTF-8"?>';
  489. $doc = new DOMDocument('1.0','UTF-8'); // нормализация xml
  490. $doc->loadHTML($HXML.$content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD | LIBXML_NOCDATA);
  491. // $doc->encoding = 'UTF-8';
  492. $doc->normalizeDocument();
  493. $content = $doc->saveXML($doc->documentElement);
  494. $content = html_entity_decode($content);
  495. $content = str_replace( '<?xml version="1.0" standalone="yes"?>', '', $content);
  496. $content = str_replace( '<?xml version="1.0" encoding="UTF-8"??>', '', $content);
  497. $content = str_replace( '<?xml version="1.0" encoding="UTF-8"?>', '', $content);
  498. $xml = simplexml_load_string( $content, 'SimpleXMLElement',LIBXML_HTML_NODEFDTD | LIBXML_NOXMLDECL |LIBXML_HTML_NOIMPLIED );
  499. if( $xml ){
  500. $attrs = $attributes =$xml->attributes();
  501. //print_r( $attrs );
  502. $xmlo = simplexml_load_string( $HXML.'<span><picture class="w-100"><img /></picture></span>', 'SimpleXMLElement', LIBXML_NOCDATA );
  503. // var_dump($attrs);
  504. $url = isset($attrs->longdesc)?$attrs->longdesc:'';
  505. foreach( $attrs as $key=>$attr ){
  506. if( $key == 'height'){
  507. $xmlo->addAttribute('data-height', $attr);
  508. continue;
  509. }
  510. if( $key == 'style'){
  511. $attr = trim( $attr, " ;\r\n" );
  512. //$attr = str_replace(' ', '', $attr);
  513. $css = explode( ";", $attr );
  514. $stylesd = array();
  515. $stylesi = array();
  516. foreach( $css as $attrx ){
  517. list($key1, $value) = explode( ":", $attrx );
  518. $key1 = trim($key1);
  519. if( $key1 == 'height' || $key1 == '' ){
  520. continue;
  521. }elseif( stristr( 'margin', $key1 ) !== false ){
  522. $stylesd[] = "{$key1}:{$value}";
  523. }elseif( $key1 == 'float' ){
  524. $stylesd[] = "{$key1}:{$value}";
  525. }elseif( $key1 == 'width' ){
  526. //$value = preg_replace("/[^0-9\-.]/", '', $value);
  527. if( preg_replace("/[^0-9\-.]/", '', $value) > 720-150 ){
  528. $value = '100%';
  529. }
  530. $stylesd[] = "{$key1}:{$value}";
  531. $stylesi[] = "{$key1}:100%";
  532. $stylesd[] = "display:block";
  533. }elseif( $key1 && $value){
  534. $stylesd[] = "{$key1}:{$value}";
  535. if( $key1 == 'margin-right' || $key1 == 'margin-left' ) $value = 0;
  536. if( $key1 != 'margin' ) {
  537. $stylesi[] = "{$key1}:{$value}";
  538. }
  539. }
  540. }
  541. $attr = implode('; ', $stylesd);
  542. $xmlo->addAttribute($key, $attr);
  543. $attr = implode('; ', $stylesi);
  544. $xmlo->picture->img->addAttribute($key, $attr);
  545. }
  546. $title = '';
  547. if( $key == 'title'){
  548. $title = str_replace( '"', "'", trim($attr));
  549. $xmlo->picture->img->addAttribute($key, $title);
  550. /*
  551. if( isset( $attrs['rel-credit'] ) && trim($attrs->rel-credit) != ''){
  552. $attr = trim($attrs->{rel-credit})?$attrs->rel-credit:'';
  553. $title .= ' фото: '.$attr;
  554. }
  555. */
  556. }else{
  557. if( $xmlo->picture->img->$key && trim($key) != ''){
  558. $xmlo->picture->img->$key = $attr;
  559. }else{
  560. if( trim($key) != '' ) @$xmlo->picture->img->addAttribute($key, $attr);
  561. }
  562. }
  563. if( $title ){
  564. $e = $xmlo->addChild('span', $title); // class="image-title" style="margin-top: 20px;"
  565. $e->addAttribute('class',"image-title image-title-fix");
  566. //$e->addAttribute('style',"margin-top: 20px;");
  567. if( $url ){
  568. $e1 = $e->addChild('a', $url);
  569. $e1->addAttribute('href', $url);
  570. }
  571. }
  572. }
  573. if( isset( $xmlo->attributes()->style ) ){
  574. $s = $xmlo->attributes()->style .= ';overflow: hidden;';
  575. unset($xmlo->attributes()->style);
  576. $xmlo->addAttribute('style',$s );
  577. }else{
  578. $xmlo->addAttribute('style', 'overflow: hidden;');
  579. }
  580. return str_replace('$%$','&',preg_replace('|^\<\?xml version="1.0" encoding="UTF-8"\?\>\n|i', '',$xmlo->asXML()));
  581. }
  582. return $mt[0];
  583. }, $text);
  584. return $text;
  585. }
  586. public function behaviors()
  587. {
  588. $keys = array_keys(self::$keysCache);
  589. return [
  590. 'CachedBehavior' => [
  591. 'class' => CachedBehavior::class,
  592. 'cache_key' => $keys,
  593. ]
  594. ];
  595. }
  596. public static function find0()
  597. {
  598. return parent::find();
  599. }
  600. public static function find()
  601. {
  602. return parent::find()->orderBy(["dt_pub"=>SORT_DESC]);
  603. }
  604. /**
  605. * @return ActiveQuery
  606. */
  607. public function getGalleries()
  608. {
  609. return $this->hasMany(Gallery::class,['post_id'=>'id']);
  610. }
  611. public function getYoutubeEmbedLink(){
  612. $data = parse_url($this->embed_url);
  613. if(is_array($data)){
  614. switch (ArrayHelper::getValue($data,'path')){
  615. case "/watch":
  616. $re = '/v=(.*)/m';
  617. preg_match_all($re, ArrayHelper::getValue($data,'query'), $matches, PREG_SET_ORDER, 0);
  618. $video_id = '/'.ArrayHelper::getValue($matches,'0.1');
  619. break;
  620. default:
  621. $video_id = ArrayHelper::getValue($data,'path','');
  622. }
  623. return "https://www.youtube.com/embed".$video_id;
  624. }
  625. return "";
  626. }
  627. public function inTopic(int $topic_id): bool
  628. {
  629. return (bool)$this->getTopicRelations()->andWhere(['topic_id'=>$topic_id])->count();
  630. }
  631. public static function ShowPollsWidget( $str ){
  632. preg_match_all( "|<div[^>]+>.[^<]*</div>|U", $str, $a, PREG_SET_ORDER );
  633. foreach ( $a as $item ){
  634. $xml = @simplexml_load_string( str_replace( '&nbsp;', '', $item[0] ), 'SimpleXMLElement', LIBXML_NOCDATA );
  635. if( $xml ){
  636. $attributes =$xml->attributes();
  637. if( $attributes['id'] == 'widgetpolls' ){
  638. // старый стиль url
  639. $r = preg_match( "/^https?:\/\/(.*)\/(.*)\/widget\/(\d+)\/$/i", trim($attributes['url']), $aa );
  640. if( $r && $aa[3]*1 > 0 ){
  641. if( $aa[2] == 'polls' ){
  642. $str = str_replace( $item[0], self::ShowPollsHtml( str_replace( ['http://www.amic.ru'],[''],$attributes['url']), $attributes['type'] ), $str );
  643. }
  644. }else{
  645. $r = preg_match( "/^https?:\/\/(.*)\/inquirer\/(\d+)$/i", trim($attributes['url']), $aa );
  646. if( $r && $aa[2]*1 > 0 ){
  647. $str = str_replace( $item[0], self::ShowPollsHtml( "/polls/widget/".$aa[2]*1, $attributes['type'] ), $str );
  648. }
  649. }
  650. }
  651. }
  652. }
  653. return $str;
  654. }
  655. public static function ShowPollsHtml( $url, $type ){
  656. static $i = 0;
  657. $url = trim($url);
  658. ob_start();
  659. ?>
  660. <script type="text/javascript">
  661. function AdjustIframeHeightOnLoad() { document.getElementById("form-iframe").style.height = document.getElementById("form-iframe").contentWindow.document.body.scrollHeight + "px"; }
  662. function AdjustIframeHeight(i) { document.getElementById("form-iframe").style.height = parseInt(i) + "px"; }
  663. </script>
  664. <div class="shadow p-2 mb-4 rounded" style="width:100%">
  665. <div class="header"></div>
  666. <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>
  667. <?
  668. $i++;
  669. return ob_get_clean();
  670. }
  671. }