News.php 28 KB

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