123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606 |
- <?php
- namespace manager\controllers;
- use manager\models\Gallery;
- use Yii;
- use manager\models\News;
- use \app\models\base\Tags;
- use \app\models\base\TagsRelation;
- use \app\models\base\Story;
- use \app\models\base\StoryRelation;
- use \app\models\base\NewsTopic;
- use \app\models\base\NewsTopicRelation;
- use yii\web\UploadedFile;
- use \app\helpers\Transliterator;
- use zxbodya\yii2\galleryManager\GalleryManagerAction;
- use yii\base\ErrorException;
- use \app\models\PhotoFilter;
- class NewsController extends BaseController
- {
- // ** Статьи (новости) **
- public function actions()
- {
- return [
- 'error' => [
- 'class' => 'yii\web\ErrorAction',
- ],
- 'galleryApi' => [
- 'class' => GalleryManagerAction::className(),
- // mappings between type names and model classes (should be the same as in behaviour)
- 'types' => [
- 'product' => News::className(),
- 'post_gallery' => Gallery::className()
- ]
- ],
- ];
- }
- public function actionIndex()
- {
- return $this->render("/default/news",[]);
- }
- public function actionList()
- {
- if (Yii::$app->request->isGet && Yii::$app->request->get('id')){
- Yii::$app->session->get('dt-newslistadm');
- }else{
- Yii::$app->session->remove('dt-newslistadm');
- }
- return $this->render('/default/newsList', []);
- }
- public function actionInactive()
- {
- return $this->render('/default/newsInactive', []);
- }
- public function actionNewsshow($id)
- {
- $model = News::findOne($id);
- if($model) $model->Active($id);
- return $this->redirect(array('list', 'id'=>$id));
- }
- public function actionDelete($id)
- {
- if(Yii::$app->user->can('deleteNews')){
- $model = News::findOne($id);
- if( $model ){
- $model->deleteImg($id);
- $model->delete();
- }
- }
- return $this->redirect('list');
- }
- public function actionNewsnh($id)
- {
- $model = News::findOne($id);
- if($model) $model->NH($id);
- return $this->redirect(array('list', 'id'=>$id));
- }
- public function actionNewskd($id)
- {
- $model = News::findOne($id);
- if($model) $model->KD($id);
- return $this->redirect(array('list', 'id'=>$id));
- }
- public function actionNewsping($id)
- {
- $cache = Yii::$app->cache;
- $user = Yii::$app->user->identity->profile->name;
- if( $id && $res = $cache->get("editNews_$id") ){
- if( unserialize($res)['author'] != $user ){
- $cache->set('editNews_'.$id, serialize( array('author'=>$user, 'type' => 'ping' ) ), 90);
- return json_encode( ['status'=>'warn', 'author'=>unserialize($res)['author']] );
- }
- }
- $cache->set('editNews_'.$id, serialize( array('author'=>$user, 'type' => 'ping' ) ), 90);
- return json_encode( ['status'=>'ok', 'id'=>$id] );
- }
- public function actionTestping()
- {
- $authors = array();
- $cache = Yii::$app->cache;
- $post = Yii::$app->request->get('data');
- foreach( unserialize($post) as $id ){
- $r = $cache->get("editNews_$id");
- if( $r ) $authors[$id] = unserialize($r)['author'];
- }
- return json_encode( ['status'=>'ok', 'authors'=>$authors] );
- }
- public function actionCreate()
- {
- $model = new News();
- if (Yii::$app->request->isPost && $post = Yii::$app->request->post()){
- $pnews = $post['News'];
- if( isset($post['cropping']['url']) && $post['cropping']['url'] != '' ){
- $pnews['photo_name'] = $post['cropping']['url'];
- }
- $pnews = $this->formNormalizer($pnews);
- $post['News'] = [];
- $post['News'] = $pnews;
- if($model->load($post, 'News'))
- {
- if( $model->save($pnews) ){
- $id = $model->id;
- if( isset($post['Topics']) )
- {
- $tr = new NewsTopicRelation();
- $tr->saveNewsTopics($id, $post['Topics']);
- }
- if( isset($post['Story']) )
- {
- $tr = new StoryRelation();
- $tr->saveNewsStory($id, $post['Story']);
- }
- //echo "photo";
- //print_r( $_FILES );
- if (isset($_FILES['News']) && is_uploaded_file($_FILES['News']['tmp_name']['photo'])) {
- // $id = -1; //test
- $model->saveImg($id, $_FILES['News']['tmp_name']['photo'], $_FILES['News']['type']['photo']);
- }
- $tr = new TagsRelation();
- if( isset($post['Tags']) )
- {
- $tr->clearNewsSTG($id);
- try {
- $tr->saveNewsTags($id, $post['Tags']);
- }
- catch (\yii\db\Exception $e) {
- Yii::warning("Подобный тэг существует");
- }
- }
- if( isset($post['ExtTag']) )
- {
- $exttag = [];
- //удалить повторы
- foreach( $post['ExtTag'] as $item )
- {
- if( isset($post['Tags']) ){
- if( !isset( array_flip($post['Tags'])[$item] ) ) $exttag[] = $item;
- }else{
- $exttag[] = $item;
- }
- }
- try {
- $tr->saveNewsTags($id, $exttag);
- }
- catch (\yii\db\Exception $e) {
- Yii::warning("Подобный тэг существует");
- }
- }
- $PFilter = Yii::$app->request->post('PFilter');
- if($PFilter){
- $pfilter = PhotoFilter::findOne($id);
- if( !$pfilter ){
- $pfilter = new PhotoFilter();
- $pfilter->id = $id;
- }
- $pfilter->load($_POST, 'PFilter');
- $pfilter->save();
- }
- if( isset( $post['send'] ) ){
- Yii::$app->cache->delete("editNews_".$id);
- if( isset($post['News']['dt_pub']) ){
- $dt = $post['News']['dt_pub'];
- return $this->redirect(array('list', 'dt'=>$dt));
- }
- return $this->redirect('list');
- }
- //var_dump($model);
- ///echo $id; exit;
- return $this->redirect(['update', 'id'=>$id]);
- }else{
- var_dump($model->getErrors());
- }
- }else{
- var_dump($model->getErrors());
- }
- }
- return $this->render('/default/newsCreate', ['model'=>$model]);
- }
- public function actionUpdate($id)
- {
- if (Yii::$app->request->isPost && $post = Yii::$app->request->post()){
- // $model = new \app\models\News();
- // $model = $model->find()->andWhere(['id'=>$id])->one();
- // Обновить заг галереи
- if( isset($post['gallery_name']) && count($post['gallery_name']) > 0 ){
- foreach($post['gallery_name'] as $key=>$value){
- if( trim($value) == '' ) continue;
- \Yii::$app->db->createCommand()
- ->update(
- \manager\models\Gallery::tableName(),
- ['name' => $value],
- ['id' => $key]
- )->execute(); //->rawSql; //->execute();
- }
- }
- $model = News::findOne($id);
- // Удалить фото новости
- if( isset($post['News']['del_photo']) && $post['News']['del_photo'] == 'Y'){
- $model->deleteImg($id);
- }
- $pnews = $post['News'];
- if( isset($post['cropping']['url']) && $post['cropping']['url'] != '' ){
- $pnews['photo_name'] = $post['cropping']['url'];
- }
- $pnews = $this->formNormalizer($pnews);
- $post['News'] = [];
- $post['News'] = $pnews;
- $model->rev++;
- $model->dt_upd = date("Y-m-d H:i:s", time());
- if($model->load($post, 'News'))
- {
- if($model->save($pnews))
- {
- $tr = new NewsTopicRelation();
- if( isset($post['Topics']) )
- {
- $tr->clearNewsSTG($id);
- $tr->saveNewsTopics($id, $post['Topics']);
- }else{
- $tr->clearNewsSTG($id);
- }
- $tr = new StoryRelation();
- if( isset($post['Story']) )
- {
- $tr->clearNewsSTG($id);
- $tr->saveNewsStory($id, $post['Story']);
- }else{
- $tr->clearNewsSTG($id);
- }
- //print_r($_FILES['News']);
- //print_r($_REQUEST['cropping']);
- if (isset($_FILES['News']) && is_uploaded_file($_FILES['News']['tmp_name']['photo'])) {
- // $id = -1; //test
- $model->saveImg($id, $_FILES['News']['tmp_name']['photo'], $_FILES['News']['type']['photo']);
- }
- $tr = new TagsRelation();
- if( isset($post['Tags']) )
- {
- $tr->clearNewsSTG($id);
- try {
- $tr->saveNewsTags($id, $post['Tags']);
- }
- catch (\yii\db\Exception $e) {
- Yii::warning("Подобный тэг существует");
- }
- }else{
- $tr->clearNewsSTG($id);
- }
- // добавить тэги для меню фильтров
- if( isset($post['ExtTag']) )
- {
- $exttag = [];
- //удалить повторы
- foreach( $post['ExtTag'] as $item )
- {
- if( isset($post['Tags']) ){
- if( !isset( array_flip($post['Tags'])[$item] ) ) $exttag[] = $item;
- }else{
- $exttag[] = $item;
- }
- }
- try {
- $tr->saveNewsTags($id, $exttag);
- }
- catch (\yii\db\Exception $e) {
- Yii::warning("Подобный тэг существует");
- }
- }
- $PFilter = Yii::$app->request->post('PFilter');
- if($PFilter){
- //var_dump($PFilter);exit;
- $pfilter = PhotoFilter::findOne($id);
- if( !$pfilter ){
- $pfilter = new PhotoFilter();
- $pfilter->id = $id;
- }
- $pfilter->load($_POST, 'PFilter');
- $pfilter->save();
- }
- Yii::$app->cache->delete("editNews_".$id);
- if( isset( $post['send'] ) ){
- if( isset($post['News']['dt_pub']) ){
- $dt = $post['News']['dt_pub'];
- return $this->redirect(array('list', 'dt'=>$dt));
- }
- return $this->redirect('list');
- }
- }else{
- echo "no save";
- var_dump($model->getErrors());
- }
- }else{
- echo "load";
- var_dump($model->getErrors());
- }
- return $this->render('/default/newsUpdate', ['id'=>$id, 'model'=>$model]);
- }
- return $this->render('/default/newsUpdate', ['id'=>$id]);
- }
- public function formNormalizer($post)
- {
- $profile = Yii::$app->user->identity->profile;
- $post['title'] = trim(str_replace( "\xc2\xa0", ' ', $post['title'] ));
- $post['title'] = str_replace( ['«','»','«','»','«','«'], '"', $post['title'] );
- $post['lid'] = trim(str_replace( "\xc2\xa0", ' ', $post['lid'] ));
- $post['lid'] = str_replace( ['«','»','«','»','«','«'], '"', $post['lid'] );
- $post['text'] = str_replace( "\xc2\xa0", ' ', $post['text'] );
- //удалить 4х-байтные символы UTF
- $post['text'] = preg_replace("/[\xf0-\xf7][\x80-\xbf]{3}/", " ", $post['text'] );
- $post['active'] = $this->CheckYN(@$post['active']);
- $post['show_author'] = $this->CheckYN(@$post['show_author']);
- $post['verifed'] = $this->CheckYN(@$post['verifed']);
- $post['photo_include'] = $this->CheckYN(@$post['photo_include']);
- $post['photo_rcol'] = $this->CheckYN(@$post['photo_rcol']);
- $post['top'] = $this->CheckYN(@$post['top']);
- if( isset($post['NH']) ){
- if( $post['NH'] == 'Y' ){
- $post['NH'] = 'Y';
- }
- if( $post['NH'] == 'F' ){
- $post['NH'] = 'F';
- }
- }else{
- $post['NH'] = 'N';
- }
- $post['photo'] = $this->CheckYN(@$post['photo']);
- $post['video'] = $this->CheckYN(@$post['video']);
- $post['audio'] = $this->CheckYN(@$post['audio']);
- $post['comments'] = ( isset($post['comments']) || ( isset($post['comments']) && $post['comments'] == 'Y') )?'N':'Y';
- $post['noindex'] = $this->CheckYN(@$post['noindex']);
- $post['export_rss'] = (isset($post['fdzen']) && $post['fdzen'] == 'Y')?1:0;
- $post['export_rss'] += (isset($post['fmail']) && $post['fmail'] == 'Y')?2:0;
- $post['inscription'] = isset($post['commerc'])?$post['commerc']*1:0;
- $post['dt_pub'] = date("Y-m-d H:i:s", strtotime($post['dt_pub']));
- $post['alias'] = (isset($post['alias']) && trim( $post['alias'] ) != '' && $post['active'] == 'Y')?$post['alias']:Transliterator::toUrl($post['title']);
- $post['editors'] = $post['editors'].(($post['editors'])?',':'').$profile->name;
- $post['photo_name'] = isset($post['photo_name'])?$post['photo_name']:'';
- $post['flags'] = isset($post['nofirst'])?1:0;
- return $post;
- }
- public function CheckYN($attr)
- {
- return (isset($attr) && $attr == 'Y')?'Y':'N';
- }
- // ** Рубрики **
- public function actionTopiclist()
- {
- return $this->render('/default/topicList', []);
- }
- public function actionTopicall()
- {
- return $this->render('/default/topicAll', []);
- }
- public function actionTopicdel($id)
- {
- $model = $this->findTopicModel($id);
- if($model) $model->del($id);
- Yii::$app->cache->delete("archive_rubrics-{$id}");
- return $this->render('/default/topicList', []);
- }
- public function actionTopicshow($id)
- {
- $model = $this->findTopicModel($id);
- if($model) $model->Show($id);
- Yii::$app->cache->delete("archive_rubrics-{$id}");
- return $this->redirect('topiclist');
- }
- public function actionTopicactive($id)
- {
- $model = $this->findTopicModel($id);
- if($model) $model->Active($id);
- Yii::$app->cache->delete("archive_rubrics-{$id}");
- return $this->redirect('topiclist');
- }
- public function actionTopicsort()
- {
- if (isset($_POST['item']) && is_array($_POST['item'])) {
- $i = 0;
- $a = array();
- // beginTransaction(); было бы неплохо обернуть в транзакцию но хз как это сделать
- foreach ($_POST['item'] as $item) {
- $model = $this->findTopicModel($item);
- $model->order = $i;
- $a[$model->id] = $i;
- $model->save(true, ['order']);
- // print_a($model->errors);
- $i++;
- }
- Yii::$app->cache->delete("archive_rubrics-");
- return json_encode(['status'=>'ok','data'=>$a]);
- }
- return json_encode(['status'=>'err']);
- }
- public function actionTopiccreate()
- {
- $model = new NewsTopic();
- if (Yii::$app->request->isPost && Yii::$app->request->post()){
- if($model->load($_POST) && $model->save()){
- if (is_uploaded_file($_FILES['NewsTopic']['tmp_name']['photo'])) {
- // $id = -1; //test
- $model->saveImg($model->id, $_FILES['NewsTopic']['tmp_name']['photo'], $_FILES['NewsTopic']['type']['photo']);
- Yii::$app->cache->delete("archive_rubrics-{$model->id}");
- }
- }else{
- print_a($model->errors);
- }
- return $this->redirect('topiclist');
- }
- return $this->render('/default/topicCreate', ['model'=>$model]);
- }
- public function actionTopicupdate($id)
- {
- $model = $this->findTopicModel($id);
- if (Yii::$app->request->isPost && Yii::$app->request->post()){
- if($model->load($_POST) && $model->save()){
- // обновление фото
- if (is_uploaded_file($_FILES['NewsTopic']['tmp_name']['photo'])) {
- $model->saveImg($model->id, $_FILES['NewsTopic']['tmp_name']['photo'], $_FILES['NewsTopic']['type']['photo']);
- Yii::$app->cache->delete("archive_rubrics-{$id}");
- }
- }else{
- print_a($model->errors);
- }
- return $this->redirect('topiclist');
- }
- return $this->render('/default/topicUpdate', ['model'=>$model]);
- }
- // ** Сюжеты **
- public function actionStorylist()
- {
- return $this->render('/default/storyList', []);
- }
- public function actionStorydel($id)
- {
- $model = $this->findStoryModel($id);
- if($model) $model->del($id);
- return $this->render('/default/storyList', []);
- }
- public function actionStoryshow($id)
- {
- $model = $this->findStoryModel($id);
- if($model) $model->Show($id);
- return $this->render('/default/storyList', []);
- }
- public function actionAjaxstory()
- {
- if (Yii::$app->request->isGet && $get = Yii::$app->request->get('q')){
- $model = new Story();
- $items = $model->search($get, 20);
- $res = array();
- if( $items && is_array( $items ) ){
- foreach( $items as $item ){
- $res[] = array( 'id'=>$item['id']*1, 'label'=>$item['title'] );
- }
- return json_encode( ['status'=>'ok', 'item'=>$res] );
- }
- }
- return json_encode( ['status'=>'err'] );
- }
- public function actionStoryactive($id)
- {
- $model = $this->findStoryModel($id);
- if($model) $model->Active($id);
- return $this->render('/default/storyList', []);
- }
- public function actionStorycreate()
- {
- $model = new Story();
- if (Yii::$app->request->isPost && Yii::$app->request->post()){
- if($model->load($_POST) && $model->save()){
- if (is_uploaded_file($_FILES['Story']['tmp_name']['photo'])) {
- // $id = -1; //test
- $model->saveImg($model->id, $_FILES['Story']['tmp_name']['photo'], $_FILES['Story']['type']['photo']);
- }
- }else{
- print_a($model->errors);
- }
- return $this->redirect('storylist');
- }
- return $this->render('/default/storyCreate', ['model'=>$model]);
- }
- public function actionStoryupdate($id)
- {
- $model = $this->findStoryModel($id);
- if (Yii::$app->request->isPost && Yii::$app->request->post()){
- if($model->load($_POST) && $model->save()){
- // обновление фото
- if (is_uploaded_file($_FILES['Story']['tmp_name']['photo'])) {
- $model->saveImg($model->id, $_FILES['Story']['tmp_name']['photo'], $_FILES['Story']['type']['photo']);
- }
- }else{
- print_a($model->errors);
- }
- return $this->redirect('storylist');
- }
- return $this->render('/default/storyUpdate', ['model'=>$model]);
- }
- public function actionAddGallery()
- {
- $gallery = new \manager\models\Gallery();
- $gallery->load(Yii::$app->request->get(),'');
- $gallery->save();
- return $this->renderPartial('@manager/views/news/form/galleryItem',["model"=>$gallery]);
- }
- public function actionRemoveGallery($id)
- {
- $gallery = \manager\models\Gallery::find()->andWhere(['id'=>$id])->one();
- $gallery->delete();
- return true;
- }
- // ** отладка **
- public function actionTest()
- {
- return $this->render('/default/test', []);
- }
- /**
- * Найти сюжет.
- *
- * @param $id
- * @return Story|null
- * @throws NotFoundHttpException
- */
- protected function findStoryModel($id)
- {
- if (($model = Story::findOne($id)) !== null) {
- return $model;
- }
- throw new NotFoundHttpException('Ой! сюжет не найдена.');
- return false;
- }
- /**
- * Найти Ркбрику.
- *
- * @param $id
- * @return Story|null
- * @throws NotFoundHttpException
- */
- protected function findTopicModel($id)
- {
- if (($model = NewsTopic::findOne($id)) !== null) {
- return $model;
- }
- throw new NotFoundHttpException('Ой! рубрика не найдена.');
- return false;
- }
- }
|