News.php 29 KB

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