Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nordeveloper/9827371 to your computer and use it in GitHub Desktop.
Save nordeveloper/9827371 to your computer and use it in GitHub Desktop.
<?php defined('SYSPATH') or die('No direct access allowed.');
/**
* Ajax Template Controller template
*
* @package Templates
* @author Sergei Gladkovskiy <smgladkovskiy@gmail.com>
*/
abstract class Controller_Ajax_Template extends Controller {
/**
* The need of authorization
*
* @var bool
*/
protected $_auth_required = TRUE;
/**
* Send response in JSON format
*
* @var bool
*/
protected $_render_json = TRUE;
/**
* User container
*
* @var Model_User
*/
protected $_user = NULL;
/**
* Roles container
*
* @var array
*/
protected $_user_roles = NULL;
/**
* ACL
*
* @var Deputy
*/
protected $_deputy = NULL;
/**
* Site config container
*
* @var Config_Group
*/
protected $_site_config = NULL;
/**
* Response body array
*
* @var array
*/
private $response_body;
const ERROR = 0;
const SUCCESS = 1;
/**
* Статус ответа. По умолчанию - успешный ответ.
*
* @var int
*/
protected $status = self::SUCCESS;
/**
* Контейнер для ошибок
*
* @var mixed
*/
protected $errors = NULL;
/**
* Контейнер для сообщений
*
* @var mixed
*/
protected $message = NULL;
/**
* Контейнер для данных
*
* @var mixed
*/
protected $data = NULL;
/**
* Контейнер для содержания в виде HTML.
* При заполнении контейнера, данные передаются не в виде json массива, а в виде text/html
*
* @var mixed
*/
protected $content = NULL;
/**
* Ссылка для редиректа
*
* @var mixed
*/
protected $redirect = NULL;
/**
* Наименование таблицы, которую нужно проапдейтить (для гридов темаф)
*
* @var mixed
*/
protected $refresh_table_name = NULL;
/**
* Constructor
*
* @param Request $request
* @param Response $response
*/
public function __construct(Request $request, Response $response)
{
// Ajax-like request setting if HMVC call or POST request with param `is_ajax` == `true`
if ($request->is_ajax() OR $request !== Request::initial()
OR ($request->method() === HTTP_Request::POST AND $request->post('is_ajax') === 'true'))
{
$request->requested_with('xmlhttprequest');
}
parent::__construct($request, $response);
}
/**
* Before actions
*/
public function before()
{
parent::before();
// Установка языка
I18n::$lang = $this->request->param('lang');
$this->status = self::SUCCESS;
// Auth check
$this->_auth_check();
$this->_site_config = Kohana::$config->load('site');
}
/**
* After actions
*/
public function after()
{
// Передаём ошибки при наличии в массив ответа
if($this->errors)
{
$this->response_body['errors'] = $this->errors;
// Если в результате обработки появились ошибки, то статус ответа должен быть "ошибка"
if($this->status != self::ERROR)
$this->status = self::ERROR;
}
// Передаём сообщения в массив ответа
if($this->message)
$this->response_body['message'] = $this->message;
// Передаём данные в массив ответа
if($this->data)
$this->response_body['data'] = $this->data;
// Передаём ссылку для редиректа в массив ответа
if($this->redirect)
{
$this->response_body['redirect'] = $this->redirect;
// Определяем, что нужно рефрешить всю страницу
$this->response_body['table_refresh'] = FALSE;
}
// Передаём статус ответа в массив ответа
$this->response_body['status'] = $this->status;
// Передаём название таблицы, которую нужно обновить
if($this->refresh_table_name)
{
$this->response_body['refresh_table_name'] = $this->refresh_table_name;
$this->response_body['table_refresh'] = TRUE;
}
// ЕБАТЬ! Да у нас тут plain html! Пиздец, вся предыдущая работа - коту под хвост! Тупо передаём html в тело ответа.
if($this->content)
{
$this->response_body = ($this->content instanceof View) ?$this->content->render() : $this->content;
$this->response->body($this->response_body);
}
else // Либо как нормальные пацаны передаём чоткий json
{
// Encode JSON to readable view if UTF-8 chars are used
if(PHP_MAJOR_VERSION == 5 AND PHP_MINOR_VERSION < 4)
{
$this->response->body(str_replace('\/','/', Text::my_json_encode($this->response_body)));
}
else
{
$this->response->body(json_encode($this->response_body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
}
$this->response->headers('Content-Type', 'application/json');
}
$this->response->headers('ETag', $this->response->generate_etag());
$this->response->send_headers();
parent::after();
}
protected function _auth_check()
{
// Auth require check and setting $this->_user
if ($this->_auth_required AND class_exists('Auth') AND ! Auth::instance()->logged_in())
{
Session::instance()->set('url', $_SERVER['REQUEST_URI']);
HTTP::redirect(Route::url('auth', array('lang' => I18n::$lang, 'action' => 'login')));
}
elseif($this->_auth_required AND (class_exists('Auth') AND Auth::instance()->logged_in() OR Auth::instance()->logged_in()))
{
$this->_user = Jelly::query('user', Auth::instance()->get_user()->id)->select();
$this->_check_activity();
View::set_global('_user', $this->_user);
}
if(class_exists('Auth') AND Auth::instance()->logged_in() AND ! $this->_user)
{
$this->_user = Jelly::query('user', Auth::instance()->get_user()->id)->select();
$this->_check_activity();
View::set_global('_user', $this->_user);
}
}
protected function _check_activity()
{
if( ! $this->_user->is_active AND $this->request->controller() != 'Error')
throw HTTP_Exception::factory(403, __('Пользователь не зарегистирован или отключён'));
$this->_user_roles = $this->_user->roles->as_array('id', 'name');
$this->_deputy = Deputy::instance();
$roles = Arr::extract(Kohana::$config->load('deputy.ajax_roles'), $this->_user_roles);
$this->_deputy->set_roles($roles);
$resource = array(
$this->request->directory(),
$this->request->controller(),
$this->request->action(),
);
$resource = implode('/', $resource);
if($this->_deputy->allowed($resource) == FALSE)
throw HTTP_Exception::factory(403, __('Действие запрещено'));
// $this->_check_rules_acceptance();
}
} // End Controller_Ajax_Template
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment