Admin Widget Controller
Class declared in MODPATH/gleez/classes/controller/admin/widget.php on line 10.
boolean $auto_renderAuto render template?
boolean $debugTurn debugging on?
Request $requestRequest that created the controller
Response $responseThe response that will be returned from controller
string $site_nameThe site name
string $templatePage template
string $titleThe page title
string $title_separatorThe delimiter page header and site name
$WIDGET_REGION_NONEDenotes that a widget is not enabled in any region and should not be shown.
integer -1
array $_accept_formatsList all supported formats for this controller (accept-type => path to format template)
boolean $_ajaxIs ajax request?
object $_authThe Auth Object
array $_benchmarkProfiling
Kohana_Config $_configThe configuration settings
$_current_userarray $_destiThe destination url
Format $_formatAn Format instance
boolean $_internalis internal request?
string $_page_classCurrent page class
string $_page_idCurrent page id, defaults to controller name
array $_regionsThe sidebar content
string $_response_formatHold the response format for this request
boolean $_sidebarsEnable sidebars for this request? For example: add or edit page don't requires sidebars
array $_tabsTabs navigation
object $_widgetsThe Widgets Object
array $redirectThe destination url
Adding Widgets
public function action_add()
{
$widget = ORM::factory('widget');
$widget_regions = array();
$theme_name = Kohana::$config->load('site.theme', Gleez::$theme);
$theme = Theme::get_info($theme_name);
if(isset($theme->regions) AND ! empty($theme->regions))
{
$widget_regions = $theme->regions;
}
// Add a last region for disabled blocks.
$widget_regions = Arr::merge($widget_regions, array(self::$WIDGET_REGION_NONE => self::$WIDGET_REGION_NONE));
if (isset($widget_regions[self::$WIDGET_REGION_NONE]))
{
$widget_regions[self::$WIDGET_REGION_NONE] = __('Disabled');
}
$all_roles = ORM::factory('role')->find_all()->as_array('id', 'name');
$this->title = __('Add widget');
$view = View::factory('admin/widget/form')
->set('widget', $widget)
->set('fields', '')
->set('roles', $all_roles)
->set('regions', $widget_regions);
if ($this->valid_post('widget'))
{
$widget->values($_POST);
try
{
$widget->name = 'static/'. Text::random('alnum', 6);
$widget->module = 'gleez';
$widget->save();
Message::success(__('Widget %name created successful!', array('%name' => $widget->title)));
Cache::instance('widgets')->delete_all();
// Redirect to listing
if ( ! $this->_internal)
{
$this->request->redirect(Route::get('admin/widget')->uri());
}
}
catch (ORM_Validation_Exception $e)
{
$view->errors = $e->errors('models');
}
}
$this->response->body($view);
}
Deleting Widgets
public function action_delete()
{
$id = (int) $this->request->param('id', 0);
$widget = ORM::factory('widget', $id);
if ( ! $widget->loaded())
{
Message::error(__('Widget doesn\'t exists!'));
Kohana::$log->add(LOG::ERROR, 'Attempt to access non-existent widget');
if ( ! $this->_internal)
{
$this->request->redirect(Route::get('admin/widget')->uri());
}
}
$split_name = explode('/', $widget->name);
$static = ($split_name AND $split_name[0] == 'static') ? TRUE : FALSE;
// we can only delete if its a custom widget
if( ! $static)
{
$this->request->redirect(Route::get('admin/widget')->uri());
}
$handler = Widget::factory($widget->name, $widget);
$this->title = __('Delete :title', array(':title' => $widget->title ));
$destination = ($this->request->query('destination') !== NULL) ?
array('destination' => $this->request->query('destination')) : array();
$view = View::factory('form/confirm')
->set('action', Route::get('admin/widget')
->uri( array('action' => 'delete', 'id' => $widget->id) ).URL::query($destination) )
->set('title', $widget->title);
// If deletion is not desired, redirect to post
if (isset($_POST['no']) AND $this->valid_post())
{
$this->request->redirect(Route::get('admin/widget')->uri(array('id' => $widget->id)));
}
// If deletion is confirmed
if (isset($_POST['yes']) AND $this->valid_post())
{
try
{
$title = $widget->title;
$widget->delete();
$handler->delete($_POST);
Message::success(__('Widget :title deleted successful!', array(':title' => $title)));
Cache::instance('widgets')->delete_all();
}
catch (Exception $e)
{
Kohana::$log->add(LOG::ERROR, 'Error occured deleting widget id: :id, :message',
array(
':id' => $widget->id,
':message' => $e->getMessage()
)
);
Message::error(__('An error occured deleting widget :title.', array(':title' => $widget->title)));
}
$redirect = empty($destination) ? Route::get('admin/widget')->uri() :
$this->request->query('destination');
if ( ! $this->_internal)
{
$this->request->redirect($redirect);
}
}
$this->response->body($view);
}
Editing Widgets
public function action_edit()
{
$id = (int) $this->request->param('id', 0);
$widget = ORM::factory('widget', $id);
if ( ! $widget->loaded())
{
Message::error(__('Widget doesn\'t exists!'));
Kohana::$log->add(LOG::ERROR, 'Attempt to access non-existent widget');
if ( ! $this->_internal)
{
$this->request->redirect(Route::get('admin/widget')->uri());
}
}
$widget_regions = array();
$theme_name = Kohana::$config->load('site.theme', Gleez::$theme);
$theme = Theme::get_info($theme_name);
$handler = Widget::factory($widget->name, $widget);
$fields = $handler->form();
if(isset($theme->regions) AND ! empty($theme->regions))
{
$widget_regions = $theme->regions;
}
// Add a last region for disabled blocks.
$widget_regions = Arr::merge($widget_regions, array(self::$WIDGET_REGION_NONE => self::$WIDGET_REGION_NONE));
if (isset($widget_regions[self::$WIDGET_REGION_NONE]))
{
$widget_regions[self::$WIDGET_REGION_NONE] = __('Disabled');
}
$all_roles = ORM::factory('role')
->find_all()
->as_array('id', 'name');
$this->title = __('Edit %widget widget', array('%widget' => $widget->title));
$view = View::factory('admin/widget/form')
->set('widget', $widget)
->set('fields', $fields)
->set('roles', $all_roles)
->set('regions', $widget_regions);
if ($this->valid_post('widget'))
{
$widget->values($_POST);
try
{
$widget->save();
if(isset($_POST['widget']))
{
unset($_POST['widget'], $_POST['_token'], $_POST['_action']);
}
$handler->save($_POST);
Message::success(__('Widget %name updated successful!', array('%name' => $widget->title)));
Cache::instance('widgets')->delete_all();
// Redirect to listing
if ( ! $this->_internal)
{
$this->request->redirect(Route::get('admin/widget')->uri());
}
}
catch (ORM_Validation_Exception $e)
{
$view->errors = $e->errors('models');
}
}
$this->response->body($view);
}
Listing Widgets
public function action_index()
{
$this->title = __('Widgets');
$view = View::factory('admin/widget/list')
->bind('widget_regions', $widget_regions)
->bind('weight_delta', $weight_delta)
->bind('widgets', $widget_listing);
$widget_regions = array();
$theme_name = Kohana::$config->load('site.theme', Gleez::$theme);
$theme = Theme::get_info($theme_name);
if(isset($theme->regions) AND ! empty($theme->regions))
{
$widget_regions = $theme->regions;
}
// Add a last region for disabled blocks.
$widget_regions = Arr::merge($widget_regions, array(self::$WIDGET_REGION_NONE => self::$WIDGET_REGION_NONE));
//$current_widgets = Kohana::list_files('classes/widget');
$widgets = ORM::factory('widget')
->order_by('region')
->order_by('weight')
->find_all();
// Weights range from -delta to +delta, so delta should be at least half
// of the amount of blocks present. This makes sure all blocks in the same
// region get an unique weight.
$weight_delta = round(count($widgets) / 2);
if (isset($widget_regions[self::$WIDGET_REGION_NONE]))
{
$widget_regions[self::$WIDGET_REGION_NONE] = __('Disabled');
}
foreach ($widget_regions as $key => $value)
{
// Initialize an empty array for the region.
$widget_listing[$key] = array();
}
// Initialize disabled widgets array.
$widget_listing[self::$WIDGET_REGION_NONE] = array();
// Add each block in the form to the appropriate place in the widget listing.
foreach ($widgets as $widget)
{
// Fetch the region for the current widget.
$region = (isset($widget->region) ? $widget->region : self::$WIDGET_REGION_NONE);
$widget_listing[$region][] = $widget;
}
Assets::js('widgets', 'media/js/widgets.js', array('jquery'), FALSE, array('weight' => 5));
foreach ($widget_regions as $region => $title)
{
Assets::tabledrag('widgets','match','sibling','widget-region-select','widget-region-'.$region,NULL,FALSE);
Assets::tabledrag('widgets', 'order', 'sibling', 'widget-weight', 'widget-weight-' . $region);
}
if ($this->valid_post('widget-list'))
{
foreach ($_POST['widgets'] as $widget)
{
$widget['status'] = (int) ($widget['region'] != self::$WIDGET_REGION_NONE);
$widget['region'] = $widget['status'] ? $widget['region'] : self::$WIDGET_REGION_NONE;
DB::update('widgets')
->set(array(
'status'=> $widget['status'],
'weight' => $widget['weight'],
'region' => $widget['region'])
)
->where('id','=',$widget['id'])
->execute();
}
Message::success(__('The Widget settings have been updated.'));
Cache::instance('widgets')->delete_all();
if ( ! $this->_internal)
{
$this->request->redirect(Route::get('admin/widget')->uri());
}
}
$this->response->body($view);
}
final public function action_skip()
{
// Do nothing
}
If debugging is enabled, append profiler stats for non-production environments.
voidpublic function after()
{
parent::after();
}
Loads the template View object, if it is direct request
voidpublic function before()
{
// Inform tht we're in admin section for themers/developers
Theme::$is_admin = TRUE;
if ( class_exists('ACL') )
{
ACL::required('administer site');
}
parent::before();
}
public function index()
{
$this->response->body( __('Welcome to admin') );
}
Is frontpage?
booleanpublic function is_frontpage()
{
$uri = preg_replace("#(/p\d+)+$#uD", '', rtrim($this->request->uri(), '/'));
return (empty($uri) OR ($uri === $this->_config->front_page));
}
Returns TRUE if the POST has a valid CSRF
Usage:
if ($this->valid_post('upload_photo')) { ... }
string|NULL
$submit
= NULL - Submit value [Optional]boolean - Return TRUE if it's valid $_POSTpublic function valid_post($submit = NULL)
{
if ( ! $this->request->is_post())
{
return FALSE;
}
if (Request::post_max_size_exceeded())
{
Message::error(__('Max file size of :max Bytes exceeded!',
array(':max' => Request::get_post_max_size())
));
return FALSE;
}
if ( ! is_null($submit) )
{
if ( ! isset($_POST[$submit]))
{
Message::error(__('This form has altered. Please try submitting it again.'));
return FALSE;
}
}
$_token = $this->request->post('_token');
$_action = $this->request->post('_action');
$has_csrf = ! empty($_token) AND ! empty($_action);
$valid_csrf = $has_csrf AND CSRF::valid($_token, $_action);
if ($has_csrf AND ! $valid_csrf)
{
// CSRF was submitted but expired
Message::error(__('This form has expired. Please try submitting it again.'));
return FALSE;
}
if (isset($_POST['_captcha']))
{
$captcha = $this->request->post('_captcha');
if (empty($captcha))
{
// CSRF was not entered
Message::error(__('The security code can\'t be empty.'));
return FALSE;
}
elseif ( ! Captcha::valid($captcha))
{
Message::error(__('The security answer was wrong.'));
return FALSE;
}
}
return $has_csrf AND $valid_csrf;
}
Creates a new controller instance. Each controller must be constructed with the request object that created it.
Request
$request
required - Request that created the controllerResponse
$response
required - The request's responsevoidpublic function __construct(Request $request, Response $response)
{
// Assign the request to the controller
$this->request = $request;
// Assign a response to the controller
$this->response = $response;
}
Add sidebar column class
This method is chainable.
protected function _set_column_class()
{
$sidebar_left = $this->template->sidebar_left;
$sidebar_right = $this->template->sidebar_right;
if ( ! empty($sidebar_left) AND ! empty($sidebar_right))
{
$this->template->column_class = 'main-both';
$this->template->main_column = 6;
}
else
{
if ( ! empty($sidebar_left))
{
$this->template->column_class = 'main-left';
$this->template->main_column = 9;
}
if ( ! empty($sidebar_right))
{
$this->template->column_class = 'main-right';
$this->template->main_column = 9;
}
}
return $this;
}
Set default CSS
protected function _set_default_css()
{
Assets::css('bootstrap', 'media/css/bootstrap.min.css', NULL, array('weight' => -15));
Assets::css('font-awesome', 'media/css/font-awesome.min.css', array('weight' => -13));
Assets::css('default', 'media/css/default.css', NULL, array('weight' => 0));
Assets::css('style', 'media/css/style.css', array('default'), array('weight' => 1));
}
Set default JavaScript
protected function _set_default_js()
{
Assets::js('bootstrap', 'media/js/bootstrap.min.js', array('jquery'), FALSE, array('weight' => 5));
// Google js only in production and not in admin section
if (Kohana::PRODUCTION === Kohana::$environment AND Theme::$is_admin === FALSE)
{
$ua = $this->_config->get('google_ua', NULL);
if ( ! is_null($ua))
{
Assets::google_stats($ua);
}
}
}
Set the default meta links
Used configuration settings.
protected function _set_default_meta_links()
{
$meta = $this->_config->get('meta', array());
$links = Arr::get($meta, 'links');
if ($links)
{
foreach ($links as $url => $attributes)
{
Meta::links($url, $attributes);
}
}
}
Set the default meta tags
Using configuration settings.
protected function _set_default_meta_tags()
{
$meta = $this->_config->get('meta', array());
$tags = Arr::get($meta, 'tags');
if ($tags)
{
foreach ($tags as $handle => $value)
{
$conditional = NULL;
if (is_array($value))
{
$conditional = Arr::get($value, 'conditional');
$value = Arr::get($value, 'value', '');
}
$attrs = array();
if (isset($conditional))
{
$attrs['conditional'] = $conditional;
}
Meta::tags($handle, $value, $attrs);
}
}
}
Set the default server headers
protected function _set_default_server_headers()
{
$headers = $this->_config->get('headers', array());
$headers['X-Gleez-Version'] = 'Gleez CMS v ' . Gleez::VERSION . ' (' . Gleez::CODENAME . ')';
$xmlrpc = $this->_config->get('xmlrpc', NULL);
/** @var $xmlrpc string|NULL */
if ( ! is_null($xmlrpc))
{
$headers['X-Pingback'] = URL::site($xmlrpc, TRUE);
}
$this->_set_server_headers($headers);
}
Set the page title
protected function _set_head_title()
{
if ($this->title)
{
$head_title = array(
strip_tags($this->title),
$this->template->site_name
);
}
else
{
$head_title = array(
$this->template->site_name
);
if ($this->template->site_slogan)
{
$head_title[] = $this->template->site_slogan;
}
}
$this->template->head_title = implode($this->title_separator, $head_title);
}
Set the profiler stats into template.
protected function _set_profiler_stats()
{
$queries = 0;
if (Kohana::$profiling)
{
// DB queries
foreach (Profiler::groups() as $group => $benchmarks)
{
if (strpos($group, 'database') === 0)
{
$queries += count($benchmarks);
}
}
}
// Get the total memory and execution time
$total = array(
'{memory_usage}' => number_format((memory_get_peak_usage() - KOHANA_START_MEMORY) / 1024 / 1024, 2) . 'MB',
'{gleez_version}' => Gleez::VERSION,
'{execution_time}' => number_format(microtime(TRUE) - KOHANA_START_TIME, 3) . ' seconds',
'{included_files}' => count(get_included_files()),
'{database_queries}' => $queries
);
// Insert the totals into the response
$this->template = strtr((string) $this->template, $total);
}
Set the server headers
array
$headers
required - An associative array of server headersprotected function _set_server_headers($headers)
{
if (is_array($headers) AND ! empty($headers))
{
$this->response->headers($headers);
}
}
Add sidebars
This method is chainable.
protected function _set_sidebars()
{
if ($this->_sidebars !== FALSE)
{
$this->template->sidebar_left = $this->_widgets->render('left');
$this->template->sidebar_right = $this->_widgets->render('right');
}
return $this;
}