Fixes #149
[akelos.git] / lib / AkActionController.php
blob454720a2d5e885304819716eda79daf61bf28d71
1 <?php
2 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
4 // +----------------------------------------------------------------------+
5 // | Akelos Framework - http://www.akelos.org |
6 // +----------------------------------------------------------------------+
7 // | Copyright (c) 2002-2006, Akelos Media, S.L. & Bermi Ferrer Martinez |
8 // | Released under the GNU Lesser General Public License, see LICENSE.txt|
9 // +----------------------------------------------------------------------+
11 require_once(AK_LIB_DIR.DS.'AkObject.php');
13 defined('AK_HIGH_LOAD_MODE') ? null : define('AK_HIGH_LOAD_MODE', false);
14 defined('AK_APP_NAME') ? null : define('AK_APP_NAME', 'Application');
16 /**
17 * @package ActionController
18 * @subpackage Base
19 * @author Bermi Ferrer <bermi a.t akelos c.om>
20 * @copyright Copyright (c) 2002-2006, Akelos Media, S.L. http://www.akelos.org
21 * @license GNU Lesser General Public License <http://www.gnu.org/copyleft/lesser.html>
24 class AkActionController extends AkObject
26 var $_high_load_mode = AK_HIGH_LOAD_MODE;
27 var $_enable_plugins = true;
28 var $_auto_instantiate_models = true;
29 var $validate_output = false;
31 var $_ssl_requirement = false;
32 var $_ssl_allowed_actions = array();
33 var $ssl_for_all_actions = true;
35 /**
36 * Determines whether the view has access to controller internals $this->Request, $this->Response, $this->session, and $this->Template.
37 * By default, it does.
39 var $_view_controller_internals = true;
41 /**
42 * Protected instance variable cache
44 var $_protected_variables_cache = array();
46 /**
47 * Prepends all the URL-generating helpers from AssetHelper.
48 * This makes it possible to easily move javascripts, stylesheets,
49 * and images to a dedicated asset server away from the main web server.
50 * Example:
51 * $this->_asset_host = 'http://assets.example.com';
53 var $asset_host = AK_ASSET_HOST;
56 var $_Logger;
58 /**
59 * Determines which template class should be used by AkActionController.
61 var $TemplateClass;
63 /**
64 * Turn on +_ignore_missing_templates+ if you want to unit test actions without
65 * making the associated templates.
67 var $_ignore_missing_templates;
69 /**
70 * Holds the Request object that's primarily used to get environment variables
72 var $Request;
74 /**
75 * Holds an array of all the GET, POST, and Url parameters passed to the action.
76 * Accessed like <tt>$this->params['post_id'];</tt>
77 * to get the post_id.
79 var $params = array();
81 /**
82 * Holds the Response object that's primarily used to set additional HTTP _headers
83 * through access like <tt>$this->Response->_headers['Cache-Control'] = 'no-cache';</tt>.
84 * Can also be used to access the final body HTML after a template
85 * has been rendered through $this->Response->body -- useful for <tt>after_filter</tt>s
86 * that wants to manipulate the output, such as a OutputCompressionFilter.
88 var $Response;
90 /**
91 * Holds an array of objects in the session. Accessed like <tt>$this->session['person']</tt>
92 * to get the object tied to the 'person' key. The session will hold any type of object
93 * as values, but the key should be a string.
95 var $session;
97 /**
98 * Holds an array of header names and values. Accessed like <tt>$this->_headers['Cache-Control']</tt>
99 * to get the value of the Cache-Control directive. Values should always be specified as strings.
101 var $_headers = array();
104 * Holds the array of variables that are passed on to the template class to be
105 * made available to the view. This array is generated by taking a snapshot of
106 * all the instance variables in the current scope just before a template is rendered.
108 var $_assigns = array();
111 * Holds the name of the action this controller is processing.
113 var $_action_name;
115 var $cookies;
117 var $helpers = 'default';
119 var $app_helpers;
120 var $plugin_helpers = 'all';
122 var $web_service;
123 var $web_services = array();
125 var $web_service_api;
126 var $web_service_apis = array();
128 var $module_name;
129 var $_module_path;
132 * Old fashioned way of dispatching requests. Please use AkDispatcher or roll your own.
134 * @deprecated
136 function handleRequest()
138 AK_LOG_EVENTS && empty($this->_Logger) ? ($this->_Logger =& Ak::getLogger()) : null;
139 AK_LOG_EVENTS && !empty($this->_Logger) ? $this->_Logger->warning('Using deprecated request dispatcher AkActionController::handleRequest. Use to AkDispatcher + AkDispatcher::dispatch instead.') : null;
140 require_once(AK_LIB_DIR.DS.'AkDispatcher.php');
141 $Dispatcher =& new AkDispatcher();
142 $Dispatcher->dispatch();
145 function process(&$Request, &$Response)
147 AK_LOG_EVENTS && empty($this->_Logger) ? ($this->_Logger =& Ak::getLogger()) : null;
149 $this->Request =& $Request;
150 $this->Response =& $Response;
151 $this->params = $this->Request->getParams();
152 $this->_action_name = $this->Request->getAction();
154 $this->_ensureActionExists();
156 Ak::t('Akelos'); // We need to get locales ready
158 if($this->_high_load_mode !== true){
159 if(!empty($this->_auto_instantiate_models)){
160 $this->instantiateIncludedModelClasses();
162 if(!empty($this->_enable_plugins)){
163 $this->loadPlugins();
165 if(!empty($this->helpers)){
166 $this->instantiateHelpers();
168 }else{
169 $this->_enableLayoutOnRender = false;
172 $this->_ensureProperProtocol();
174 // After filters
175 $this->afterFilter('_handleFlashAttribute');
177 $this->_loadActionView();
179 if(isset($this->api)){
180 require_once(AK_LIB_DIR.DS.'AkActionWebService.php');
181 $this->aroundFilter(new AkActionWebService($this));
184 $this->performActionWithFilters($this->_action_name);
186 if (!$this->_hasPerformed()){
187 $this->_enableLayoutOnRender ? $this->renderWithLayout() : $this->renderWithoutLayout();
190 if(!empty($this->validate_output)){
191 $this->_validateGeneratedXhtml();
194 $this->Response->outputResults();
197 function _loadActionView()
199 empty($this->_assigns) ? ($this->_assigns = array()) : null;
200 empty($this->_default_render_status_code) ? ($this->_default_render_status_code = 200) : null;
201 $this->_enableLayoutOnRender = !isset($this->_enableLayoutOnRender) ? true : $this->_enableLayoutOnRender;
202 $this->passed_args = !isset($this->Request->pass)? array() : $this->Request->pass;
203 empty($this->cookies) && isset($_COOKIE) ? ($this->cookies =& $_COOKIE) : null;
205 if(empty($this->Template)){
206 require_once(AK_LIB_DIR.DS.'AkActionView.php');
207 require_once(AK_LIB_DIR.DS.'AkActionView'.DS.'AkPhpTemplateHandler.php');
208 $this->Template =& new AkActionView($this->_getTemplateBasePath(),
209 $this->Request->getParameters(),$this->Request->getController());
211 $this->Template->_controllerInstance =& $this;
212 $this->Template->_registerTemplateHandler('tpl','AkPhpTemplateHandler');
216 function loadPlugins()
218 Ak::loadPlugins();
222 * Creates an instance of each available helper and links it into into current controller.
224 * Per example, if a helper TextHelper is located into the file text_helper.php.
225 * An instance is created on current controller
226 * at $this->text_helper. This instance is also available on the view by calling $text_helper.
228 * Helpers can be found at lib/AkActionView/helpers (this might change in a future)
230 function instantiateHelpers()
232 $helpers = $this->getDefaultHelpers();
233 $helpers = array_merge($helpers, $this->getApplicationHelpers());
234 $helpers = array_merge($helpers, $this->getPluginHelpers());
235 $helpers = array_merge($helpers, $this->getModuleHelper());
236 $helpers = array_merge($helpers, $this->getCurrentControllerHelper());
238 require_once(AK_LIB_DIR.DS.'AkActionView'.DS.'AkActionViewHelper.php');
240 $available_helpers = array();
241 foreach ($helpers as $file=>$helper){
242 $helper_class_name = strstr($helper, 'Helper') ? $helper : $helper.'Helper';
243 $full_path = preg_match('/[\\\\\/]+/',$file);
244 $file_path = $full_path ? $file : AK_LIB_DIR.DS.'AkActionView'.DS.'helpers'.DS.$file;
245 include_once($file_path);
246 if(class_exists($helper_class_name)){
247 $attribute_name = $full_path ? AkInflector::underscore($helper_class_name) : substr($file,0,-4);
248 $available_helpers[] = $attribute_name;
249 $this->$attribute_name =& new $helper_class_name(&$this);
250 if(method_exists($this->$attribute_name,'setController')){
251 $this->$attribute_name->setController(&$this);
253 if(method_exists($this->$attribute_name,'init')){
254 $this->$attribute_name->init();
258 defined('AK_ACTION_CONTROLLER_AVAILABLE_HELPERS') ? null : define('AK_ACTION_CONTROLLER_AVAILABLE_HELPERS', join(',',$available_helpers));
261 function getCurrentControllerHelper()
263 $helper = $this->getControllerName();
264 $helper = AkInflector::is_plural($helper)?AkInflector::singularize($helper):$helper;
265 $helper_file_name = AK_HELPERS_DIR.DS.$this->_module_path.AkInflector::underscore($helper).'_helper.php';
267 if(file_exists($helper_file_name)){
268 return array($helper_file_name => $helper);
270 return array();
273 function getModuleHelper()
275 $this->getControllerName(); // module name is set when we first retrieve the controller name
276 if(!empty($this->module_name)){
277 $helper_file_name = AK_HELPERS_DIR.DS.AkInflector::underscore($this->module_name).'_helper.php';
278 if(file_exists($helper_file_name)){
279 return array($helper_file_name => $this->module_name);
282 return array();
285 function getDefaultHelpers()
287 if($this->helpers == 'default'){
288 $available_helpers = Ak::dir(AK_LIB_DIR.DS.'AkActionView'.DS.'helpers',array('dirs'=>false));
289 $helper_names = array();
290 foreach ($available_helpers as $available_helper){
291 $helper_names[$available_helper] = AkInflector::classify(substr($available_helper,0,-10));
293 return $helper_names;
294 }elseif (is_string($this->helpers)){
295 return Ak::stringToArray($this->helpers);
297 return $this->helpers;
300 function getApplicationHelpers()
302 $helper_names = array();
303 if ($this->app_helpers == 'all'){
304 $available_helpers = Ak::dir(AK_HELPERS_DIR,array('dirs'=>false));
305 $helper_names = array();
306 foreach ($available_helpers as $available_helper){
307 $helper_names[AK_HELPERS_DIR.DS.$available_helper] = AkInflector::classify(substr($available_helper,0,-10));
310 } elseif (!empty($this->app_helpers)){
311 foreach (Ak::toArray($this->app_helpers) as $helper_name){
312 $helper_names[AK_HELPERS_DIR.DS.AkInflector::underscore($helper_name).'_helper.php'] = AkInflector::camelize($helper_name);
315 return $helper_names;
318 function getPluginHelpers()
320 $helper_names = AkActionController::addPluginHelper(false); // Trick for getting helper names set by AkPlugin::addHelper
321 if(empty($helper_names)){
322 return array();
323 }elseif ($this->plugin_helpers == 'all'){
324 return $helper_names;
325 }else {
326 $selected_helper_names = array();
327 foreach (Ak::toArray($this->plugin_helpers) as $helper_name){
328 $helper_name = AkInflector::camelize($helper_name);
329 if($path = array_shift(array_keys($helper_names, AkInflector::camelize($helper_name)))){
330 $selected_helper_names[$path] = $helper_names[$path];
333 return $selected_helper_names;
338 * Used for adding helpers to the base class like those added by the plugins engine.
340 * @param string $helper_name Helper class name like CalendarHelper
341 * @param array $options - path: Path to the helper class, defaults to AK_PLUGINS_DIR/helper_name/lib/helper_name.php
343 function addPluginHelper($helper_name, $options = array())
345 static $helpers = array();
346 if($helper_name === false){
347 return $helpers;
349 $underscored_helper_name = AkInflector::underscore($helper_name);
350 $default_options = array(
351 'path' => AK_PLUGINS_DIR.DS.$underscored_helper_name.DS.'lib'.DS.$underscored_helper_name.'.php'
353 $options = array_merge($default_options, $options);
354 $helpers[$options['path']] = $helper_name;
357 function _validateGeneratedXhtml()
359 require_once(AK_LIB_DIR.DS.'AkXhtmlValidator.php');
360 $XhtmlValidator = new AkXhtmlValidator();
361 if($XhtmlValidator->validate($this->Response->body) === false){
362 $this->Response->sendHeaders();
363 echo '<h1>'.Ak::t('Ooops! There are some errors on current XHTML page').'</h1>';
364 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";
365 $XhtmlValidator->showErrors();
366 echo "<hr /><h2>".Ak::t('Showing XHTML code')."</h2><hr /><div style='border:5px solid red;margin:5px;padding:15px;'>".$this->Response->body."</pre>";
367 die();
373 * Methods for loading desired models into this controller
375 function setModel($model)
377 $this->instantiateIncludedModelClasses(array($model));
380 function setModels($models)
382 $this->instantiateIncludedModelClasses($models);
385 function instantiateIncludedModelClasses($models = array())
387 require_once(AK_LIB_DIR.DS.'AkActiveRecord.php');
388 require_once(AK_APP_DIR.DS.'shared_model.php');
390 empty($this->model) ? ($this->model = $this->params['controller']) : null;
391 empty($this->models) ? ($this->models = array()) : null;
393 $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))));
395 foreach ($models as $model){
396 $this->instantiateModelClass($model, (empty($this->finder_options[$model])?array():$this->finder_options[$model]));
400 function instantiateModelClass($model_class_name, $finder_options = array())
402 $underscored_model_class_name = AkInflector::underscore($model_class_name);
403 $controller_name = $this->getControllerName();
404 $id = empty($this->params[$underscored_model_class_name]['id']) ?
405 (empty($this->params['id']) ? false :
406 (($model_class_name == $controller_name || $model_class_name == AkInflector::singularize($controller_name)) ? $this->params['id'] : false)) :
407 $this->params[$underscored_model_class_name]['id'];
409 if(class_exists($model_class_name)){
410 $underscored_model_class_name = AkInflector::underscore($model_class_name);
412 if(!isset($this->$model_class_name) || !isset($this->$underscored_model_class_name)){
413 if($finder_options !== false && is_numeric($id)){
414 $model =& new $model_class_name();
415 if(empty($finder_options)){
416 $model =& $model->find($id);
417 }else{
418 $model =& $model->find($id, $finder_options);
420 }else{
421 $model =& new $model_class_name();
423 if(!isset($this->$model_class_name)){
424 $this->$model_class_name =& $model;
426 if(!isset($this->$underscored_model_class_name)){
427 $this->$underscored_model_class_name =& $model;
436 Rendering content
437 ====================================================================
441 * Renders the content that will be returned to the browser as the Response body.
443 * === Rendering an action
445 * Action rendering is the most common form and the type used automatically by
446 * Action Controller when nothing else is specified. By default, actions are
447 * rendered within the current layout (if one exists).
449 * * Renders the template for the action "goal" within the current controller
451 * $this->render(array('action'=>'goal'));
453 * * Renders the template for the action "short_goal" within the current controller,
454 * but without the current active layout
456 * $this->render(array('action'=>'short_goal','layout'=>false));
458 * * Renders the template for the action "long_goal" within the current controller,
459 * but with a custom layout
461 * $this->render(array('action'=>'long_goal','layout'=>'spectacular'));
463 * === Rendering partials
465 * Partial rendering is most commonly used together with Ajax calls that only update
466 * one or a few elements on a page without reloading. Rendering of partials from
467 * the controller makes it possible to use the same partial template in
468 * both the full-page rendering (by calling it from within the template) and when
469 * sub-page updates happen (from the controller action responding to Ajax calls).
470 * By default, the current layout is not used.
472 * * Renders the partial located at app/views/controller/_win.tpl
474 * $this->render(array('partial'=>'win'));
476 * * Renders the partial with a status code of 500 (internal error)
478 * $this->render(array('partial'=>'broken','status'=>500));
480 * * Renders the same partial but also makes a local variable available to it
482 * $this->render(array('partial' => 'win', 'locals' => array('name'=>'david')));
484 * * Renders a collection of the same partial by making each element of $wins available through
485 * the local variable "win" as it builds the complete Response
487 * $this->render(array('partial'=>'win','collection'=>$wins));
489 * * Renders the same collection of partials, but also renders the win_divider partial in between
490 * each win partial.
492 * $this->render(array('partial'=>'win','collection'=>$wins,'spacer_template'=>'win_divider'));
494 * === Rendering a template
496 * Template rendering works just like action rendering except that it takes a
497 * path relative to the template root.
498 * The current layout is automatically applied.
500 * * Renders the template located in app/views/weblog/show.tpl
501 * $this->render(array('template'=>'weblog/show'));
503 * === Rendering a file
505 * File rendering works just like action rendering except that it takes a
506 * filesystem path. By default, the path is assumed to be absolute, and the
507 * current layout is not applied.
509 * * Renders the template located at the absolute filesystem path
510 * $this->render(array('file'=>'/path/to/some/template.tpl'));
511 * $this->render(array('file'=>'c:/path/to/some/template.tpl'));
513 * * Renders a template within the current layout, and with a 404 status code
514 * $this->render(array('file' => '/path/to/some/template.tpl', 'layout' => true, 'status' => 404));
515 * $this->render(array('file' => 'c:/path/to/some/template.tpl', 'layout' => true, 'status' => 404));
517 * * Renders a template relative to the template root and chooses the proper file extension
518 * $this->render(array('file' => 'some/template', 'use_full_path' => true));
521 * === Rendering text
523 * Rendering of text is usually used for tests or for rendering prepared content,
524 * such as a cache. By default, text
525 * rendering is not done within the active layout.
527 * * Renders the clear text "hello world" with status code 200
528 * $this->render(array('text' => 'hello world!'));
530 * * Renders the clear text "Explosion!" with status code 500
531 * $this->render(array('text' => "Explosion!", 'status' => 500 ));
533 * * Renders the clear text "Hi there!" within the current active layout (if one exists)
534 * $this->render(array('text' => "Explosion!", 'layout' => true));
536 * * Renders the clear text "Hi there!" within the layout
537 * * placed in "app/views/layouts/special.tpl"
538 * $this->render(array('text' => "Explosion!", 'layout => "special"));
541 * === Rendering an inline template
543 * Rendering of an inline template works as a cross between text and action
544 * rendering where the source for the template
545 * is supplied inline, like text, but its evaled by PHP, like action. By default,
546 * PHP is used for rendering and the current layout is not used.
548 * * Renders "hello, hello, hello, again"
549 * $this->render(array('inline' => "<?php echo str_repeat('hello, ', 3).'again'?>" ));
551 * * Renders "hello david"
552 * $this->render(array('inline' => "<?php echo 'hello ' . $name ?>", 'locals' => array('name' => 'david')));
555 * === Rendering nothing
557 * Rendering nothing is often convenient in combination with Ajax calls that
558 * perform their effect client-side or
559 * when you just want to communicate a status code. Due to a bug in Safari, nothing
560 * actually means a single space.
562 * * Renders an empty Response with status code 200
563 * $this->render(array('nothing' => true));
565 * * Renders an empty Response with status code 401 (access denied)
566 * $this->render(array('nothing' => true, 'status' => 401));
568 function render($options = null, $status = 200)
570 if(empty($options['partial']) && $this->_hasPerformed()){
571 $this->_doubleRenderError(Ak::t("Can only render or redirect once per action"));
572 return false;
575 $this->_flash_handled ? null : $this->_handleFlashAttribute();
577 if(!is_array($options)){
578 return $this->renderFile(empty($options) ? $this->getDefaultTemplateName() : $options, $status, true);
581 if(!empty($options['text'])){
582 return $this->renderText($options['text'], @$options['status']);
583 }else{
585 if(!empty($options['file'])){
586 return $this->renderFile($options['file'], @$options['status'], @$options['use_full_path'], @(array)$options['locals']);
587 }elseif(!empty($options['template'])){
588 return $this->renderFile($options['template'], @$options['status'], true);
589 }elseif(!empty($options['inline'])){
590 return $this->renderTemplate($options['inline'], @$options['status'], @$options['type'], @(array)$options['locals']);
591 }elseif(!empty($options['action'])){
592 return $this->renderAction($options['action'], @$options['status'], @$options['layout']);
593 }elseif(!empty($options['partial'])){
594 if($options['partial'] === true){
595 $options['partial'] = !empty($options['template']) ? $options['template'] : $this->getDefaultTemplateName();
597 if(!empty($options['collection'])){
598 return $this->renderPartialCollection($options['partial'], $options['collection'], @$options['spacer_template'], @$options['locals'], @$options['status']);
599 }else{
600 return $this->renderPartial($options['partial'], @$options['object'], @$options['locals'], @$options['status']);
602 }elseif(!empty($options['nothing'])){
603 // Safari doesn't pass the _headers of the return if the Response is zero length
604 return $this->renderText(' ', @$options['status']);
605 }else{
606 return $this->renderFile($this->getDefaultTemplateName(), @$options['status'], true);
608 return true;
613 * Renders according to the same rules as <tt>render</tt>, but returns the result in a string instead
614 * of sending it as the Response body to the browser.
616 function renderToString($options = null)
618 $result = $this->render($options);
619 $this->eraseRenderResults();
620 $this->variables_added = null;
621 $this->Template->_assigns_added = null;
622 return $result;
625 function renderAction($_action_name, $status = null, $with_layout = true)
627 $this->$_action_name();
628 $template = $this->getDefaultTemplateName($_action_name);
629 if(!empty($with_layout) && !$this->_isTemplateExemptFromLayout($template)){
630 return $this->renderWithLayout($template, $status, $with_layout);
631 }else{
632 return $this->renderWithoutLayout($template, $status);
636 function renderFile($template_path, $status = null, $use_full_path = false, $locals = array())
638 $this->_addVariablesToAssigns();
639 $locals = array_merge($locals,$this->_assigns);
641 if($use_full_path){
642 $this->_assertExistanceOfTemplateFile($template_path);
645 AK_LOG_EVENTS && !empty($this->_Logger) ? $this->_Logger->message("Rendering $this->full_template_path" . (!empty($status) ? " ($status)":'')) : null;
647 return $this->renderText($this->Template->renderFile($template_path, $use_full_path, $locals), $status);
650 function renderTemplate($template, $status = null, $type = 'tpl', $local_assigns = array())
652 $this->_addVariablesToAssigns();
653 $local_assigns = array_merge($local_assigns,$this->_assigns);
654 return $this->renderText($this->Template->renderTemplate($type, $template, null, $local_assigns), $status);
657 function renderText($text = null, $status = null)
659 $this->performed_render = true;
660 $this->Response->_headers['Status'] = !empty($status) ? $status : $this->_default_render_status_code;
661 $this->Response->body = $text;
662 return $text;
665 function renderNothing($status = null)
667 return $this->renderText(' ', $status);
670 function renderPartial($partial_path = null, $object = null, $local_assigns = null, $status = null)
672 $partial_path = empty($partial_path) ? $this->getDefaultTemplateName() : $partial_path;
673 $this->variables_added = false;
674 $this->performed_render = false;
675 $this->_addVariablesToAssigns();
676 $this->Template->controller =& $this;
677 $this->$partial_path = $this->renderText($this->Template->renderPartial($partial_path, $object, array_merge($this->_assigns, (array)$local_assigns)), $status);
678 return $this->$partial_path;
681 function renderPartialCollection($partial_name, $collection, $partial_spacer_template = null, $local_assigns = null, $status = null)
683 $this->_addVariablesToAssigns();
684 $collection_name = AkInflector::pluralize($partial_name).'_collection';
685 $result = $this->Template->renderPartialCollection($partial_name, $collection, $partial_spacer_template, $local_assigns);
686 if(empty($this->$collection_name)){
687 $this->$collection_name = $result;
689 $this->variables_added = false;
690 $this->performed_render = false;
692 return $result;
695 function renderWithLayout($template_name = null, $status = null, $layout = null)
697 $template_name = empty($template_name) ? $this->getDefaultTemplateName() : $template_name;
698 return $this->renderWithALayout($template_name, $status, $layout);
701 function renderWithoutLayout($template_name = null, $status = null)
703 $template_name = empty($template_name) ? $this->getDefaultTemplateName() : $template_name;
704 return $this->render($template_name, $status);
708 * Clears the rendered results, allowing for another render to be performed.
710 function eraseRenderResults()
712 $this->Response->body = '';
713 $this->performed_render = false;
714 $this->variables_added = false;
717 function _addVariablesToAssigns()
719 if(empty($this->variables_added)){
720 $this->_addInstanceVariablesToAssigns();
721 $this->variables_added = true;
725 function _addInstanceVariablesToAssigns()
727 $this->_protected_variables_cache = array_merge($this->_protected_variables_cache, $this->_getProtectedInstanceVariables());
729 foreach (array_diff(array_keys(get_object_vars($this)), $this->_protected_variables_cache) as $attribute){
730 if($attribute[0] != '_'){
731 $this->_assigns[$attribute] =& $this->$attribute;
736 function _getProtectedInstanceVariables()
738 return !empty($this->_view_controller_internals) ?
739 array('_assigns', 'performed_redirect', 'performed_render','db') :
740 array('_assigns', 'performed_redirect', 'performed_render', 'session', 'cookies',
741 'Template','db','helpers','models','layout','Response','Request',
742 'params','passed_args');
747 * Use this to translate strings in the scope of your controller
749 * @see Ak::t
751 function t($string, $array = null)
753 return Ak::t($string, $array, AkInflector::underscore($this->getControllerName()));
759 Redirects
760 ====================================================================
764 * Redirects the browser to the target specified in +options+. This parameter can take one of three forms:
766 * * <tt>Array</tt>: The URL will be generated by calling $this->UrlFor with the +options+.
767 * * <tt>String starting with protocol:// (like http://)</tt>: Is passed straight through
768 * as the target for redirection.
769 * * <tt>String not containing a protocol</tt>: The current protocol and host is prepended to the string.
770 * * <tt>back</tt>: Back to the page that issued the Request-> Useful for forms that are
771 * triggered from multiple places.
772 * Short-hand for redirectTo(Request->env["HTTP_REFERER"])
774 * Examples:
775 * redirectTo(array('action' => 'show', 'id' => 5));
776 * redirectTo('http://www.akelos.com');
777 * redirectTo('/images/screenshot.jpg');
778 * redirectTo('back');
780 * The redirection happens as a "302 Moved" header.
782 function redirectTo($options = array(), $parameters_for_method_reference = null)
784 if(is_string($options)) {
785 if(preg_match('/^\w+:\/\/.*/',$options)){
786 if($this->_hasPerformed()){
787 $this->_doubleRenderError();
789 AK_LOG_EVENTS && !empty($this->_Logger) ? $this->_Logger->message('Redirected to '.$options) : null;
790 $this->_handleFlashAttribute();
791 $this->Response->redirect($options);
792 $this->Response->redirected_to = $options;
793 $this->performed_redirect = true;
794 }elseif ($options == 'back'){
795 $this->redirectTo($this->Request->env['HTTP_REFERER']);
796 }else{
797 $this->redirectTo($this->Request->getProtocol(). $this->Request->getHostWithPort(). $options);
799 }else{
800 if(empty($parameters_for_method_reference)){
801 $this->redirectTo($this->UrlFor($options));
802 $this->Response->redirected_to = $options;
803 }else{
804 $this->redirectTo($this->UrlFor($options, $parameters_for_method_reference));
805 $this->Response->redirected_to = $options;
806 $this->Response->redirected_to_method_params = $parameters_for_method_reference;
811 function redirectToAction($action, $options = array())
813 $this->redirectTo(array_merge(array('action'=>$action), $options));
818 * This methods are required for retrieving available controllers for URL Routing
820 function rewriteOptions($options)
822 $defaults = $this->defaultUrlOptions($options);
823 if(!empty($this->module_name)){
824 $defaults['module'] = $this->getModuleName();
826 if(!empty($options['controller']) && strstr($options['controller'], '/')){
827 $defaults['module'] = substr($options['controller'], 0, strrpos($options['controller'], '/'));
828 $options['controller'] = substr($options['controller'], strrpos($options['controller'], '/') + 1);
830 $options = !empty($defaults) ? array_merge($defaults, $options) : $options;
831 $options['controller'] = empty($options['controller']) ? AkInflector::underscore($this->getControllerName()) : $options['controller'];
832 return $options;
835 function getControllerName()
837 if(!isset($this->controller_name)){
838 $current_class_name = str_replace('_', '::', get_class($this));
839 if (!AK_PHP5){
840 $current_class_name = $this->__getControllerName_PHP4_fix($current_class_name);
842 $controller_name = substr($current_class_name,0,-10);
843 $this->controller_name = $this->_removeModuleNameFromControllerName($controller_name);
845 return $this->controller_name;
848 function __getControllerName_PHP4_fix($class_name)
850 $included_controllers = $this->_getIncludedControllerNames();
851 $lowercase_included_controllers = array_map('strtolower', $included_controllers);
852 $key = array_search(strtolower($class_name), $lowercase_included_controllers, true);
853 return $included_controllers[$key];
856 function getModuleName()
858 return $this->module_name;
861 function setModuleName($module_name)
863 return $this->module_name = $module_name;
867 * Removes the modules name from the controller if exists and sets it.
869 * @return $controller_name
871 function _removeModuleNameFromControllerName($controller_name)
873 if(strstr($controller_name, '::')){
874 $module_parts = explode ('::',$controller_name);
875 $controller_name = array_pop($module_parts);
876 $this->setModuleName(join('/', array_map(array('AkInflector','underscore'), $module_parts)));
878 return $controller_name;
881 function _getTemplateBasePath()
883 return AK_APP_DIR.DS.'views'.DS.(empty($this->_module_path)?'':$this->_module_path).$this->Request->getController();
886 function _getIncludedControllerNames()
888 $controllers = array();
889 foreach (get_included_files() as $file_name){
890 if(strstr($file_name,AK_CONTROLLERS_DIR)){
891 $controllers[] = AkInflector::classify(str_replace(array(AK_CONTROLLERS_DIR.DS,'.php', DS, '//'),array('','','/', '/'),$file_name));
894 return $controllers;
901 URL generation/rewriting
902 ====================================================================
907 * Overwrite to implement a number of default options that all urlFor-based methods will use.
908 * The default options should come in
909 * the form of a an array, just like the one you would use for $this->UrlFor directly. Example:
911 * function defaultUrlOptions($options)
913 * return array('project' => ($this->Project->isActive() ? $this->Project->url_name : 'unknown'));
916 * As you can infer from the example, this is mostly useful for situations where you want to
917 * centralize dynamic decisions about the urls as they stem from the business domain.
918 * Please note that any individual $this->UrlFor call can always override the defaults set
919 * by this method.
921 function defaultUrlOptions($options)
927 * Returns a URL that has been rewritten according to the options array and the defined Routes.
928 * (For doing a complete redirect, use redirectTo).
930 * <tt>$this->UrlFor</tt> is used to:
932 * All keys given to $this->UrlFor are forwarded to the Route module, save for the following:
933 * * <tt>anchor</tt> -- specifies the anchor name to be appended to the path. For example,
934 * <tt>$this->UrlFor(array('controller' => 'posts', 'action' => 'show', 'id' => 10, 'anchor' => 'comments'</tt>
935 * will produce "/posts/show/10#comments".
936 * * <tt>only_path</tt> -- if true, returns the absolute URL (omitting the protocol, host name, and port)
937 * * <tt>trailing_slash</tt> -- if true, adds a trailing slash, as in "/archive/2005/". Note that this
938 * is currently not recommended since it breaks caching.
939 * * <tt>host</tt> -- overrides the default (current) host if provided
940 * * <tt>protocol</tt> -- overrides the default (current) protocol if provided
942 * The URL is generated from the remaining keys in the array. A URL contains two key parts: the <base> and a query string.
943 * Routes composes a query string as the key/value pairs not included in the <base>.
945 * The default Routes setup supports a typical Akelos Framework path of "controller/action/id"
946 * where action and id are optional, with
947 * action defaulting to 'index' when not given. Here are some typical $this->UrlFor statements
948 * and their corresponding URLs:
950 * $this->UrlFor(array('controller'=>'posts','action'=>'recent')); // 'proto://host.com/posts/recent'
951 * $this->UrlFor(array('controller'=>'posts','action'=>'index')); // 'proto://host.com/posts'
952 * $this->UrlFor(array('controller'=>'posts','action'=>'show','id'=>10)); // 'proto://host.com/posts/show/10'
954 * When generating a new URL, missing values may be filled in from the current
955 * Request's parameters. For example,
956 * <tt>$this->UrlFor(array('action'=>'some_action'));</tt> will retain the current controller,
957 * as expected. This behavior extends to other parameters, including <tt>controller</tt>,
958 * <tt>id</tt>, and any other parameters that are placed into a Route's path.
960 * The URL helpers such as <tt>$this->UrlFor</tt> have a limited form of memory:
961 * when generating a new URL, they can look for missing values in the current Request's parameters.
962 * Routes attempts to guess when a value should and should not be
963 * taken from the defaults. There are a few simple rules on how this is performed:
965 * * If the controller name begins with a slash, no defaults are used: <tt>$this->UrlFor(array('controller'=>'/home'));</tt>
966 * * If the controller changes, the action will default to index unless provided
968 * The final rule is applied while the URL is being generated and is best illustrated by an example. Let us consider the
969 * route given by <tt>map->connect('people/:last/:first/:action', array('action' => 'bio', 'controller' => 'people'))</tt>.
971 * Suppose that the current URL is "people/hh/david/contacts". Let's consider a few
972 * different cases of URLs which are generated from this page.
974 * * <tt>$this->UrlFor(array('action'=>'bio'));</tt> -- During the generation of this URL,
975 * default values will be used for the first and
976 * last components, and the action shall change. The generated URL will be, "people/hh/david/bio".
977 * * <tt>$this->UrlFor(array('first'=>'davids-little-brother'));</tt> This
978 * generates the URL 'people/hh/davids-little-brother' -- note
979 * that this URL leaves out the assumed action of 'bio'.
981 * However, you might ask why the action from the current Request, 'contacts', isn't
982 * carried over into the new URL. The answer has to do with the order in which
983 * the parameters appear in the generated path. In a nutshell, since the
984 * value that appears in the slot for <tt>first</tt> is not equal to default value
985 * for <tt>first</tt> we stop using defaults. On it's own, this rule can account
986 * for much of the typical Akelos Framework URL behavior.
988 * Although a convienence, defaults can occasionaly get in your way. In some cases
989 * a default persists longer than desired.
990 * The default may be cleared by adding <tt>'name' => null</tt> to <tt>$this->UrlFor</tt>'s options.
991 * This is often required when writing form helpers, since the defaults in play
992 * may vary greatly depending upon where the helper is used from. The following line
993 * will redirect to PostController's default action, regardless of the page it is
994 * displayed on:
996 * $this->UrlFor(array('controller' => 'posts', 'action' => null));
998 * If you explicitly want to create a URL that's almost the same as the current URL, you can do so using the
999 * overwrite_params options. Say for your posts you have different views for showing and printing them.
1000 * Then, in the show view, you get the URL for the print view like this
1002 * $this->UrlFor(array('overwrite_params' => array('action' => 'print')));
1004 * This takes the current URL as is and only exchanges the action. In contrast,
1005 * <tt>$this->UrlFor(array('action'=>'print'));</tt>
1006 * would have slashed-off the path components after the changed action.
1008 function urlFor($options = array(), $parameters_for_method_reference = null)
1010 return $this->rewrite($this->rewriteOptions($options));
1013 function addToUrl($options = array(), $options_to_exclude = array())
1015 $options_to_exclude = array_merge(array('ak','lang',AK_SESSION_NAME,'AK_SESSID','PHPSESSID'), $options_to_exclude);
1016 $options = array_merge(array_merge(array('action'=>$this->Request->getAction()),$this->params),$options);
1017 foreach ($options_to_exclude as $option_to_exclude){
1018 unset($options[$option_to_exclude]);
1020 return $this->urlFor($options);
1023 function getActionName()
1025 return $this->Request->getAction();
1029 function _doubleRenderError($message = null)
1031 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);
1034 function _hasPerformed()
1036 return !empty($this->performed_render) || !empty($this->performed_redirect);
1039 function _getRequestOrigin()
1041 return $this->Request->remote_ip.' at '.Ak::getDate();
1044 function _getCompleteRequestUri()
1046 return $this->Request->protocol . $this->Request->host . $this->Request->request_uri;
1049 function _closeSession()
1051 !empty($this->session) ? session_write_close() : null;
1055 function _hasTemplate($template_name = null)
1057 return file_exists(empty($template_name) ? $this->getDefaultTemplateName() : $template_name);
1060 function _templateIsPublic($template_name = null)
1062 $template_name = empty($template_name) ? $this->getDefaultTemplateName() : $template_name;
1063 return $this->Template->fileIsPublic($template_name);
1066 function _isTemplateExemptFromLayout($template_name = null)
1068 $template_name = empty($template_name) ? $this->getDefaultTemplateName() : $template_name;
1069 return $this->Template->_javascriptTemplateExists($template_name);
1072 function _assertExistanceOfTemplateFile($template_name)
1074 $extension = $this->Template->delegateTemplateExists($template_name);
1075 $this->full_template_path = $this->Template->getFullTemplatePath($template_name, $extension ? $extension : 'tpl');
1076 if(!$this->_hasTemplate($this->full_template_path)){
1077 if(!empty($this->_ignore_missing_templates) && $this->_ignore_missing_templates === true){
1078 return;
1080 $template_type = strstr($template_name,'layouts') ? 'layout' : 'template';
1081 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);
1085 function getDefaultTemplateName($default_action_name = null)
1087 return empty($default_action_name) ? (empty($this->_default_template_name) ? $this->_action_name : $this->_default_template_name) : $default_action_name;
1090 function setDefaultTemplateName($template_name)
1092 $this->_default_template_name = $template_name;
1097 function rewrite($options = array())
1099 return $this->_rewriteUrl($this->_rewritePath($options), $options);
1103 function toString()
1105 return $this->Request->getProtocol().$this->Request->getHostWithPort().
1106 $this->Request->getPath().@$this->parameters['controller'].
1107 @$this->parameters['action'].@$this->parameters['inspect'];
1111 * Given a path and options, returns a rewritten URL string
1113 function _rewriteUrl($path, $options)
1115 $rewritten_url = '';
1116 if(empty($options['only_path'])){
1117 $rewritten_url .= !empty($options['protocol']) ? $options['protocol'] : $this->Request->getProtocol();
1118 $rewritten_url .= empty($rewritten_url) || strpos($rewritten_url,'://') ? '' : '://';
1119 $rewritten_url .= $this->_rewriteAuthentication($options);
1120 $rewritten_url .= !empty($options['host']) ? $options['host'] : $this->Request->getHostWithPort();
1121 $options = Ak::delete($options, array('user','password','host','protocol'));
1124 $rewritten_url .= empty($options['skip_relative_url_root']) ? $this->Request->getRelativeUrlRoot() : '';
1126 if(empty($options['skip_url_locale'])){
1127 $locale = $this->Request->getLocaleFromUrl();
1128 if(empty($options['lang'])){
1129 $rewritten_url .= (empty($locale) ? '' : '/').$locale;
1134 $rewritten_url .= (substr($rewritten_url,-1) == '/' ? '' : (AK_URL_REWRITE_ENABLED ? '' : (!empty($path[0]) && $path[0] != '/' ? '/' : '')));
1135 $rewritten_url .= $path;
1136 $rewritten_url .= empty($options['trailing_slash']) ? '' : '/';
1137 $rewritten_url .= empty($options['anchor']) ? '' : '#'.$options['anchor'];
1139 return $rewritten_url;
1142 function _rewriteAuthentication($options)
1144 if(!isset($options['user']) && isset($options['password'])){
1145 return urlencode($options['user']).':'.urlencode($options['password']).'@';
1146 }else{
1147 return '';
1151 function _rewritePath($options)
1153 if(!empty($options['params'])){
1154 foreach ($options['params'] as $k=>$v){
1155 $options[$k] = $v;
1157 unset($options['params']);
1159 if(!empty($options['overwrite_params'])){
1160 foreach ($options['overwrite_params'] as $k=>$v){
1161 $options[$k] = $v;
1163 unset($options['overwrite_params']);
1165 foreach (array('anchor', 'params', 'only_path', 'host', 'protocol', 'trailing_slash', 'skip_relative_url_root') as $k){
1166 unset($options[$k]);
1168 $path = Ak::toUrl($options);
1169 return $path;
1173 * Returns a query string with escaped keys and values from the passed array. If the passed
1174 * array contains an 'id' it'll
1175 * be added as a path element instead of a regular parameter pair.
1177 function buildQueryString($array, $only_keys = null)
1179 $array = !empty($only_keys) ? array_keys($array) : $array;
1180 return Ak::toUrl($array);
1187 Layouts
1188 ====================================================================
1190 * Layouts reverse the common pattern of including shared headers and footers in many templates
1191 * to isolate changes in repeated setups. The inclusion pattern has pages that look like this:
1193 * <?php echo $controller->render('shared/header') ?>
1194 * Hello World
1195 * <?php echo $controller->render('shared/footer') ?>
1197 * This approach is a decent way of keeping common structures isolated from the
1198 * changing content, but it's verbose and if( you ever want to change the structure
1199 * of these two includes, you'll have to change all the templates.
1201 * With layouts, you can flip it around and have the common structure know where
1202 * to insert changing content. This means that the header and footer are only
1203 * mentioned in one place, like this:
1205 * <!-- The header part of this layout -->
1206 * <?php echo $content_for_layout ?>
1207 * <!-- The footer part of this layout -->
1209 * And then you have content pages that look like this:
1211 * hello world
1213 * Not a word about common structures. At rendering time, the content page is
1214 * computed and then inserted in the layout,
1215 * like this:
1217 * <!-- The header part of this layout -->
1218 * hello world
1219 * <!-- The footer part of this layout -->
1221 * == Accessing shared variables
1223 * Layouts have access to variables specified in the content pages and vice versa.
1224 * This allows you to have layouts with references that won't materialize before
1225 * rendering time:
1227 * <h1><?php echo $page_title ?></h1>
1228 * <?php echo $content_for_layout ?>
1230 * ...and content pages that fulfill these references _at_ rendering time:
1232 * <?php $page_title = 'Welcome'; ?>
1233 * Off-world colonies offers you a chance to start a new life
1235 * The result after rendering is:
1237 * <h1>Welcome</h1>
1238 * Off-world colonies offers you a chance to start a new life
1240 * == Automatic layout assignment
1242 * If there is a template in <tt>app/views/layouts/</tt> with the same name as
1243 * the current controller then it will be automatically
1244 * set as that controller's layout unless explicitly told otherwise. Say you have
1245 * a WeblogController, for example. If a template named <tt>app/views/layouts/weblog.tpl</tt>
1246 * exists then it will be automatically set as the layout for your WeblogController.
1247 * You can create a layout with the name <tt>application.tpl</tt>
1248 * and this will be set as the default controller if there is no layout with
1249 * the same name as the current controller and there is no layout explicitly
1250 * assigned on the +layout+ attribute. Setting a layout explicitly will always
1251 * override the automatic behaviour
1252 * for the controller where the layout is set. Explicitly setting the layout
1253 * in a parent class, though, will not override the
1254 * child class's layout assignement if the child class has a layout with the same name.
1256 * == Inheritance for layouts
1258 * Layouts are shared downwards in the inheritance hierarchy, but not upwards. Examples:
1260 * class BankController extends AkActionController
1262 * var $layout = 'bank_standard';
1265 * class InformationController extends BankController
1269 * class VaultController extends BankController
1271 * var $layout = 'access_level_layout';
1274 * class EmployeeController extends BankController
1276 * var $layout = null;
1279 * The InformationController uses 'bank_standard' inherited from the BankController, the VaultController
1280 * and picks the layout 'access_level_layout', and the EmployeeController doesn't want to use a layout at all.
1282 * == Types of layouts
1284 * Layouts are basically just regular templates, but the name of this template needs not be specified statically. Sometimes
1285 * you want to alternate layouts depending on runtime information, such as whether someone is logged in or not. This can
1286 * be done either by an inline method.
1288 * The method reference is the preferred approach to variable layouts and is used like this:
1290 * class WeblogController extends AkActionController
1292 * function __construct()
1294 * $this->setLayout(array(&$this, '_writersAndReaders'));
1297 * function index()
1299 * // fetching posts
1302 * function _writersAndReaders()
1304 * return is_logged_in() ? 'writer_layout' : 'reader_layout';
1308 * Now when a new request for the index action is processed, the layout will vary depending on whether the person accessing
1309 * is logged in or not.
1311 * The most common way of specifying a layout is still just as a plain template name:
1313 * class WeblogController extends AkActionController
1315 * var $layout = 'weblog_standard';
1318 * If no directory is specified for the template name, the template will by default by looked for in +app/views/layouts/+.
1320 * == Conditional layouts
1322 * If you have a layout that by default is applied to all the actions of a controller, you still have the option of rendering
1323 * 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
1324 * <tt>only</tt> and <tt>except</tt> options can be passed to the layout call. For example:
1326 * class WeblogController extends AkActionController
1328 * function __construct()
1330 * $this->setLayout('weblog_standard', array('except' => 'rss'));
1333 * // ...
1337 * This will assign 'weblog_standard' as the WeblogController's layout except for the +rss+ action, which will not wrap a layout
1338 * around the rendered view.
1340 * Both the <tt>only</tt> and <tt>except</tt> condition can accept an arbitrary number of method names, so
1341 * <tt>'except' => array('rss', 'text_only')</tt> is valid, as is <tt>'except' => 'rss'</tt>.
1343 * == Using a different layout in the action render call
1345 * If most of your actions use the same layout, it makes perfect sense to define a controller-wide layout as described above.
1346 * Some times you'll have exceptions, though, where one action wants to use a different layout than the rest of the controller.
1347 * This is possible using the <tt>render</tt> method. It's just a bit more manual work as you'll have to supply fully
1348 * qualified template and layout names as this example shows:
1350 * class WeblogController extends AkActionController
1352 * function help()
1354 * $this->render(array('action'=>'help/index','layout'=>'help'));
1360 * If a layout is specified, all actions rendered through render and render_action will have their result assigned
1361 * to <tt>$this->content_for_layout</tt>, which can then be used by the layout to insert their contents with
1362 * <tt><?php echo $$this->content_for_layout ?></tt>. This layout can itself depend on instance variables assigned during action
1363 * performance and have access to them as any normal template would.
1365 function setLayout($template_name, $conditions = array())
1367 $this->_addLayoutConditions($conditions);
1368 $this->layout = $template_name;
1371 function getLayoutConditions()
1373 return empty($this->_layout_conditions) ? array() : $this->_layout_conditions;
1376 function _addLayoutConditions($conditions)
1378 $this->_layout_conditions = $conditions;
1384 * Returns the name of the active layout. If the layout was specified as a method reference, this method
1385 * is called and the return value is used. Likewise if( the layout was specified as an inline method (through a method
1386 * object). If the layout was defined without a directory, layouts is assumed. So <tt>setLayout('weblog/standard')</tt> will return
1387 * weblog/standard, but <tt>setLayout('standard')</tt> will return layouts/standard.
1389 function getActiveLayout($passed_layout = null)
1391 if(empty($passed_layout)){
1392 $layout = !isset($this->layout) ? AkInflector::underscore($this->getControllerName()) : $this->layout;
1393 }else{
1394 $layout =& $passed_layout;
1396 if(is_array($layout) && is_object($layout[0]) && method_exists($layout[0], $layout[1])){
1397 $this->active_layout = $layout[0]->{$layout[1]}();
1398 }elseif(method_exists($this,$layout) && strtolower(get_class($this)) !== strtolower($layout)){
1399 $this->active_layout = $this->$layout();
1400 }else{
1401 $this->active_layout = $layout;
1404 if(!empty($this->active_layout)){
1405 return strstr($this->active_layout,DS) ? $this->active_layout : 'layouts'.DS.$this->active_layout;
1410 function renderWithALayout($options = null, $status = null, $layout = null)
1412 $template_with_options = !empty($options) && is_array($options);
1414 if($this->_canApplyLayout($template_with_options, $options) && ($layout = $this->_pickLayout($template_with_options, $options, $layout))){
1416 $options = $template_with_options? array_merge((array)$options,array('layout'=>false)) : $options;
1418 $this->content_for_layout = $this->render($options, $status);
1420 if($template_with_options){
1421 $status = empty($options['status']) ? $status : $options['status'];
1424 $this->eraseRenderResults();
1425 $this->_addVariablesToAssigns();
1427 return $this->renderText($this->Template->renderFile($layout, true, &$this->_assigns), $status);
1428 }else{
1429 return $this->render($options, $status, &$this->_assigns);
1433 function _canApplyLayout($template_with_options, $options)
1435 return !empty($template_with_options) ? $this->_isCandidateForLayout($options) : !$this->_isTemplateExemptFromLayout();
1438 function _isCandidateForLayout($options)
1440 return !empty($options['layout']) ||
1441 (empty($options['text']) && empty($options['file']) && empty($options['inline']) && empty($options['partial']) && empty($options['nothing'])) &&
1442 !$this->_isTemplateExemptFromLayout($this->_getDefaultTemplateName(empty($options['action']) ? $options['template'] : $options['action']));
1445 function _pickLayout($template_with_options, $options, $layout = null)
1447 if(!empty($template_with_options)){
1448 $layout = empty($options['layout']) ? ($this->_doesActionHasLayout() ? $this->getActiveLayout(): false) : $this->getActiveLayout($options['layout']);
1449 }elseif(empty($layout) || $layout === true){
1450 $layout = $this->_doesActionHasLayout() ? $this->getActiveLayout() : false;
1452 if(!empty($layout)){
1453 $layout = strstr($layout,'/') || strstr($layout,DS) ? $layout : 'layouts'.DS.$layout;
1454 $layout = substr($layout,0,7) === 'layouts' ?
1455 (empty($this->_module_path) ? AK_VIEWS_DIR.DS.$layout.'.tpl' : AK_VIEWS_DIR.DS.'layouts'.DS.trim($this->_module_path, DS).'.tpl') :
1456 $layout.'.tpl';
1457 if (file_exists($layout)) {
1458 return $layout;
1460 $layout = null;
1462 if(empty($layout) && $layout !== false && defined('AK_DEFAULT_LAYOUT')){
1463 $layout = AK_VIEWS_DIR.DS.'layouts'.DS.AK_DEFAULT_LAYOUT.'.tpl';
1465 return file_exists($layout) ? $layout : false;
1468 function _doesActionHasLayout()
1470 $conditions = $this->getLayoutConditions();
1472 $action_name = $this->Request->getAction();
1473 if(!empty($conditions['only']) && ((is_array($conditions['only']) && in_array($action_name,$conditions['only'])) ||
1474 (is_string($conditions['only']) && $action_name == $conditions['only']))){
1475 return true;
1476 }elseif (!empty($conditions['only'])){
1477 return false;
1479 if(!empty($conditions['except']) && ((is_array($conditions['except']) && in_array($action_name,$conditions['except'])) ||
1480 (is_string($conditions['except']) && $action_name == $conditions['except']))){
1481 return false;
1484 return true;
1491 Filters
1492 ====================================================================
1494 * Filters enable controllers to run shared pre and post processing code for its actions. These filters can be used to do
1495 * authentication, caching, or auditing before the intended action is performed. Or to do localization or output
1496 * compression after the action has been performed.
1498 * Filters have access to the request, response, and all the instance variables set by other filters in the chain
1499 * or by the action (in the case of after filters). Additionally, it's possible for a pre-processing <tt>beforeFilter</tt>
1500 * to halt the processing before the intended action is processed by returning false or performing a redirect or render.
1501 * This is especially useful for filters like authentication where you're not interested in allowing the action to be
1502 * performed if the proper credentials are not in order.
1504 * == Filter inheritance
1506 * Controller inheritance hierarchies share filters downwards, but subclasses can also add new filters without
1507 * affecting the superclass. For example:
1509 * class BankController extends AkActionController
1511 * function __construct()
1513 * $this->beforeFilter('_audit');
1516 * function _audit(&$controller)
1518 * // record the action and parameters in an audit log
1522 * class VaultController extends BankController
1524 * function __construct()
1526 * $this->beforeFilter('_verifyCredentials');
1529 * function _verifyCredentials(&$controller)
1531 * // make sure the user is allowed into the vault
1535 * Now any actions performed on the BankController will have the audit method called before. On the VaultController,
1536 * first the audit method is called, then the _verifyCredentials method. If the _audit method returns false, then
1537 * _verifyCredentials and the intended action are never called.
1539 * == Filter types
1541 * A filter can take one of three forms: method reference, external class, or inline method. The first
1542 * is the most common and works by referencing a method somewhere in the inheritance hierarchy of
1543 * the controller by use of a method name. In the bank example above, both BankController and VaultController use this form.
1545 * Using an external class makes for more easily reused generic filters, such as output compression. External filter classes
1546 * are implemented by having a static +filter+ method on any class and then passing this class to the filter method. Example:
1548 * class OutputCompressionFilter
1550 * function filter(&$controller)
1552 * $controller->response->body = compress($controller->response->body);
1556 * class NewspaperController extends AkActionController
1558 * function __construct()
1560 * $this->afterFilter(new OutputCompressionFilter());
1564 * The filter method is passed the controller instance and is hence granted access to all aspects of the controller and can
1565 * manipulate them as it sees fit.
1568 * == Filter chain ordering
1570 * Using <tt>beforeFilter</tt> and <tt>afterFilter</tt> appends the specified filters to the existing chain. That's usually
1571 * just fine, but some times you care more about the order in which the filters are executed. When that's the case, you
1572 * can use <tt>prependBeforeFilter</tt> and <tt>prependAfterFilter</tt>. Filters added by these methods will be put at the
1573 * beginning of their respective chain and executed before the rest. For example:
1575 * class ShoppingController extends AkActionController
1577 * function __construct()
1579 * $this->beforeFilter('verifyOpenShop');
1584 * class CheckoutController extends AkActionController
1586 * function __construct()
1588 * $this->prependBeforeFilter('ensureItemsInCart', 'ensureItemsInStock');
1592 * The filter chain for the CheckoutController is now <tt>ensureItemsInCart, ensureItemsInStock,</tt>
1593 * <tt>verifyOpenShop</tt>. So if either of the ensure filters return false, we'll never get around to see if the shop
1594 * is open or not.
1596 * You may pass multiple filter arguments of each type.
1598 * == Around filters
1600 * In addition to the individual before and after filters, it's also possible to specify that a single object should handle
1601 * both the before and after call. That's especially useful when you need to keep state active between the before and after,
1602 * such as the example of a benchmark filter below:
1604 * class WeblogController extends AkActionController
1606 * function __construct()
1608 * $this->aroundFilter(new BenchmarkingFilter());
1611 * // Before this action is performed, BenchmarkingFilter->before($controller) is executed
1612 * function index()
1615 * // After this action has been performed, BenchmarkingFilter->after($controller) is executed
1618 * class BenchmarkingFilter
1620 * function before(&$controller)
1622 * start_timer();
1625 * function after(&$controller)
1627 * stop_timer();
1628 * report_result();
1632 * == Filter chain skipping
1634 * Some times its convenient to specify a filter chain in a superclass that'll hold true for the majority of the
1635 * subclasses, but not necessarily all of them. The subclasses that behave in exception can then specify which filters
1636 * they would like to be relieved of. Examples
1638 * class ApplicationController extends AkActionController
1640 * function __construct()
1642 * $this->beforeFilter('authenticate');
1646 * class WeblogController extends ApplicationController
1648 * // will run the authenticate filter
1651 * class SignupController extends AkActionController
1653 * function __construct()
1655 * $this->skipBeforeFilter('authenticate');
1657 * // will not run the authenticate filter
1660 * == Filter conditions
1662 * Filters can be limited to run for only specific actions. This can be expressed either by listing the actions to
1663 * exclude or the actions to include when executing the filter. Available conditions are +only+ or +except+, both
1664 * of which accept an arbitrary number of method references. For example:
1666 * class Journal extends AkActionController
1668 * function __construct()
1669 * { // only require authentication if the current action is edit or delete
1670 * $this->beforeFilter(array('_authorize'=>array('only'=>array('edit','delete')));
1673 * function _authorize(&$controller)
1675 * // redirect to login unless authenticated
1680 var $_includedActions = array(), $_beforeFilters = array(), $_afterFilters = array(), $_excludedActions = array();
1682 * The passed <tt>filters</tt> will be appended to the array of filters that's run _before_ actions
1683 * on this controller are performed.
1685 function appendBeforeFilter()
1687 $filters = array_reverse(func_get_args());
1688 foreach (array_keys($filters) as $k){
1689 $conditions = $this->_extractConditions(&$filters[$k]);
1690 $this->_addActionConditions($filters[$k], $conditions);
1691 $this->_appendFilterToChain('before', $filters[$k]);
1696 * The passed <tt>filters</tt> will be prepended to the array of filters that's run _before_ actions
1697 * on this controller are performed.
1699 function prependBeforeFilter()
1701 $filters = array_reverse(func_get_args());
1702 foreach (array_keys($filters) as $k){
1703 $conditions = $this->_extractConditions(&$filters[$k]);
1704 $this->_addActionConditions($filters[$k], $conditions);
1705 $this->_prependFilterToChain('before', $filters[$k]);
1710 * Short-hand for appendBeforeFilter since that's the most common of the two.
1712 function beforeFilter()
1714 $filters = func_get_args();
1715 foreach (array_keys($filters) as $k){
1716 $this->appendBeforeFilter($filters[$k]);
1721 * The passed <tt>filters</tt> will be appended to the array of filters that's run _after_ actions
1722 * on this controller are performed.
1724 function appendAfterFilter()
1726 $filters = array_reverse(func_get_args());
1727 foreach (array_keys($filters) as $k){
1728 $conditions = $this->_extractConditions(&$filters[$k]);
1729 $this->_addActionConditions(&$filters[$k], $conditions);
1730 $this->_appendFilterToChain('after', &$filters[$k]);
1736 * The passed <tt>filters</tt> will be prepended to the array of filters that's run _after_ actions
1737 * on this controller are performed.
1739 function prependAfterFilter()
1741 $filters = array_reverse(func_get_args());
1742 foreach (array_keys($filters) as $k){
1743 $conditions = $this->_extractConditions(&$filters[$k]);
1744 $this->_addActionConditions(&$filters[$k], $conditions);
1745 $this->_prependFilterToChain('after', &$filters[$k]);
1750 * Short-hand for appendAfterFilter since that's the most common of the two.
1751 * */
1752 function afterFilter()
1754 $filters = func_get_args();
1755 foreach (array_keys($filters) as $k){
1756 $this->appendAfterFilter($filters[$k]);
1761 * The passed <tt>filters</tt> will have their +before+ method appended to the array of filters that's run both before actions
1762 * on this controller are performed and have their +after+ method prepended to the after actions. The filter objects must all
1763 * respond to both +before+ and +after+. So if you do appendAroundFilter(new A(), new B()), the callstack will look like:
1765 * B::before()
1766 * A::before()
1767 * A::after()
1768 * B::after()
1770 function appendAroundFilter()
1772 $filters = func_get_args();
1773 foreach (array_keys($filters) as $k){
1774 $this->_ensureFilterRespondsToBeforeAndAfter(&$filters[$k]);
1775 $this->appendBeforeFilter(array(&$filters[$k],'before'));
1777 $filters = array_reverse($filters);
1778 foreach (array_keys($filters) as $k){
1779 $this->prependAfterFilter(array(&$filters[$k],'after'));
1784 * The passed <tt>filters</tt> will have their +before+ method prepended to the array of filters that's run both before actions
1785 * on this controller are performed and have their +after+ method appended to the after actions. The filter objects must all
1786 * respond to both +before+ and +after+. So if you do appendAroundFilter(new A(), new B()), the callstack will look like:
1788 * A::before()
1789 * B::before()
1790 * B::after()
1791 * A::after()
1793 function prependAroundFilter()
1795 $filters = func_get_args();
1796 foreach (array_keys($filters) as $k){
1797 $this->_ensureFilterRespondsToBeforeAndAfter(&$filters[$k]);
1798 $this->prependBeforeFilter(array(&$filters[$k],'before'));
1800 $filters = array_reverse($filters);
1801 foreach (array_keys($filters) as $k){
1802 $this->appendAfterFilter(array(&$filters[$k],'after'));
1807 * Short-hand for appendAroundFilter since that's the most common of the two.
1809 function aroundFilter()
1811 $filters = func_get_args();
1812 call_user_func_array(array(&$this,'appendAroundFilter'), $filters);
1816 * Removes the specified filters from the +before+ filter chain.
1817 * This is especially useful for managing the chain in inheritance hierarchies where only one out
1818 * of many sub-controllers need a different hierarchy.
1820 function skipBeforeFilter($filters)
1822 $filters = func_get_args();
1823 $this->_skipFilter($filters, 'before');
1827 * Removes the specified filters from the +after+ filter chain. Note that this only works for skipping method-reference
1828 * filters, not instances. This is especially useful for managing the chain in inheritance hierarchies where only one out
1829 * of many sub-controllers need a different hierarchy.
1831 function skipAfterFilter($filters)
1833 $filters = func_get_args();
1834 $this->_skipFilter($filters, 'after');
1837 function _skipFilter(&$filters, $type)
1839 $_filters =& $this->{'_'.$type.'Filters'};
1840 // array_diff doesn't play nice with some PHP5 releases when it comes to
1841 // Objects as it only diff equal references, not object types
1842 foreach (array_keys($filters) as $k){
1843 if(AK_PHP5){
1844 if(is_object($filters[$k])){
1845 foreach (array_keys($_filters) as $k2){
1846 if(is_object($_filters[$k2]) && get_class($_filters[$k2]) == get_class($filters[$k])){
1847 $pos = $k2;
1848 break;
1851 }else{
1852 $pos = array_search($filters[$k], $_filters);
1855 array_splice($_filters, $pos, 1, null);
1856 return ;
1858 $_filters = array_diff($_filters,array($filters[$k]));
1863 * Returns all the before filters for this class.
1865 function beforeFilters()
1867 return $this->_beforeFilters;
1871 * Returns all the after filters for this class and all its ancestors.
1873 function afterFilters()
1875 return $this->_afterFilters;
1879 * Returns a mapping between filters and the actions that may run them.
1881 function includedActions()
1883 return $this->_includedActions;
1887 * Returns a mapping between filters and actions that may not run them.
1889 function excludedActions()
1891 return $this->_excludedActions;
1895 function _appendFilterToChain($condition, $filters)
1897 $this->{"_{$condition}Filters"}[] =& $filters;
1900 function _prependFilterToChain($condition, $filters)
1902 array_unshift($this->{"_{$condition}Filters"}, $filters);
1905 function _ensureFilterRespondsToBeforeAndAfter(&$filter_object)
1907 if(!method_exists(&$filter_object,'before') && !method_exists(&$filter_object,'after')){
1908 trigger_error(Ak::t('Filter object must respond to both before and after'), E_USER_ERROR);
1912 function _extractConditions(&$filters)
1914 if(is_array($filters) && !isset($filters[0])){
1915 $keys = array_keys($filters);
1916 $conditions = $filters[$keys[0]];
1917 $filters = $keys[0];
1918 return $conditions;
1922 function _addActionConditions($filters, $conditions)
1924 if(!empty($conditions['only'])){
1925 $this->_includedActions[$this->_filterId($filters)] = $this->_conditionArray($this->_includedActions, $conditions['only']);
1927 if(!empty($conditions['except'])){
1928 $this->_excludedActions[$this->_filterId($filters)] = $this->_conditionArray($this->_excludedActions, $conditions['except']);
1932 function _conditionArray($actions, $filter_actions)
1934 $filter_actions = is_array($filter_actions) ? $filter_actions : array($filter_actions);
1935 $filter_actions = array_map(array(&$this,'_filterId'),$filter_actions);
1936 return array_unique(array_merge($actions, $filter_actions));
1940 function _filterId($filters)
1942 return is_string($filters) ? $filters : md5(serialize($filters));
1945 function performActionWithoutFilters($action)
1947 if(method_exists(&$this, $action)){
1948 call_user_func_array(array(&$this, $action), @(array)$this->passed_args);
1952 function performActionWithFilters($method = '')
1954 if ($this->beforeAction($method) !== false || empty($this->_performed)){
1955 $this->performActionWithoutFilters($method);
1956 $this->afterAction($method);
1957 return true;
1959 return $this->performActionWithoutFilters($method);
1962 function performAction($method = '')
1964 $this->performActionWithFilters($method);
1969 * Calls all the defined before-filter filters, which are added by using "beforeFilter($method)".
1970 * If any of the filters return false, no more filters will be executed and the action is aborted.
1972 function beforeAction($method = '')
1974 Ak::profile('Running before controller action filters '.__CLASS__.'::'.__FUNCTION__.' '.__LINE__);
1975 return $this->_callFilters($this->_beforeFilters, $method);
1979 * Calls all the defined after-filter filters, which are added by using "afterFilter($method)".
1980 * If any of the filters return false, no more filters will be executed.
1982 function afterAction($method = '')
1984 Ak::profile('Running after controller action filters '.__CLASS__.'::'.__FUNCTION__.' '.__LINE__);
1985 return $this->_callFilters(&$this->_afterFilters, $method);
1989 function _callFilters(&$filters, $method = '')
1991 $filter_result = null;
1992 foreach (array_keys($filters) as $k){
1993 $filter =& $filters[$k];
1994 if(!$this->_actionIsExempted($filter, $method)){
1995 if(is_array($filter) && is_object($filter[0]) && method_exists($filter[0], $filter[1])){
1996 $filter_result = $filter[0]->$filter[1]($this);
1997 }elseif(!is_object($filter) && method_exists($this, $filter)){
1998 $filter_result = $this->$filter($this);
1999 }elseif(is_object($filter) && method_exists($filter, 'filter')){
2000 $filter_result = $filter->filter($this);
2001 }else{
2002 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);
2006 if($filter_result === false){
2007 !empty($this->_Logger) ? $this->_Logger->info(Ak::t('Filter chain halted as '.$filter.' returned false')) : null;
2008 return false;
2011 return $filter_result;
2015 function _actionIsExempted($filter, $method = '')
2017 $method_id = is_string($method) ? $method : $this->_filterId($method);
2018 $filter_id = $this->_filterId($filter);
2020 if((!empty($this->_includedActions[$filter_id]) && !in_array($method_id, $this->_includedActions[$filter_id])) ||
2021 (!empty($this->_excludedActions[$filter_id]) && in_array($method_id, $this->_excludedActions[$filter_id]))){
2022 return true;
2025 return false;
2031 Flash communication between actions
2032 ====================================================================
2034 * The flash provides a way to pass temporary objects between actions. Anything you place in the flash will be exposed
2035 * to the very next action and then cleared out. This is a great way of doing notices and alerts, such as a create action
2036 * that sets <tt>flash['notice] = 'Successfully created'</tt> before redirecting to a display action that can then expose
2037 * the flash to its template. Actually, that exposure is automatically done. Example:
2039 * class WeblogController extends ActionController
2041 * function create()
2043 * // save post
2044 * $this->flash['notice] = 'Successfully created post';
2045 * $this->redirectTo(array('action'=>'display','params' => array('id' =>$Post->id)));
2048 * function display()
2050 * // doesn't need to assign the flash notice to the template, that's done automatically
2054 * display.tpl
2055 * <?php if($flash['notice']) : ?><div class='notice'><?php echo $flash['notice'] ?></div><?php endif; ?>
2057 * 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
2058 * as you like at a time too. Just remember: They'll be gone by the time the next action has been performed.
2060 * ==flash_now
2062 * Sets a flash that will not be available to the next action, only to the current.
2064 * $this->flash_now['message] = 'Hello current action';
2066 * This method enables you to use the flash as a central messaging system in your app.
2067 * When you need to pass an object to the next action, you use the standard flash assign (<tt>[]=</tt>).
2068 * When you need to pass an object to the current action, you use <tt>now</tt>, and your object will
2069 * vanish when the current action is done.
2071 * Entries set via <tt>flash_now</tt> are accessed the same way as standard entries: <tt>flash['my-key']</tt>.
2073 var $flash = array();
2074 var $flash_now = array();
2075 var $flash_options = array();
2076 var $_flash_handled = false;
2078 function _handleFlashAttribute()
2080 $this->_flash_handled = true;
2082 $next_flash = empty($this->flash) ? false : $this->flash;
2083 $this->flash = array();
2084 if(isset($_SESSION['__flash'])){
2085 $this->flash = $_SESSION['__flash'];
2087 $_SESSION['__flash'] = $next_flash;
2088 if(!empty($this->flash_now)){
2089 $this->flash = array_merge((array)$this->flash,(array)$this->flash_now);
2091 $this->_handleFlashOptions();
2094 function _handleFlashOptions()
2096 $next_flash_options = empty($this->flash_options) ? false : $this->flash_options;
2097 $this->flash_options = array();
2098 if(isset($_SESSION['__flash_options'])){
2099 $this->flash_options = $_SESSION['__flash_options'];
2101 $_SESSION['__flash_options'] = $next_flash_options;
2102 if(!empty($this->flash_now_options)){
2103 $this->flash_options = array_merge((array)$this->flash_options,(array)$this->flash_now_options);
2108 function _mergeFlashOnFlashNow()
2110 $this->flash_now = array_merge($this->flash_now,$this->flash);
2115 Pagination for Active Record collections
2116 ====================================================================
2118 * The Pagination module aids in the process of paging large collections of
2119 * Active Record objects. It offers macro-style automatic fetching of your
2120 * model for multiple views, or explicit fetching for single actions. And if
2121 * the magic isn't flexible enough for your needs, you can create your own
2122 * paginators with a minimal amount of code.
2124 * The Pagination module can handle as much or as little as you wish. In the
2125 * controller, have it automatically query your model for pagination; or,
2126 * if you prefer, create Paginator objects yourself
2128 * Pagination is included automatically for all controllers.
2130 * For help rendering pagination links, see
2131 * Helpers/PaginationHelper.
2133 * ==== Automatic pagination for every action in a controller
2135 * class PersonController extends ApplicationController
2137 * var $model = 'person';
2138 * var $paginate = array('people'=>array('order' => 'last_name, first_name',
2139 * 'per_page' => 20));
2142 * Each action in this controller now has access to a <tt>$this->people</tt>
2143 * instance variable, which is an ordered collection of model objects for the
2144 * current page (at most 20, sorted by last name and first name), and a
2145 * <tt>$this->person_pages</tt> Paginator instance. The current page is determined
2146 * by the <tt>$params['page']</tt> variable.
2148 * ==== Pagination for a single action
2150 * function show_all()
2152 * list($this->person_pages, $this->people) =
2153 * $this->paginate('people', array('order' => 'last_name, first_name'));
2156 * Like the previous example, but explicitly creates <tt>$this->person_pages</tt>
2157 * and <tt>$this->people</tt> for a single action, and uses the default of 10 items
2158 * per page.
2160 * ==== Custom/"classic" pagination
2162 * function list()
2164 * $this->person_pages = new AkPaginator(&$this, $Person->count(), 10, $params['page']);
2165 * $this->people = $this->Person->find('all', array(
2166 * 'order'=> 'last_name, first_name',
2167 * 'limit' => $this->person_pages->items_per_page,
2168 * 'offset' => $this->person_pages->getOffset()));
2171 * Explicitly creates the paginator from the previous example and uses
2172 * AkPaginator::toSql to retrieve <tt>$this->people</tt> from the model.
2174 // An array holding options for controllers using macro-style pagination
2175 var $_pagination_options = array(
2176 'class_name' => null,
2177 'singular_name' => null,
2178 'per_page' => 10,
2179 'conditions' => null,
2180 'order_by' => null,
2181 'order' => null,
2182 'join' => null,
2183 'joins' => null,
2184 'include' => null,
2185 'select' => null,
2186 'parameter' => 'page'
2189 // The default options for pagination
2190 var $_pagination_default_options = array(
2191 'class_name' => null,
2192 'singular_name' => null,
2193 'per_page' => 10,
2194 'conditions' => null,
2195 'order_by' => null,
2196 'order' => null,
2197 'join' => null,
2198 'joins' => null,
2199 'include' => null,
2200 'select' => null,
2201 'parameter' => 'page'
2204 var $_pagination_actions = array();
2206 function _paginationValidateOptions($collection_id, $options = array(), $in_action)
2208 $this->_pagination_options = array_merge($this->_pagination_default_options, $this->_pagination_options);
2209 $valid_options = array_keys($this->_pagination_default_options);
2211 $valid_options = !in_array($in_action, $valid_options) ? array_merge($valid_options, $this->_pagination_actions) : $valid_options;
2213 $unknown_option_keys = array_diff(array_keys($this->_pagination_options) , $valid_options);
2215 if(!empty($unknown_option_keys)){
2216 trigger_error(Ak::t('Unknown options for pagination: %unknown_option',array('%unknown_option'=>join(', ',$unknown_option_keys))), E_USER_WARNING);
2219 $this->_pagination_options['singular_name'] = !empty($this->_pagination_options['singular_name']) ? $this->_pagination_options['singular_name'] : AkInflector::singularize($collection_id);
2220 $this->_pagination_options['class_name'] = !empty($this->_pagination_options['class_name']) ? $this->_pagination_options['class_name'] : AkInflector::camelize($this->_pagination_options['singular_name']);
2224 * Returns a paginator and a collection of Active Record model instances
2225 * for the paginator's current page. This is designed to be used in a
2226 * single action.
2228 * +options+ are:
2229 * <tt>singular_name</tt>:: the singular name to use, if it can't be inferred by
2230 * singularizing the collection name
2231 * <tt>class_name</tt>:: the class name to use, if it can't be inferred by
2232 * camelizing the singular name
2233 * <tt>per_page</tt>:: the maximum number of items to include in a
2234 * single page. Defaults to 10
2235 * <tt>conditions</tt>:: optional conditions passed to Model::find('all', $this->params); and
2236 * Model::count()
2237 * <tt>order</tt>:: optional order parameter passed to Model::find('all', $this->params);
2238 * <tt>order_by</tt>:: (deprecated, used :order) optional order parameter passed to Model::find('all', $this->params)
2239 * <tt>joins</tt>:: optional joins parameter passed to Model::find('all', $this->params)
2240 * and Model::count()
2241 * <tt>join</tt>:: (deprecated, used :joins or :include) optional join parameter passed to Model::find('all', $this->params)
2242 * and Model::count()
2243 * <tt>include</tt>:: optional eager loading parameter passed to Model::find('all', $this->params)
2244 * and Model::count()
2246 * Creates a +before_filter+ which automatically paginates an Active
2247 * Record model for all actions in a controller (or certain actions if
2248 * specified with the <tt>actions</tt> option).
2250 * +options+ are the same as PaginationHelper::paginate, with the addition
2251 * of:
2252 * <tt>actions</tt>:: an array of actions for which the pagination is
2253 * active. Defaults to +null+ (i.e., every action)
2255 function paginate($collection_id, $options = array())
2257 $this->_paginationValidateOptions($collection_id, $options, true);
2258 $this->_paginationLoadPaginatorAndCollection($collection_id, $this->_pagination_options);
2259 $this->beforeFilter('_paginationCreateAndRetrieveCollections');
2263 function _paginationCreateAndRetrieveCollections()
2265 foreach($this->_pagination_options[$this->class] as $collection_id=>$options){
2266 if(!empty($options['actions']) && in_array($options['actions'], $action_name)){
2267 continue;
2270 list($paginator, $collection) = $this->_paginationLoadPaginatorAndCollection($collection_id, $this->_pagination_options);
2272 $this->{$options['singular_name'].'_pages'} =& $paginator;
2273 $this->$collection_name =& $collection;
2278 * Returns the total number of items in the collection to be paginated for
2279 * the +model+ and given +conditions+. Override this method to implement a
2280 * custom counter.
2282 function _paginationCountCollection(&$model, $conditions, $joins)
2284 return $model->count($conditions, $joins);
2288 * Returns a collection of items for the given +$model+ and +$options['conditions']+,
2289 * ordered by +$options['order']+, for the current page in the given +$paginator+.
2290 * Override this method to implement a custom finder.
2292 function _paginationFindCollection(&$model, $options, &$paginator)
2294 return $model->find('all', array(
2295 'conditions' => $this->_pagination_options['conditions'],
2296 'order' => !empty($options['order_by']) ? $options['order_by'] : $options['order'],
2297 'joins' => !empty($options['join']) ? $options['join'] : $options['joins'],
2298 'include' => $this->_pagination_options['include'],
2299 'select' => $this->_pagination_options['select'],
2300 'limit' => $this->_pagination_options['per_page'],
2301 'offset' => $paginator->getOffset()));
2305 * @todo Fix this function
2307 function _paginationLoadPaginatorAndCollection($collection_id, $options)
2309 $page = $this->params[$options['parameter']];
2310 $count = $this->_paginationCountCollection($klass, $options['conditions'],
2311 empty($options['join']) ? $options['join'] : $options['joins']);
2313 require_once(AK_LIB_DIR.DS.'AkActionController'.DS.'AkPaginator.php');
2314 $paginator =& new AkPaginator($this, $count, $options['per_page'], $page);
2315 $collection =& $this->_paginationFindCollection($options['class_name'], $options, $paginator);
2317 return array(&$paginator, &$collection);
2321 Protocol conformance
2322 ====================================================================
2326 * Specifies that the named actions requires an SSL connection to be performed (which is enforced by ensure_proper_protocol).
2328 function setSslRequiredActions($actions)
2330 $this->_ssl_required_actions = empty($this->_ssl_required_actions) ?
2331 (is_string($actions) ? Ak::stringToArray($actions) : $actions) :
2332 array_merge($this->_ssl_required_actions, (is_string($actions) ? Ak::stringToArray($actions) : $actions));
2335 function setSslAllowedActions($actions)
2337 $this->_ssl_allowed_actions = empty($this->_ssl_allowed_actions) ?
2338 (is_string($actions) ? Ak::stringToArray($actions) : $actions) :
2339 array_merge($this->_ssl_allowed_actions, (is_string($actions) ? Ak::stringToArray($actions) : $actions));
2343 * Returns true if the current action is supposed to run as SSL
2345 function _isSslRequired()
2347 return !empty($this->_ssl_required_actions) && is_array($this->_ssl_required_actions) && isset($this->_action_name) ?
2348 in_array($this->_action_name, $this->_ssl_required_actions) : false;
2351 function _isSslAllowed()
2353 return (!empty($this->ssl_for_all_actions) && empty($this->_ssl_allowed_actions)) ||
2354 (!empty($this->_ssl_allowed_actions) && is_array($this->_ssl_allowed_actions) && isset($this->_action_name) ?
2355 in_array($this->_action_name, $this->_ssl_allowed_actions) : false);
2358 function _ensureProperProtocol()
2360 if($this->_isSslAllowed()){
2361 return true;
2363 if ($this->_isSslRequired() && !$this->Request->isSsl()){
2364 $this->redirectTo(substr_replace(AK_CURRENT_URL,'s:',4,1));
2365 return false;
2366 }elseif($this->Request->isSsl() && !$this->_isSslRequired()){
2367 $this->redirectTo(substr_replace(AK_CURRENT_URL,'',4,1));
2368 return false;
2373 Account Location
2374 ====================================================================
2376 * Account location is a set of methods that supports the account-key-as-subdomain
2377 * way of identifying the current scope. These methods allow you to easily produce URLs that
2378 * match this style and to get the current account key from the subdomain.
2380 * The methods are: getAccountUrl, getAccountHost, and getAccountDomain.
2382 * Example:
2384 * include_once('AkAccountLocation.php');
2386 * class ApplicationController extends AkActionController
2388 * var $before_filter = '_findAccount';
2390 * function _findAccount()
2392 * $this->account = Account::find(array('conditions'=>array('username = ?', $this->account_domain)));
2395 * class AccountController extends ApplicationController
2397 * function new_account()
2399 * $this->new_account = Account::create($this->params['new_account']);
2400 * $this->redirectTo(array('host' => $this->accountHost($this->new_account->username), 'controller' => 'weblog'));
2403 * function authenticate()
2405 * $this->session[$this->account_domain] = 'authenticated';
2406 * $this->redirectTo(array('controller => 'weblog'));
2409 * function _isAuthenticated()
2411 * return !empty($this->session['account_domain']) ? $this->session['account_domain'] == 'authenticated' : false;
2415 * // The view:
2416 * Your domain: {account_url?}
2418 * By default, all the methods will query for $this->account->username as the account key, but you can
2419 * specialize that by overwriting defaultAccountSubdomain. You can of course also pass it in
2420 * as the first argument to all the methods.
2422 function defaultAccountSubdomain()
2424 if(!empty($this->account)){
2425 return $this->account->respondsTo('username');
2429 function accountUrl($account_subdomain = null, $use_ssl = null)
2431 $account_subdomain = empty($account_subdomain) ? 'default_account_subdomain' : $account_subdomain;
2432 $use_ssl = empty($use_ssl) ? $use_ssl : $this->Request->isSsl();
2433 return ($use_ssl ? 'https://' : 'http://') . $this->accountHost($account_subdomain);
2436 function accountHost($account_subdomain = null)
2438 $account_subdomain = empty($account_subdomain) ? 'default_account_subdomain' : $account_subdomain;
2439 $account_host = '';
2440 $account_host .= $account_subdomain . '.';
2441 $account_host .= $this->accountDomain();
2442 return $account_host;
2445 function accountDomain()
2447 $account_domain = '';
2448 if(count($this->Request->getSubdomains()) > 1){
2449 $account_domain .= join('.',$this->Request->getSubdomains()) . '.';
2451 $account_domain .= $this->Request->getDomain() . $this->Request->getPortString();
2452 return $account_domain;
2455 function getAccountSubdomain()
2457 return array_shift($this->Request->getSubdomains());
2462 Data streaming
2463 ====================================================================
2464 Methods for sending files and streams to the browser instead of rendering.
2467 var $default_send_file_options = array(
2468 'type' => 'application/octet-stream',
2469 'disposition' => 'attachment',
2470 'stream' => true,
2471 'buffer_size' => 4096
2475 * Sends the file by streaming it 4096 bytes at a time. This way the
2476 * whole file doesn't need to be read into memory at once. This makes
2477 * it feasible to send even large files.
2479 * Be careful to sanitize the path parameter if it coming from a web
2480 * page. sendFile($params['path']) allows a malicious user to
2481 * download any file on your server.
2483 * Options:
2484 * * <tt>filename</tt> - suggests a filename for the browser to use.
2485 * Defaults to realpath($path).
2486 * * <tt>type</tt> - specifies an HTTP content type.
2487 * Defaults to 'application/octet-stream'.
2488 * * <tt>disposition</tt> - specifies whether the file will be shown inline or downloaded.
2489 * Valid values are 'inline' and 'attachment' (default).
2490 * * <tt>stream</tt> - whether to send the file to the user agent as it is read (true)
2491 * or to read the entire file before sending (false). Defaults to true.
2492 * * <tt>buffer_size</tt> - specifies size (in bytes) of the buffer used to stream the file.
2493 * Defaults to 4096.
2495 * The default Content-Type and Content-Disposition headers are
2496 * set to download arbitrary binary files in as many browsers as
2497 * possible. IE versions 4, 5, 5.5, and 6 are all known to have
2498 * a variety of quirks (especially when downloading over SSL).
2500 * Simple download:
2501 * sendFile('/path/to.zip');
2503 * Show a JPEG in browser:
2504 * sendFile('/path/to.jpeg', array('type' => 'image/jpeg', 'disposition' => 'inline'));
2506 * Read about the other Content-* HTTP headers if you'd like to
2507 * provide the user with more information (such as Content-Description).
2508 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11
2510 * Also be aware that the document may be cached by proxies and browsers.
2511 * The Pragma and Cache-Control headers declare how the file may be cached
2512 * by intermediaries. They default to require clients to validate with
2513 * the server before releasing cached responses. See
2514 * http://www.mnot.net/cache_docs/ for an overview of web caching and
2515 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9
2516 * for the Cache-Control header spec.
2518 function sendFile($path, $options = array())
2520 $path = realpath($path);
2521 if(!file_exists($path)){
2522 trigger_error(Ak::t('Cannot read file %path',array('%path'=>$path)), E_USER_NOTICE);
2523 return false;
2525 $options['length'] = empty($options['length']) ? filesize($path) : $options['length'];
2526 $options['filename'] = empty($options['filename']) ? basename($path) : $options['filename'];
2527 $options['type'] = empty($options['type']) ? Ak::mime_content_type($path) : $options['type'];
2529 $this->performed_render = false;
2530 $this->_sendFileHeaders($options);
2532 if(!empty($options['stream'])){
2533 require_once(AK_LIB_DIR.DS.'AkStream.php');
2534 $this->render(array('text'=> new AkStream($path,$options['buffer_size'])));
2535 }else{
2536 $this->render(array('text'=> Ak::file_get_contents($path)));
2541 * Send binary data to the user as a file download. May set content type, apparent file name,
2542 * and specify whether to show data inline or download as an attachment.
2544 * Options:
2545 * * <tt>filename</tt> - Suggests a filename for the browser to use.
2546 * * <tt>type</tt> - specifies an HTTP content type.
2547 * Defaults to 'application/octet-stream'.
2548 * * <tt>disposition</tt> - specifies whether the file will be shown inline or downloaded.
2549 * Valid values are 'inline' and 'attachment' (default).
2551 * Generic data download:
2552 * sendData($buffer)
2554 * Download a dynamically-generated tarball:
2555 * sendData(Ak::compress('dir','tgz'), array('filename' => 'dir.tgz'));
2557 * Display an image Active Record in the browser:
2558 * sendData($image_data, array('type' =>Ak::mime_content_type('image_name.png'), 'disposition' => 'inline'));
2560 * See +sendFile+ for more information on HTTP Content-* headers and caching.
2562 function sendData($data, $options = array())
2564 $options['length'] = empty($options['length']) ? Ak::size($data) : $options['length'];
2565 $this->_sendFileHeaders($options);
2566 $this->performed_render = false;
2567 $this->renderText($data);
2571 * Creates a file for streaming from a file.
2572 * This way you might free memory usage is file is too large
2574 function sendDataAsStream($data, $options)
2576 $temp_file_name = tempnam(AK_TMP_DIR, Ak::randomString());
2577 $fp = fopen($temp_file_name, 'w');
2578 fwrite($fp, $data);
2579 fclose($fp);
2580 $this->sendFile($temp_file_name, $options);
2584 function _sendFileHeaders(&$options)
2586 $options = array_merge($this->default_send_file_options,$options);
2587 foreach (array('length', 'type', 'disposition') as $arg){
2588 empty($options[$arg]) ? trigger_error(Ak::t('%arg option required', array('%arg'=>$arg)), E_USER_ERROR) : null;
2590 $disposition = empty($options['disposition']) ? 'attachment' : $options['disposition'];
2591 $disposition .= !empty($options['filename']) ? '; filename="'.$options['filename'].'"' : '';
2592 $this->Response->addHeader(array(
2593 'Content-Length' => $options['length'],
2594 'Content-Type' => trim($options['type']), // fixes a problem with extra '\r' with some browsers
2595 'Content-Disposition' => $disposition,
2596 'Content-Transfer-Encoding' => 'binary'
2602 function redirectToLocale($locale)
2604 if($this->Request->__internationalization_support_enabled){
2605 $lang = isset($this->params['lang']) ? $this->params['lang'] : $locale;
2607 if($locale != $lang){
2608 $this->redirectTo(array_merge($this->Request->getParams(),array('lang'=>$locale)));
2609 return true;
2612 return false;
2616 function api($protocol = 'xml_rpc')
2618 $web_services = array_merge(Ak::toArray($this->web_services), Ak::toArray($this->web_service));
2619 if(!empty($web_services)){
2620 $web_services = array_unique($web_services);
2621 require_once(AK_LIB_DIR.DS.'AkActionWebService.php');
2622 require_once(AK_LIB_DIR.DS.'AkActionWebService'.DS.'AkActionWebServiceServer.php');
2623 $Server =& new AkActionWebServiceServer($protocol);
2624 foreach ($web_services as $web_service){
2625 $Server->addService($web_service);
2627 $Server->init();
2628 $Server->serve();
2629 exit;
2630 }else{
2631 die(Ak::t('There is not any webservice configured at this endpoint'));
2638 HTTP Authentication
2639 ====================================================================
2641 * Simple Basic example:
2643 * class PostsController extends ApplicationController
2645 * var $_authorized_users = array('bermi' => 'secret');
2647 * function __construct(){
2648 * $this->beforeFilter(array('authenticate' => array('except' => array('index'))));
2651 * function index() {
2652 * $this->renderText("Everyone can see me!");
2655 * function edit(){
2656 * $this->renderText("I'm only accessible if you know the password");
2659 * function authenticate(){
2660 * return $this->_authenticateOrRequestWithHttpBasic('App name', $this->_authorized_users);
2664 * Here is a more advanced Basic example where only Atom feeds and the XML API is protected by HTTP authentication,
2665 * the regular HTML interface is protected by a session approach:
2667 * class ApplicationController extends AkActionController
2669 * var $models = 'account';
2671 * function __construct() {
2672 * $this->beforeFilter(array('_setAccount', 'authenticate'));
2675 * function _setAccount() {
2676 * $this->Account = $this->account->findFirstBy('url_name', array_pop($this->Request->getSubdomains()));
2679 * function authenticate() {
2680 * if($this->Request->isFormat('XML', 'ATOM')){
2681 * if($User = $this->_authenticateWithHttpBasic($Account)){
2682 * $this->CurrentUser = $User;
2683 * }else{
2684 * $this->_requestHttpBasicAuthentication();
2686 * }else{
2687 * if($this->isSessionAuthenticated()){
2688 * $this->CurrentUser = $Account->user->find($_SESSION['authenticated']['user_id']);
2689 * }else{
2690 * $this->redirectTo(array('controller'=>'login'));
2691 * return false;
2697 * On shared hosts, Apache sometimes doesn't pass authentication headers to
2698 * FCGI instances. If your environment matches this description and you cannot
2699 * authenticate, try this rule in public/.htaccess (replace the plain one):
2701 * RewriteRule ^(.*)$ index.php [E=X-HTTP_AUTHORIZATION:%{HTTP:Authorization},QSA,L]
2704 function _authenticateOrRequestWithHttpBasic($realm = AK_APP_NAME, $login_procedure)
2706 if($Result = $this->_authenticateWithHttpBasic($login_procedure)){
2707 return $Result;
2709 return $this->_requestHttpBasicAuthentication($realm);
2712 function _authenticateWithHttpBasic($login_procedure)
2714 return $this->_authenticate($login_procedure);
2717 function _requestHttpBasicAuthentication($realm = AK_APP_NAME)
2719 return $this->_authenticationRequest($realm);
2723 * This is method takes a $login_procedure for performing access authentication.
2725 * If an array is given, it will check the key for a user and the value will be verified to match given password.
2727 * You can pass and array like array('handler' => $Account, 'method' => 'verifyCredentials'), which will call
2729 * $Account->verifyCredentials($user_name, $password, $Controller)
2731 * You can also pass an object which implements an "authenticate" method. when calling
2733 * $this->_authenticate(new User());
2735 * It will call the $User->authenticate($user_name, $password, $Controller)
2737 * In both cases the authentication method should return true for valid credentials or false is invalid.
2739 * @return bool
2741 function _authenticate($login_procedure)
2743 if(!$this->_authorization()){
2744 return false;
2745 }else{
2746 list($user_name, $password) = $this->_getUserNameAndPassword();
2747 if(is_array($login_procedure)){
2748 if(!isset($login_procedure['handler'])){
2749 return isset($login_procedure[$user_name]) && $login_procedure[$user_name] == $password;
2750 }elseif(is_a($login_procedure['handler']) && method_exists($login_procedure['handler'], $login_procedure['method'])){
2751 return $login_procedure['handler']->$login_procedure['method']($user_name, $password, $this);
2753 }elseif(method_exists($login_procedure, 'authenticate')){
2754 return $login_procedure->authenticate($user_name, $password, $this);
2757 return false;
2760 function _getUserNameAndPassword()
2762 $credentials = $this->_decodeCredentials();
2763 return !is_array($credentials) ? split('/:/', $credentials , 2) : $credentials;
2766 function _authorization()
2768 return
2769 empty($this->Request->env['PHP_AUTH_USER']) ? (
2770 empty($this->Request->env['HTTP_AUTHORIZATION']) ? (
2771 empty($this->Request->env['X-HTTP_AUTHORIZATION']) ? (
2772 empty($this->Request->env['X_HTTP_AUTHORIZATION']) ? (
2773 isset($this->Request->env['REDIRECT_X_HTTP_AUTHORIZATION']) ?
2774 $this->Request->env['REDIRECT_X_HTTP_AUTHORIZATION'] : null
2775 ) : $this->Request->env['X_HTTP_AUTHORIZATION']
2776 ) : $this->Request->env['X-HTTP_AUTHORIZATION']
2777 ) : $this->Request->env['HTTP_AUTHORIZATION']
2778 ) : array($this->Request->env['PHP_AUTH_USER'], $this->Request->env['PHP_AUTH_PW']);
2781 function _decodeCredentials()
2783 $authorization = $this->_authorization();
2784 if(is_array($authorization)){
2785 return $authorization;
2787 $credentials = (array)split(' ', $authorization);
2788 return base64_decode(array_pop($credentials));
2791 function _encodeCredentials($user_name, $password)
2793 return 'Basic '.base64_encode("$user_name:$password");
2796 function _authenticationRequest($realm)
2798 header('WWW-Authenticate: Basic realm="' . str_replace('"','',$realm) . '"');
2800 if(method_exists($this, 'access_denied')){
2801 $this->access_denied();
2802 }else{
2803 header('HTTP/1.0 401 Unauthorized');
2804 echo "HTTP Basic: Access denied.\n";
2805 exit;
2809 function _ensureActionExists()
2811 if(!method_exists($this, $this->_action_name)){
2812 if(AK_ENVIRONMENT == 'development'){
2813 AK_LOG_EVENTS && !empty($this->_Logger) ? $this->_Logger->error('Action '.$this->_action_name.' not found on '.$this->getControllerName()) : null;
2814 trigger_error(Ak::t('Controller <i>%controller_name</i> can\'t handle action %action_name',
2815 array(
2816 '%controller_name' => $this->getControllerName(),
2817 '%action_name' => $this->_action_name,
2818 )), E_USER_ERROR);
2819 }elseif(@include(AK_PUBLIC_DIR.DS.'405.php')){
2820 exit;
2821 }else{
2822 header("HTTP/1.1 405 Method Not Allowed");
2823 die('405 Method Not Allowed');
2831 * Function for getting the singleton controller;
2833 * @return AkActionController instance
2835 function &AkActionController()
2837 $params = func_num_args() == 0 ? null : func_get_args();
2838 $AkActionController =& Ak::singleton('AkActionController', $params);
2839 return $AkActionController;