/lib/AkActionController.php
PHP | 2846 lines | 1355 code | 290 blank | 1201 comment | 177 complexity | d9d05d2b37031605d95621cb9c8f3024 MD5 | raw file
Possible License(s): LGPL-2.1
- <?php
- /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
- // +----------------------------------------------------------------------+
- // | Akelos Framework - http://www.akelos.org |
- // +----------------------------------------------------------------------+
- // | Copyright (c) 2002-2006, Akelos Media, S.L. & Bermi Ferrer Martinez |
- // | Released under the GNU Lesser General Public License, see LICENSE.txt|
- // +----------------------------------------------------------------------+
- require_once(AK_LIB_DIR.DS.'AkObject.php');
- defined('AK_HIGH_LOAD_MODE') ? null : define('AK_HIGH_LOAD_MODE', false);
- defined('AK_APP_NAME') ? null : define('AK_APP_NAME', 'Application');
- /**
- * @package ActionController
- * @subpackage Base
- * @author Bermi Ferrer <bermi a.t akelos c.om>
- * @copyright Copyright (c) 2002-2006, Akelos Media, S.L. http://www.akelos.org
- * @license GNU Lesser General Public License <http://www.gnu.org/copyleft/lesser.html>
- */
- class AkActionController extends AkObject
- {
- var $_high_load_mode = AK_HIGH_LOAD_MODE;
- var $_enable_plugins = true;
- var $_auto_instantiate_models = true;
- var $validate_output = false;
- var $_ssl_requirement = false;
- var $_ssl_allowed_actions = array();
- var $ssl_for_all_actions = true;
- /**
- * Determines whether the view has access to controller internals $this->Request, $this->Response, $this->session, and $this->Template.
- * By default, it does.
- */
- var $_view_controller_internals = true;
- /**
- * Protected instance variable cache
- */
- var $_protected_variables_cache = array();
- /**
- * Prepends all the URL-generating helpers from AssetHelper.
- * This makes it possible to easily move javascripts, stylesheets,
- * and images to a dedicated asset server away from the main web server.
- * Example:
- * $this->_asset_host = 'http://assets.example.com';
- */
- var $asset_host = AK_ASSET_HOST;
- var $_Logger;
- /**
- * Determines which template class should be used by AkActionController.
- */
- var $TemplateClass;
- /**
- * Turn on +_ignore_missing_templates+ if you want to unit test actions without
- * making the associated templates.
- */
- var $_ignore_missing_templates;
- /**
- * Holds the Request object that's primarily used to get environment variables
- */
- var $Request;
- /**
- * Holds an array of all the GET, POST, and Url parameters passed to the action.
- * Accessed like <tt>$this->params['post_id'];</tt>
- * to get the post_id.
- */
- var $params = array();
- /**
- * Holds the Response object that's primarily used to set additional HTTP _headers
- * through access like <tt>$this->Response->_headers['Cache-Control'] = 'no-cache';</tt>.
- * Can also be used to access the final body HTML after a template
- * has been rendered through $this->Response->body -- useful for <tt>after_filter</tt>s
- * that wants to manipulate the output, such as a OutputCompressionFilter.
- */
- var $Response;
- /**
- * Holds an array of objects in the session. Accessed like <tt>$this->session['person']</tt>
- * to get the object tied to the 'person' key. The session will hold any type of object
- * as values, but the key should be a string.
- */
- var $session;
- /**
- * Holds an array of header names and values. Accessed like <tt>$this->_headers['Cache-Control']</tt>
- * to get the value of the Cache-Control directive. Values should always be specified as strings.
- */
- var $_headers = array();
- /**
- * Holds the array of variables that are passed on to the template class to be
- * made available to the view. This array is generated by taking a snapshot of
- * all the instance variables in the current scope just before a template is rendered.
- */
- var $_assigns = array();
- /**
- * Holds the name of the action this controller is processing.
- */
- var $_action_name;
- var $cookies;
- var $helpers = 'default';
- var $app_helpers;
- var $plugin_helpers = 'all';
- var $web_service;
- var $web_services = array();
- var $web_service_api;
- var $web_service_apis = array();
- var $module_name;
- var $_module_path;
- /**
- * Old fashioned way of dispatching requests. Please use AkDispatcher or roll your own.
- *
- * @deprecated
- */
- function handleRequest()
- {
- AK_LOG_EVENTS && empty($this->_Logger) ? ($this->_Logger =& Ak::getLogger()) : null;
- AK_LOG_EVENTS && !empty($this->_Logger) ? $this->_Logger->warning('Using deprecated request dispatcher AkActionController::handleRequest. Use to AkDispatcher + AkDispatcher::dispatch instead.') : null;
- require_once(AK_LIB_DIR.DS.'AkDispatcher.php');
- $Dispatcher =& new AkDispatcher();
- $Dispatcher->dispatch();
- }
- function process(&$Request, &$Response)
- {
- AK_LOG_EVENTS && empty($this->_Logger) ? ($this->_Logger =& Ak::getLogger()) : null;
- $this->Request =& $Request;
- $this->Response =& $Response;
- $this->params = $this->Request->getParams();
- $this->_action_name = $this->Request->getAction();
- $this->_ensureActionExists();
- Ak::t('Akelos'); // We need to get locales ready
- if($this->_high_load_mode !== true){
- if(!empty($this->_auto_instantiate_models)){
- $this->instantiateIncludedModelClasses();
- }
- if(!empty($this->_enable_plugins)){
- $this->loadPlugins();
- }
- if(!empty($this->helpers)){
- $this->instantiateHelpers();
- }
- }else{
- $this->_enableLayoutOnRender = false;
- }
- $this->_ensureProperProtocol();
- // After filters
- $this->afterFilter('_handleFlashAttribute');
- $this->_loadActionView();
- if(isset($this->api)){
- require_once(AK_LIB_DIR.DS.'AkActionWebService.php');
- $this->aroundFilter(new AkActionWebService($this));
- }
- $this->performActionWithFilters($this->_action_name);
- if (!$this->_hasPerformed()){
- $this->_enableLayoutOnRender ? $this->renderWithLayout() : $this->renderWithoutLayout();
- }
- if(!empty($this->validate_output)){
- $this->_validateGeneratedXhtml();
- }
- $this->Response->outputResults();
- }
- function _loadActionView()
- {
- empty($this->_assigns) ? ($this->_assigns = array()) : null;
- empty($this->_default_render_status_code) ? ($this->_default_render_status_code = 200) : null;
- $this->_enableLayoutOnRender = !isset($this->_enableLayoutOnRender) ? true : $this->_enableLayoutOnRender;
- $this->passed_args = !isset($this->Request->pass)? array() : $this->Request->pass;
- empty($this->cookies) && isset($_COOKIE) ? ($this->cookies =& $_COOKIE) : null;
- if(empty($this->Template)){
- require_once(AK_LIB_DIR.DS.'AkActionView.php');
- require_once(AK_LIB_DIR.DS.'AkActionView'.DS.'AkPhpTemplateHandler.php');
- $this->Template =& new AkActionView($this->_getTemplateBasePath(),
- $this->Request->getParameters(),$this->Request->getController());
- $this->Template->_controllerInstance =& $this;
- $this->Template->_registerTemplateHandler('tpl','AkPhpTemplateHandler');
- }
- }
- function loadPlugins()
- {
- Ak::loadPlugins();
- }
- /**
- * Creates an instance of each available helper and links it into into current controller.
- *
- * Per example, if a helper TextHelper is located into the file text_helper.php.
- * An instance is created on current controller
- * at $this->text_helper. This instance is also available on the view by calling $text_helper.
- *
- * Helpers can be found at lib/AkActionView/helpers (this might change in a future)
- */
- function instantiateHelpers()
- {
- $helpers = $this->getDefaultHelpers();
- $helpers = array_merge($helpers, $this->getApplicationHelpers());
- $helpers = array_merge($helpers, $this->getPluginHelpers());
- $helpers = array_merge($helpers, $this->getModuleHelper());
- $helpers = array_merge($helpers, $this->getCurrentControllerHelper());
- require_once(AK_LIB_DIR.DS.'AkActionView'.DS.'AkActionViewHelper.php');
- $available_helpers = array();
- foreach ($helpers as $file=>$helper){
- $helper_class_name = AkInflector::camelize(AkInflector::demodulize(strstr($helper, 'Helper') ? $helper : $helper.'Helper'));
- $full_path = preg_match('/[\\\\\/]+/',$file);
- $file_path = $full_path ? $file : AK_LIB_DIR.DS.'AkActionView'.DS.'helpers'.DS.$file;
- include_once($file_path);
- if(class_exists($helper_class_name)){
- $attribute_name = $full_path ? AkInflector::underscore($helper_class_name) : substr($file,0,-4);
- $available_helpers[] = $attribute_name;
- $this->$attribute_name =& new $helper_class_name(&$this);
- if(method_exists($this->$attribute_name,'setController')){
- $this->$attribute_name->setController(&$this);
- }
- if(method_exists($this->$attribute_name,'init')){
- $this->$attribute_name->init();
- }
- }
- }
- defined('AK_ACTION_CONTROLLER_AVAILABLE_HELPERS') ? null : define('AK_ACTION_CONTROLLER_AVAILABLE_HELPERS', join(',',$available_helpers));
- }
- function getCurrentControllerHelper()
- {
- $helper = $this->getControllerName();
- $helper = AkInflector::is_plural($helper)?AkInflector::singularize($helper):$helper;
- $helper_file_name = AK_HELPERS_DIR.DS.$this->_module_path.AkInflector::underscore($helper).'_helper.php';
- if(file_exists($helper_file_name)){
- return array($helper_file_name => $helper);
- }
- return array();
- }
- function getModuleHelper()
- {
- $this->getControllerName(); // module name is set when we first retrieve the controller name
- if(!empty($this->module_name)){
- $helper_file_name = AK_HELPERS_DIR.DS.AkInflector::underscore($this->module_name).'_helper.php';
- if(file_exists($helper_file_name)){
- return array($helper_file_name => $this->module_name);
- }
- }
- return array();
- }
- function getDefaultHelpers()
- {
- if($this->helpers == 'default'){
- $available_helpers = Ak::dir(AK_LIB_DIR.DS.'AkActionView'.DS.'helpers',array('dirs'=>false));
- $helper_names = array();
- foreach ($available_helpers as $available_helper){
- $helper_names[$available_helper] = AkInflector::classify(substr($available_helper,0,-10));
- }
- return $helper_names;
- }else{
- $this->helpers = Ak::toArray($this->helpers);
- }
- return $this->helpers;
- }
- function getApplicationHelpers()
- {
- $helper_names = array();
- if ($this->app_helpers == 'all'){
- $available_helpers = Ak::dir(AK_HELPERS_DIR,array('dirs'=>false));
- $helper_names = array();
- foreach ($available_helpers as $available_helper){
- $helper_names[AK_HELPERS_DIR.DS.$available_helper] = AkInflector::classify(substr($available_helper,0,-10));
- }
- } elseif (!empty($this->app_helpers)){
- foreach (Ak::toArray($this->app_helpers) as $helper_name){
- $helper_names[AK_HELPERS_DIR.DS.AkInflector::underscore($helper_name).'_helper.php'] = AkInflector::camelize($helper_name);
- }
- }
- return $helper_names;
- }
- function getPluginHelpers()
- {
- $helper_names = AkActionController::addPluginHelper(false); // Trick for getting helper names set by AkPlugin::addHelper
- if(empty($helper_names)){
- return array();
- }elseif ($this->plugin_helpers == 'all'){
- return $helper_names;
- }else {
- $selected_helper_names = array();
- foreach (Ak::toArray($this->plugin_helpers) as $helper_name){
- $helper_name = AkInflector::camelize($helper_name);
- if($path = array_shift(array_keys($helper_names, AkInflector::camelize($helper_name)))){
- $selected_helper_names[$path] = $helper_names[$path];
- }
- }
- return $selected_helper_names;
- }
- }
- /**
- * Used for adding helpers to the base class like those added by the plugins engine.
- *
- * @param string $helper_name Helper class name like CalendarHelper
- * @param array $options - path: Path to the helper class, defaults to AK_PLUGINS_DIR/helper_name/lib/helper_name.php
- */
- function addPluginHelper($helper_name, $options = array())
- {
- static $helpers = array();
- if($helper_name === false){
- return $helpers;
- }
- $underscored_helper_name = AkInflector::underscore($helper_name);
- $default_options = array(
- 'path' => AK_PLUGINS_DIR.DS.$underscored_helper_name.DS.'lib'.DS.$underscored_helper_name.'.php'
- );
- $options = array_merge($default_options, $options);
- $helpers[$options['path']] = $helper_name;
- }
- function _validateGeneratedXhtml()
- {
- require_once(AK_LIB_DIR.DS.'AkXhtmlValidator.php');
- $XhtmlValidator = new AkXhtmlValidator();
- if($XhtmlValidator->validate($this->Response->body) === false){
- $this->Response->sendHeaders();
- echo '<h1>'.Ak::t('Ooops! There are some errors on current XHTML page').'</h1>';
- echo '<small>'.Ak::t('In order to disable XHTML validation, set the <b>AK_ENABLE_STRICT_XHTML_VALIDATION</b> constant to false on your config/development.php file')."</small><hr />\n";
- $XhtmlValidator->showErrors();
- echo "<hr /><h2>".Ak::t('Showing XHTML code')."</h2><hr /><div style='border:5px solid red;margin:5px;padding:15px;'>".$this->Response->body."</pre>";
- die();
- }
- }
- /**
- * Methods for loading desired models into this controller
- */
- function setModel($model)
- {
- $this->instantiateIncludedModelClasses(array($model));
- }
- function setModels($models)
- {
- $this->instantiateIncludedModelClasses($models);
- }
- function instantiateIncludedModelClasses($models = array())
- {
- require_once(AK_LIB_DIR.DS.'AkActiveRecord.php');
- require_once(AK_APP_DIR.DS.'shared_model.php');
- empty($this->model) ? ($this->model = $this->params['controller']) : null;
- empty($this->models) ? ($this->models = array()) : null;
- $models = array_unique(array_merge(Ak::import($this->model), Ak::import($this->models), Ak::import($models), (empty($this->app_models)?array(): Ak::import($this->app_models))));
- foreach ($models as $model){
- $this->instantiateModelClass($model, (empty($this->finder_options[$model])?array():$this->finder_options[$model]));
- }
- }
- function instantiateModelClass($model_class_name, $finder_options = array())
- {
- $underscored_model_class_name = AkInflector::underscore($model_class_name);
- $controller_name = $this->getControllerName();
- $id = empty($this->params[$underscored_model_class_name]['id']) ?
- (empty($this->params['id']) ? false :
- (($model_class_name == $controller_name || $model_class_name == AkInflector::singularize($controller_name)) ? $this->params['id'] : false)) :
- $this->params[$underscored_model_class_name]['id'];
- if(class_exists($model_class_name)){
- $underscored_model_class_name = AkInflector::underscore($model_class_name);
- if(!isset($this->$model_class_name) || !isset($this->$underscored_model_class_name)){
- if($finder_options !== false && is_numeric($id)){
- $model =& new $model_class_name();
- if(empty($finder_options)){
- $model =& $model->find($id);
- }else{
- $model =& $model->find($id, $finder_options);
- }
- }else{
- $model =& new $model_class_name();
- }
- if(!isset($this->$model_class_name)){
- $this->$model_class_name =& $model;
- }
- if(!isset($this->$underscored_model_class_name)){
- $this->$underscored_model_class_name =& $model;
- }
- }
- }
- }
- /**
- Rendering content
- ====================================================================
- */
- /**
- * Renders the content that will be returned to the browser as the Response body.
- *
- * === Rendering an action
- *
- * Action rendering is the most common form and the type used automatically by
- * Action Controller when nothing else is specified. By default, actions are
- * rendered within the current layout (if one exists).
- *
- * * Renders the template for the action "goal" within the current controller
- *
- * $this->render(array('action'=>'goal'));
- *
- * * Renders the template for the action "short_goal" within the current controller,
- * but without the current active layout
- *
- * $this->render(array('action'=>'short_goal','layout'=>false));
- *
- * * Renders the template for the action "long_goal" within the current controller,
- * but with a custom layout
- *
- * $this->render(array('action'=>'long_goal','layout'=>'spectacular'));
- *
- * === Rendering partials
- *
- * Partial rendering is most commonly used together with Ajax calls that only update
- * one or a few elements on a page without reloading. Rendering of partials from
- * the controller makes it possible to use the same partial template in
- * both the full-page rendering (by calling it from within the template) and when
- * sub-page updates happen (from the controller action responding to Ajax calls).
- * By default, the current layout is not used.
- *
- * * Renders the partial located at app/views/controller/_win.tpl
- *
- * $this->render(array('partial'=>'win'));
- *
- * * Renders the partial with a status code of 500 (internal error)
- *
- * $this->render(array('partial'=>'broken','status'=>500));
- *
- * * Renders the same partial but also makes a local variable available to it
- *
- * $this->render(array('partial' => 'win', 'locals' => array('name'=>'david')));
- *
- * * Renders a collection of the same partial by making each element of $wins available through
- * the local variable "win" as it builds the complete Response
- *
- * $this->render(array('partial'=>'win','collection'=>$wins));
- *
- * * Renders the same collection of partials, but also renders the win_divider partial in between
- * each win partial.
- *
- * $this->render(array('partial'=>'win','collection'=>$wins,'spacer_template'=>'win_divider'));
- *
- * === Rendering a template
- *
- * Template rendering works just like action rendering except that it takes a
- * path relative to the template root.
- * The current layout is automatically applied.
- *
- * * Renders the template located in app/views/weblog/show.tpl
- * $this->render(array('template'=>'weblog/show'));
- *
- * === Rendering a file
- *
- * File rendering works just like action rendering except that it takes a
- * filesystem path. By default, the path is assumed to be absolute, and the
- * current layout is not applied.
- *
- * * Renders the template located at the absolute filesystem path
- * $this->render(array('file'=>'/path/to/some/template.tpl'));
- * $this->render(array('file'=>'c:/path/to/some/template.tpl'));
- *
- * * Renders a template within the current layout, and with a 404 status code
- * $this->render(array('file' => '/path/to/some/template.tpl', 'layout' => true, 'status' => 404));
- * $this->render(array('file' => 'c:/path/to/some/template.tpl', 'layout' => true, 'status' => 404));
- *
- * * Renders a template relative to the template root and chooses the proper file extension
- * $this->render(array('file' => 'some/template', 'use_full_path' => true));
- *
- *
- * === Rendering text
- *
- * Rendering of text is usually used for tests or for rendering prepared content,
- * such as a cache. By default, text
- * rendering is not done within the active layout.
- *
- * * Renders the clear text "hello world" with status code 200
- * $this->render(array('text' => 'hello world!'));
- *
- * * Renders the clear text "Explosion!" with status code 500
- * $this->render(array('text' => "Explosion!", 'status' => 500 ));
- *
- * * Renders the clear text "Hi there!" within the current active layout (if one exists)
- * $this->render(array('text' => "Explosion!", 'layout' => true));
- *
- * * Renders the clear text "Hi there!" within the layout
- * * placed in "app/views/layouts/special.tpl"
- * $this->render(array('text' => "Explosion!", 'layout => "special"));
- *
- *
- * === Rendering an inline template
- *
- * Rendering of an inline template works as a cross between text and action
- * rendering where the source for the template
- * is supplied inline, like text, but its evaled by PHP, like action. By default,
- * PHP is used for rendering and the current layout is not used.
- *
- * * Renders "hello, hello, hello, again"
- * $this->render(array('inline' => "<?php echo str_repeat('hello, ', 3).'again'?>" ));
- *
- * * Renders "hello david"
- * $this->render(array('inline' => "<?php echo 'hello ' . $name ?>", 'locals' => array('name' => 'david')));
- *
- *
- * === Rendering nothing
- *
- * Rendering nothing is often convenient in combination with Ajax calls that
- * perform their effect client-side or
- * when you just want to communicate a status code. Due to a bug in Safari, nothing
- * actually means a single space.
- *
- * * Renders an empty Response with status code 200
- * $this->render(array('nothing' => true));
- *
- * * Renders an empty Response with status code 401 (access denied)
- * $this->render(array('nothing' => true, 'status' => 401));
- */
- function render($options = null, $status = 200)
- {
- if(empty($options['partial']) && $this->_hasPerformed()){
- $this->_doubleRenderError(Ak::t("Can only render or redirect once per action"));
- return false;
- }
- $this->_flash_handled ? null : $this->_handleFlashAttribute();
- if(!is_array($options)){
- return $this->renderFile(empty($options) ? $this->getDefaultTemplateName() : $options, $status, true);
- }
- if(!empty($options['text'])){
- return $this->renderText($options['text'], @$options['status']);
- }else{
- if(!empty($options['file'])){
- return $this->renderFile($options['file'], @$options['status'], @$options['use_full_path'], @(array)$options['locals']);
- }elseif(!empty($options['template'])){
- return $this->renderFile($options['template'], @$options['status'], true);
- }elseif(!empty($options['inline'])){
- return $this->renderTemplate($options['inline'], @$options['status'], @$options['type'], @(array)$options['locals']);
- }elseif(!empty($options['action'])){
- return $this->renderAction($options['action'], @$options['status'], @$options['layout']);
- }elseif(!empty($options['partial'])){
- if($options['partial'] === true){
- $options['partial'] = !empty($options['template']) ? $options['template'] : $this->getDefaultTemplateName();
- }
- if(!empty($options['collection'])){
- return $this->renderPartialCollection($options['partial'], $options['collection'], @$options['spacer_template'], @$options['locals'], @$options['status']);
- }else{
- return $this->renderPartial($options['partial'], @$options['object'], @$options['locals'], @$options['status']);
- }
- }elseif(!empty($options['nothing'])){
- // Safari doesn't pass the _headers of the return if the Response is zero length
- return $this->renderText(' ', @$options['status']);
- }else{
- return $this->renderFile($this->getDefaultTemplateName(), @$options['status'], true);
- }
- return true;
- }
- }
- /**
- * Renders according to the same rules as <tt>render</tt>, but returns the result in a string instead
- * of sending it as the Response body to the browser.
- */
- function renderToString($options = null)
- {
- $result = $this->render($options);
- $this->eraseRenderResults();
- $this->variables_added = null;
- $this->Template->_assigns_added = null;
- return $result;
- }
- function renderAction($_action_name, $status = null, $with_layout = true)
- {
- $template = $this->getDefaultTemplateName($_action_name);
- if(!empty($with_layout) && !$this->_isTemplateExemptFromLayout($template)){
- return $this->renderWithLayout($template, $status, $with_layout);
- }else{
- return $this->renderWithoutLayout($template, $status);
- }
- }
- function renderFile($template_path, $status = null, $use_full_path = false, $locals = array())
- {
- $this->_addVariablesToAssigns();
- $locals = array_merge($locals,$this->_assigns);
- if($use_full_path){
- $this->_assertExistanceOfTemplateFile($template_path);
- }
- AK_LOG_EVENTS && !empty($this->_Logger) ? $this->_Logger->message("Rendering $this->full_template_path" . (!empty($status) ? " ($status)":'')) : null;
- return $this->renderText($this->Template->renderFile($template_path, $use_full_path, $locals), $status);
- }
- function renderTemplate($template, $status = null, $type = 'tpl', $local_assigns = array())
- {
- $this->_addVariablesToAssigns();
- $local_assigns = array_merge($local_assigns,$this->_assigns);
- return $this->renderText($this->Template->renderTemplate($type, $template, null, $local_assigns), $status);
- }
- function renderText($text = null, $status = null)
- {
- $this->performed_render = true;
- $this->Response->_headers['Status'] = !empty($status) ? $status : $this->_default_render_status_code;
- $this->Response->body = $text;
- return $text;
- }
- function renderNothing($status = null)
- {
- return $this->renderText(' ', $status);
- }
- function renderPartial($partial_path = null, $object = null, $local_assigns = null, $status = null)
- {
- $partial_path = empty($partial_path) ? $this->getDefaultTemplateName() : $partial_path;
- $this->variables_added = false;
- $this->performed_render = false;
- $this->_addVariablesToAssigns();
- $this->Template->controller =& $this;
- $this->$partial_path = $this->renderText($this->Template->renderPartial($partial_path, $object, array_merge($this->_assigns, (array)$local_assigns)), $status);
- return $this->$partial_path;
- }
- function renderPartialCollection($partial_name, $collection, $partial_spacer_template = null, $local_assigns = null, $status = null)
- {
- $this->_addVariablesToAssigns();
- $collection_name = AkInflector::pluralize($partial_name).'_collection';
- $result = $this->Template->renderPartialCollection($partial_name, $collection, $partial_spacer_template, $local_assigns);
- if(empty($this->$collection_name)){
- $this->$collection_name = $result;
- }
- $this->variables_added = false;
- $this->performed_render = false;
- return $result;
- }
- function renderWithLayout($template_name = null, $status = null, $layout = null)
- {
- $template_name = empty($template_name) ? $this->getDefaultTemplateName() : $template_name;
- return $this->renderWithALayout($template_name, $status, $layout);
- }
- function renderWithoutLayout($template_name = null, $status = null)
- {
- $template_name = empty($template_name) ? $this->getDefaultTemplateName() : $template_name;
- return $this->render($template_name, $status);
- }
- /**
- * Clears the rendered results, allowing for another render to be performed.
- */
- function eraseRenderResults()
- {
- $this->Response->body = '';
- $this->performed_render = false;
- $this->variables_added = false;
- }
- function _addVariablesToAssigns()
- {
- if(empty($this->variables_added)){
- $this->_addInstanceVariablesToAssigns();
- $this->variables_added = true;
- }
- }
- function _addInstanceVariablesToAssigns()
- {
- $this->_protected_variables_cache = array_merge($this->_protected_variables_cache, $this->_getProtectedInstanceVariables());
- foreach (array_diff(array_keys(get_object_vars($this)), $this->_protected_variables_cache) as $attribute){
- if($attribute[0] != '_'){
- $this->_assigns[$attribute] =& $this->$attribute;
- }
- }
- }
- function _getProtectedInstanceVariables()
- {
- return !empty($this->_view_controller_internals) ?
- array('_assigns', 'performed_redirect', 'performed_render','db') :
- array('_assigns', 'performed_redirect', 'performed_render', 'session', 'cookies',
- 'Template','db','helpers','models','layout','Response','Request',
- 'params','passed_args');
- }
- /**
- * Use this to translate strings in the scope of your controller
- *
- * @see Ak::t
- */
- function t($string, $array = null)
- {
- return Ak::t($string, $array, AkInflector::underscore($this->getControllerName()));
- }
- /**
- Redirects
- ====================================================================
- */
- /**
- * Redirects the browser to the target specified in +options+. This parameter can take one of three forms:
- *
- * * <tt>Array</tt>: The URL will be generated by calling $this->UrlFor with the +options+.
- * * <tt>String starting with protocol:// (like http://)</tt>: Is passed straight through
- * as the target for redirection.
- * * <tt>String not containing a protocol</tt>: The current protocol and host is prepended to the string.
- * * <tt>back</tt>: Back to the page that issued the Request-> Useful for forms that are
- * triggered from multiple places.
- * Short-hand for redirectTo(Request->env["HTTP_REFERER"])
- *
- * Examples:
- * redirectTo(array('action' => 'show', 'id' => 5));
- * redirectTo('http://www.akelos.com');
- * redirectTo('/images/screenshot.jpg');
- * redirectTo('back');
- *
- * The redirection happens as a "302 Moved" header.
- */
- function redirectTo($options = array(), $parameters_for_method_reference = null)
- {
- if(is_string($options)) {
- if(preg_match('/^\w+:\/\/.*/',$options)){
- if($this->_hasPerformed()){
- $this->_doubleRenderError();
- }
- AK_LOG_EVENTS && !empty($this->_Logger) ? $this->_Logger->message('Redirected to '.$options) : null;
- $this->_handleFlashAttribute();
- $this->Response->redirect($options);
- $this->Response->redirected_to = $options;
- $this->performed_redirect = true;
- }elseif ($options == 'back'){
- $this->redirectTo($this->Request->env['HTTP_REFERER']);
- }else{
- $this->redirectTo($this->Request->getProtocol(). $this->Request->getHostWithPort(). $options);
- }
- }else{
- if(empty($parameters_for_method_reference)){
- $this->redirectTo($this->UrlFor($options));
- $this->Response->redirected_to = $options;
- }else{
- $this->redirectTo($this->UrlFor($options, $parameters_for_method_reference));
- $this->Response->redirected_to = $options;
- $this->Response->redirected_to_method_params = $parameters_for_method_reference;
- }
- }
- }
- function redirectToAction($action, $options = array())
- {
- $this->redirectTo(array_merge(array('action'=>$action), $options));
- }
- /**
- * This methods are required for retrieving available controllers for URL Routing
- */
- function rewriteOptions($options)
- {
- $defaults = $this->defaultUrlOptions($options);
- if(!empty($this->module_name)){
- $defaults['module'] = $this->getModuleName();
- }
- if(!empty($options['controller']) && strstr($options['controller'], '/')){
- $defaults['module'] = substr($options['controller'], 0, strrpos($options['controller'], '/'));
- $options['controller'] = substr($options['controller'], strrpos($options['controller'], '/') + 1);
- }
- $options = !empty($defaults) ? array_merge($defaults, $options) : $options;
- $options['controller'] = empty($options['controller']) ? AkInflector::underscore($this->getControllerName()) : $options['controller'];
- return $options;
- }
- function getControllerName()
- {
- if(!isset($this->controller_name)){
- $current_class_name = str_replace('_', '::', get_class($this));
- if (!AK_PHP5){
- $current_class_name = $this->__getControllerName_PHP4_fix($current_class_name);
- }
- $controller_name = substr($current_class_name,0,-10);
- $this->controller_name = $this->_removeModuleNameFromControllerName($controller_name);
- }
- return $this->controller_name;
- }
- function __getControllerName_PHP4_fix($class_name)
- {
- $included_controllers = $this->_getIncludedControllerNames();
- $lowercase_included_controllers = array_map('strtolower', $included_controllers);
- $key = array_search(strtolower($class_name), $lowercase_included_controllers, true);
- return $included_controllers[$key];
- }
- function getModuleName()
- {
- return $this->module_name;
- }
- function setModuleName($module_name)
- {
- return $this->module_name = $module_name;
- }
- /**
- * Removes the modules name from the controller if exists and sets it.
- *
- * @return $controller_name
- */
- function _removeModuleNameFromControllerName($controller_name)
- {
- if(strstr($controller_name, '::')){
- $module_parts = explode ('::',$controller_name);
- $controller_name = array_pop($module_parts);
- $this->setModuleName(join('/', array_map(array('AkInflector','underscore'), $module_parts)));
- }
- return $controller_name;
- }
- function _getTemplateBasePath()
- {
- return AK_APP_DIR.DS.'views'.DS.(empty($this->_module_path)?'':$this->_module_path).$this->Request->getController();
- }
- function _getIncludedControllerNames()
- {
- $controllers = array();
- foreach (get_included_files() as $file_name){
- if(strstr($file_name,AK_CONTROLLERS_DIR)){
- $controllers[] = AkInflector::classify(str_replace(array(AK_CONTROLLERS_DIR.DS,'.php', DS, '//'),array('','','/', '/'),$file_name));
- }
- }
- return $controllers;
- }
- /**
- URL generation/rewriting
- ====================================================================
- */
- /**
- * Overwrite to implement a number of default options that all urlFor-based methods will use.
- * The default options should come in
- * the form of a an array, just like the one you would use for $this->UrlFor directly. Example:
- *
- * function defaultUrlOptions($options)
- * {
- * return array('project' => ($this->Project->isActive() ? $this->Project->url_name : 'unknown'));
- * }
- *
- * As you can infer from the example, this is mostly useful for situations where you want to
- * centralize dynamic decisions about the urls as they stem from the business domain.
- * Please note that any individual $this->UrlFor call can always override the defaults set
- * by this method.
- */
- function defaultUrlOptions($options)
- {
- }
- /**
- * Returns a URL that has been rewritten according to the options array and the defined Routes.
- * (For doing a complete redirect, use redirectTo).
- *
- * <tt>$this->UrlFor</tt> is used to:
- *
- * All keys given to $this->UrlFor are forwarded to the Route module, save for the following:
- * * <tt>anchor</tt> -- specifies the anchor name to be appended to the path. For example,
- * <tt>$this->UrlFor(array('controller' => 'posts', 'action' => 'show', 'id' => 10, 'anchor' => 'comments'</tt>
- * will produce "/posts/show/10#comments".
- * * <tt>only_path</tt> -- if true, returns the absolute URL (omitting the protocol, host name, and port)
- * * <tt>trailing_slash</tt> -- if true, adds a trailing slash, as in "/archive/2005/". Note that this
- * is currently not recommended since it breaks caching.
- * * <tt>host</tt> -- overrides the default (current) host if provided
- * * <tt>protocol</tt> -- overrides the default (current) protocol if provided
- *
- * The URL is generated from the remaining keys in the array. A URL contains two key parts: the <base> and a query string.
- * Routes composes a query string as the key/value pairs not included in the <base>.
- *
- * The default Routes setup supports a typical Akelos Framework path of "controller/action/id"
- * where action and id are optional, with
- * action defaulting to 'index' when not given. Here are some typical $this->UrlFor statements
- * and their corresponding URLs:
- *
- * $this->UrlFor(array('controller'=>'posts','action'=>'recent')); // 'proto://host.com/posts/recent'
- * $this->UrlFor(array('controller'=>'posts','action'=>'index')); // 'proto://host.com/posts'
- * $this->UrlFor(array('controller'=>'posts','action'=>'show','id'=>10)); // 'proto://host.com/posts/show/10'
- *
- * When generating a new URL, missing values may be filled in from the current
- * Request's parameters. For example,
- * <tt>$this->UrlFor(array('action'=>'some_action'));</tt> will retain the current controller,
- * as expected. This behavior extends to other parameters, including <tt>controller</tt>,
- * <tt>id</tt>, and any other parameters that are placed into a Route's path.
- *
- * The URL helpers such as <tt>$this->UrlFor</tt> have a limited form of memory:
- * when generating a new URL, they can look for missing values in the current Request's parameters.
- * Routes attempts to guess when a value should and should not be
- * taken from the defaults. There are a few simple rules on how this is performed:
- *
- * * If the controller name begins with a slash, no defaults are used: <tt>$this->UrlFor(array('controller'=>'/home'));</tt>
- * * If the controller changes, the action will default to index unless provided
- *
- * The final rule is applied while the URL is being generated and is best illustrated by an example. Let us consider the
- * route given by <tt>map->connect('people/:last/:first/:action', array('action' => 'bio', 'controller' => 'people'))</tt>.
- *
- * Suppose that the current URL is "people/hh/david/contacts". Let's consider a few
- * different cases of URLs which are generated from this page.
- *
- * * <tt>$this->UrlFor(array('action'=>'bio'));</tt> -- During the generation of this URL,
- * default values will be used for the first and
- * last components, and the action shall change. The generated URL will be, "people/hh/david/bio".
- * * <tt>$this->UrlFor(array('first'=>'davids-little-brother'));</tt> This
- * generates the URL 'people/hh/davids-little-brother' -- note
- * that this URL leaves out the assumed action of 'bio'.
- *
- * However, you might ask why the action from the current Request, 'contacts', isn't
- * carried over into the new URL. The answer has to do with the order in which
- * the parameters appear in the generated path. In a nutshell, since the
- * value that appears in the slot for <tt>first</tt> is not equal to default value
- * for <tt>first</tt> we stop using defaults. On it's own, this rule can account
- * for much of the typical Akelos Framework URL behavior.
- *
- * Although a convienence, defaults can occasionaly get in your way. In some cases
- * a default persists longer than desired.
- * The default may be cleared by adding <tt>'name' => null</tt> to <tt>$this->UrlFor</tt>'s options.
- * This is often required when writing form helpers, since the defaults in play
- * may vary greatly depending upon where the helper is used from. The following line
- * will redirect to PostController's default action, regardless of the page it is
- * displayed on:
- *
- * $this->UrlFor(array('controller' => 'posts', 'action' => null));
- *
- * If you explicitly want to create a URL that's almost the same as the current URL, you can do so using the
- * overwrite_params options. Say for your posts you have different views for showing and printing them.
- * Then, in the show view, you get the URL for the print view like this
- *
- * $this->UrlFor(array('overwrite_params' => array('action' => 'print')));
- *
- * This takes the current URL as is and only exchanges the action. In contrast,
- * <tt>$this->UrlFor(array('action'=>'print'));</tt>
- * would have slashed-off the path components after the changed action.
- */
- function urlFor($options = array(), $parameters_for_method_reference = null)
- {
- return $this->rewrite($this->rewriteOptions($options));
- }
- function addToUrl($options = array(), $options_to_exclude = array())
- {
- $options_to_exclude = array_merge(array('ak','lang',AK_SESSION_NAME,'AK_SESSID','PHPSESSID'), $options_to_exclude);
- $options = array_merge(array_merge(array('action'=>$this->Request->getAction()),$this->params),$options);
- foreach ($options_to_exclude as $option_to_exclude){
- unset($options[$option_to_exclude]);
- }
- return $this->urlFor($options);
- }
- function getActionName()
- {
- return $this->Request->getAction();
- }
- function _doubleRenderError($message = null)
- {
- trigger_error(!empty($message) ? $message : Ak::t("Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and only once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like \"redirectTo(...); return;\". Finally, note that to cause a before filter to halt execution of the rest of the filter chain, the filter must return false, explicitly, so \"render(...); return; false\"."),E_USER_ERROR);
- }
- function _hasPerformed()
- {
- return !empty($this->performed_render) || !empty($this->performed_redirect);
- }
- function _getRequestOrigin()
- {
- return $this->Request->remote_ip.' at '.Ak::getDate();
- }
- function _getCompleteRequestUri()
- {
- return $this->Request->protocol . $this->Request->host . $this->Request->request_uri;
- }
- function _closeSession()
- {
- !empty($this->session) ? session_write_close() : null;
- }
- function _hasTemplate($template_name = null)
- {
- return file_exists(empty($template_name) ? $this->getDefaultTemplateName() : $template_name);
- }
- function _templateIsPublic($template_name = null)
- {
- $template_name = empty($template_name) ? $this->getDefaultTemplateName() : $template_name;
- return $this->Template->fileIsPublic($template_name);
- }
- function _isTemplateExemptFromLayout($template_name = null)
- {
- $template_name = empty($template_name) ? $this->getDefaultTemplateName() : $template_name;
- return $this->Template->_javascriptTemplateExists($template_name);
- }
- function _assertExistanceOfTemplateFile($template_name)
- {
- $extension = $this->Template->delegateTemplateExists($template_name);
- $this->full_template_path = $this->Template->getFullTemplatePath($template_name, $extension ? $extension : 'tpl');
- if(!$this->_hasTemplate($this->full_template_path)){
- if(!empty($this->_ignore_missing_templates) && $this->_ignore_missing_templates === true){
- return;
- }
- $template_type = strstr($template_name,'layouts') ? 'layout' : 'template';
- trigger_error(Ak::t('Missing %template_type %full_template_path',array('%template_type'=>$template_type, '%full_template_path'=>$this->full_template_path)), E_USER_WARNING);
- }
- }
- function getDefaultTemplateName($default_action_name = null)
- {
- return empty($default_action_name) ? (empty($this->_default_template_name) ? $this->_action_name : $this->_default_template_name) : $default_action_name;
- }
- function setDefaultTemplateName($template_name)
- {
- $this->_default_template_name = $template_name;
- }
- function rewrite($options = array())
- {
- return $this->_rewriteUrl($this->_rewritePath($options), $options);
- }
- function toString()
- {
- return $this->Request->getProtocol().$this->Request->getHostWithPort().
- $this->Request->getPath().@$this->parameters['controller'].
- @$this->parameters['action'].@$this->parameters['inspect'];
- }
- /**
- * Given a path and options, returns a rewritten URL string
- */
- function _rewriteUrl($path, $options)
- {
- $rewritten_url = '';
- if(empty($options['only_path'])){
- $rewritten_url .= !empty($options['protocol']) ? $options['protocol'] : $this->Request->getProtocol();
- $rewritten_url .= empty($rewritten_url) || strpos($rewritten_url,'://') ? '' : '://';
- $rewritten_url .= $this->_rewriteAuthentication($options);
- $rewritten_url .= !empty($options['host']) ? $options['host'] : $this->Request->getHostWithPort();
- $options = Ak::delete($options, array('user','password','host','protocol'));
- }
- $rewritten_url .= empty($options['skip_relative_url_root']) ? $this->Request->getRelativeUrlRoot() : '';
- if(empty($options['skip_url_locale'])){
- $locale = $this->Request->getLocaleFromUrl();
- if(empty($options['lang'])){
- $rewritten_url .= (empty($locale) ? '' : '/').$locale;
- }
- }
- $rewritten_url .= (substr($rewritten_url,-1) == '/' ? '' : (AK_URL_REWRITE_ENABLED ? '' : (!empty($path[0]) && $path[0] != '/' ? '/' : '')));
- $rewritten_url .= $path;
- $rewritten_url .= empty($options['trailing_slash']) ? '' : '/';
- $rewritten_url .= empty($options['anchor']) ? '' : '#'.$options['anchor'];
- return $rewritten_url;
- }
- function _rewriteAuthentication($options)
- {
- if(!isset($options['user']) && isset($options['password'])){
- return urlencode($options['user']).':'.urlencode($options['password']).'@';
- }else{
- return '';
- }
- }
- function _rewritePath($options)
- {
- if(!empty($options['params'])){
- foreach ($options['params'] as $k=>$v){
- $options[$k] = $v;
- }
- unset($options['params']);
- }
- if(!empty($options['overwrite_params'])){
- foreach ($options['overwrite_params'] as $k=>$v){
- $options[$k] = $v;
- }
- unset($options['overwrite_params']);
- }
- foreach (array('anchor', 'params', 'only_path', 'host', 'protocol', 'trailing_slash', 'skip_relative_url_root') as $k){
- unset($options[$k]);
- }
- $path = Ak::toUrl($options);
- return $path;
- }
- /**
- * Returns a query string with escaped keys and values from the passed array. If the passed
- * array contains an 'id' it'll
- * be added as a path element instead of a regular parameter pair.
- */
- function buildQueryString($array, $only_keys = null)
- {
- $array = !empty($only_keys) ? array_keys($array) : $array;
- return Ak::toUrl($array);
- }
- /**
- Layouts
- ====================================================================
- *
- * Layouts reverse the common pattern of including shared headers and footers in many templates
- * to isolate changes in repeated setups. The inclusion pattern has pages that look like this:
- *
- * <?php echo $controller->render('shared/header') ?>
- * Hello World
- * <?php echo $controller->render('shared/footer') ?>
- *
- * This approach is a decent way of keeping common structures isolated from the
- * changing content, but it's verbose and if( you ever want to change the structure
- * of these two includes, you'll have to change all the templates.
- *
- * With layouts, you can flip it around and have the common structure know where
- * to insert changing content. This means that the header and footer are only
- * mentioned in one place, like this:
- *
- * <!-- The header part of this layout -->
- * <?php echo $content_for_layout ?>
- * <!-- The footer part of this layout -->
- *
- * And then you have content pages that look like this:
- *
- * hello world
- *
- * Not a word about common structures. At rendering time, the content page is
- * computed and then inserted in the layout,
- * like this:
- *
- * <!-- The header part of this layout -->
- * hello world
- * <!-- The footer part of this layout -->
- *
- * == Accessing shared variables
- *
- * Layouts have access to variables specified in the content pages and vice versa.
- * This allows you to have layouts with references that won't materialize before
- * rendering time:
- *
- * <h1><?php echo $page_title ?></h1>
- * <?php echo $content_for_layout ?>
- *
- * ...and content pages that fulfill these references _at_ rendering time:
- *
- * <?php $page_title = 'Welcome'; ?>
- * Off-world colonies offers you a chance to start a new life
- *
- * The result after rendering is:
- *
- * <h1>Welcome</h1>
- * Off-world colonies offers you a chance to start a new life
- *
- * == Automatic layout assignment
- *
- * If there is a template in <tt>app/views/layouts/</tt> with the same name as
- * the current controller then it will be automatically
- * set as that controller's layout unless explicitly told otherwise. Say you have
- * a WeblogController, for example. If a template named <tt>app/views/layouts/weblog.tpl</tt>
- * exists then it will be automatically set as the layout for your WeblogController.
- * You can create a layout with the name <tt>application.tpl</tt>
- * and this will be set as the default controller if there is no layout with
- * the same name as the current controller and there is no layout explicitly
- * assigned on the +layout+ attribute. Setting a layout explicitly will always
- * override the automatic behaviour
- * for the controller where the layout is set. Explicitly setting the layout
- * in a parent class, though, will not override the
- * child class's layout assignement if the child class has a layout with the same name.
- *
- * == Inheritance for layouts
- *
- * Layouts are shared downwards in the inheritance hierarchy, but not upwards. Examples:
- *
- * class BankController extends AkActionController
- * {
- * var $layout = 'bank_standard';
- * }
- *
- * class InformationController extends BankController
- * {
- * }
- *
- * class VaultController extends BankController
- * {
- * var $layout = 'access_level_layout';
- * }
- *
- * class EmployeeController extends BankController
- * {
- * var $layout = null;
- * }
- *
- * The InformationController uses 'bank_standard' inherited from the BankController, the VaultController
- * and picks the layout 'access_level_layout', and the EmployeeController doesn't want to use a layout at all.
- *
- * == Types of layouts
- *
- * Layouts are basically just regular templates, but the name of this template needs not be specified statically. Sometimes
- * you want to alternate layouts depending on runtime information, such as whether someone is logged in or not. This can
- * be done either by an inline method.
- *
- * The method reference is the preferred approach to variable layouts and is used like this:
- *
- * class WeblogController extends AkActionController
- * {
- * function __construct()
- * {
- * $this->setLayout(array(&$this, '_writersAndReaders'));
- * }
- *
- * function index()
- * {
- * // fetching posts
- * }
- *
- * function _writersAndReaders()
- * {
- * return is_logged_in() ? 'writer_layout' : 'reader_layout';
- * }
- * }
- *
- * Now when a new request for the index action is processed, the layout will vary depending on whether the person accessing
- * is logged in or not.
- *
- * The most common way of specifying a layout is still just as a plain template name:
- *
- * class WeblogController extends AkActionController
- * {
- * var $layout = 'weblog_standard';
- * }
- *
- * If no directory is specified for the template name, the template will by default by looked for in +app/views/layouts/+.
- *
- * == Conditional layouts
- *
- * If you have a layout that by default is applied to all the actions of a controller, you still have the option of rendering
- * a given action or set of actions without a layout, or restricting a layout to only a single action or a set of actions. The
- * <tt>only</tt> and <tt>except</tt> options can be passed to the layout call. For example:
- *
- * class WeblogController extends AkActionController
- * {
- * function __construct()
- * {
- * $this->setLayout('weblog_standard', array('except' => 'rss'));
- * }
- *
- * // ...
- *
- * }
- *
- * This will assign 'weblog_standard' as the WeblogController's layout except for the +rss+ action, which will not wrap a layout
- * around the rendered view.
- *
- * Both the <tt>only</tt> and <tt>except</tt> condition can accept an arbitrary number of method names, so
- * <tt>'except' => array('rss', 'text_only')</tt> is valid, as is <tt>'except' => 'rss'</tt>.
- *
- * == Using a different layout in the action render call
- *
- * If most of your actions use the same layout, it makes perfect sense to define a controller-wide layout as described above.
- * Some times you'll have exceptions, though, where one action wants to use a different layout than the rest of the controller.
- * This is possible using the <tt>render</tt> method. It's just a bit more manual work as you'll have to supply fully
- * qualified template and layout names as this example shows:
- *
- * class WeblogController extends AkActionController
- * {
- * function help()
- * {
- * $this->render(array('action'=>'help/index','layout'=>'help'));
- * }
- * }
- */
- /**
- * If a layout is specified, all actions rendered through render and render_action will have their result assigned
- * to <tt>$this->content_for_layout</tt>, which can then be used by the layout to insert their contents with
- * <tt><?php echo $$this->content_for_layout ?></tt>. This layout can itself depend on instance variables assigned during action
- * performance and have access to them as any normal template would.
- */
- function setLayout($template_name, $conditions = array())
- {
- $this->_addLayoutConditions($conditions);
- $this->layout = $template_name;
- }
- function getLayoutConditions()
- {
- return empty($this->_layout_conditions) ? array() : $this->_layout_conditions;
- }
- function _addLayoutConditions($conditions)
- {
- $this->_layout_conditions = $conditions;
- }
- /**
- * Returns the name of the active layout. If the layout was specified as a method reference, this method
- * is called and the return value is used. Likewise if( the layout was specified as an inline method (through a method
- * object). If the layout was defined without a directory, layouts is assumed. So <tt>setLayout('weblog/standard')</tt> will return
- * weblog/standard, but <tt>setLayout('standard')</tt> will return layouts/standard.
- */
- function getActiveLayout($passed_layout = null)
- {
- if(empty($passed_layout)){
- $layout = !isset($this->layout) ? AkInflector::underscore($this->getControllerName()) : $this->layout;
- }else{
- $layout =& $passed_layout;
- }
- if(is_array($layout) && is_object($layout[0]) && method_exists($layout[0], $layout[1])){
- $this->active_layout = $layout[0]->{$layout[1]}();
- }elseif(method_exists($this,$layout) && strtolower(get_class($this)) !== strtolower($layout)){
- $this->active_layout = $this->$layout();
- }else{
- $this->active_layout = $layout;
- }
- if(!empty($this->active_layout)){
- return strstr($this->active_layout,DS) ? $this->active_layout : 'layouts'.DS.$this->active_layout;
- }
- }
- function renderWithALayout($options = null, $status = null, $layout = null)
- {
- $template_with_options = !empty($options) && is_array($options);
- if($this->_canApplyLayout($template_with_options, $options) && ($layout = $this->_pickLayout($template_with_options, $options, $layout))){
- $options = $template_with_options? array_merge((array)$options,array('layout'=>false)) : $options;
- $this->content_for_layout = $this->render($options, $status);
- if($template_with_options){
- $status = empty($options['status']) ? $status : $options['status'];
- }
- $this->eraseRenderResults();
- $this->_addVariablesToAssigns();
- return $this->renderText($this->Template->renderFile($layout, true, &$this->_assigns), $status);
- }else{
- return $this->render($options, $status, &$this->_assigns);
- }
- }
- function _canApplyLayout($template_with_options, $options)
- {
- return !empty($template_with_options) ? $this->_isCandidateForLayout($options) : !$this->_isTemplateExemptFromLayout();
- }
- function _isCandidateForLayout($options)
- {
- return !empty($options['layout']) ||
- (empty($options['text']) && empty($options['file']) && empty($options['inline']) && empty($options['partial']) && empty($options['nothing'])) &&
- !$this->_isTemplateExemptFromLayout($this->_getDefaultTemplateName(empty($options['action']) ? $options['template'] : $options['action']));
- }
- function _pickLayout($template_with_options, $options, $layout = null)
- {
- if(!empty($template_with_options)){
- $layout = empty($options['layout']) ? ($this->_doesActionHasLayout() ? $this->getActiveLayout(): false) : $this->getActiveLayout($options['layout']);
- }elseif(empty($layout) || $layout === true){
- $layout = $this->_doesActionHasLayout() ? $this->getActiveLayout() : false;
- }
- if(!empty($layout)){
- $layout = strstr($layout,'/') || strstr($layout,DS) ? $layout : 'layouts'.DS.$layout;
- $layout = preg_replace('/\.tpl$/', '', $layout);
- $layout = substr($layout,0,7) === 'layouts' ?
- (empty($this->_module_path) || !empty($this->layout) ? AK_VIEWS_DIR.DS.$layout.'.tpl' : AK_VIEWS_DIR.DS.'layouts'.DS.trim($this->_module_path, DS).'.tpl') :
- $layout.'.tpl';
- if (file_exists($layout)) {
- return $layout;
- }
- $layout = null;
- }
- if(empty($layout) && $layout !== false && defined('AK_DEFAULT_LAYOUT')){
- $layout = AK_VIEWS_DIR.DS.'layouts'.DS.AK_DEFAULT_LAYOUT.'.tpl';
- }
- return file_exists($layout) ? $layout : false;
- }
- function _doesActionHasLayout()
- {
- $conditions = $this->getLayoutConditions();
- $action_name = $this->Request->getAction();
- if(!empty($conditions['only']) && ((is_array($conditions['only']) && in_array($action_name,$conditions['only'])) ||
- (is_string($conditions['only']) && $action_name == $conditions['only']))){
- return true;
- }elseif (!empty($conditions['only'])){
- return false;
- }
- if(!empty($conditions['except']) && ((is_array($conditions['except']) && in_array($action_name,$conditions['except'])) ||
- (is_string($conditions['except']) && $action_name == $conditions['except']))){
- return false;
- }
- return true;
- }
- /**
- Filters
- ====================================================================
- *
- * Filters enable controllers to run shared pre and post processing code for its actions. These filters can be used to do
- * authentication, caching, or auditing before the intended action is performed. Or to do localization or output
- * compression after the action has been performed.
- *
- * Filters have access to the request, response, and all the instance variables set by other filters in the chain
- * or by the action (in the case of after filters). Additionally, it's possible for a pre-processing <tt>beforeFilter</tt>
- * to halt the processing before the intended action is processed by returning false or performing a redirect or render.
- * This is especially useful for filters like authentication where you're not interested in allowing the action to be
- * performed if the proper credentials are not in order.
- *
- * == Filter inheritance
- *
- * Controller inheritance hierarchies share filters downwards, but subclasses can also add new filters without
- * affecting the superclass. For example:
- *
- * class BankController extends AkActionController
- * {
- * function __construct()
- * {
- * $this->beforeFilter('_audit');
- * }
- *
- * function _audit(&$controller)
- * {
- * // record the action and parameters in an audit log
- * }
- * }
- *
- * class VaultController extends BankController
- * {
- * function __construct()
- * {
- * $this->beforeFilter('_verifyCredentials');
- * }
- *
- * function _verifyCredentials(&$controller)
- * {
- * // make sure the user is allowed into the vault
- * }
- * }
- *
- * Now any actions performed on the BankController will have the audit method called before. On the VaultController,
- * first the audit method is called, then the _verifyCredentials method. If the _audit method returns false, then
- * _verifyCredentials and the intended action are never called.
- *
- * == Filter types
- *
- * A filter can take one of three forms: method reference, external class, or inline method. The first
- * is the most common and works by referencing a method somewhere in the inheritance hierarchy of
- * the controller by use of a method name. In the bank example above, both BankController and VaultController use this form.
- *
- * Using an external class makes for more easily reused generic filters, such as output compression. External filter classes
- * are implemented by having a static +filter+ method on any class and then passing this class to the filter method. Example:
- *
- * class OutputCompressionFilter
- * {
- * function filter(&$controller)
- * {
- * $controller->response->body = compress($controller->response->body);
- * }
- * }
- *
- * class NewspaperController extends AkActionController
- * {
- * function __construct()
- * {
- * $this->afterFilter(new OutputCompressionFilter());
- * }
- * }
- *
- * The filter method is passed the controller instance and is hence granted access to all aspects of the controller and can
- * manipulate them as it sees fit.
- *
- *
- * == Filter chain ordering
- *
- * Using <tt>beforeFilter</tt> and <tt>afterFilter</tt> appends the specified filters to the existing chain. That's usually
- * just fine, but some times you care more about the order in which the filters are executed. When that's the case, you
- * can use <tt>prependBeforeFilter</tt> and <tt>prependAfterFilter</tt>. Filters added by these methods will be put at the
- * beginning of their respective chain and executed before the rest. For example:
- *
- * class ShoppingController extends AkActionController
- * {
- * function __construct()
- * {
- * $this->beforeFilter('verifyOpenShop');
- * }
- * }
- *
- *
- * class CheckoutController extends AkActionController
- * {
- * function __construct()
- * {
- * $this->prependBeforeFilter('ensureItemsInCart', 'ensureItemsInStock');
- * }
- * }
- *
- * The filter chain for the CheckoutController is now <tt>ensureItemsInCart, ensureItemsInStock,</tt>
- * <tt>verifyOpenShop</tt>. So if either of the ensure filters return false, we'll never get around to see if the shop
- * is open or not.
- *
- * You may pass multiple filter arguments of each type.
- *
- * == Around filters
- *
- * In addition to the individual before and after filters, it's also possible to specify that a single object should handle
- * both the before and after call. That's especially useful when you need to keep state active between the before and after,
- * such as the example of a benchmark filter below:
- *
- * class WeblogController extends AkActionController
- * {
- * function __construct()
- * {
- * $this->aroundFilter(new BenchmarkingFilter());
- * }
- *
- * // Before this action is performed, BenchmarkingFilter->before($controller) is executed
- * function index()
- * {
- * }
- * // After this action has been performed, BenchmarkingFilter->after($controller) is executed
- * }
- *
- * class BenchmarkingFilter
- * {
- * function before(&$controller)
- * {
- * start_timer();
- * }
- *
- * function after(&$controller)
- * {
- * stop_timer();
- * report_result();
- * }
- * }
- *
- * == Filter chain skipping
- *
- * Some times its convenient to specify a filter chain in a superclass that'll hold true for the majority of the
- * subclasses, but not necessarily all of them. The subclasses that behave in exception can then specify which filters
- * they would like to be relieved of. Examples
- *
- * class ApplicationController extends AkActionController
- * {
- * function __construct()
- * {
- * $this->beforeFilter('authenticate');
- * }
- * }
- *
- * class WeblogController extends ApplicationController
- * {
- * // will run the authenticate filter
- * }
- *
- * class SignupController extends AkActionController
- * {
- * function __construct()
- * {
- * $this->skipBeforeFilter('authenticate');
- * }
- * // will not run the authenticate filter
- * }
- *
- * == Filter conditions
- *
- * Filters can be limited to run for only specific actions. This can be expressed either by listing the actions to
- * exclude or the actions to include when executing the filter. Available conditions are +only+ or +except+, both
- * of which accept an arbitrary number of method references. For example:
- *
- * class Journal extends AkActionController
- * {
- * function __construct()
- * { // only require authentication if the current action is edit or delete
- * $this->beforeFilter(array('_authorize'=>array('only'=>array('edit','delete')));
- * }
- *
- * function _authorize(&$controller)
- * {
- * // redirect to login unless authenticated
- * }
- * }
- */
- var $_includedActions = array(), $_beforeFilters = array(), $_afterFilters = array(), $_excludedActions = array();
- /**
- * The passed <tt>filters</tt> will be appended to the array of filters that's run _before_ actions
- * on this controller are performed.
- */
- function appendBeforeFilter()
- {
- $filters = array_reverse(func_get_args());
- foreach (array_keys($filters) as $k){
- $conditions = $this->_extractConditions(&$filters[$k]);
- $this->_addActionConditions($filters[$k], $conditions);
- $this->_appendFilterToChain('before', $filters[$k]);
- }
- }
- /**
- * The passed <tt>filters</tt> will be prepended to the array of filters that's run _before_ actions
- * on this controller are performed.
- */
- function prependBeforeFilter()
- {
- $filters = array_reverse(func_get_args());
- foreach (array_keys($filters) as $k){
- $conditions = $this->_extractConditions(&$filters[$k]);
- $this->_addActionConditions($filters[$k], $conditions);
- $this->_prependFilterToChain('before', $filters[$k]);
- }
- }
- /**
- * Short-hand for appendBeforeFilter since that's the most common of the two.
- */
- function beforeFilter()
- {
- $filters = func_get_args();
- foreach (array_keys($filters) as $k){
- $this->appendBeforeFilter($filters[$k]);
- }
- }
- /**
- * The passed <tt>filters</tt> will be appended to the array of filters that's run _after_ actions
- * on this controller are performed.
- */
- function appendAfterFilter()
- {
- $filters = array_reverse(func_get_args());
- foreach (array_keys($filters) as $k){
- $conditions = $this->_extractConditions(&$filters[$k]);
- $this->_addActionConditions(&$filters[$k], $conditions);
- $this->_appendFilterToChain('after', &$filters[$k]);
- }
- }
- /**
- * The passed <tt>filters</tt> will be prepended to the array of filters that's run _after_ actions
- * on this controller are performed.
- */
- function prependAfterFilter()
- {
- $filters = array_reverse(func_get_args());
- foreach (array_keys($filters) as $k){
- $conditions = $this->_extractConditions(&$filters[$k]);
- $this->_addActionConditions(&$filters[$k], $conditions);
- $this->_prependFilterToChain('after', &$filters[$k]);
- }
- }
- /**
- * Short-hand for appendAfterFilter since that's the most common of the two.
- * */
- function afterFilter()
- {
- $filters = func_get_args();
- foreach (array_keys($filters) as $k){
- $this->appendAfterFilter($filters[$k]);
- }
- }
- /**
- * The passed <tt>filters</tt> will have their +before+ method appended to the array of filters that's run both before actions
- * on this controller are performed and have their +after+ method prepended to the after actions. The filter objects must all
- * respond to both +before+ and +after+. So if you do appendAroundFilter(new A(), new B()), the callstack will look like:
- *
- * B::before()
- * A::before()
- * A::after()
- * B::after()
- */
- function appendAroundFilter()
- {
- $filters = func_get_args();
- foreach (array_keys($filters) as $k){
- $this->_ensureFilterRespondsToBeforeAndAfter(&$filters[$k]);
- $this->appendBeforeFilter(array(&$filters[$k],'before'));
- }
- $filters = array_reverse($filters);
- foreach (array_keys($filters) as $k){
- $this->prependAfterFilter(array(&$filters[$k],'after'));
- }
- }
- /**
- * The passed <tt>filters</tt> will have their +before+ method prepended to the array of filters that's run both before actions
- * on this controller are performed and have their +after+ method appended to the after actions. The filter objects must all
- * respond to both +before+ and +after+. So if you do appendAroundFilter(new A(), new B()), the callstack will look like:
- *
- * A::before()
- * B::before()
- * B::after()
- * A::after()
- */
- function prependAroundFilter()
- {
- $filters = func_get_args();
- foreach (array_keys($filters) as $k){
- $this->_ensureFilterRespondsToBeforeAndAfter(&$filters[$k]);
- $this->prependBeforeFilter(array(&$filters[$k],'before'));
- }
- $filters = array_reverse($filters);
- foreach (array_keys($filters) as $k){
- $this->appendAfterFilter(array(&$filters[$k],'after'));
- }
- }
- /**
- * Short-hand for appendAroundFilter since that's the most common of the two.
- */
- function aroundFilter()
- {
- $filters = func_get_args();
- call_user_func_array(array(&$this,'appendAroundFilter'), $filters);
- }
- /**
- * Removes the specified filters from the +before+ filter chain.
- * This is especially useful for managing the chain in inheritance hierarchies where only one out
- * of many sub-controllers need a different hierarchy.
- */
- function skipBeforeFilter($filters)
- {
- $filters = func_get_args();
- $this->_skipFilter($filters, 'before');
- }
- /**
- * Removes the specified filters from the +after+ filter chain. Note that this only works for skipping method-reference
- * filters, not instances. This is especially useful for managing the chain in inheritance hierarchies where only one out
- * of many sub-controllers need a different hierarchy.
- */
- function skipAfterFilter($filters)
- {
- $filters = func_get_args();
- $this->_skipFilter($filters, 'after');
- }
- function _skipFilter(&$filters, $type)
- {
- $_filters =& $this->{'_'.$type.'Filters'};
- // array_diff doesn't play nice with some PHP5 releases when it comes to
- // Objects as it only diff equal references, not object types
- foreach (array_keys($filters) as $k){
- if(AK_PHP5){
- if(is_object($filters[$k])){
- foreach (array_keys($_filters) as $k2){
- if(is_object($_filters[$k2]) && get_class($_filters[$k2]) == get_class($filters[$k])){
- $pos = $k2;
- break;
- }
- }
- }else{
- $pos = array_search($filters[$k], $_filters);
- }
- array_splice($_filters, $pos, 1, null);
- return ;
- }
- $_filters = array_diff($_filters,array($filters[$k]));
- }
- }
- /**
- * Returns all the before filters for this class.
- */
- function beforeFilters()
- {
- return $this->_beforeFilters;
- }
- /**
- * Returns all the after filters for this class and all its ancestors.
- */
- function afterFilters()
- {
- return $this->_afterFilters;
- }
- /**
- * Returns a mapping between filters and the actions that may run them.
- */
- function includedActions()
- {
- return $this->_includedActions;
- }
- /**
- * Returns a mapping between filters and actions that may not run them.
- */
- function excludedActions()
- {
- return $this->_excludedActions;
- }
- function _appendFilterToChain($condition, $filters)
- {
- $this->{"_{$condition}Filters"}[] =& $filters;
- }
- function _prependFilterToChain($condition, $filters)
- {
- array_unshift($this->{"_{$condition}Filters"}, $filters);
- }
- function _ensureFilterRespondsToBeforeAndAfter(&$filter_object)
- {
- if(!method_exists(&$filter_object,'before') && !method_exists(&$filter_object,'after')){
- trigger_error(Ak::t('Filter object must respond to both before and after'), E_USER_ERROR);
- }
- }
- function _extractConditions(&$filters)
- {
- if(is_array($filters) && !isset($filters[0])){
- $keys = array_keys($filters);
- $conditions = $filters[$keys[0]];
- $filters = $keys[0];
- return $conditions;
- }
- }
- function _addActionConditions($filters, $conditions)
- {
- if(!empty($conditions['only'])){
- $this->_includedActions[$this->_filterId($filters)] = $this->_conditionArray($this->_includedActions, $conditions['only']);
- }
- if(!empty($conditions['except'])){
- $this->_excludedActions[$this->_filterId($filters)] = $this->_conditionArray($this->_excludedActions, $conditions['except']);
- }
- }
- function _conditionArray($actions, $filter_actions)
- {
- $filter_actions = is_array($filter_actions) ? $filter_actions : array($filter_actions);
- $filter_actions = array_map(array(&$this,'_filterId'),$filter_actions);
- return array_unique(array_merge($actions, $filter_actions));
- }
- function _filterId($filters)
- {
- return is_string($filters) ? $filters : md5(serialize($filters));
- }
- function performActionWithoutFilters($action)
- {
- if(method_exists(&$this, $action)){
- call_user_func_array(array(&$this, $action), @(array)$this->passed_args);
- }
- }
- function performActionWithFilters($method = '')
- {
- if ($this->beforeAction($method) !== false && !$this->_hasPerformed()){
- $this->performActionWithoutFilters($method);
- $this->afterAction($method);
- return true;
- }
- return false;
- }
- function performAction($method = '')
- {
- $this->performActionWithFilters($method);
- }
- /**
- * Calls all the defined before-filter filters, which are added by using "beforeFilter($method)".
- * If any of the filters return false, no more filters will be executed and the action is aborted.
- */
- function beforeAction($method = '')
- {
- Ak::profile('Running before controller action filters '.__CLASS__.'::'.__FUNCTION__.' '.__LINE__);
- return $this->_callFilters($this->_beforeFilters, $method);
- }
- /**
- * Calls all the defined after-filter filters, which are added by using "afterFilter($method)".
- * If any of the filters return false, no more filters will be executed.
- */
- function afterAction($method = '')
- {
- Ak::profile('Running after controller action filters '.__CLASS__.'::'.__FUNCTION__.' '.__LINE__);
- return $this->_callFilters(&$this->_afterFilters, $method);
- }
- function _callFilters(&$filters, $method = '')
- {
- $filter_result = null;
- foreach (array_keys($filters) as $k){
- $filter =& $filters[$k];
- if(!$this->_actionIsExempted($filter, $method)){
- if(is_array($filter) && is_object($filter[0]) && method_exists($filter[0], $filter[1])){
- $filter_result = $filter[0]->$filter[1]($this);
- }elseif(!is_object($filter) && method_exists($this, $filter)){
- $filter_result = $this->$filter($this);
- }elseif(is_object($filter) && method_exists($filter, 'filter')){
- $filter_result = $filter->filter($this);
- }else{
- trigger_error(Ak::t('Invalid filter %filter. Filters need to be a method name or a class implementing a static filter method', array('%filter'=>$filter)), E_USER_WARNING);
- }
- }
- if($filter_result === false){
- !empty($this->_Logger) ? $this->_Logger->info(Ak::t('Filter chain halted as '.$filter.' returned false')) : null;
- return false;
- }
- }
- return $filter_result;
- }
- function _actionIsExempted($filter, $method = '')
- {
- $method_id = is_string($method) ? $method : $this->_filterId($method);
- $filter_id = $this->_filterId($filter);
- if((!empty($this->_includedActions[$filter_id]) && !in_array($method_id, $this->_includedActions[$filter_id])) ||
- (!empty($this->_excludedActions[$filter_id]) && in_array($method_id, $this->_excludedActions[$filter_id]))){
- return true;
- }
- return false;
- }
- /**
- Flash communication between actions
- ====================================================================
- *
- * The flash provides a way to pass temporary objects between actions. Anything you place in the flash will be exposed
- * to the very next action and then cleared out. This is a great way of doing notices and alerts, such as a create action
- * that sets <tt>flash['notice] = 'Successfully created'</tt> before redirecting to a display action that can then expose
- * the flash to its template. Actually, that exposure is automatically done. Example:
- *
- * class WeblogController extends ActionController
- * {
- * function create()
- * {
- * // save post
- * $this->flash['notice] = 'Successfully created post';
- * $this->redirectTo(array('action'=>'display','params' => array('id' =>$Post->id)));
- * }
- *
- * function display()
- * {
- * // doesn't need to assign the flash notice to the template, that's done automatically
- * }
- * }
- *
- * display.tpl
- * <?php if($flash['notice']) : ?><div class='notice'><?php echo $flash['notice'] ?></div><?php endif; ?>
- *
- * This example just places a string in the flash, but you can put any object in there. And of course, you can put as many
- * as you like at a time too. Just remember: They'll be gone by the time the next action has been performed.
- *
- * ==flash_now
- *
- * Sets a flash that will not be available to the next action, only to the current.
- *
- * $this->flash_now['message] = 'Hello current action';
- *
- * This method enables you to use the flash as a central messaging system in your app.
- * When you need to pass an object to the next action, you use the standard flash assign (<tt>[]=</tt>).
- * When you need to pass an object to the current action, you use <tt>now</tt>, and your object will
- * vanish when the current action is done.
- *
- * Entries set via <tt>flash_now</tt> are accessed the same way as standard entries: <tt>flash['my-key']</tt>.
- */
- var $flash = array();
- var $flash_now = array();
- var $flash_options = array();
- var $_flash_handled = false;
- function _handleFlashAttribute()
- {
- $this->_flash_handled = true;
- $next_flash = empty($this->flash) ? false : $this->flash;
- $this->flash = array();
- if(isset($_SESSION['__flash'])){
- $this->flash = $_SESSION['__flash'];
- }
- $_SESSION['__flash'] = $next_flash;
- if(!empty($this->flash_now)){
- $this->flash = array_merge((array)$this->flash,(array)$this->flash_now);
- }
- $this->_handleFlashOptions();
- }
- function _handleFlashOptions()
- {
- $next_flash_options = empty($this->flash_options) ? false : $this->flash_options;
- $this->flash_options = array();
- if(isset($_SESSION['__flash_options'])){
- $this->flash_options = $_SESSION['__flash_options'];
- }
- $_SESSION['__flash_options'] = $next_flash_options;
- if(!empty($this->flash_now_options)){
- $this->flash_options = array_merge((array)$this->flash_options,(array)$this->flash_now_options);
- }
- }
- function _mergeFlashOnFlashNow()
- {
- $this->flash_now = array_merge($this->flash_now,$this->flash);
- }
- /**
- Pagination for Active Record collections
- ====================================================================
- *
- * The Pagination module aids in the process of paging large collections of
- * Active Record objects. It offers macro-style automatic fetching of your
- * model for multiple views, or explicit fetching for single actions. And if
- * the magic isn't flexible enough for your needs, you can create your own
- * paginators with a minimal amount of code.
- *
- * The Pagination module can handle as much or as little as you wish. In the
- * controller, have it automatically query your model for pagination; or,
- * if you prefer, create Paginator objects yourself
- *
- * Pagination is included automatically for all controllers.
- *
- * For help rendering pagination links, see
- * Helpers/PaginationHelper.
- *
- * ==== Automatic pagination for every action in a controller
- *
- * class PersonController extends ApplicationController
- * {
- * var $model = 'person';
- * var $paginate = array('people'=>array('order' => 'last_name, first_name',
- * 'per_page' => 20));
- * }
- *
- * Each action in this controller now has access to a <tt>$this->people</tt>
- * instance variable, which is an ordered collection of model objects for the
- * current page (at most 20, sorted by last name and first name), and a
- * <tt>$this->person_pages</tt> Paginator instance. The current page is determined
- * by the <tt>$params['page']</tt> variable.
- *
- * ==== Pagination for a single action
- *
- * function show_all()
- * {
- * list($this->person_pages, $this->people) =
- * $this->paginate('people', array('order' => 'last_name, first_name'));
- * }
- *
- * Like the previous example, but explicitly creates <tt>$this->person_pages</tt>
- * and <tt>$this->people</tt> for a single action, and uses the default of 10 items
- * per page.
- *
- * ==== Custom/"classic" pagination
- *
- * function list()
- * {
- * $this->person_pages = new AkPaginator(&$this, $Person->count(), 10, $params['page']);
- * $this->people = $this->Person->find('all', array(
- * 'order'=> 'last_name, first_name',
- * 'limit' => $this->person_pages->items_per_page,
- * 'offset' => $this->person_pages->getOffset()));
- * }
- *
- * Explicitly creates the paginator from the previous example and uses
- * AkPaginator::toSql to retrieve <tt>$this->people</tt> from the model.
- */
- // An array holding options for controllers using macro-style pagination
- var $_pagination_options = array(
- 'class_name' => null,
- 'singular_name' => null,
- 'per_page' => 10,
- 'conditions' => null,
- 'order_by' => null,
- 'order' => null,
- 'join' => null,
- 'joins' => null,
- 'include' => null,
- 'select' => null,
- 'parameter' => 'page'
- );
- // The default options for pagination
- var $_pagination_default_options = array(
- 'class_name' => null,
- 'singular_name' => null,
- 'per_page' => 10,
- 'conditions' => null,
- 'order_by' => null,
- 'order' => null,
- 'join' => null,
- 'joins' => null,
- 'include' => null,
- 'select' => null,
- 'parameter' => 'page'
- );
- var $_pagination_actions = array();
- function _paginationValidateOptions($collection_id, $options = array(), $in_action)
- {
- $this->_pagination_options = array_merge($this->_pagination_default_options, $this->_pagination_options);
- $valid_options = array_keys($this->_pagination_default_options);
- $valid_options = !in_array($in_action, $valid_options) ? array_merge($valid_options, $this->_pagination_actions) : $valid_options;
- $unknown_option_keys = array_diff(array_keys($this->_pagination_options) , $valid_options);
- if(!empty($unknown_option_keys)){
- trigger_error(Ak::t('Unknown options for pagination: %unknown_option',array('%unknown_option'=>join(', ',$unknown_option_keys))), E_USER_WARNING);
- }
- $this->_pagination_options['singular_name'] = !empty($this->_pagination_options['singular_name']) ? $this->_pagination_options['singular_name'] : AkInflector::singularize($collection_id);
- $this->_pagination_options['class_name'] = !empty($this->_pagination_options['class_name']) ? $this->_pagination_options['class_name'] : AkInflector::camelize($this->_pagination_options['singular_name']);
- }
- /**
- * Returns a paginator and a collection of Active Record model instances
- * for the paginator's current page. This is designed to be used in a
- * single action.
- *
- * +options+ are:
- * <tt>singular_name</tt>:: the singular name to use, if it can't be inferred by
- * singularizing the collection name
- * <tt>class_name</tt>:: the class name to use, if it can't be inferred by
- * camelizing the singular name
- * <tt>per_page</tt>:: the maximum number of items to include in a
- * single page. Defaults to 10
- * <tt>conditions</tt>:: optional conditions passed to Model::find('all', $this->params); and
- * Model::count()
- * <tt>order</tt>:: optional order parameter passed to Model::find('all', $this->params);
- * <tt>order_by</tt>:: (deprecated, used :order) optional order parameter passed to Model::find('all', $this->params)
- * <tt>joins</tt>:: optional joins parameter passed to Model::find('all', $this->params)
- * and Model::count()
- * <tt>join</tt>:: (deprecated, used :joins or :include) optional join parameter passed to Model::find('all', $this->params)
- * and Model::count()
- * <tt>include</tt>:: optional eager loading parameter passed to Model::find('all', $this->params)
- * and Model::count()
- *
- * Creates a +before_filter+ which automatically paginates an Active
- * Record model for all actions in a controller (or certain actions if
- * specified with the <tt>actions</tt> option).
- *
- * +options+ are the same as PaginationHelper::paginate, with the addition
- * of:
- * <tt>actions</tt>:: an array of actions for which the pagination is
- * active. Defaults to +null+ (i.e., every action)
- */
- function paginate($collection_id, $options = array())
- {
- $this->_paginationValidateOptions($collection_id, $options, true);
- $this->_paginationLoadPaginatorAndCollection($collection_id, $this->_pagination_options);
- $this->beforeFilter('_paginationCreateAndRetrieveCollections');
- }
- function _paginationCreateAndRetrieveCollections()
- {
- foreach($this->_pagination_options[$this->class] as $collection_id=>$options){
- if(!empty($options['actions']) && in_array($options['actions'], $action_name)){
- continue;
- }
- list($paginator, $collection) = $this->_paginationLoadPaginatorAndCollection($collection_id, $this->_pagination_options);
- $this->{$options['singular_name'].'_pages'} =& $paginator;
- $this->$collection_name =& $collection;
- }
- }
- /**
- * Returns the total number of items in the collection to be paginated for
- * the +model+ and given +conditions+. Override this method to implement a
- * custom counter.
- */
- function _paginationCountCollection(&$model, $conditions, $joins)
- {
- return $model->count($conditions, $joins);
- }
- /**
- * Returns a collection of items for the given +$model+ and +$options['conditions']+,
- * ordered by +$options['order']+, for the current page in the given +$paginator+.
- * Override this method to implement a custom finder.
- */
- function _paginationFindCollection(&$model, $options, &$paginator)
- {
- return $model->find('all', array(
- 'conditions' => $this->_pagination_options['conditions'],
- 'order' => !empty($options['order_by']) ? $options['order_by'] : $options['order'],
- 'joins' => !empty($options['join']) ? $options['join'] : $options['joins'],
- 'include' => $this->_pagination_options['include'],
- 'select' => $this->_pagination_options['select'],
- 'limit' => $this->_pagination_options['per_page'],
- 'offset' => $paginator->getOffset()));
- }
- /**
- * @todo Fix this function
- */
- function _paginationLoadPaginatorAndCollection($collection_id, $options)
- {
- $page = $this->params[$options['parameter']];
- $count = $this->_paginationCountCollection($klass, $options['conditions'],
- empty($options['join']) ? $options['join'] : $options['joins']);
- require_once(AK_LIB_DIR.DS.'AkActionController'.DS.'AkPaginator.php');
- $paginator =& new AkPaginator($this, $count, $options['per_page'], $page);
- $collection =& $this->_paginationFindCollection($options['class_name'], $options, $paginator);
- return array(&$paginator, &$collection);
- }
- /**
- Protocol conformance
- ====================================================================
- */
- /**
- * Specifies that the named actions requires an SSL connection to be performed (which is enforced by ensure_proper_protocol).
- */
- function setSslRequiredActions($actions)
- {
- $this->_ssl_required_actions = empty($this->_ssl_required_actions) ?
- (is_string($actions) ? Ak::stringToArray($actions) : $actions) :
- array_merge($this->_ssl_required_actions, (is_string($actions) ? Ak::stringToArray($actions) : $actions));
- }
- function setSslAllowedActions($actions)
- {
- $this->_ssl_allowed_actions = empty($this->_ssl_allowed_actions) ?
- (is_string($actions) ? Ak::stringToArray($actions) : $actions) :
- array_merge($this->_ssl_allowed_actions, (is_string($actions) ? Ak::stringToArray($actions) : $actions));
- }
- /**
- * Returns true if the current action is supposed to run as SSL
- */
- function _isSslRequired()
- {
- return !empty($this->_ssl_required_actions) && is_array($this->_ssl_required_actions) && isset($this->_action_name) ?
- in_array($this->_action_name, $this->_ssl_required_actions) : false;
- }
- function _isSslAllowed()
- {
- return (!empty($this->ssl_for_all_actions) && empty($this->_ssl_allowed_actions)) ||
- (!empty($this->_ssl_allowed_actions) && is_array($this->_ssl_allowed_actions) && isset($this->_action_name) ?
- in_array($this->_action_name, $this->_ssl_allowed_actions) : false);
- }
- function _ensureProperProtocol()
- {
- if($this->_isSslAllowed()){
- return true;
- }
- if ($this->_isSslRequired() && !$this->Request->isSsl()){
- $this->redirectTo(substr_replace(AK_CURRENT_URL,'s:',4,1));
- return false;
- }elseif($this->Request->isSsl() && !$this->_isSslRequired()){
- $this->redirectTo(substr_replace(AK_CURRENT_URL,'',4,1));
- return false;
- }
- }
- /**
- Account Location
- ====================================================================
- *
- * Account location is a set of methods that supports the account-key-as-subdomain
- * way of identifying the current scope. These methods allow you to easily produce URLs that
- * match this style and to get the current account key from the subdomain.
- *
- * The methods are: getAccountUrl, getAccountHost, and getAccountDomain.
- *
- * Example:
- *
- * include_once('AkAccountLocation.php');
- *
- * class ApplicationController extends AkActionController
- * {
- * var $before_filter = '_findAccount';
- *
- * function _findAccount()
- * {
- * $this->account = Account::find(array('conditions'=>array('username = ?', $this->account_domain)));
- * }
- *
- * class AccountController extends ApplicationController
- * {
- * function new_account()
- * {
- * $this->new_account = Account::create($this->params['new_account']);
- * $this->redirectTo(array('host' => $this->accountHost($this->new_account->username), 'controller' => 'weblog'));
- * }
- *
- * function authenticate()
- * {
- * $this->session[$this->account_domain] = 'authenticated';
- * $this->redirectTo(array('controller => 'weblog'));
- * }
- *
- * function _isAuthenticated()
- * {
- * return !empty($this->session['account_domain']) ? $this->session['account_domain'] == 'authenticated' : false;
- * }
- * }
- *
- * // The view:
- * Your domain: {account_url?}
- *
- * By default, all the methods will query for $this->account->username as the account key, but you can
- * specialize that by overwriting defaultAccountSubdomain. You can of course also pass it in
- * as the first argument to all the methods.
- */
- function defaultAccountSubdomain()
- {
- if(!empty($this->account)){
- return $this->account->respondsTo('username');
- }
- }
- function accountUrl($account_subdomain = null, $use_ssl = null)
- {
- $account_subdomain = empty($account_subdomain) ? 'default_account_subdomain' : $account_subdomain;
- $use_ssl = empty($use_ssl) ? $use_ssl : $this->Request->isSsl();
- return ($use_ssl ? 'https://' : 'http://') . $this->accountHost($account_subdomain);
- }
- function accountHost($account_subdomain = null)
- {
- $account_subdomain = empty($account_subdomain) ? 'default_account_subdomain' : $account_subdomain;
- $account_host = '';
- $account_host .= $account_subdomain . '.';
- $account_host .= $this->accountDomain();
- return $account_host;
- }
- function accountDomain()
- {
- $account_domain = '';
- if(count($this->Request->getSubdomains()) > 1){
- $account_domain .= join('.',$this->Request->getSubdomains()) . '.';
- }
- $account_domain .= $this->Request->getDomain() . $this->Request->getPortString();
- return $account_domain;
- }
- function getAccountSubdomain()
- {
- return array_shift($this->Request->getSubdomains());
- }
- /**
- Data streaming
- ====================================================================
- Methods for sending files and streams to the browser instead of rendering.
- */
- var $default_send_file_options = array(
- 'type' => 'application/octet-stream',
- 'disposition' => 'attachment',
- 'stream' => true,
- 'buffer_size' => 4096
- );
- /**
- * Sends the file by streaming it 4096 bytes at a time. This way the
- * whole file doesn't need to be read into memory at once. This makes
- * it feasible to send even large files.
- *
- * Be careful to sanitize the path parameter if it coming from a web
- * page. sendFile($params['path']) allows a malicious user to
- * download any file on your server.
- *
- * Options:
- * * <tt>filename</tt> - suggests a filename for the browser to use.
- * Defaults to realpath($path).
- * * <tt>type</tt> - specifies an HTTP content type.
- * Defaults to 'application/octet-stream'.
- * * <tt>disposition</tt> - specifies whether the file will be shown inline or downloaded.
- * Valid values are 'inline' and 'attachment' (default).
- * * <tt>stream</tt> - whether to send the file to the user agent as it is read (true)
- * or to read the entire file before sending (false). Defaults to true.
- * * <tt>buffer_size</tt> - specifies size (in bytes) of the buffer used to stream the file.
- * Defaults to 4096.
- *
- * The default Content-Type and Content-Disposition headers are
- * set to download arbitrary binary files in as many browsers as
- * possible. IE versions 4, 5, 5.5, and 6 are all known to have
- * a variety of quirks (especially when downloading over SSL).
- *
- * Simple download:
- * sendFile('/path/to.zip');
- *
- * Show a JPEG in browser:
- * sendFile('/path/to.jpeg', array('type' => 'image/jpeg', 'disposition' => 'inline'));
- *
- * Read about the other Content-* HTTP headers if you'd like to
- * provide the user with more information (such as Content-Description).
- * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11
- *
- * Also be aware that the document may be cached by proxies and browsers.
- * The Pragma and Cache-Control headers declare how the file may be cached
- * by intermediaries. They default to require clients to validate with
- * the server before releasing cached responses. See
- * http://www.mnot.net/cache_docs/ for an overview of web caching and
- * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9
- * for the Cache-Control header spec.
- */
- function sendFile($path, $options = array())
- {
- $path = realpath($path);
- if(!file_exists($path)){
- trigger_error(Ak::t('Cannot read file %path',array('%path'=>$path)), E_USER_NOTICE);
- return false;
- }
- $options['length'] = empty($options['length']) ? filesize($path) : $options['length'];
- $options['filename'] = empty($options['filename']) ? basename($path) : $options['filename'];
- $options['type'] = empty($options['type']) ? Ak::mime_content_type($path) : $options['type'];
- $this->performed_render = false;
- $this->_sendFileHeaders($options);
- if(!empty($options['stream'])){
- require_once(AK_LIB_DIR.DS.'AkStream.php');
- $this->render(array('text'=> new AkStream($path,$options['buffer_size'])));
- }else{
- $this->render(array('text'=> Ak::file_get_contents($path)));
- }
- }
- /**
- * Send binary data to the user as a file download. May set content type, apparent file name,
- * and specify whether to show data inline or download as an attachment.
- *
- * Options:
- * * <tt>filename</tt> - Suggests a filename for the browser to use.
- * * <tt>type</tt> - specifies an HTTP content type.
- * Defaults to 'application/octet-stream'.
- * * <tt>disposition</tt> - specifies whether the file will be shown inline or downloaded.
- * Valid values are 'inline' and 'attachment' (default).
- *
- * Generic data download:
- * sendData($buffer)
- *
- * Download a dynamically-generated tarball:
- * sendData(Ak::compress('dir','tgz'), array('filename' => 'dir.tgz'));
- *
- * Display an image Active Record in the browser:
- * sendData($image_data, array('type' =>Ak::mime_content_type('image_name.png'), 'disposition' => 'inline'));
- *
- * See +sendFile+ for more information on HTTP Content-* headers and caching.
- */
- function sendData($data, $options = array())
- {
- $options['length'] = empty($options['length']) ? Ak::size($data) : $options['length'];
- $this->_sendFileHeaders($options);
- $this->performed_render = false;
- $this->renderText($data);
- }
- /**
- * Creates a file for streaming from a file.
- * This way you might free memory usage is file is too large
- */
- function sendDataAsStream($data, $options)
- {
- $temp_file_name = tempnam(AK_TMP_DIR, Ak::randomString());
- $fp = fopen($temp_file_name, 'w');
- fwrite($fp, $data);
- fclose($fp);
- $this->sendFile($temp_file_name, $options);
- }
- function _sendFileHeaders(&$options)
- {
- $options = array_merge($this->default_send_file_options,$options);
- foreach (array('length', 'type', 'disposition') as $arg){
- empty($options[$arg]) ? trigger_error(Ak::t('%arg option required', array('%arg'=>$arg)), E_USER_ERROR) : null;
- }
- $disposition = empty($options['disposition']) ? 'attachment' : $options['disposition'];
- $disposition .= !empty($options['filename']) ? '; filename="'.$options['filename'].'"' : '';
- $this->Response->addHeader(array(
- 'Content-Length' => $options['length'],
- 'Content-Type' => trim($options['type']), // fixes a problem with extra '\r' with some browsers
- 'Content-Disposition' => $disposition,
- 'Content-Transfer-Encoding' => 'binary'
- ));
- }
- function redirectToLocale($locale)
- {
- if($this->Request->__internationalization_support_enabled){
- $lang = isset($this->params['lang']) ? $this->params['lang'] : $locale;
- if($locale != $lang){
- $this->redirectTo(array_merge($this->Request->getParams(),array('lang'=>$locale)));
- return true;
- }
- }
- return false;
- }
- function api($protocol = 'xml_rpc')
- {
- $web_services = array_merge(Ak::toArray($this->web_services), Ak::toArray($this->web_service));
- if(!empty($web_services)){
- $web_services = array_unique($web_services);
- require_once(AK_LIB_DIR.DS.'AkActionWebService.php');
- require_once(AK_LIB_DIR.DS.'AkActionWebService'.DS.'AkActionWebServiceServer.php');
- $Server =& new AkActionWebServiceServer($protocol);
- foreach ($web_services as $web_service){
- $Server->addService($web_service);
- }
- $Server->init();
- $Server->serve();
- exit;
- }else{
- die(Ak::t('There is not any webservice configured at this endpoint'));
- }
- }
- /**
- HTTP Authentication
- ====================================================================
- *
- * Simple Basic example:
- *
- * class PostsController extends ApplicationController
- * {
- * var $_authorized_users = array('bermi' => 'secret');
- *
- * function __construct(){
- * $this->beforeFilter(array('authenticate' => array('except' => array('index'))));
- * }
- *
- * function index() {
- * $this->renderText("Everyone can see me!");
- * }
- *
- * function edit(){
- * $this->renderText("I'm only accessible if you know the password");
- * }
- *
- * function authenticate(){
- * return $this->_authenticateOrRequestWithHttpBasic('App name', $this->_authorized_users);
- * }
- * }
- *
- * Here is a more advanced Basic example where only Atom feeds and the XML API is protected by HTTP authentication,
- * the regular HTML interface is protected by a session approach:
- *
- * class ApplicationController extends AkActionController
- * {
- * var $models = 'account';
- *
- * function __construct() {
- * $this->beforeFilter(array('_setAccount', 'authenticate'));
- * }
- *
- * function _setAccount() {
- * $this->Account = $this->account->findFirstBy('url_name', array_pop($this->Request->getSubdomains()));
- * }
- *
- * function authenticate() {
- * if($this->Request->isFormat('XML', 'ATOM')){
- * if($User = $this->_authenticateWithHttpBasic($Account)){
- * $this->CurrentUser = $User;
- * }else{
- * $this->_requestHttpBasicAuthentication();
- * }
- * }else{
- * if($this->isSessionAuthenticated()){
- * $this->CurrentUser = $Account->user->find($_SESSION['authenticated']['user_id']);
- * }else{
- * $this->redirectTo(array('controller'=>'login'));
- * return false;
- * }
- * }
- * }
- * }
- *
- * On shared hosts, Apache sometimes doesn't pass authentication headers to
- * FCGI instances. If your environment matches this description and you cannot
- * authenticate, try this rule in public/.htaccess (replace the plain one):
- *
- * RewriteRule ^(.*)$ index.php [E=X-HTTP_AUTHORIZATION:%{HTTP:Authorization},QSA,L]
- */
- function _authenticateOrRequestWithHttpBasic($realm = AK_APP_NAME, $login_procedure)
- {
- if($Result = $this->_authenticateWithHttpBasic($login_procedure)){
- return $Result;
- }
- return $this->_requestHttpBasicAuthentication($realm);
- }
- function _authenticateWithHttpBasic($login_procedure)
- {
- return $this->_authenticate($login_procedure);
- }
- function _requestHttpBasicAuthentication($realm = AK_APP_NAME)
- {
- return $this->_authenticationRequest($realm);
- }
- /**
- * This is method takes a $login_procedure for performing access authentication.
- *
- * If an array is given, it will check the key for a user and the value will be verified to match given password.
- *
- * You can pass and array like array('handler' => $Account, 'method' => 'verifyCredentials'), which will call
- *
- * $Account->verifyCredentials($user_name, $password, $Controller)
- *
- * You can also pass an object which implements an "authenticate" method. when calling
- *
- * $this->_authenticate(new User());
- *
- * It will call the $User->authenticate($user_name, $password, $Controller)
- *
- * In both cases the authentication method should return true for valid credentials or false is invalid.
- *
- * @return bool
- */
- function _authenticate($login_procedure)
- {
- if(!$this->_authorization()){
- return false;
- }else{
- list($user_name, $password) = $this->_getUserNameAndPassword();
- if(is_array($login_procedure)){
- if(!isset($login_procedure['handler'])){
- return isset($login_procedure[$user_name]) && $login_procedure[$user_name] == $password;
- }elseif(is_a($login_procedure['handler']) && method_exists($login_procedure['handler'], $login_procedure['method'])){
- return $login_procedure['handler']->$login_procedure['method']($user_name, $password, $this);
- }
- }elseif(method_exists($login_procedure, 'authenticate')){
- return $login_procedure->authenticate($user_name, $password, $this);
- }
- }
- return false;
- }
- function _getUserNameAndPassword()
- {
- $credentials = $this->_decodeCredentials();
- return !is_array($credentials) ? split('/:/', $credentials , 2) : $credentials;
- }
- function _authorization()
- {
- return
- empty($this->Request->env['PHP_AUTH_USER']) ? (
- empty($this->Request->env['HTTP_AUTHORIZATION']) ? (
- empty($this->Request->env['X-HTTP_AUTHORIZATION']) ? (
- empty($this->Request->env['X_HTTP_AUTHORIZATION']) ? (
- isset($this->Request->env['REDIRECT_X_HTTP_AUTHORIZATION']) ?
- $this->Request->env['REDIRECT_X_HTTP_AUTHORIZATION'] : null
- ) : $this->Request->env['X_HTTP_AUTHORIZATION']
- ) : $this->Request->env['X-HTTP_AUTHORIZATION']
- ) : $this->Request->env['HTTP_AUTHORIZATION']
- ) : array($this->Request->env['PHP_AUTH_USER'], $this->Request->env['PHP_AUTH_PW']);
- }
- function _decodeCredentials()
- {
- $authorization = $this->_authorization();
- if(is_array($authorization)){
- return $authorization;
- }
- $credentials = (array)split(' ', $authorization);
- return base64_decode(array_pop($credentials));
- }
- function _encodeCredentials($user_name, $password)
- {
- return 'Basic '.base64_encode("$user_name:$password");
- }
- function _authenticationRequest($realm)
- {
- header('WWW-Authenticate: Basic realm="' . str_replace('"','',$realm) . '"');
- if(method_exists($this, 'access_denied')){
- $this->access_denied();
- }else{
- header('HTTP/1.0 401 Unauthorized');
- echo "HTTP Basic: Access denied.\n";
- exit;
- }
- }
- function _ensureActionExists()
- {
- if(!method_exists($this, $this->_action_name)){
- if(AK_ENVIRONMENT == 'development'){
- AK_LOG_EVENTS && !empty($this->_Logger) ? $this->_Logger->error('Action '.$this->_action_name.' not found on '.$this->getControllerName()) : null;
- trigger_error(Ak::t('Controller <i>%controller_name</i> can\'t handle action %action_name',
- array(
- '%controller_name' => $this->getControllerName(),
- '%action_name' => $this->_action_name,
- )), E_USER_ERROR);
- }elseif(@include(AK_PUBLIC_DIR.DS.'405.php')){
- exit;
- }else{
- header("HTTP/1.1 405 Method Not Allowed");
- die('405 Method Not Allowed');
- }
- }
- }
- }
- /**
- * Function for getting the singleton controller;
- *
- * @return AkActionController instance
- */
- function &AkActionController()
- {
- $params = func_num_args() == 0 ? null : func_get_args();
- $AkActionController =& Ak::singleton('AkActionController', $params);
- return $AkActionController;
- }
- ?>