NewsController.php 17 KB

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