NewsController.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. <?php
  2. namespace manager\controllers;
  3. use manager\models\Gallery;
  4. use Yii;
  5. use manager\models\News;
  6. use \app\models\base\Tags;
  7. use \app\models\base\TagsRelation;
  8. use \app\models\base\Story;
  9. use \app\models\base\StoryRelation;
  10. use \app\models\base\NewsTopic;
  11. use \app\models\base\NewsTopicRelation;
  12. use yii\web\UploadedFile;
  13. use \app\helpers\Transliterator;
  14. use zxbodya\yii2\galleryManager\GalleryManagerAction;
  15. use yii\base\ErrorException;
  16. use \app\models\PhotoFilter;
  17. class NewsController extends BaseController
  18. {
  19. // ** Статьи (новости) **
  20. public function actions()
  21. {
  22. return [
  23. 'error' => [
  24. 'class' => 'yii\web\ErrorAction',
  25. ],
  26. 'galleryApi' => [
  27. 'class' => GalleryManagerAction::className(),
  28. // mappings between type names and model classes (should be the same as in behaviour)
  29. 'types' => [
  30. 'product' => News::className(),
  31. 'post_gallery' => Gallery::className()
  32. ]
  33. ],
  34. ];
  35. }
  36. public function actionIndex()
  37. {
  38. return $this->render("/default/news",[]);
  39. }
  40. public function actionList()
  41. {
  42. if (Yii::$app->request->isGet && Yii::$app->request->get('id')){
  43. Yii::$app->session->get('dt-newslistadm');
  44. }else{
  45. Yii::$app->session->remove('dt-newslistadm');
  46. }
  47. return $this->render('/default/newsList', []);
  48. }
  49. public function actionInactive()
  50. {
  51. return $this->render('/default/newsInactive', []);
  52. }
  53. public function actionNewsshow($id)
  54. {
  55. $model = News::findOne($id);
  56. if($model) $model->Active($id);
  57. return $this->redirect(array('list', 'id'=>$id));
  58. }
  59. public function actionDelete($id)
  60. {
  61. if(Yii::$app->user->can('deleteNews')){
  62. $model = News::findOne($id);
  63. if( $model ){
  64. $model->deleteImg($id);
  65. $model->delete();
  66. }
  67. }
  68. return $this->redirect('list');
  69. }
  70. public function actionNewsnh($id)
  71. {
  72. $model = News::findOne($id);
  73. if($model) $model->NH($id);
  74. return $this->redirect(array('list', 'id'=>$id));
  75. }
  76. public function actionNewskd($id)
  77. {
  78. $model = News::findOne($id);
  79. if($model) $model->KD($id);
  80. return $this->redirect(array('list', 'id'=>$id));
  81. }
  82. public function actionNewsping($id)
  83. {
  84. $cache = Yii::$app->cache;
  85. $user = Yii::$app->user->identity->profile->name;
  86. if( $id && $res = $cache->get("editNews_$id") ){
  87. if( unserialize($res)['author'] != $user ){
  88. $cache->set('editNews_'.$id, serialize( array('author'=>$user, 'type' => 'ping' ) ), 90);
  89. return json_encode( ['status'=>'warn', 'author'=>unserialize($res)['author']] );
  90. }
  91. }
  92. $cache->set('editNews_'.$id, serialize( array('author'=>$user, 'type' => 'ping' ) ), 90);
  93. return json_encode( ['status'=>'ok', 'id'=>$id] );
  94. }
  95. public function actionTestping()
  96. {
  97. $authors = array();
  98. $cache = Yii::$app->cache;
  99. $post = Yii::$app->request->get('data');
  100. foreach( unserialize($post) as $id ){
  101. $r = $cache->get("editNews_$id");
  102. if( $r ) $authors[$id] = unserialize($r)['author'];
  103. }
  104. return json_encode( ['status'=>'ok', 'authors'=>$authors] );
  105. }
  106. public function actionCreate()
  107. {
  108. $model = new News();
  109. if (Yii::$app->request->isPost && $post = Yii::$app->request->post()){
  110. $pnews = $post['News'];
  111. if( isset($post['cropping']['url']) && $post['cropping']['url'] != '' ){
  112. $pnews['photo_name'] = $post['cropping']['url'];
  113. }
  114. $pnews = $this->formNormalizer($pnews);
  115. $post['News'] = [];
  116. $post['News'] = $pnews;
  117. if($model->load($post, 'News'))
  118. {
  119. if( $model->save($pnews) ){
  120. $id = $model->id;
  121. if( isset($post['Topics']) )
  122. {
  123. $tr = new NewsTopicRelation();
  124. $tr->saveNewsTopics($id, $post['Topics']);
  125. }
  126. if( isset($post['Story']) )
  127. {
  128. $tr = new StoryRelation();
  129. $tr->saveNewsStory($id, $post['Story']);
  130. }
  131. //echo "photo";
  132. //print_r( $_FILES );
  133. if (isset($_FILES['News']) && is_uploaded_file($_FILES['News']['tmp_name']['photo'])) {
  134. // $id = -1; //test
  135. $model->saveImg($id, $_FILES['News']['tmp_name']['photo'], $_FILES['News']['type']['photo']);
  136. }
  137. $tr = new TagsRelation();
  138. if( isset($post['Tags']) )
  139. {
  140. $tr->clearNewsSTG($id);
  141. try {
  142. $tr->saveNewsTags($id, $post['Tags']);
  143. }
  144. catch (\yii\db\Exception $e) {
  145. Yii::warning("Подобный тэг существует");
  146. }
  147. }
  148. if( isset($post['ExtTag']) )
  149. {
  150. $exttag = [];
  151. //удалить повторы
  152. foreach( $post['ExtTag'] as $item )
  153. {
  154. if( isset($post['Tags']) ){
  155. if( !isset( array_flip($post['Tags'])[$item] ) ) $exttag[] = $item;
  156. }else{
  157. $exttag[] = $item;
  158. }
  159. }
  160. try {
  161. $tr->saveNewsTags($id, $exttag);
  162. }
  163. catch (\yii\db\Exception $e) {
  164. Yii::warning("Подобный тэг существует");
  165. }
  166. }
  167. $PFilter = Yii::$app->request->post('PFilter');
  168. if($PFilter){
  169. $pfilter = PhotoFilter::findOne($id);
  170. if( !$pfilter ){
  171. $pfilter = new PhotoFilter();
  172. $pfilter->id = $id;
  173. }
  174. $pfilter->load($_POST, 'PFilter');
  175. $pfilter->save();
  176. }
  177. if( isset( $post['send'] ) ){
  178. Yii::$app->cache->delete("editNews_".$id);
  179. if( isset($post['News']['dt_pub']) ){
  180. $dt = $post['News']['dt_pub'];
  181. return $this->redirect(array('list', 'dt'=>$dt));
  182. }
  183. return $this->redirect('list');
  184. }
  185. //var_dump($model);
  186. ///echo $id; exit;
  187. return $this->redirect(['update', 'id'=>$id]);
  188. }else{
  189. var_dump($model->getErrors());
  190. }
  191. }else{
  192. var_dump($model->getErrors());
  193. }
  194. }
  195. return $this->render('/default/newsCreate', ['model'=>$model]);
  196. }
  197. public function actionUpdate($id)
  198. {
  199. if (Yii::$app->request->isPost && $post = Yii::$app->request->post()){
  200. // $model = new \app\models\News();
  201. // $model = $model->find()->andWhere(['id'=>$id])->one();
  202. // Обновить заг галереи
  203. if( isset($post['gallery_name']) && count($post['gallery_name']) > 0 ){
  204. foreach($post['gallery_name'] as $key=>$value){
  205. if( trim($value) == '' ) continue;
  206. \Yii::$app->db->createCommand()
  207. ->update(
  208. \manager\models\Gallery::tableName(),
  209. ['name' => $value],
  210. ['id' => $key]
  211. )->execute(); //->rawSql; //->execute();
  212. }
  213. }
  214. $model = News::findOne($id);
  215. // Удалить фото новости
  216. if( isset($post['News']['del_photo']) && $post['News']['del_photo'] == 'Y'){
  217. $model->deleteImg($id);
  218. }
  219. $pnews = $post['News'];
  220. if( isset($post['cropping']['url']) && $post['cropping']['url'] != '' ){
  221. $pnews['photo_name'] = $post['cropping']['url'];
  222. }
  223. $pnews = $this->formNormalizer($pnews);
  224. $post['News'] = [];
  225. $post['News'] = $pnews;
  226. $model->rev++;
  227. $model->dt_upd = date("Y-m-d H:i:s", time());
  228. if($model->load($post, 'News'))
  229. {
  230. if($model->save($pnews))
  231. {
  232. $tr = new NewsTopicRelation();
  233. if( isset($post['Topics']) )
  234. {
  235. $tr->clearNewsSTG($id);
  236. $tr->saveNewsTopics($id, $post['Topics']);
  237. }else{
  238. $tr->clearNewsSTG($id);
  239. }
  240. $tr = new StoryRelation();
  241. if( isset($post['Story']) )
  242. {
  243. $tr->clearNewsSTG($id);
  244. $tr->saveNewsStory($id, $post['Story']);
  245. }else{
  246. $tr->clearNewsSTG($id);
  247. }
  248. //print_r($_FILES['News']);
  249. //print_r($_REQUEST['cropping']);
  250. if (isset($_FILES['News']) && is_uploaded_file($_FILES['News']['tmp_name']['photo'])) {
  251. // $id = -1; //test
  252. $model->saveImg($id, $_FILES['News']['tmp_name']['photo'], $_FILES['News']['type']['photo']);
  253. }
  254. $tr = new TagsRelation();
  255. if( isset($post['Tags']) )
  256. {
  257. $tr->clearNewsSTG($id);
  258. try {
  259. $tr->saveNewsTags($id, $post['Tags']);
  260. }
  261. catch (\yii\db\Exception $e) {
  262. Yii::warning("Подобный тэг существует");
  263. }
  264. }else{
  265. $tr->clearNewsSTG($id);
  266. }
  267. // добавить тэги для меню фильтров
  268. if( isset($post['ExtTag']) )
  269. {
  270. $exttag = [];
  271. //удалить повторы
  272. foreach( $post['ExtTag'] as $item )
  273. {
  274. if( isset($post['Tags']) ){
  275. if( !isset( array_flip($post['Tags'])[$item] ) ) $exttag[] = $item;
  276. }else{
  277. $exttag[] = $item;
  278. }
  279. }
  280. try {
  281. $tr->saveNewsTags($id, $exttag);
  282. }
  283. catch (\yii\db\Exception $e) {
  284. Yii::warning("Подобный тэг существует");
  285. }
  286. }
  287. $PFilter = Yii::$app->request->post('PFilter');
  288. if($PFilter){
  289. //var_dump($PFilter);exit;
  290. $pfilter = PhotoFilter::findOne($id);
  291. if( !$pfilter ){
  292. $pfilter = new PhotoFilter();
  293. $pfilter->id = $id;
  294. }
  295. $pfilter->load($_POST, 'PFilter');
  296. $pfilter->save();
  297. }
  298. Yii::$app->cache->delete("editNews_".$id);
  299. if( isset( $post['send'] ) ){
  300. if( isset($post['News']['dt_pub']) ){
  301. $dt = $post['News']['dt_pub'];
  302. return $this->redirect(array('list', 'dt'=>$dt));
  303. }
  304. return $this->redirect('list');
  305. }
  306. }else{
  307. echo "no save";
  308. var_dump($model->getErrors());
  309. }
  310. }else{
  311. echo "load";
  312. var_dump($model->getErrors());
  313. }
  314. return $this->render('/default/newsUpdate', ['id'=>$id, 'model'=>$model]);
  315. }
  316. return $this->render('/default/newsUpdate', ['id'=>$id]);
  317. }
  318. public function formNormalizer($post)
  319. {
  320. $profile = Yii::$app->user->identity->profile;
  321. $post['title'] = trim(str_replace( "\xc2\xa0", ' ', $post['title'] ));
  322. $post['title'] = str_replace( ['«','»','&laquo;','&raquo;','&#171;','&laquo;'], '"', $post['title'] );
  323. $post['lid'] = trim(str_replace( "\xc2\xa0", ' ', $post['lid'] ));
  324. $post['lid'] = str_replace( ['«','»','&laquo;','&raquo;','&#171;','&laquo;'], '"', $post['lid'] );
  325. $post['text'] = str_replace( "\xc2\xa0", ' ', $post['text'] );
  326. //удалить 4х-байтные символы UTF
  327. $post['text'] = preg_replace("/[\xf0-\xf7][\x80-\xbf]{3}/", " ", $post['text'] );
  328. $post['active'] = $this->CheckYN(@$post['active']);
  329. $post['show_author'] = $this->CheckYN(@$post['show_author']);
  330. $post['verifed'] = $this->CheckYN(@$post['verifed']);
  331. $post['photo_include'] = $this->CheckYN(@$post['photo_include']);
  332. $post['photo_rcol'] = $this->CheckYN(@$post['photo_rcol']);
  333. $post['top'] = $this->CheckYN(@$post['top']);
  334. if( isset($post['NH']) ){
  335. if( $post['NH'] == 'Y' ){
  336. $post['NH'] = 'Y';
  337. }
  338. if( $post['NH'] == 'F' ){
  339. $post['NH'] = 'F';
  340. }
  341. }else{
  342. $post['NH'] = 'N';
  343. }
  344. $post['photo'] = $this->CheckYN(@$post['photo']);
  345. $post['video'] = $this->CheckYN(@$post['video']);
  346. $post['audio'] = $this->CheckYN(@$post['audio']);
  347. $post['comments'] = ( isset($post['comments']) || ( isset($post['comments']) && $post['comments'] == 'Y') )?'N':'Y';
  348. $post['noindex'] = $this->CheckYN(@$post['noindex']);
  349. $post['export_rss'] = (isset($post['fdzen']) && $post['fdzen'] == 'Y')?1:0;
  350. $post['export_rss'] += (isset($post['fmail']) && $post['fmail'] == 'Y')?2:0;
  351. $post['inscription'] = isset($post['commerc'])?$post['commerc']*1:0;
  352. $post['dt_pub'] = date("Y-m-d H:i:s", strtotime($post['dt_pub']));
  353. $post['alias'] = (isset($post['alias']) && trim( $post['alias'] ) != '' && $post['active'] == 'Y')?$post['alias']:Transliterator::toUrl($post['title']);
  354. $post['editors'] = $post['editors'].(($post['editors'])?',':'').$profile->name;
  355. $post['photo_name'] = isset($post['photo_name'])?$post['photo_name']:'';
  356. $post['flags'] = isset($post['nofirst'])?1:0;
  357. return $post;
  358. }
  359. public function CheckYN($attr)
  360. {
  361. return (isset($attr) && $attr == 'Y')?'Y':'N';
  362. }
  363. // ** Рубрики **
  364. public function actionTopiclist()
  365. {
  366. return $this->render('/default/topicList', []);
  367. }
  368. public function actionTopicall()
  369. {
  370. return $this->render('/default/topicAll', []);
  371. }
  372. public function actionTopicdel($id)
  373. {
  374. $model = $this->findTopicModel($id);
  375. if($model) $model->del($id);
  376. Yii::$app->cache->delete("archive_rubrics-{$id}");
  377. return $this->render('/default/topicList', []);
  378. }
  379. public function actionTopicshow($id)
  380. {
  381. $model = $this->findTopicModel($id);
  382. if($model) $model->Show($id);
  383. Yii::$app->cache->delete("archive_rubrics-{$id}");
  384. return $this->redirect('topiclist');
  385. }
  386. public function actionTopicactive($id)
  387. {
  388. $model = $this->findTopicModel($id);
  389. if($model) $model->Active($id);
  390. Yii::$app->cache->delete("archive_rubrics-{$id}");
  391. return $this->redirect('topiclist');
  392. }
  393. public function actionTopicsort()
  394. {
  395. if (isset($_POST['item']) && is_array($_POST['item'])) {
  396. $i = 0;
  397. $a = array();
  398. // beginTransaction(); было бы неплохо обернуть в транзакцию но хз как это сделать
  399. foreach ($_POST['item'] as $item) {
  400. $model = $this->findTopicModel($item);
  401. $model->order = $i;
  402. $a[$model->id] = $i;
  403. $model->save(true, ['order']);
  404. // print_a($model->errors);
  405. $i++;
  406. }
  407. Yii::$app->cache->delete("archive_rubrics-");
  408. return json_encode(['status'=>'ok','data'=>$a]);
  409. }
  410. return json_encode(['status'=>'err']);
  411. }
  412. public function actionTopiccreate()
  413. {
  414. $model = new NewsTopic();
  415. if (Yii::$app->request->isPost && Yii::$app->request->post()){
  416. if($model->load($_POST) && $model->save()){
  417. if (is_uploaded_file($_FILES['NewsTopic']['tmp_name']['photo'])) {
  418. // $id = -1; //test
  419. $model->saveImg($model->id, $_FILES['NewsTopic']['tmp_name']['photo'], $_FILES['NewsTopic']['type']['photo']);
  420. Yii::$app->cache->delete("archive_rubrics-{$model->id}");
  421. }
  422. }else{
  423. print_a($model->errors);
  424. }
  425. return $this->redirect('topiclist');
  426. }
  427. return $this->render('/default/topicCreate', ['model'=>$model]);
  428. }
  429. public function actionTopicupdate($id)
  430. {
  431. $model = $this->findTopicModel($id);
  432. if (Yii::$app->request->isPost && Yii::$app->request->post()){
  433. if($model->load($_POST) && $model->save()){
  434. // обновление фото
  435. if (is_uploaded_file($_FILES['NewsTopic']['tmp_name']['photo'])) {
  436. $model->saveImg($model->id, $_FILES['NewsTopic']['tmp_name']['photo'], $_FILES['NewsTopic']['type']['photo']);
  437. Yii::$app->cache->delete("archive_rubrics-{$id}");
  438. }
  439. }else{
  440. print_a($model->errors);
  441. }
  442. return $this->redirect('topiclist');
  443. }
  444. return $this->render('/default/topicUpdate', ['model'=>$model]);
  445. }
  446. // ** Сюжеты **
  447. public function actionStorylist()
  448. {
  449. return $this->render('/default/storyList', []);
  450. }
  451. public function actionStorydel($id)
  452. {
  453. $model = $this->findStoryModel($id);
  454. if($model) $model->del($id);
  455. return $this->render('/default/storyList', []);
  456. }
  457. public function actionStoryshow($id)
  458. {
  459. $model = $this->findStoryModel($id);
  460. if($model) $model->Show($id);
  461. return $this->render('/default/storyList', []);
  462. }
  463. public function actionAjaxstory()
  464. {
  465. if (Yii::$app->request->isGet && $get = Yii::$app->request->get('q')){
  466. $model = new Story();
  467. $items = $model->search($get, 20);
  468. $res = array();
  469. if( $items && is_array( $items ) ){
  470. foreach( $items as $item ){
  471. $res[] = array( 'id'=>$item['id']*1, 'label'=>$item['title'] );
  472. }
  473. return json_encode( ['status'=>'ok', 'item'=>$res] );
  474. }
  475. }
  476. return json_encode( ['status'=>'err'] );
  477. }
  478. public function actionStoryactive($id)
  479. {
  480. $model = $this->findStoryModel($id);
  481. if($model) $model->Active($id);
  482. return $this->render('/default/storyList', []);
  483. }
  484. public function actionStorycreate()
  485. {
  486. $model = new Story();
  487. if (Yii::$app->request->isPost && Yii::$app->request->post()){
  488. if($model->load($_POST) && $model->save()){
  489. if (is_uploaded_file($_FILES['Story']['tmp_name']['photo'])) {
  490. // $id = -1; //test
  491. $model->saveImg($model->id, $_FILES['Story']['tmp_name']['photo'], $_FILES['Story']['type']['photo']);
  492. }
  493. }else{
  494. print_a($model->errors);
  495. }
  496. return $this->redirect('storylist');
  497. }
  498. return $this->render('/default/storyCreate', ['model'=>$model]);
  499. }
  500. public function actionStoryupdate($id)
  501. {
  502. $model = $this->findStoryModel($id);
  503. if (Yii::$app->request->isPost && Yii::$app->request->post()){
  504. if($model->load($_POST) && $model->save()){
  505. // обновление фото
  506. if (is_uploaded_file($_FILES['Story']['tmp_name']['photo'])) {
  507. $model->saveImg($model->id, $_FILES['Story']['tmp_name']['photo'], $_FILES['Story']['type']['photo']);
  508. }
  509. }else{
  510. print_a($model->errors);
  511. }
  512. return $this->redirect('storylist');
  513. }
  514. return $this->render('/default/storyUpdate', ['model'=>$model]);
  515. }
  516. public function actionAddGallery()
  517. {
  518. $gallery = new \manager\models\Gallery();
  519. $gallery->load(Yii::$app->request->get(),'');
  520. $gallery->save();
  521. return $this->renderPartial('@manager/views/news/form/galleryItem',["model"=>$gallery]);
  522. }
  523. public function actionRemoveGallery($id)
  524. {
  525. $gallery = \manager\models\Gallery::find()->andWhere(['id'=>$id])->one();
  526. $gallery->delete();
  527. return true;
  528. }
  529. // ** отладка **
  530. public function actionTest()
  531. {
  532. return $this->render('/default/test', []);
  533. }
  534. /**
  535. * Найти сюжет.
  536. *
  537. * @param $id
  538. * @return Story|null
  539. * @throws NotFoundHttpException
  540. */
  541. protected function findStoryModel($id)
  542. {
  543. if (($model = Story::findOne($id)) !== null) {
  544. return $model;
  545. }
  546. throw new NotFoundHttpException('Ой! сюжет не найдена.');
  547. return false;
  548. }
  549. /**
  550. * Найти Ркбрику.
  551. *
  552. * @param $id
  553. * @return Story|null
  554. * @throws NotFoundHttpException
  555. */
  556. protected function findTopicModel($id)
  557. {
  558. if (($model = NewsTopic::findOne($id)) !== null) {
  559. return $model;
  560. }
  561. throw new NotFoundHttpException('Ой! рубрика не найдена.');
  562. return false;
  563. }
  564. }