Файл: protected/controllers/RatingController.php
Строк: 47
<?php
/*
* Система рейтинга статей
*/
class RatingController extends Controller
{
/*
* Действие по умолчанию
*/
public $defaultAction = 'vote';
/*
* Фильтры
*/
public function filters ()
{
return array (
'accessControl'
);
}
/*
* Правила доступа
*/
public function accessRules ()
{
return array (
array (
'allow',
'users' => array ('@')
),
array (
'allow',
'users' => array ('?'),
'actions' => array ('vote', 'top')
),
array (
'deny',
'users' => array ('*')
)
);
}
/*
* Голосование за/против статьи
*/
public function actionVote ($id)
{
if (isset ($_POST["rating"]))
{
// Если юзер уже голосовал
if (isset (Yii::app ()->request->cookies[Config::COOKIE_PREFIX . 'vote' . $id]))
{
$this->render ('//msg', array ('title' => 'Ошибка', 'msg' => 'Вы уже голосовали!'));
Yii::app()->end();
}
$post = $this->loadPost ($id);
if (isset ($_POST["rating"]["yes"]) && isset ($_POST["rating"]["no"]))
{
$this->render ('//msg', array ('msg' => 'Нельзя голосавать сразу и за и против!'));
Yii::app()->end();
}
if (isset ($_POST["rating"]["yes"]))
{
// Увеличиваем рейтинг
$post->positive_votes++;
}
elseif (isset ($_POST["rating"]["no"]))
{
// Уменьшаем рейтинг
$post->negative_votes++;
}
if ($post->save ())
{
// Ставим куку
$cookie = new CHttpCookie (Config::COOKIE_PREFIX . 'vote' . $post->id, 1);
$cookie->expire = time () + (3600 * 24 * 365 * 17);
Yii::app ()->request->cookies["vote{$post->id}"] = $cookie;
$this->render ('//msg', array ('msg' => 'Спасибо, ваш голос учтен!'));
}
}
else
{
$this->render ('//msg', array ('msg' => 'Выбирите тип голоса!'));
}
}
/*
* Топ статей
*/
public function actionTop ()
{
$this->render ('top', array (
'postProvider' => Post::model ()->loadByRating ()
));
}
/*
* Загрузка статьи
*/
private function loadPost ($id)
{
$model = Post::model()->findByPk ((int)$id);
if ($model === NULL) throw new CHttpException (404, 'Статья не найдена');
return $model;
}
}