/lib/AkActionController.php
PHP | 2846 lines | 1355 code | 290 blank | 1201 comment | 177 complexity | d9d05d2b37031605d95621cb9c8f3024 MD5 | raw file
Possible License(s): LGPL-2.1
Large files files are truncated, but you can click here to view the full file
- <?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 …
Large files files are truncated, but you can click here to view the full file