Файл: protected/controllers/PostController.php
Строк: 68
<?php
/*
* Управление статьями
*/
class PostController extends Controller
{
/*
* Действие по умолчанию
*/
public $defaultAction = 'view';
/*
* Фильтры
*/
public function filters ()
{
return array (
'accessControl'
);
}
/*
* Правила доступа
*/
public function accessRules ()
{
return array (
array (
'allow',
'users' => array ('@')// Разрешить доступ авторизованным
),
array (
'allow',
'users' => array ('?'),// Разрешить определенные действия гостям
'actions' => array ('view')
),
array (
'deny',
'users' => array ('*')// Запретить всем остальным
)
);
}
/*
* Добавление новой статьи
*/
public function actionCreate ()
{
$post = new Post;
$modelCategory = new Category;
$categoryProvider = $modelCategory->loadCategories ();
if (isset ($_POST["post"]))
{
$post->attributes = $_POST["post"];
if ($post->save ())
{
// Синхронизируем теги
Tag::model ()->createPostTags (explode (Tag::RAZD, $post->tags));
$this->redirect (array ('view', 'id' => $post->id));
Yii::app()->end();// Корректно завершаем приложение
}
}
if (Yii::app ()->controller->action->id == 'create')
{
$this->render ('create', array (
'post' => $post,
'categoryProvider' => $categoryProvider
));
}
elseif (Yii::app ()->controller->action->id == 'createNews')
{
$this->render ('createNews', array (
'post' => $post,
'cat_news' => Category::model ()->findByPk (Category::ID_NEWS)
));
}
}
/*
* Добавление новости
*/
public function actionCreateNews ()
{
$this->actionCreate ();
}
/*
* Изменение статьи
*/
public function actionUpdate ($id)
{
$post = $this->loadPost ($id);
// Информация для обновления тегов
$tags_old = explode (Tag::RAZD, $post->tags);
$tags_new = explode (Tag::RAZD, $_POST["post"]["tags"]);
if (isset ($_POST["post"]))
{
$post->status = Post::STATUS_PUBLISHED;// Из-за особенностей сохранения статей явно указываем статус статьи
$post->attributes = $_POST["post"];
if ($post->save ())
{
// Синхронизируем теги---------------------------------------------------------------
Tag::model ()->updatePostTags ($tags_old, $tags_new);
//-----------------------------------------------------------------------------------
$this->redirect (array ('view', 'id' => $post->id));
Yii::app()->end();// Корректно завершаем приложение
}
}
$this->render('update', array (
'post' => $post,
'categoryProvider' => Category::model ()->loadCategories ()
));
}
/*
* Удаление статьи
*/
public function actionDelete ($id)
{
$post = $this->loadPost ($id);
if (!isset ($_POST["delete"]))
{
$this->render ('delete', array ('postID' => $id, 'post' => $post));
}
else
{
// Синхронизируем теги
Tag::model ()->deletePostTags (explode (Tag::RAZD, $post->tags));
// Удаляем статью
$post->delete ();
// Удаляем комменты. Если настроены вторичные ключи (а по умолчанию они настроены), комменты удалятся сами
//Comment::model ()->deleteAll('`id_post`=:id_post', array (':id_post' => $post->id));
$this->redirect (array ('//'));
}
}
/*
* Просмотр статьи (И комментариев заодно)
*/
public function actionView ($id)
{
$post = $this->loadPost ($id);
// Если статья - черновик, посылаем юзера (если он не админ)
if ($post->status == Post::STATUS_DRAFT && Yii::app ()->user->isGuest)
{
$this->redirect (array ('//login'));
Yii::app ()->end ();
}
// Увеличиваем все просмотры
$post->all_views++;
// Увеличиваем уникальные просмотры
if (!isset (Yii::app ()->request->cookies[Config::COOKIE_PREFIX . 'view' . $id]))
{
$post->unique_views++;
// Ставим куку
$cookie = new CHttpCookie(Config::COOKIE_PREFIX . 'view' . $post->id, 1);
$cookie->expire = time () + (3600 * 24 * 365 * 17);
Yii::app ()->request->cookies["view{$post->id}"] = $cookie;
}
$post->save ();
$this->render('view', array(
'post' => $post,
// Комментарии
'commentProvider' => Comment::model ()->loadComments($id)
));
}
/*
* Черновики
*/
public function actionDrafts ()
{
$this->render ('drafts', array (
'postProvider' => Post::model ()->loadDrafts ()
));
}
/*
* Загрузка статьи
*/
private function loadPost ($id)
{
$model = Post::model()->findByPk ((int)$id);
if ($model === NULL) throw new CHttpException (404, 'Статья не найдена');
return $model;
}
}