News.php 28 KB

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