Fixing file upload params ($_FILES) normalization. Closes #75
[akelos.git] / lib / AkActionController.php
blobf71da42a288c1d4a082f1a7cb7e0a3f151d5daaa
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 if(!class_exists('AkActionController')){
13 require_once(AK_LIB_DIR.DS.'AkObject.php');
15 defined('AK_HIGH_LOAD_MODE') ? null : define('AK_HIGH_LOAD_MODE', false);
17 /**
18 * @package ActionController
19 * @subpackage Base
20 * @author Bermi Ferrer <bermi a.t akelos c.om>
21 * @copyright Copyright (c) 2002-2006, Akelos Media, S.L. http://www.akelos.org
22 * @license GNU Lesser General Public License <http://www.gnu.org/copyleft/lesser.html>
25 class AkActionController extends AkObject
27 var $_high_load_mode = AK_HIGH_LOAD_MODE;
28 var $_enable_plugins = true;
29 var $_auto_instantiate_models = true;
30 var $validate_output = false;
32 var $_ssl_requirement = false;
33 var $_ssl_allowed_actions = array();
34 var $ssl_for_all_actions = true;
36 /**
37 * Determines whether the view has access to controller internals $this->Request, $this->Response, $this->session, and $this->Template.
38 * By default, it does.
40 var $_view_controller_internals = true;
42 /**
43 * Protected instance variable cache
45 var $_protected_variables_cache = array();
47 /**
48 * Prepends all the URL-generating helpers from AssetHelper.
49 * This makes it possible to easily move javascripts, stylesheets,
50 * and images to a dedicated asset server away from the main web server.
51 * Example:
52 * $this->_asset_host = 'http://assets.example.com';
54 var $asset_host = AK_ASSET_HOST;
57 var $_Logger;
59 /**
60 * Determines which template class should be used by AkActionController.
62 var $TemplateClass;
64 /**
65 * Turn on +_ignore_missing_templates+ if you want to unit test actions without
66 * making the associated templates.
68 var $_ignore_missing_templates;
70 /**
71 * Holds the Request object that's primarily used to get environment variables
73 var $Request;
75 /**
76 * Holds an array of all the GET, POST, and Url parameters passed to the action.
77 * Accessed like <tt>$this->params['post_id'];</tt>
78 * to get the post_id.
80 var $params = array();
82 /**
83 * Holds the Response object that's primarily used to set additional HTTP _headers
84 * through access like <tt>$this->Response->_headers['Cache-Control'] = 'no-cache';</tt>.
85 * Can also be used to access the final body HTML after a template
86 * has been rendered through $this->Response->body -- useful for <tt>after_filter</tt>s
87 * that wants to manipulate the output, such as a OutputCompressionFilter.
89 var $Response;
91 /**
92 * Holds an array of objects in the session. Accessed like <tt>$this->session['person']</tt>
93 * to get the object tied to the 'person' key. The session will hold any type of object
94 * as values, but the key should be a string.
96 var $session;
98 /**
99 * Holds an array of header names and values. Accessed like <tt>$this->_headers['Cache-Control']</tt>
100 * to get the value of the Cache-Control directive. Values should always be specified as strings.
102 var $_headers = array();
105 * Holds the array of variables that are passed on to the template class to be
106 * made available to the view. This array is generated by taking a snapshot of
107 * all the instance variables in the current scope just before a template is rendered.
109 var $_assigns = array();
112 * Holds the name of the action this controller is processing.
114 var $_action_name;
116 var $cookies;
118 var $helpers = 'default';
120 var $app_helpers;
121 var $plugin_helpers = 'all';
123 var $web_service;
124 var $web_services = array();
126 var $web_service_api;
127 var $web_service_apis = array();
129 var $module_name;
130 var $_module_path;
133 * Old fashioned way of dispatching requests. Please use AkDispatcher or roll your own.
135 * @deprecated
137 function handleRequest()
139 AK_LOG_EVENTS && empty($this->_Logger) ? ($this->_Logger =& Ak::getLogger()) : null;
140 AK_LOG_EVENTS && !empty($this->_Logger) ? $this->_Logger->warning('Using deprecated request dispatcher AkActionController::handleRequest. Use to AkDispatcher + AkDispatcher::dispatch instead.') : null;
141 require_once(AK_LIB_DIR.DS.'AkDispatcher.php');
142 $Dispatcher =& new AkDispatcher();
143 $Dispatcher->dispatch();
146 function process(&$Request, &$Response)
148 AK_LOG_EVENTS && empty($this->_Logger) ? ($this->_Logger =& Ak::getLogger()) : null;
150 $this->Request =& $Request;
151 $this->Response =& $Response;
152 $this->params = $this->Request->getParams();
153 $this->_action_name = $this->Request->getAction();
155 if(!method_exists($this, $this->_action_name)){
156 trigger_error(Ak::t('Controller <i>%controller_name</i> can\'t handle action %action_name',
157 array(
158 '%controller_name' => $this->getControllerName(),
159 '%action_name' => $this->_action_name,
160 )), E_USER_ERROR);
163 Ak::t('Akelos'); // We need to get locales ready
165 if($this->_high_load_mode !== true){
166 if(!empty($this->_auto_instantiate_models)){
167 $this->instantiateIncludedModelClasses();
169 if(!empty($this->_enable_plugins)){
170 $this->loadPlugins();
172 if(!empty($this->helpers)){
173 $this->instantiateHelpers();
175 }else{
176 $this->_enableLayoutOnRender = false;
179 $this->_ensureProperProtocol();
181 // After filters
182 $this->afterFilter('_handleFlashAttribute');
184 if(!empty($this->validate_output)){
185 $this->beforeFilter('_validateGeneratedXhtml');
189 $this->_loadActionView();
191 if(isset($this->api)){
192 require_once(AK_LIB_DIR.DS.'AkActionWebService.php');
193 $this->aroundFilter(new AkActionWebService($this));
196 $this->performActionWithFilters($this->_action_name);
198 if (!$this->_hasPerformed()){
199 $this->_enableLayoutOnRender ? $this->renderWithLayout() : $this->renderWithoutLayout();
202 $this->Response->outputResults();
205 function _loadActionView()
207 empty($this->_assigns) ? ($this->_assigns = array()) : null;
208 empty($this->_default_render_status_code) ? ($this->_default_render_status_code = 200) : null;
209 $this->_enableLayoutOnRender = !isset($this->_enableLayoutOnRender) ? true : $this->_enableLayoutOnRender;
210 $this->passed_args = !isset($this->Request->pass)? array() : $this->Request->pass;
211 empty($this->cookies) && isset($_COOKIE) ? ($this->cookies =& $_COOKIE) : null;
213 if(empty($this->Template)){
214 require_once(AK_LIB_DIR.DS.'AkActionView.php');
215 require_once(AK_LIB_DIR.DS.'AkActionView'.DS.'AkPhpTemplateHandler.php');
216 $this->Template =& new AkActionView($this->_getTemplateBasePath(),
217 $this->Request->getParameters(),$this->Request->getController());
219 $this->Template->_controllerInstance =& $this;
220 $this->Template->_registerTemplateHandler('tpl','AkPhpTemplateHandler');
224 function loadPlugins()
226 Ak::loadPlugins();
230 * Creates an instance of each available helper and links it into into current controller.
232 * Per example, if a helper TextHelper is located into the file text_helper.php.
233 * An instance is created on current controller
234 * at $this->text_helper. This instance is also available on the view by calling $text_helper.
236 * Helpers can be found at lib/AkActionView/helpers (this might change in a future)
238 function instantiateHelpers()
240 $helpers = $this->getDefaultHelpers();
241 $helpers = array_merge($helpers, $this->getApplicationHelpers());
242 $helpers = array_merge($helpers, $this->getPluginHelpers());
244 require_once(AK_LIB_DIR.DS.'AkActionView'.DS.'AkActionViewHelper.php');
246 $current_controller_helper = $this->getControllerName();
247 $current_controller_helper_file_name = AK_HELPERS_DIR.DS.$this->_module_path.AkInflector::underscore($current_controller_helper).'_helper.php';
249 if(file_exists($current_controller_helper_file_name)){
250 $helpers[$current_controller_helper_file_name] = $current_controller_helper;
253 $available_helpers = array();
254 foreach ($helpers as $file=>$helper){
255 $helper_class_name = strstr($helper, 'Helper') ? $helper : $helper.'Helper';
256 $full_path = preg_match('/[\\\\\/]+/',$file);
257 $file_path = $full_path ? $file : AK_LIB_DIR.DS.'AkActionView'.DS.'helpers'.DS.$file;
258 include_once($file_path);
259 if(class_exists($helper_class_name)){
260 $attribute_name = $full_path ? AkInflector::underscore($helper_class_name) : substr($file,0,-4);
261 $available_helpers[] = $attribute_name;
262 $this->$attribute_name =& new $helper_class_name(&$this);
263 if(method_exists($this->$attribute_name,'setController')){
264 $this->$attribute_name->setController(&$this);
266 if(method_exists($this->$attribute_name,'init')){
267 $this->$attribute_name->init();
271 defined('AK_ACTION_CONTROLLER_AVAILABLE_HELPERS') ? null : define('AK_ACTION_CONTROLLER_AVAILABLE_HELPERS', join(',',$available_helpers));
274 function getDefaultHelpers()
276 if($this->helpers == 'default'){
277 $available_helpers = Ak::dir(AK_LIB_DIR.DS.'AkActionView'.DS.'helpers',array('dirs'=>false));
278 $helper_names = array();
279 foreach ($available_helpers as $available_helper){
280 $helper_names[$available_helper] = AkInflector::classify(substr($available_helper,0,-10));
282 return $helper_names;
283 }elseif (is_string($this->helpers)){
284 return Ak::stringToArray($this->helpers);
286 return $this->helpers;
289 function getApplicationHelpers()
291 $helper_names = array();
292 if ($this->app_helpers == 'all'){
293 $available_helpers = Ak::dir(AK_HELPERS_DIR,array('dirs'=>false));
294 $helper_names = array();
295 foreach ($available_helpers as $available_helper){
296 $helper_names[AK_HELPERS_DIR.DS.$available_helper] = AkInflector::classify(substr($available_helper,0,-10));
299 } elseif (!empty($this->app_helpers)){
300 foreach (Ak::toArray($this->app_helpers) as $helper_name){
301 $helper_names[AK_HELPERS_DIR.DS.AkInflector::underscore($helper_name).'_helper.php'] = AkInflector::camelize($helper_name);
304 return $helper_names;
307 function getPluginHelpers()
309 $helper_names = AkActionController::addPluginHelper(false); // Trick for getting helper names set by AkPlugin::addHelper
310 if(empty($helper_names)){
311 return array();
312 }elseif ($this->plugin_helpers == 'all'){
313 return $helper_names;
314 }else {
315 $selected_helper_names = array();
316 foreach (Ak::toArray($this->plugin_helpers) as $helper_name){
317 $helper_name = AkInflector::camelize($helper_name);
318 if($path = array_shift(array_keys($helper_names, AkInflector::camelize($helper_name)))){
319 $selected_helper_names[$path] = $helper_names[$path];
322 return $selected_helper_names;
327 * Used for adding helpers to the base class like those added by the plugins engine.
329 * @param string $helper_name Helper class name like CalendarHelper
330 * @param array $options - path: Path to the helper class, defaults to AK_PLUGINS_DIR/helper_name/lib/helper_name.php
332 function addPluginHelper($helper_name, $options = array())
334 static $helpers = array();
335 if($helper_name === false){
336 return $helpers;
338 $underscored_helper_name = AkInflector::underscore($helper_name);
339 $default_options = array(
340 'path' => AK_PLUGINS_DIR.DS.$underscored_helper_name.DS.'lib'.DS.$underscored_helper_name.'.php'
342 $options = array_merge($default_options, $options);
343 $helpers[$options['path']] = $helper_name;
346 function _validateGeneratedXhtml()
348 require_once(AK_LIB_DIR.DS.'AkXhtmlValidator.php');
349 $XhtmlValidator = new AkXhtmlValidator();
350 if($XhtmlValidator->validate($this->Response->body) === false){
351 $this->Response->sendHeaders();
352 echo '<h1>'.Ak::t('Ooops! There are some errors on current XHTML page').'</h1>';
353 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";
354 $XhtmlValidator->showErrors();
355 echo "<hr /><h2>".Ak::t('Showing XHTML code')."</h2><hr /><div style='border:5px solid red;margin:5px;padding:15px;'>".$this->Response->body."</pre>";
356 die();
362 * Methods for loading desired models into this controller
364 function setModel($model)
366 $this->instantiateIncludedModelClasses(array($model));
369 function setModels($models)
371 $this->instantiateIncludedModelClasses($models);
374 function instantiateIncludedModelClasses()
376 require_once(AK_LIB_DIR.DS.'AkActiveRecord.php');
377 require_once(AK_APP_DIR.DS.'shared_model.php');
379 empty($this->model) ? ($this->model = $this->params['controller']) : null;
380 empty($this->models) ? ($this->models = array()) : null;
382 $models =array_unique(array_merge(
383 Ak::import($this->model),
384 Ak::import($this->models)));
386 foreach ($models as $model){
387 $this->instantiateModelClass($model);
391 function instantiateModelClass($model_class_name, $finder_options = array())
393 $underscored_model_class_name = AkInflector::underscore($model_class_name);
395 $id = empty($this->params[$underscored_model_class_name]['id']) ?
396 (empty($this->params['id']) ? false :
397 ($model_class_name == $this->getControllerName() ? $this->params['id'] : false)) :
398 $this->params[$underscored_model_class_name]['id'];
400 if(class_exists($model_class_name)){
401 $underscored_model_class_name = AkInflector::underscore($model_class_name);
403 if(!isset($this->$model_class_name) || !isset($this->$underscored_model_class_name)){
404 if($finder_options !== false && is_numeric($id)){
405 $model =& new $model_class_name();
406 if(empty($finder_options)){
407 $model =& $model->find($id);
408 }else{
409 $model =& $model->find($id, $finder_options);
411 }else{
412 $model =& new $model_class_name();
414 if(!isset($this->$model_class_name)){
415 $this->$model_class_name =& $model;
417 if(!isset($this->$underscored_model_class_name)){
418 $this->$underscored_model_class_name =& $model;
427 * Renders the content that will be returned to the browser as the Response body.
429 * === Rendering an action
431 * Action rendering is the most common form and the type used automatically by
432 * Action Controller when nothing else is specified. By default, actions are
433 * rendered within the current layout (if one exists).
435 * * Renders the template for the action "goal" within the current controller
437 * $this->render(array('action'=>'goal'));
439 * * Renders the template for the action "short_goal" within the current controller,
440 * but without the current active layout
442 * $this->render(array('action'=>'short_goal','layout'=>false));
444 * * Renders the template for the action "long_goal" within the current controller,
445 * but with a custom layout
447 * $this->render(array('action'=>'long_goal','layout'=>'spectacular'));
449 * === Rendering partials
451 * Partial rendering is most commonly used together with Ajax calls that only update
452 * one or a few elements on a page without reloading. Rendering of partials from
453 * the controller makes it possible to use the same partial template in
454 * both the full-page rendering (by calling it from within the template) and when
455 * sub-page updates happen (from the controller action responding to Ajax calls).
456 * By default, the current layout is not used.
458 * * Renders the partial located at app/views/controller/_win.tpl
460 * $this->render(array('partial'=>'win'));
462 * * Renders the partial with a status code of 500 (internal error)
464 * $this->render(array('partial'=>'broken','status'=>500));
466 * * Renders the same partial but also makes a local variable available to it
468 * $this->render(array('partial' => 'win', 'locals' => array('name'=>'david')));
470 * * Renders a collection of the same partial by making each element of $wins available through
471 * the local variable "win" as it builds the complete Response
473 * $this->render(array('partial'=>'win','collection'=>$wins));
475 * * Renders the same collection of partials, but also renders the win_divider partial in between
476 * each win partial.
478 * $this->render(array('partial'=>'win','collection'=>$wins,'spacer_template'=>'win_divider'));
480 * === Rendering a template
482 * Template rendering works just like action rendering except that it takes a
483 * path relative to the template root.
484 * The current layout is automatically applied.
486 * * Renders the template located in app/views/weblog/show.tpl
487 * $this->render(array('template'=>'weblog/show'));
489 * === Rendering a file
491 * File rendering works just like action rendering except that it takes a
492 * filesystem path. By default, the path is assumed to be absolute, and the
493 * current layout is not applied.
495 * * Renders the template located at the absolute filesystem path
496 * $this->render(array('file'=>'/path/to/some/template.tpl'));
497 * $this->render(array('file'=>'c:/path/to/some/template.tpl'));
499 * * Renders a template within the current layout, and with a 404 status code
500 * $this->render(array('file' => '/path/to/some/template.tpl', 'layout' => true, 'status' => 404));
501 * $this->render(array('file' => 'c:/path/to/some/template.tpl', 'layout' => true, 'status' => 404));
503 * * Renders a template relative to the template root and chooses the proper file extension
504 * $this->render(array('file' => 'some/template', 'use_full_path' => true));
507 * === Rendering text
509 * Rendering of text is usually used for tests or for rendering prepared content,
510 * such as a cache. By default, text
511 * rendering is not done within the active layout.
513 * * Renders the clear text "hello world" with status code 200
514 * $this->render(array('text' => 'hello world!'));
516 * * Renders the clear text "Explosion!" with status code 500
517 * $this->render(array('text' => "Explosion!", 'status' => 500 ));
519 * * Renders the clear text "Hi there!" within the current active layout (if one exists)
520 * $this->render(array('text' => "Explosion!", 'layout' => true));
522 * * Renders the clear text "Hi there!" within the layout
523 * * placed in "app/views/layouts/special.tpl"
524 * $this->render(array('text' => "Explosion!", 'layout => "special"));
527 * === Rendering an inline template
529 * Rendering of an inline template works as a cross between text and action
530 * rendering where the source for the template
531 * is supplied inline, like text, but its evaled by PHP, like action. By default,
532 * PHP is used for rendering and the current layout is not used.
534 * * Renders "hello, hello, hello, again"
535 * $this->render(array('inline' => "<?php echo str_repeat('hello, ', 3).'again'?>" ));
537 * * Renders "hello david"
538 * $this->render(array('inline' => "<?php echo 'hello ' . $name ?>", 'locals' => array('name' => 'david')));
541 * === Rendering nothing
543 * Rendering nothing is often convenient in combination with Ajax calls that
544 * perform their effect client-side or
545 * when you just want to communicate a status code. Due to a bug in Safari, nothing
546 * actually means a single space.
548 * * Renders an empty Response with status code 200
549 * $this->render(array('nothing' => true));
551 * * Renders an empty Response with status code 401 (access denied)
552 * $this->render(array('nothing' => true, 'status' => 401));
554 function render($options = null, $status = 200)
556 if(empty($options['partial']) && $this->_hasPerformed()){
557 $this->_doubleRenderError(Ak::t("Can only render or redirect once per action"));
558 return false;
561 $this->_flash_handled ? null : $this->_handleFlashAttribute();
563 if(!is_array($options)){
564 return $this->renderFile(empty($options) ? $this->getDefaultTemplateName() : $options, $status, true);
567 if(!empty($options['text'])){
568 return $this->renderText($options['text'], @$options['status']);
569 }else{
571 if(!empty($options['file'])){
572 return $this->renderFile($options['file'], @$options['status'], @$options['use_full_path'], @(array)$options['locals']);
573 }elseif(!empty($options['template'])){
574 return $this->renderFile($options['template'], @$options['status'], true);
575 }elseif(!empty($options['inline'])){
576 return $this->renderTemplate($options['inline'], @$options['status'], @$options['type'], @(array)$options['locals']);
577 }elseif(!empty($options['action'])){
578 return $this->renderAction($options['action'], @$options['status'], @$options['layout']);
579 }elseif(!empty($options['partial'])){
580 if($options['partial'] === true){
581 $options['partial'] = !empty($options['template']) ? $options['template'] : $this->getDefaultTemplateName();
583 if(!empty($options['collection'])){
584 return $this->renderPartialCollection($options['partial'], $options['collection'], @$options['spacer_template'], @$options['locals'], @$options['status']);
585 }else{
586 return $this->renderPartial($options['partial'], @$options['object'], @$options['locals'], @$options['status']);
588 }elseif(!empty($options['nothing'])){
589 // Safari doesn't pass the _headers of the return if the Response is zero length
590 return $this->renderText(' ', @$options['status']);
591 }else{
592 return $this->renderFile($this->getDefaultTemplateName(), @$options['status'], true);
594 return true;
599 * Renders according to the same rules as <tt>render</tt>, but returns the result in a string instead
600 * of sending it as the Response body to the browser.
602 function renderToString($options = null)
604 $result = $this->render($options);
605 $this->eraseRenderResults();
606 $this->variables_added = null;
607 $this->Template->_assigns_added = null;
608 return $result;
611 function renderAction($_action_name, $status = null, $with_layout = true)
613 $this->$_action_name();
614 $template = $this->getDefaultTemplateName($_action_name);
615 if(!empty($with_layout) && !$this->_isTemplateExemptFromLayout($template)){
616 return $this->renderWithLayout($template, $status, $with_layout);
617 }else{
618 return $this->renderWithoutLayout($template, $status);
622 function renderFile($template_path, $status = null, $use_full_path = false, $locals = array())
624 $this->_addVariablesToAssigns();
625 $locals = array_merge($locals,$this->_assigns);
627 if($use_full_path){
628 $this->_assertExistanceOfTemplateFile($template_path);
631 AK_LOG_EVENTS && !empty($this->_Logger) ? $this->_Logger->message("Rendering $this->full_template_path" . (!empty($status) ? " ($status)":'')) : null;
633 return $this->renderText($this->Template->renderFile($template_path, $use_full_path, $locals), $status);
636 function renderTemplate($template, $status = null, $type = 'tpl', $local_assigns = array())
638 $this->_addVariablesToAssigns();
639 $local_assigns = array_merge($local_assigns,$this->_assigns);
640 return $this->renderText($this->Template->renderTemplate($type, $template, null, $local_assigns), $status);
643 function renderText($text = null, $status = null)
645 $this->performed_render = true;
646 $this->Response->_headers['Status'] = !empty($status) ? $status : $this->_default_render_status_code;
647 $this->Response->body = $text;
648 return $text;
651 function renderNothing($status = null)
653 return $this->renderText(' ', $status);
656 function renderPartial($partial_path = null, $object = null, $local_assigns = null, $status = null)
658 $partial_path = empty($partial_path) ? $this->getDefaultTemplateName() : $partial_path;
659 $this->variables_added = false;
660 $this->performed_render = false;
661 $this->_addVariablesToAssigns();
662 $this->Template->controller =& $this;
663 $this->$partial_path = $this->renderText($this->Template->renderPartial($partial_path, $object, array_merge($this->_assigns, (array)$local_assigns)), $status);
664 return $this->$partial_path;
667 function renderPartialCollection($partial_name, $collection, $partial_spacer_template = null, $local_assigns = null, $status = null)
669 $this->_addVariablesToAssigns();
670 $collection_name = AkInflector::pluralize($partial_name).'_collection';
671 $result = $this->Template->renderPartialCollection($partial_name, $collection, $partial_spacer_template, $local_assigns);
672 if(empty($this->$collection_name)){
673 $this->$collection_name = $result;
675 $this->variables_added = false;
676 $this->performed_render = false;
678 return $result;
681 function renderWithLayout($template_name = null, $status = null, $layout = null)
683 $template_name = empty($template_name) ? $this->getDefaultTemplateName() : $template_name;
684 return $this->renderWithALayout($template_name, $status, $layout);
687 function renderWithoutLayout($template_name = null, $status = null)
689 $template_name = empty($template_name) ? $this->getDefaultTemplateName() : $template_name;
690 return $this->render($template_name, $status);
694 * Clears the rendered results, allowing for another render to be performed.
696 function eraseRenderResults()
698 $this->Response->body = '';
699 $this->performed_render = false;
700 $this->variables_added = false;
703 function _addVariablesToAssigns()
705 if(empty($this->variables_added)){
706 $this->_addInstanceVariablesToAssigns();
707 $this->variables_added = true;
711 function _addInstanceVariablesToAssigns()
713 $this->_protected_variables_cache = array_merge($this->_protected_variables_cache, $this->_getProtectedInstanceVariables());
715 foreach (array_diff(array_keys(get_object_vars($this)), $this->_protected_variables_cache) as $attribute){
716 if($attribute[0] != '_'){
717 $this->_assigns[$attribute] =& $this->$attribute;
722 function _getProtectedInstanceVariables()
724 return !empty($this->_view_controller_internals) ?
725 array('_assigns', 'performed_redirect', 'performed_render','db') :
726 array('_assigns', 'performed_redirect', 'performed_render', 'session', 'cookies',
727 'Template','db','helpers','models','layout','Response','Request',
728 'params','passed_args');
733 * Use this to translate strings in the scope of your controller
735 * @see Ak::t
737 function t($string, $array = null)
739 return Ak::t($string, $array, AkInflector::underscore($this->getControllerName()));
745 * Redirects the browser to the target specified in +options+. This parameter can take one of three forms:
747 * * <tt>Array</tt>: The URL will be generated by calling $this->UrlFor with the +options+.
748 * * <tt>String starting with protocol:// (like http://)</tt>: Is passed straight through
749 * as the target for redirection.
750 * * <tt>String not containing a protocol</tt>: The current protocol and host is prepended to the string.
751 * * <tt>back</tt>: Back to the page that issued the Request-> Useful for forms that are
752 * triggered from multiple places.
753 * Short-hand for redirectTo(Request->env["HTTP_REFERER"])
755 * Examples:
756 * redirectTo(array('action' => 'show', 'id' => 5));
757 * redirectTo('http://www.akelos.com');
758 * redirectTo('/images/screenshot.jpg');
759 * redirectTo('back');
761 * The redirection happens as a "302 Moved" header.
763 function redirectTo($options = array(), $parameters_for_method_reference = null)
765 if(is_string($options)) {
766 if(preg_match('/^\w+:\/\/.*/',$options)){
767 if($this->_hasPerformed()){
768 $this->_doubleRenderError();
770 AK_LOG_EVENTS && !empty($this->_Logger) ? $this->_Logger->message('Redirected to '.$options) : null;
771 $this->_handleFlashAttribute();
772 $this->Response->redirect($options);
773 $this->Response->redirected_to = $options;
774 $this->performed_redirect = true;
775 }elseif ($options == 'back'){
776 $this->redirectTo($this->Request->env['HTTP_REFERER']);
777 }else{
778 $this->redirectTo($this->Request->getProtocol(). $this->Request->getHostWithPort(). $options);
780 }else{
781 if(empty($parameters_for_method_reference)){
782 $this->redirectTo($this->UrlFor($options));
783 $this->Response->redirected_to = $options;
784 }else{
785 $this->redirectTo($this->UrlFor($options, $parameters_for_method_reference));
786 $this->Response->redirected_to = $options;
787 $this->Response->redirected_to_method_params = $parameters_for_method_reference;
792 function redirectToAction($action, $options = array())
794 $this->redirectTo(array_merge(array('action'=>$action), $options));
799 * This methods are required for retrieving available controllers for URL Routing
801 function rewriteOptions($options)
803 $defaults = $this->defaultUrlOptions($options);
804 if(!empty($this->module_name)){
805 $defaults['module'] = $this->getModuleName();
807 if(!empty($options['controller']) && strstr($options['controller'], '/')){
808 $defaults['module'] = substr($options['controller'], 0, strrpos($options['controller'], '/'));
809 $options['controller'] = substr($options['controller'], strrpos($options['controller'], '/') + 1);
811 $options = !empty($defaults) ? array_merge($defaults, $options) : $options;
812 $options['controller'] = empty($options['controller']) ? AkInflector::underscore($this->getControllerName()) : $options['controller'];
813 return $options;
816 function getControllerName()
819 if(!isset($this->controller_name)){
820 $current_class_name = str_replace('_', '::', get_class($this));
822 $included_controllers = $this->_getIncludedControllerNames();
823 $lowercase_included_controllers = array_map('strtolower', $included_controllers);
824 $key = array_search(strtolower($current_class_name), $lowercase_included_controllers, true);
825 $found_controller = substr($included_controllers[$key], 0, -10);
826 $this->controller_name = $found_controller;
827 $this->_removeModuleNameFromControllerName();
830 return $this->controller_name;
833 function getModuleName()
835 return $this->module_name;
839 * Removes the modules name from the controller if exists.
841 * Additionally it sets the default url_options for this controller and the module name scope.
843 function _removeModuleNameFromControllerName()
845 if(strstr($this->controller_name, '::')){
846 $module_parts = substr($this->controller_name, 0, strrpos($this->controller_name, '::'));
847 $this->module_name = join('/', array_map(array('AkInflector','underscore'), strstr($module_parts, '::') ? explode('::', $module_parts) : array($module_parts)));
848 $this->controller_name = substr($this->controller_name, strrpos($this->controller_name, '::')+2);
853 function _getTemplateBasePath()
855 return AK_APP_DIR.DS.'views'.DS.(empty($this->_module_path)?'':$this->_module_path).$this->Request->getController();
858 function _getIncludedControllerNames()
860 $controllers = array();
861 foreach (get_included_files() as $file_name){
862 if(strstr($file_name,AK_CONTROLLERS_DIR)){
863 $controllers[] = AkInflector::modulize(str_replace(array(AK_CONTROLLERS_DIR.DS,'.php'),'',$file_name));
866 return $controllers;
874 * Overwrite to implement a number of default options that all urlFor-based methods will use.
875 * The default options should come in
876 * the form of a an array, just like the one you would use for $this->UrlFor directly. Example:
878 * function defaultUrlOptions($options)
880 * return array('project' => ($this->Project->isActive() ? $this->Project->url_name : 'unknown'));
883 * As you can infer from the example, this is mostly useful for situations where you want to
884 * centralize dynamic decisions about the urls as they stem from the business domain.
885 * Please note that any individual $this->UrlFor call can always override the defaults set
886 * by this method.
888 function defaultUrlOptions($options)
894 * Returns a URL that has been rewritten according to the options array and the defined Routes.
895 * (For doing a complete redirect, use redirectTo).
897 * <tt>$this->UrlFor</tt> is used to:
899 * All keys given to $this->UrlFor are forwarded to the Route module, save for the following:
900 * * <tt>anchor</tt> -- specifies the anchor name to be appended to the path. For example,
901 * <tt>$this->UrlFor(array('controller' => 'posts', 'action' => 'show', 'id' => 10, 'anchor' => 'comments'</tt>
902 * will produce "/posts/show/10#comments".
903 * * <tt>only_path</tt> -- if true, returns the absolute URL (omitting the protocol, host name, and port)
904 * * <tt>trailing_slash</tt> -- if true, adds a trailing slash, as in "/archive/2005/". Note that this
905 * is currently not recommended since it breaks caching.
906 * * <tt>host</tt> -- overrides the default (current) host if provided
907 * * <tt>protocol</tt> -- overrides the default (current) protocol if provided
909 * The URL is generated from the remaining keys in the array. A URL contains two key parts: the <base> and a query string.
910 * Routes composes a query string as the key/value pairs not included in the <base>.
912 * The default Routes setup supports a typical Akelos Framework path of "controller/action/id"
913 * where action and id are optional, with
914 * action defaulting to 'index' when not given. Here are some typical $this->UrlFor statements
915 * and their corresponding URLs:
917 * $this->UrlFor(array('controller'=>'posts','action'=>'recent')); // 'proto://host.com/posts/recent'
918 * $this->UrlFor(array('controller'=>'posts','action'=>'index')); // 'proto://host.com/posts'
919 * $this->UrlFor(array('controller'=>'posts','action'=>'show','id'=>10)); // 'proto://host.com/posts/show/10'
921 * When generating a new URL, missing values may be filled in from the current
922 * Request's parameters. For example,
923 * <tt>$this->UrlFor(array('action'=>'some_action'));</tt> will retain the current controller,
924 * as expected. This behavior extends to other parameters, including <tt>controller</tt>,
925 * <tt>id</tt>, and any other parameters that are placed into a Route's path.
927 * The URL helpers such as <tt>$this->UrlFor</tt> have a limited form of memory:
928 * when generating a new URL, they can look for missing values in the current Request's parameters.
929 * Routes attempts to guess when a value should and should not be
930 * taken from the defaults. There are a few simple rules on how this is performed:
932 * * If the controller name begins with a slash, no defaults are used: <tt>$this->UrlFor(array('controller'=>'/home'));</tt>
933 * * If the controller changes, the action will default to index unless provided
935 * The final rule is applied while the URL is being generated and is best illustrated by an example. Let us consider the
936 * route given by <tt>map->connect('people/:last/:first/:action', array('action' => 'bio', 'controller' => 'people'))</tt>.
938 * Suppose that the current URL is "people/hh/david/contacts". Let's consider a few
939 * different cases of URLs which are generated from this page.
941 * * <tt>$this->UrlFor(array('action'=>'bio'));</tt> -- During the generation of this URL,
942 * default values will be used for the first and
943 * last components, and the action shall change. The generated URL will be, "people/hh/david/bio".
944 * * <tt>$this->UrlFor(array('first'=>'davids-little-brother'));</tt> This
945 * generates the URL 'people/hh/davids-little-brother' -- note
946 * that this URL leaves out the assumed action of 'bio'.
948 * However, you might ask why the action from the current Request, 'contacts', isn't
949 * carried over into the new URL. The answer has to do with the order in which
950 * the parameters appear in the generated path. In a nutshell, since the
951 * value that appears in the slot for <tt>first</tt> is not equal to default value
952 * for <tt>first</tt> we stop using defaults. On it's own, this rule can account
953 * for much of the typical Akelos Framework URL behavior.
955 * Although a convienence, defaults can occasionaly get in your way. In some cases
956 * a default persists longer than desired.
957 * The default may be cleared by adding <tt>'name' => null</tt> to <tt>$this->UrlFor</tt>'s options.
958 * This is often required when writing form helpers, since the defaults in play
959 * may vary greatly depending upon where the helper is used from. The following line
960 * will redirect to PostController's default action, regardless of the page it is
961 * displayed on:
963 * $this->UrlFor(array('controller' => 'posts', 'action' => null));
965 * If you explicitly want to create a URL that's almost the same as the current URL, you can do so using the
966 * overwrite_params options. Say for your posts you have different views for showing and printing them.
967 * Then, in the show view, you get the URL for the print view like this
969 * $this->UrlFor(array('overwrite_params' => array('action' => 'print')));
971 * This takes the current URL as is and only exchanges the action. In contrast,
972 * <tt>$this->UrlFor(array('action'=>'print'));</tt>
973 * would have slashed-off the path components after the changed action.
975 function urlFor($options = array(), $parameters_for_method_reference = null)
977 return $this->rewrite($this->rewriteOptions($options));
980 function addToUrl($options = array(), $options_to_exclude = array())
982 $options_to_exclude = array_merge(array('ak','lang',AK_SESSION_NAME,'AK_SESSID','PHPSESSID'), $options_to_exclude);
983 $options = array_merge(array_merge(array('action'=>$this->Request->getAction()),$this->params),$options);
984 foreach ($options_to_exclude as $option_to_exclude){
985 unset($options[$option_to_exclude]);
987 return $this->urlFor($options);
990 function getActionName()
992 return $this->Request->getAction();
996 function _doubleRenderError($message = null)
998 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);
1001 function _hasPerformed()
1003 return !empty($this->performed_render) || !empty($this->performed_redirect);
1006 function _getRequestOrigin()
1008 return $this->Request->remote_ip.' at '.Ak::getDate();
1011 function _getCompleteRequestUri()
1013 return $this->Request->protocol . $this->Request->host . $this->Request->request_uri;
1016 function _closeSession()
1018 !empty($this->session) ? session_write_close() : null;
1022 function _hasTemplate($template_name = null)
1024 return file_exists(empty($template_name) ? $this->getDefaultTemplateName() : $template_name);
1027 function _templateIsPublic($template_name = null)
1029 $template_name = empty($template_name) ? $this->getDefaultTemplateName() : $template_name;
1030 return $this->Template->fileIsPublic($template_name);
1033 function _isTemplateExemptFromLayout($template_name = null)
1035 $template_name = empty($template_name) ? $this->getDefaultTemplateName() : $template_name;
1036 return $this->Template->_javascriptTemplateExists($template_name);
1039 function _assertExistanceOfTemplateFile($template_name)
1041 $extension = $this->Template->delegateTemplateExists($template_name);
1042 $this->full_template_path = $this->Template->getFullTemplatePath($template_name, $extension ? $extension : 'tpl');
1043 if(!$this->_hasTemplate($this->full_template_path)){
1044 if(!empty($this->_ignore_missing_templates) && $this->_ignore_missing_templates === true){
1045 return;
1047 $template_type = strstr($template_name,'layouts') ? 'layout' : 'template';
1048 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);
1052 function getDefaultTemplateName($default_action_name = null)
1054 return empty($default_action_name) ? (empty($this->_default_template_name) ? $this->_action_name : $this->_default_template_name) : $default_action_name;
1057 function setDefaultTemplateName($template_name)
1059 $this->_default_template_name = $template_name;
1064 function rewrite($options = array())
1066 return $this->_rewriteUrl($this->_rewritePath($options), $options);
1070 function toString()
1072 return $this->Request->getProtocol().$this->Request->getHostWithPort().
1073 $this->Request->getPath().$this->parameters['controller'].$this->parameters['action'].$this->parameters['inspect'];
1077 * Given a path and options, returns a rewritten URL string
1079 function _rewriteUrl($path, $options)
1081 $rewritten_url = '';
1082 if(empty($options['only_path'])){
1083 $rewritten_url .= !empty($options['protocol']) ? $options['protocol'] : $this->Request->getProtocol();
1084 $rewritten_url .= empty($rewritten_url) || strpos($rewritten_url,'://') ? '' : '://';
1085 $rewritten_url .= $this->_rewriteAuthentication($options);
1086 $rewritten_url .= !empty($options['host']) ? $options['host'] : $this->Request->getHostWithPort();
1087 $options = Ak::delete($options, array('user','password','host','protocol'));
1090 $rewritten_url .= empty($options['skip_relative_url_root']) ? $this->Request->getRelativeUrlRoot() : '';
1092 if(empty($options['skip_url_locale'])){
1093 $locale = $this->Request->getLocaleFromUrl();
1094 if(empty($options['lang'])){
1095 $rewritten_url .= (empty($locale) ? '' : '/').$locale;
1100 $rewritten_url .= (substr($rewritten_url,-1) == '/' ? '' : (AK_URL_REWRITE_ENABLED ? '' : (!empty($path[0]) && $path[0] != '/' ? '/' : '')));
1101 $rewritten_url .= $path;
1102 $rewritten_url .= empty($options['trailing_slash']) ? '' : '/';
1103 $rewritten_url .= empty($options['anchor']) ? '' : '#'.$options['anchor'];
1105 return $rewritten_url;
1108 function _rewriteAuthentication($options)
1110 if(!isset($options['user']) && isset($options['password'])){
1111 return urlencode($options['user']).':'.urlencode($options['password']).'@';
1112 }else{
1113 return '';
1117 function _rewritePath($options)
1119 if(!empty($options['params'])){
1120 foreach ($options['params'] as $k=>$v){
1121 $options[$k] = $v;
1123 unset($options['params']);
1125 if(!empty($options['overwrite_params'])){
1126 foreach ($options['overwrite_params'] as $k=>$v){
1127 $options[$k] = $v;
1129 unset($options['overwrite_params']);
1131 foreach (array('anchor', 'params', 'only_path', 'host', 'protocol', 'trailing_slash', 'skip_relative_url_root') as $k){
1132 unset($options[$k]);
1134 $path = Ak::toUrl($options);
1135 return $path;
1139 * Returns a query string with escaped keys and values from the passed array. If the passed
1140 * array contains an 'id' it'll
1141 * be added as a path element instead of a regular parameter pair.
1143 function buildQueryString($array, $only_keys = null)
1145 $array = !empty($only_keys) ? array_keys($array) : $array;
1146 return Ak::toUrl($array);
1151 * Layouts reverse the common pattern of including shared headers and footers in many templates
1152 * to isolate changes in repeated setups. The inclusion pattern has pages that look like this:
1154 * <?php echo $controller->render('shared/header') ?>
1155 * Hello World
1156 * <?php echo $controller->render('shared/footer') ?>
1158 * This approach is a decent way of keeping common structures isolated from the
1159 * changing content, but it's verbose and if( you ever want to change the structure
1160 * of these two includes, you'll have to change all the templates.
1162 * With layouts, you can flip it around and have the common structure know where
1163 * to insert changing content. This means that the header and footer are only
1164 * mentioned in one place, like this:
1166 * <!-- The header part of this layout -->
1167 * <?php echo $content_for_layout ?>
1168 * <!-- The footer part of this layout -->
1170 * And then you have content pages that look like this:
1172 * hello world
1174 * Not a word about common structures. At rendering time, the content page is
1175 * computed and then inserted in the layout,
1176 * like this:
1178 * <!-- The header part of this layout -->
1179 * hello world
1180 * <!-- The footer part of this layout -->
1182 * == Accessing shared variables
1184 * Layouts have access to variables specified in the content pages and vice versa.
1185 * This allows you to have layouts with references that won't materialize before
1186 * rendering time:
1188 * <h1><?php echo $page_title ?></h1>
1189 * <?php echo $content_for_layout ?>
1191 * ...and content pages that fulfill these references _at_ rendering time:
1193 * <?php $page_title = 'Welcome'; ?>
1194 * Off-world colonies offers you a chance to start a new life
1196 * The result after rendering is:
1198 * <h1>Welcome</h1>
1199 * Off-world colonies offers you a chance to start a new life
1201 * == Automatic layout assignment
1203 * If there is a template in <tt>app/views/layouts/</tt> with the same name as
1204 * the current controller then it will be automatically
1205 * set as that controller's layout unless explicitly told otherwise. Say you have
1206 * a WeblogController, for example. If a template named <tt>app/views/layouts/weblog.tpl</tt>
1207 * exists then it will be automatically set as the layout for your WeblogController.
1208 * You can create a layout with the name <tt>application.tpl</tt>
1209 * and this will be set as the default controller if there is no layout with
1210 * the same name as the current controller and there is no layout explicitly
1211 * assigned on the +layout+ attribute. Setting a layout explicitly will always
1212 * override the automatic behaviour
1213 * for the controller where the layout is set. Explicitly setting the layout
1214 * in a parent class, though, will not override the
1215 * child class's layout assignement if the child class has a layout with the same name.
1217 * == Inheritance for layouts
1219 * Layouts are shared downwards in the inheritance hierarchy, but not upwards. Examples:
1221 * class BankController extends AkActionController
1223 * var $layout = 'bank_standard';
1226 * class InformationController extends BankController
1230 * class VaultController extends BankController
1232 * var $layout = 'access_level_layout';
1235 * class EmployeeController extends BankController
1237 * var $layout = null;
1240 * The InformationController uses 'bank_standard' inherited from the BankController, the VaultController
1241 * and picks the layout 'access_level_layout', and the EmployeeController doesn't want to use a layout at all.
1243 * == Types of layouts
1245 * Layouts are basically just regular templates, but the name of this template needs not be specified statically. Sometimes
1246 * you want to alternate layouts depending on runtime information, such as whether someone is logged in or not. This can
1247 * be done either by an inline method.
1249 * The method reference is the preferred approach to variable layouts and is used like this:
1251 * class WeblogController extends AkActionController
1253 * function __construct()
1255 * $this->setLayout(array(&$this, '_writersAndReaders'));
1258 * function index()
1260 * // fetching posts
1263 * function _writersAndReaders()
1265 * return is_logged_in() ? 'writer_layout' : 'reader_layout';
1269 * Now when a new request for the index action is processed, the layout will vary depending on whether the person accessing
1270 * is logged in or not.
1272 * The most common way of specifying a layout is still just as a plain template name:
1274 * class WeblogController extends AkActionController
1276 * var $layout = 'weblog_standard';
1279 * If no directory is specified for the template name, the template will by default by looked for in +app/views/layouts/+.
1281 * == Conditional layouts
1283 * If you have a layout that by default is applied to all the actions of a controller, you still have the option of rendering
1284 * 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
1285 * <tt>only</tt> and <tt>except</tt> options can be passed to the layout call. For example:
1287 * class WeblogController extends AkActionController
1289 * function __construct()
1291 * $this->setLayout('weblog_standard', array('except' => 'rss'));
1294 * // ...
1298 * This will assign 'weblog_standard' as the WeblogController's layout except for the +rss+ action, which will not wrap a layout
1299 * around the rendered view.
1301 * Both the <tt>only</tt> and <tt>except</tt> condition can accept an arbitrary number of method names, so
1302 * <tt>'except' => array('rss', 'text_only')</tt> is valid, as is <tt>'except' => 'rss'</tt>.
1304 * == Using a different layout in the action render call
1306 * If most of your actions use the same layout, it makes perfect sense to define a controller-wide layout as described above.
1307 * Some times you'll have exceptions, though, where one action wants to use a different layout than the rest of the controller.
1308 * This is possible using the <tt>render</tt> method. It's just a bit more manual work as you'll have to supply fully
1309 * qualified template and layout names as this example shows:
1311 * class WeblogController extends AkActionController
1313 * function help()
1315 * $this->render(array('action'=>'help/index','layout'=>'help'));
1321 * If a layout is specified, all actions rendered through render and render_action will have their result assigned
1322 * to <tt>$this->content_for_layout</tt>, which can then be used by the layout to insert their contents with
1323 * <tt><?php echo $$this->content_for_layout ?></tt>. This layout can itself depend on instance variables assigned during action
1324 * performance and have access to them as any normal template would.
1326 function setLayout($template_name, $conditions = array())
1328 $this->_addLayoutConditions($conditions);
1329 $this->layout = $template_name;
1332 function getLayoutConditions()
1334 return empty($this->_layout_conditions) ? array() : $this->_layout_conditions;
1337 function _addLayoutConditions($conditions)
1339 $this->_layout_conditions = $conditions;
1345 * Returns the name of the active layout. If the layout was specified as a method reference, this method
1346 * is called and the return value is used. Likewise if( the layout was specified as an inline method (through a method
1347 * object). If the layout was defined without a directory, layouts is assumed. So <tt>setLayout('weblog/standard')</tt> will return
1348 * weblog/standard, but <tt>setLayout('standard')</tt> will return layouts/standard.
1350 function getActiveLayout($passed_layout = null)
1352 if(empty($passed_layout)){
1353 $layout = !isset($this->layout) ? AkInflector::underscore($this->getControllerName()) : $this->layout;
1354 }else{
1355 $layout =& $passed_layout;
1357 if(is_array($layout) && is_object($layout[0]) && method_exists($layout[0], $layout[1])){
1358 $this->active_layout = $layout[0]->{$layout[1]}();
1359 }elseif(method_exists($this,$layout) && strtolower(get_class($this)) !== strtolower($layout)){
1360 $this->active_layout = $this->$layout();
1361 }else{
1362 $this->active_layout = $layout;
1365 if(!empty($this->active_layout)){
1366 return strstr($this->active_layout,DS) ? $this->active_layout : 'layouts'.DS.$this->active_layout;
1371 function renderWithALayout($options = null, $status = null, $layout = null)
1373 $template_with_options = !empty($options) && is_array($options);
1375 if($this->_canApplyLayout($template_with_options, $options) && ($layout = $this->_pickLayout($template_with_options, $options, $layout))){
1377 $options = $template_with_options? array_merge((array)$options,array('layout'=>false)) : $options;
1379 $this->content_for_layout = $this->render($options, $status);
1381 if($template_with_options){
1382 $status = empty($options['status']) ? $status : $options['status'];
1385 $this->eraseRenderResults();
1386 $this->_addVariablesToAssigns();
1388 return $this->renderText($this->Template->renderFile($layout, true, &$this->_assigns), $status);
1389 }else{
1390 return $this->render($options, $status, &$this->_assigns);
1394 function _canApplyLayout($template_with_options, $options)
1396 return !empty($template_with_options) ? $this->_isCandidateForLayout($options) : !$this->_isTemplateExemptFromLayout();
1399 function _isCandidateForLayout($options)
1401 return !empty($options['layout']) ||
1402 (empty($options['text']) && empty($options['file']) && empty($options['inline']) && empty($options['partial']) && empty($options['nothing'])) &&
1403 !$this->_isTemplateExemptFromLayout($this->_getDefaultTemplateName(empty($options['action']) ? $options['template'] : $options['action']));
1406 function _pickLayout($template_with_options, $options, $layout = null)
1408 if(!empty($template_with_options)){
1409 $layout = empty($options['layout']) ? ($this->_doesActionHasLayout() ? $this->getActiveLayout(): false) : $this->getActiveLayout($options['layout']);
1410 }elseif(empty($layout) || $layout === true){
1411 $layout = $this->_doesActionHasLayout() ? $this->getActiveLayout() : false;
1413 if(!empty($layout)){
1414 $layout = strstr($layout,'/') || strstr($layout,DS) ? $layout : 'layouts'.DS.$layout;
1415 $layout = substr($layout,0,7) === 'layouts' ?
1416 (empty($this->_module_path) ? AK_VIEWS_DIR.DS.$layout.'.tpl' : AK_VIEWS_DIR.DS.'layouts'.DS.trim($this->_module_path, DS).'.tpl') :
1417 $layout.'.tpl';
1418 if (file_exists($layout)) {
1419 return $layout;
1421 $layout = null;
1423 if(empty($layout) && $layout !== false && defined('AK_DEFAULT_LAYOUT')){
1424 $layout = AK_VIEWS_DIR.DS.'layouts'.DS.AK_DEFAULT_LAYOUT.'.tpl';
1426 return file_exists($layout) ? $layout : false;
1429 function _doesActionHasLayout()
1431 $conditions = $this->getLayoutConditions();
1433 $action_name = $this->Request->getAction();
1434 if(!empty($conditions['only']) && ((is_array($conditions['only']) && in_array($action_name,$conditions['only'])) ||
1435 (is_string($conditions['only']) && $action_name == $conditions['only']))){
1436 return true;
1437 }elseif (!empty($conditions['only'])){
1438 return false;
1440 if(!empty($conditions['except']) && ((is_array($conditions['except']) && in_array($action_name,$conditions['except'])) ||
1441 (is_string($conditions['except']) && $action_name == $conditions['except']))){
1442 return false;
1445 return true;
1453 * Filters enable controllers to run shared pre and post processing code for its actions. These filters can be used to do
1454 * authentication, caching, or auditing before the intended action is performed. Or to do localization or output
1455 * compression after the action has been performed.
1457 * Filters have access to the request, response, and all the instance variables set by other filters in the chain
1458 * or by the action (in the case of after filters). Additionally, it's possible for a pre-processing <tt>beforeFilter</tt>
1459 * to halt the processing before the intended action is processed by returning false or performing a redirect or render.
1460 * This is especially useful for filters like authentication where you're not interested in allowing the action to be
1461 * performed if the proper credentials are not in order.
1463 * == Filter inheritance
1465 * Controller inheritance hierarchies share filters downwards, but subclasses can also add new filters without
1466 * affecting the superclass. For example:
1468 * class BankController extends AkActionController
1470 * function __construct()
1472 * $this->beforeFilter('_audit');
1475 * function _audit(&$controller)
1477 * // record the action and parameters in an audit log
1481 * class VaultController extends BankController
1483 * function __construct()
1485 * $this->beforeFilter('_verifyCredentials');
1488 * function _verifyCredentials(&$controller)
1490 * // make sure the user is allowed into the vault
1494 * Now any actions performed on the BankController will have the audit method called before. On the VaultController,
1495 * first the audit method is called, then the _verifyCredentials method. If the _audit method returns false, then
1496 * _verifyCredentials and the intended action are never called.
1498 * == Filter types
1500 * A filter can take one of three forms: method reference, external class, or inline method. The first
1501 * is the most common and works by referencing a method somewhere in the inheritance hierarchy of
1502 * the controller by use of a method name. In the bank example above, both BankController and VaultController use this form.
1504 * Using an external class makes for more easily reused generic filters, such as output compression. External filter classes
1505 * are implemented by having a static +filter+ method on any class and then passing this class to the filter method. Example:
1507 * class OutputCompressionFilter
1509 * function filter(&$controller)
1511 * $controller->response->body = compress($controller->response->body);
1515 * class NewspaperController extends AkActionController
1517 * function __construct()
1519 * $this->afterFilter(new OutputCompressionFilter());
1523 * The filter method is passed the controller instance and is hence granted access to all aspects of the controller and can
1524 * manipulate them as it sees fit.
1527 * == Filter chain ordering
1529 * Using <tt>beforeFilter</tt> and <tt>afterFilter</tt> appends the specified filters to the existing chain. That's usually
1530 * just fine, but some times you care more about the order in which the filters are executed. When that's the case, you
1531 * can use <tt>prependBeforeFilter</tt> and <tt>prependAfterFilter</tt>. Filters added by these methods will be put at the
1532 * beginning of their respective chain and executed before the rest. For example:
1534 * class ShoppingController extends AkActionController
1536 * function __construct()
1538 * $this->beforeFilter('verifyOpenShop');
1543 * class CheckoutController extends AkActionController
1545 * function __construct()
1547 * $this->prependBeforeFilter('ensureItemsInCart', 'ensureItemsInStock');
1551 * The filter chain for the CheckoutController is now <tt>ensureItemsInCart, ensureItemsInStock,</tt>
1552 * <tt>verifyOpenShop</tt>. So if either of the ensure filters return false, we'll never get around to see if the shop
1553 * is open or not.
1555 * You may pass multiple filter arguments of each type.
1557 * == Around filters
1559 * In addition to the individual before and after filters, it's also possible to specify that a single object should handle
1560 * both the before and after call. That's especially useful when you need to keep state active between the before and after,
1561 * such as the example of a benchmark filter below:
1563 * class WeblogController extends AkActionController
1565 * function __construct()
1567 * $this->aroundFilter(new BenchmarkingFilter());
1570 * // Before this action is performed, BenchmarkingFilter->before($controller) is executed
1571 * function index()
1574 * // After this action has been performed, BenchmarkingFilter->after($controller) is executed
1577 * class BenchmarkingFilter
1579 * function before(&$controller)
1581 * start_timer();
1584 * function after(&$controller)
1586 * stop_timer();
1587 * report_result();
1591 * == Filter chain skipping
1593 * Some times its convenient to specify a filter chain in a superclass that'll hold true for the majority of the
1594 * subclasses, but not necessarily all of them. The subclasses that behave in exception can then specify which filters
1595 * they would like to be relieved of. Examples
1597 * class ApplicationController extends AkActionController
1599 * function __construct()
1601 * $this->beforeFilter('authenticate');
1605 * class WeblogController extends ApplicationController
1607 * // will run the authenticate filter
1610 * class SignupController extends AkActionController
1612 * function __construct()
1614 * $this->skipBeforeFilter('authenticate');
1616 * // will not run the authenticate filter
1619 * == Filter conditions
1621 * Filters can be limited to run for only specific actions. This can be expressed either by listing the actions to
1622 * exclude or the actions to include when executing the filter. Available conditions are +only+ or +except+, both
1623 * of which accept an arbitrary number of method references. For example:
1625 * class Journal extends AkActionController
1627 * function __construct()
1628 * { // only require authentication if the current action is edit or delete
1629 * $this->beforeFilter(array('_authorize'=>array('only'=>array('edit','delete')));
1632 * function _authorize(&$controller)
1634 * // redirect to login unless authenticated
1639 var $_includedActions = array(), $_beforeFilters = array(), $_afterFilters = array(), $_excludedActions = array();
1641 * The passed <tt>filters</tt> will be appended to the array of filters that's run _before_ actions
1642 * on this controller are performed.
1644 function appendBeforeFilter()
1646 $filters = array_reverse(func_get_args());
1647 foreach (array_keys($filters) as $k){
1648 $conditions = $this->_extractConditions(&$filters[$k]);
1649 $this->_addActionConditions($filters[$k], $conditions);
1650 $this->_appendFilterToChain('before', $filters[$k]);
1655 * The passed <tt>filters</tt> will be prepended to the array of filters that's run _before_ actions
1656 * on this controller are performed.
1658 function prependBeforeFilter()
1660 $filters = array_reverse(func_get_args());
1661 foreach (array_keys($filters) as $k){
1662 $conditions = $this->_extractConditions(&$filters[$k]);
1663 $this->_addActionConditions($filters[$k], $conditions);
1664 $this->_prependFilterToChain('before', $filters[$k]);
1669 * Short-hand for appendBeforeFilter since that's the most common of the two.
1671 function beforeFilter()
1673 $filters = func_get_args();
1674 foreach (array_keys($filters) as $k){
1675 $this->appendBeforeFilter($filters[$k]);
1680 * The passed <tt>filters</tt> will be appended to the array of filters that's run _after_ actions
1681 * on this controller are performed.
1683 function appendAfterFilter()
1685 $filters = array_reverse(func_get_args());
1686 foreach (array_keys($filters) as $k){
1687 $conditions = $this->_extractConditions(&$filters[$k]);
1688 $this->_addActionConditions(&$filters[$k], $conditions);
1689 $this->_appendFilterToChain('after', &$filters[$k]);
1695 * The passed <tt>filters</tt> will be prepended to the array of filters that's run _after_ actions
1696 * on this controller are performed.
1698 function prependAfterFilter()
1700 $filters = array_reverse(func_get_args());
1701 foreach (array_keys($filters) as $k){
1702 $conditions = $this->_extractConditions(&$filters[$k]);
1703 $this->_addActionConditions(&$filters[$k], $conditions);
1704 $this->_prependFilterToChain('after', &$filters[$k]);
1709 * Short-hand for appendAfterFilter since that's the most common of the two.
1710 * */
1711 function afterFilter()
1713 $filters = func_get_args();
1714 foreach (array_keys($filters) as $k){
1715 $this->appendAfterFilter($filters[$k]);
1720 * The passed <tt>filters</tt> will have their +before+ method appended to the array of filters that's run both before actions
1721 * on this controller are performed and have their +after+ method prepended to the after actions. The filter objects must all
1722 * respond to both +before+ and +after+. So if you do appendAroundFilter(new A(), new B()), the callstack will look like:
1724 * B::before()
1725 * A::before()
1726 * A::after()
1727 * B::after()
1729 function appendAroundFilter()
1731 $filters = func_get_args();
1732 foreach (array_keys($filters) as $k){
1733 $this->_ensureFilterRespondsToBeforeAndAfter(&$filters[$k]);
1734 $this->appendBeforeFilter(array(&$filters[$k],'before'));
1736 $filters = array_reverse($filters);
1737 foreach (array_keys($filters) as $k){
1738 $this->prependAfterFilter(array(&$filters[$k],'after'));
1743 * The passed <tt>filters</tt> will have their +before+ method prepended to the array of filters that's run both before actions
1744 * on this controller are performed and have their +after+ method appended to the after actions. The filter objects must all
1745 * respond to both +before+ and +after+. So if you do appendAroundFilter(new A(), new B()), the callstack will look like:
1747 * A::before()
1748 * B::before()
1749 * B::after()
1750 * A::after()
1752 function prependAroundFilter()
1754 $filters = func_get_args();
1755 foreach (array_keys($filters) as $k){
1756 $this->_ensureFilterRespondsToBeforeAndAfter(&$filters[$k]);
1757 $this->prependBeforeFilter(array(&$filters[$k],'before'));
1759 $filters = array_reverse($filters);
1760 foreach (array_keys($filters) as $k){
1761 $this->appendAfterFilter(array(&$filters[$k],'after'));
1766 * Short-hand for appendAroundFilter since that's the most common of the two.
1768 function aroundFilter()
1770 $filters = func_get_args();
1771 call_user_func_array(array(&$this,'appendAroundFilter'), $filters);
1775 * Removes the specified filters from the +before+ filter chain.
1776 * This is especially useful for managing the chain in inheritance hierarchies where only one out
1777 * of many sub-controllers need a different hierarchy.
1779 function skipBeforeFilter($filters)
1781 $filters = func_get_args();
1782 $this->_skipFilter($filters, 'before');
1786 * Removes the specified filters from the +after+ filter chain. Note that this only works for skipping method-reference
1787 * filters, not instances. This is especially useful for managing the chain in inheritance hierarchies where only one out
1788 * of many sub-controllers need a different hierarchy.
1790 function skipAfterFilter($filters)
1792 $filters = func_get_args();
1793 $this->_skipFilter($filters, 'after');
1796 function _skipFilter(&$filters, $type)
1798 $_filters =& $this->{'_'.$type.'Filters'};
1799 // array_diff doesn't play nice with some PHP5 releases when it comes to
1800 // Objects as it only diff equal references, not object types
1801 foreach (array_keys($filters) as $k){
1802 if(AK_PHP5){
1803 if(is_object($filters[$k])){
1804 foreach (array_keys($_filters) as $k2){
1805 if(is_object($_filters[$k2]) && get_class($_filters[$k2]) == get_class($filters[$k])){
1806 $pos = $k2;
1807 break;
1810 }else{
1811 $pos = array_search($filters[$k], $_filters);
1814 array_splice($_filters, $pos, 1, null);
1815 return ;
1817 $_filters = array_diff($_filters,array($filters[$k]));
1822 * Returns all the before filters for this class.
1824 function beforeFilters()
1826 return $this->_beforeFilters;
1830 * Returns all the after filters for this class and all its ancestors.
1832 function afterFilters()
1834 return $this->_afterFilters;
1838 * Returns a mapping between filters and the actions that may run them.
1840 function includedActions()
1842 return $this->_includedActions;
1846 * Returns a mapping between filters and actions that may not run them.
1848 function excludedActions()
1850 return $this->_excludedActions;
1854 function _appendFilterToChain($condition, $filters)
1856 $this->{"_{$condition}Filters"}[] =& $filters;
1859 function _prependFilterToChain($condition, $filters)
1861 array_unshift($this->{"_{$condition}Filters"}, $filters);
1864 function _ensureFilterRespondsToBeforeAndAfter(&$filter_object)
1866 if(!method_exists(&$filter_object,'before') && !method_exists(&$filter_object,'after')){
1867 trigger_error(Ak::t('Filter object must respond to both before and after'), E_USER_ERROR);
1871 function _extractConditions(&$filters)
1873 if(is_array($filters) && !isset($filters[0])){
1874 $keys = array_keys($filters);
1875 $conditions = $filters[$keys[0]];
1876 $filters = $keys[0];
1877 return $conditions;
1881 function _addActionConditions($filters, $conditions)
1883 if(!empty($conditions['only'])){
1884 $this->_includedActions[$this->_filterId($filters)] = $this->_conditionArray($this->_includedActions, $conditions['only']);
1886 if(!empty($conditions['except'])){
1887 $this->_excludedActions[$this->_filterId($filters)] = $this->_conditionArray($this->_excludedActions, $conditions['except']);
1891 function _conditionArray($actions, $filter_actions)
1893 $filter_actions = is_array($filter_actions) ? $filter_actions : array($filter_actions);
1894 $filter_actions = array_map(array(&$this,'_filterId'),$filter_actions);
1895 return array_unique(array_merge($actions, $filter_actions));
1899 function _filterId($filters)
1901 return is_string($filters) ? $filters : md5(serialize($filters));
1904 function performActionWithoutFilters($action)
1906 if(method_exists(&$this, $action)){
1907 call_user_func_array(array(&$this, $action), @(array)$this->passed_args);
1911 function performActionWithFilters($method = '')
1913 if ($this->beforeAction($method) !== false || empty($this->_performed)){
1914 $this->performActionWithoutFilters($method);
1915 $this->afterAction($method);
1916 return true;
1918 return $this->performActionWithoutFilters($method);
1921 function performAction($method = '')
1923 $this->performActionWithFilters($method);
1928 * Calls all the defined before-filter filters, which are added by using "beforeFilter($method)".
1929 * If any of the filters return false, no more filters will be executed and the action is aborted.
1931 function beforeAction($method = '')
1933 Ak::profile('Running before controller action filters '.__CLASS__.'::'.__FUNCTION__.' '.__LINE__);
1934 return $this->_callFilters($this->_beforeFilters, $method);
1938 * Calls all the defined after-filter filters, which are added by using "afterFilter($method)".
1939 * If any of the filters return false, no more filters will be executed.
1941 function afterAction($method = '')
1943 Ak::profile('Running after controller action filters '.__CLASS__.'::'.__FUNCTION__.' '.__LINE__);
1944 return $this->_callFilters(&$this->_afterFilters, $method);
1948 function _callFilters(&$filters, $method = '')
1950 $filter_result = null;
1951 foreach (array_keys($filters) as $k){
1952 $filter =& $filters[$k];
1953 if(!$this->_actionIsExempted($filter, $method)){
1954 if(is_array($filter) && is_object($filter[0]) && method_exists($filter[0], $filter[1])){
1955 $filter_result = $filter[0]->$filter[1]($this);
1956 }elseif(!is_object($filter) && method_exists($this, $filter)){
1957 $filter_result = $this->$filter($this);
1958 }elseif(is_object($filter) && method_exists($filter, 'filter')){
1959 $filter_result = $filter->filter($this);
1960 }else{
1961 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);
1965 if($filter_result === false){
1966 !empty($this->_Logger) ? $this->_Logger->info(Ak::t('Filter chain halted as '.$filter.' returned false')) : null;
1967 return false;
1970 return $filter_result;
1974 function _actionIsExempted($filter, $method = '')
1976 $method_id = is_string($method) ? $method : $this->_filterId($method);
1977 $filter_id = $this->_filterId($filter);
1979 if((!empty($this->_includedActions[$filter_id]) && !in_array($method_id, $this->_includedActions[$filter_id])) ||
1980 (!empty($this->_excludedActions[$filter_id]) && in_array($method_id, $this->_excludedActions[$filter_id]))){
1981 return true;
1984 return false;
1992 * The flash provides a way to pass temporary objects between actions. Anything you place in the flash will be exposed
1993 * to the very next action and then cleared out. This is a great way of doing notices and alerts, such as a create action
1994 * that sets <tt>flash['notice] = 'Successfully created'</tt> before redirecting to a display action that can then expose
1995 * the flash to its template. Actually, that exposure is automatically done. Example:
1997 * class WeblogController extends ActionController
1999 * function create()
2001 * // save post
2002 * $this->flash['notice] = 'Successfully created post';
2003 * $this->redirectTo(array('action'=>'display','params' => array('id' =>$Post->id)));
2006 * function display()
2008 * // doesn't need to assign the flash notice to the template, that's done automatically
2012 * display.tpl
2013 * <?php if($flash['notice']) : ?><div class='notice'><?php echo $flash['notice'] ?></div><?php endif; ?>
2015 * 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
2016 * as you like at a time too. Just remember: They'll be gone by the time the next action has been performed.
2018 * ==flash_now
2020 * Sets a flash that will not be available to the next action, only to the current.
2022 * $this->flash_now['message] = 'Hello current action';
2024 * This method enables you to use the flash as a central messaging system in your app.
2025 * When you need to pass an object to the next action, you use the standard flash assign (<tt>[]=</tt>).
2026 * When you need to pass an object to the current action, you use <tt>now</tt>, and your object will
2027 * vanish when the current action is done.
2029 * Entries set via <tt>flash_now</tt> are accessed the same way as standard entries: <tt>flash['my-key']</tt>.
2031 var $flash = array();
2032 var $flash_now = array();
2033 var $flash_options = array();
2034 var $_flash_handled = false;
2036 function _handleFlashAttribute()
2038 $this->_flash_handled = true;
2040 $next_flash = empty($this->flash) ? false : $this->flash;
2041 $this->flash = array();
2042 if(isset($_SESSION['__flash'])){
2043 $this->flash = $_SESSION['__flash'];
2045 $_SESSION['__flash'] = $next_flash;
2046 if(!empty($this->flash_now)){
2047 $this->flash = array_merge((array)$this->flash,(array)$this->flash_now);
2049 $this->_handleFlashOptions();
2052 function _handleFlashOptions()
2054 $next_flash_options = empty($this->flash_options) ? false : $this->flash_options;
2055 $this->flash_options = array();
2056 if(isset($_SESSION['__flash_options'])){
2057 $this->flash_options = $_SESSION['__flash_options'];
2059 $_SESSION['__flash_options'] = $next_flash_options;
2060 if(!empty($this->flash_now_options)){
2061 $this->flash_options = array_merge((array)$this->flash_options,(array)$this->flash_now_options);
2066 function _mergeFlashOnFlashNow()
2068 $this->flash_now = array_merge($this->flash_now,$this->flash);
2075 * === Pagination for Active Record collections
2077 * The Pagination module aids in the process of paging large collections of
2078 * Active Record objects. It offers macro-style automatic fetching of your
2079 * model for multiple views, or explicit fetching for single actions. And if
2080 * the magic isn't flexible enough for your needs, you can create your own
2081 * paginators with a minimal amount of code.
2083 * The Pagination module can handle as much or as little as you wish. In the
2084 * controller, have it automatically query your model for pagination; or,
2085 * if you prefer, create Paginator objects yourself
2087 * Pagination is included automatically for all controllers.
2089 * For help rendering pagination links, see
2090 * Helpers/PaginationHelper.
2092 * ==== Automatic pagination for every action in a controller
2094 * class PersonController extends ApplicationController
2096 * var $model = 'person';
2097 * var $paginate = array('people'=>array('order' => 'last_name, first_name',
2098 * 'per_page' => 20));
2101 * Each action in this controller now has access to a <tt>$this->people</tt>
2102 * instance variable, which is an ordered collection of model objects for the
2103 * current page (at most 20, sorted by last name and first name), and a
2104 * <tt>$this->person_pages</tt> Paginator instance. The current page is determined
2105 * by the <tt>$params['page']</tt> variable.
2107 * ==== Pagination for a single action
2109 * function show_all()
2111 * list($this->person_pages, $this->people) =
2112 * $this->paginate('people', array('order' => 'last_name, first_name'));
2115 * Like the previous example, but explicitly creates <tt>$this->person_pages</tt>
2116 * and <tt>$this->people</tt> for a single action, and uses the default of 10 items
2117 * per page.
2119 * ==== Custom/"classic" pagination
2121 * function list()
2123 * $this->person_pages = new AkPaginator(&$this, $Person->count(), 10, $params['page']);
2124 * $this->people = $this->Person->find('all', array(
2125 * 'order'=> 'last_name, first_name',
2126 * 'limit' => $this->person_pages->items_per_page,
2127 * 'offset' => $this->person_pages->getOffset()));
2130 * Explicitly creates the paginator from the previous example and uses
2131 * AkPaginator::toSql to retrieve <tt>$this->people</tt> from the model.
2133 // An array holding options for controllers using macro-style pagination
2134 var $_pagination_options = array(
2135 'class_name' => null,
2136 'singular_name' => null,
2137 'per_page' => 10,
2138 'conditions' => null,
2139 'order_by' => null,
2140 'order' => null,
2141 'join' => null,
2142 'joins' => null,
2143 'include' => null,
2144 'select' => null,
2145 'parameter' => 'page'
2148 // The default options for pagination
2149 var $_pagination_default_options = array(
2150 'class_name' => null,
2151 'singular_name' => null,
2152 'per_page' => 10,
2153 'conditions' => null,
2154 'order_by' => null,
2155 'order' => null,
2156 'join' => null,
2157 'joins' => null,
2158 'include' => null,
2159 'select' => null,
2160 'parameter' => 'page'
2163 var $_pagination_actions = array();
2165 function _paginationValidateOptions($collection_id, $options = array(), $in_action)
2167 $this->_pagination_options = array_merge($this->_pagination_default_options, $this->_pagination_options);
2168 $valid_options = array_keys($this->_pagination_default_options);
2170 $valid_options = !in_array($in_action, $valid_options) ? array_merge($valid_options, $this->_pagination_actions) : $valid_options;
2172 $unknown_option_keys = array_diff(array_keys($this->_pagination_options) , $valid_options);
2174 if(!empty($unknown_option_keys)){
2175 trigger_error(Ak::t('Unknown options for pagination: %unknown_option',array('%unknown_option'=>join(', ',$unknown_option_keys))), E_USER_WARNING);
2178 $this->_pagination_options['singular_name'] = !empty($this->_pagination_options['singular_name']) ? $this->_pagination_options['singular_name'] : AkInflector::singularize($collection_id);
2179 $this->_pagination_options['class_name'] = !empty($this->_pagination_options['class_name']) ? $this->_pagination_options['class_name'] : AkInflector::camelize($this->_pagination_options['singular_name']);
2183 * Returns a paginator and a collection of Active Record model instances
2184 * for the paginator's current page. This is designed to be used in a
2185 * single action.
2187 * +options+ are:
2188 * <tt>singular_name</tt>:: the singular name to use, if it can't be inferred by
2189 * singularizing the collection name
2190 * <tt>class_name</tt>:: the class name to use, if it can't be inferred by
2191 * camelizing the singular name
2192 * <tt>per_page</tt>:: the maximum number of items to include in a
2193 * single page. Defaults to 10
2194 * <tt>conditions</tt>:: optional conditions passed to Model::find('all', $this->params); and
2195 * Model::count()
2196 * <tt>order</tt>:: optional order parameter passed to Model::find('all', $this->params);
2197 * <tt>order_by</tt>:: (deprecated, used :order) optional order parameter passed to Model::find('all', $this->params)
2198 * <tt>joins</tt>:: optional joins parameter passed to Model::find('all', $this->params)
2199 * and Model::count()
2200 * <tt>join</tt>:: (deprecated, used :joins or :include) optional join parameter passed to Model::find('all', $this->params)
2201 * and Model::count()
2202 * <tt>include</tt>:: optional eager loading parameter passed to Model::find('all', $this->params)
2203 * and Model::count()
2205 * Creates a +before_filter+ which automatically paginates an Active
2206 * Record model for all actions in a controller (or certain actions if
2207 * specified with the <tt>actions</tt> option).
2209 * +options+ are the same as PaginationHelper::paginate, with the addition
2210 * of:
2211 * <tt>actions</tt>:: an array of actions for which the pagination is
2212 * active. Defaults to +null+ (i.e., every action)
2214 function paginate($collection_id, $options = array())
2216 $this->_paginationValidateOptions($collection_id, $options, true);
2217 $this->_paginationLoadPaginatorAndCollection($collection_id, $this->_pagination_options);
2218 $this->beforeFilter('_paginationCreateAndRetrieveCollections');
2224 function _paginationCreateAndRetrieveCollections()
2226 foreach($this->_pagination_options[$this->class] as $collection_id=>$options){
2227 if(!empty($options['actions']) && in_array($options['actions'], $action_name)){
2228 continue;
2231 list($paginator, $collection) = $this->_paginationLoadPaginatorAndCollection($collection_id, $this->_pagination_options);
2233 $this->{$options['singular_name'].'_pages'} =& $paginator;
2234 $this->$collection_name =& $collection;
2239 * Returns the total number of items in the collection to be paginated for
2240 * the +model+ and given +conditions+. Override this method to implement a
2241 * custom counter.
2243 function _paginationCountCollection(&$model, $conditions, $joins)
2245 return $model->count($conditions, $joins);
2249 * Returns a collection of items for the given +$model+ and +$options['conditions']+,
2250 * ordered by +$options['order']+, for the current page in the given +$paginator+.
2251 * Override this method to implement a custom finder.
2253 function _paginationFindCollection(&$model, $options, &$paginator)
2255 return $model->find('all', array(
2256 'conditions' => $this->_pagination_options['conditions'],
2257 'order' => !empty($options['order_by']) ? $options['order_by'] : $options['order'],
2258 'joins' => !empty($options['join']) ? $options['join'] : $options['joins'],
2259 'include' => $this->_pagination_options['include'],
2260 'select' => $this->_pagination_options['select'],
2261 'limit' => $this->_pagination_options['per_page'],
2262 'offset' => $paginator->getOffset()));
2266 * @todo Fix this function
2268 function _paginationLoadPaginatorAndCollection($collection_id, $options)
2270 $page = $this->params[$options['parameter']];
2271 $count = $this->_paginationCountCollection($klass, $options['conditions'],
2272 empty($options['join']) ? $options['join'] : $options['joins']);
2274 require_once(AK_LIB_DIR.DS.'AkActionController'.DS.'AkPaginator.php');
2275 $paginator =& new AkPaginator($this, $count, $options['per_page'], $page);
2276 $collection =& $this->_paginationFindCollection($options['class_name'], $options, $paginator);
2278 return array(&$paginator, &$collection);
2283 * Specifies that the named actions requires an SSL connection to be performed (which is enforced by ensure_proper_protocol).
2285 function setSslRequiredActions($actions)
2287 $this->_ssl_required_actions = empty($this->_ssl_required_actions) ?
2288 (is_string($actions) ? Ak::stringToArray($actions) : $actions) :
2289 array_merge($this->_ssl_required_actions, (is_string($actions) ? Ak::stringToArray($actions) : $actions));
2292 function setSslAllowedActions($actions)
2294 $this->_ssl_allowed_actions = empty($this->_ssl_allowed_actions) ?
2295 (is_string($actions) ? Ak::stringToArray($actions) : $actions) :
2296 array_merge($this->_ssl_allowed_actions, (is_string($actions) ? Ak::stringToArray($actions) : $actions));
2300 * Returns true if the current action is supposed to run as SSL
2302 function _isSslRequired()
2304 return !empty($this->_ssl_required_actions) && is_array($this->_ssl_required_actions) && isset($this->_action_name) ?
2305 in_array($this->_action_name, $this->_ssl_required_actions) : false;
2308 function _isSslAllowed()
2310 return (!empty($this->ssl_for_all_actions) && empty($this->_ssl_allowed_actions)) ||
2311 (!empty($this->_ssl_allowed_actions) && is_array($this->_ssl_allowed_actions) && isset($this->_action_name) ?
2312 in_array($this->_action_name, $this->_ssl_allowed_actions) : false);
2315 function _ensureProperProtocol()
2317 if($this->_isSslAllowed()){
2318 return true;
2320 if ($this->_isSslRequired() && !$this->Request->isSsl()){
2321 $this->redirectTo(substr_replace(AK_CURRENT_URL,'s:',4,1));
2322 return false;
2323 }elseif($this->Request->isSsl() && !$this->_isSslRequired()){
2324 $this->redirectTo(substr_replace(AK_CURRENT_URL,'',4,1));
2325 return false;
2331 * Account Location
2332 * ================
2334 * Account location is a set of methods that supports the account-key-as-subdomain
2335 * way of identifying the current scope. These methods allow you to easily produce URLs that
2336 * match this style and to get the current account key from the subdomain.
2338 * The methods are: getAccountUrl, getAccountHost, and getAccountDomain.
2340 * Example:
2342 * include_once('AkAccountLocation.php');
2344 * class ApplicationController extends AkActionController
2346 * var $before_filter = '_findAccount';
2348 * function _findAccount()
2350 * $this->account = Account::find(array('conditions'=>array('username = ?', $this->account_domain)));
2353 * class AccountController extends ApplicationController
2355 * function new_account()
2357 * $this->new_account = Account::create($this->params['new_account']);
2358 * $this->redirectTo(array('host' => $this->accountHost($this->new_account->username), 'controller' => 'weblog'));
2361 * function _authenticate()
2363 * $this->session[$this->account_domain] = 'authenticated';
2364 * $this->redirectTo(array('controller => 'weblog'));
2367 * function _isAuthenticated()
2369 * return !empty($this->session['account_domain']) ? $this->session['account_domain'] == 'authenticated' : false;
2373 * // The view:
2374 * Your domain: {account_url?}
2376 * By default, all the methods will query for $this->account->username as the account key, but you can
2377 * specialize that by overwriting defaultAccountSubdomain. You can of course also pass it in
2378 * as the first argument to all the methods.
2380 function defaultAccountSubdomain()
2382 if(!empty($this->account)){
2383 return $this->account->respondsTo('username');
2387 function accountUrl($account_subdomain = null, $use_ssl = null)
2389 $account_subdomain = empty($account_subdomain) ? 'default_account_subdomain' : $account_subdomain;
2390 $use_ssl = empty($use_ssl) ? $use_ssl : $this->Request->isSsl();
2391 return ($use_ssl ? 'https://' : 'http://') . $this->accountHost($account_subdomain);
2394 function accountHost($account_subdomain = null)
2396 $account_subdomain = empty($account_subdomain) ? 'default_account_subdomain' : $account_subdomain;
2397 $account_host = '';
2398 $account_host .= $account_subdomain . '.';
2399 $account_host .= $this->accountDomain();
2400 return $account_host;
2403 function accountDomain()
2405 $account_domain = '';
2406 if(count($this->Request->getSubdomains()) > 1){
2407 $account_domain .= join('.',$this->Request->getSubdomains()) . '.';
2409 $account_domain .= $this->Request->getDomain() . $this->Request->getPortString();
2410 return $account_domain;
2413 function getAccountSubdomain()
2415 return array_shift($this->Request->getSubdomains());
2420 * Methods for sending files and streams to the browser instead of rendering.
2422 var $default_send_file_options = array(
2423 'type' => 'application/octet-stream',
2424 'disposition' => 'attachment',
2425 'stream' => true,
2426 'buffer_size' => 4096
2430 * Sends the file by streaming it 4096 bytes at a time. This way the
2431 * whole file doesn't need to be read into memory at once. This makes
2432 * it feasible to send even large files.
2434 * Be careful to sanitize the path parameter if it coming from a web
2435 * page. sendFile($params['path']) allows a malicious user to
2436 * download any file on your server.
2438 * Options:
2439 * * <tt>filename</tt> - suggests a filename for the browser to use.
2440 * Defaults to realpath($path).
2441 * * <tt>type</tt> - specifies an HTTP content type.
2442 * Defaults to 'application/octet-stream'.
2443 * * <tt>disposition</tt> - specifies whether the file will be shown inline or downloaded.
2444 * Valid values are 'inline' and 'attachment' (default).
2445 * * <tt>stream</tt> - whether to send the file to the user agent as it is read (true)
2446 * or to read the entire file before sending (false). Defaults to true.
2447 * * <tt>buffer_size</tt> - specifies size (in bytes) of the buffer used to stream the file.
2448 * Defaults to 4096.
2450 * The default Content-Type and Content-Disposition headers are
2451 * set to download arbitrary binary files in as many browsers as
2452 * possible. IE versions 4, 5, 5.5, and 6 are all known to have
2453 * a variety of quirks (especially when downloading over SSL).
2455 * Simple download:
2456 * sendFile('/path/to.zip');
2458 * Show a JPEG in browser:
2459 * sendFile('/path/to.jpeg', array('type' => 'image/jpeg', 'disposition' => 'inline'));
2461 * Read about the other Content-* HTTP headers if you'd like to
2462 * provide the user with more information (such as Content-Description).
2463 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11
2465 * Also be aware that the document may be cached by proxies and browsers.
2466 * The Pragma and Cache-Control headers declare how the file may be cached
2467 * by intermediaries. They default to require clients to validate with
2468 * the server before releasing cached responses. See
2469 * http://www.mnot.net/cache_docs/ for an overview of web caching and
2470 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9
2471 * for the Cache-Control header spec.
2473 function sendFile($path, $options = array())
2475 $path = realpath($path);
2476 if(!file_exists($path)){
2477 trigger_error(Ak::t('Cannot read file %path',array('%path'=>$path)), E_USER_NOTICE);
2478 return false;
2480 $options['length'] = empty($options['length']) ? filesize($path) : $options['length'];
2481 $options['filename'] = empty($options['filename']) ? basename($path) : $options['filename'];
2482 $options['type'] = empty($options['type']) ? Ak::mime_content_type($path) : $options['type'];
2484 $this->performed_render = false;
2485 $this->_sendFileHeaders($options);
2487 if(!empty($options['stream'])){
2488 require_once(AK_LIB_DIR.DS.'AkStream.php');
2489 $this->render(array('text'=> new AkStream($path,$options['buffer_size'])));
2490 }else{
2491 $this->render(array('text'=> Ak::file_get_contents($path)));
2496 * Send binary data to the user as a file download. May set content type, apparent file name,
2497 * and specify whether to show data inline or download as an attachment.
2499 * Options:
2500 * * <tt>filename</tt> - Suggests a filename for the browser to use.
2501 * * <tt>type</tt> - specifies an HTTP content type.
2502 * Defaults to 'application/octet-stream'.
2503 * * <tt>disposition</tt> - specifies whether the file will be shown inline or downloaded.
2504 * Valid values are 'inline' and 'attachment' (default).
2506 * Generic data download:
2507 * sendData($buffer)
2509 * Download a dynamically-generated tarball:
2510 * sendData(Ak::compress('dir','tgz'), array('filename' => 'dir.tgz'));
2512 * Display an image Active Record in the browser:
2513 * sendData($image_data, array('type' =>Ak::mime_content_type('image_name.png'), 'disposition' => 'inline'));
2515 * See +sendFile+ for more information on HTTP Content-* headers and caching.
2517 function sendData($data, $options = array())
2519 $options['length'] = empty($options['length']) ? Ak::size($data) : $options['length'];
2520 $this->_sendFileHeaders($options);
2521 $this->performed_render = false;
2522 $this->renderText($data);
2526 * Creates a file for streaming from a file.
2527 * This way you might free memory usage is file is too large
2529 function sendDataAsStream($data, $options)
2531 $temp_file_name = tempnam(AK_TMP_DIR, Ak::randomString());
2532 $fp = fopen($temp_file_name, 'w');
2533 fwrite($fp, $data);
2534 fclose($fp);
2535 $this->sendFile($temp_file_name, $options);
2539 function _sendFileHeaders(&$options)
2541 $options = array_merge($this->default_send_file_options,$options);
2542 foreach (array('length', 'type', 'disposition') as $arg){
2543 empty($options[$arg]) ? trigger_error(Ak::t('%arg option required', array('%arg'=>$arg)), E_USER_ERROR) : null;
2545 $disposition = empty($options['disposition']) ? 'attachment' : $options['disposition'];
2546 $disposition .= !empty($options['filename']) ? '; filename="'.$options['filename'].'"' : '';
2547 $this->Response->addHeader(array(
2548 'Content-Length' => $options['length'],
2549 'Content-Type' => trim($options['type']), // fixes a problem with extra '\r' with some browsers
2550 'Content-Disposition' => $disposition,
2551 'Content-Transfer-Encoding' => 'binary'
2557 function redirectToLocale($locale)
2559 if($this->Request->__internationalization_support_enabled){
2560 $lang = isset($this->params['lang']) ? $this->params['lang'] : $locale;
2562 if($locale != $lang){
2563 $this->redirectTo(array_merge($this->Request->getParams(),array('lang'=>$locale)));
2564 return true;
2567 return false;
2571 function api($protocol = 'xml_rpc')
2573 $web_services = array_merge(Ak::toArray($this->web_services), Ak::toArray($this->web_service));
2574 if(!empty($web_services)){
2575 $web_services = array_unique($web_services);
2576 require_once(AK_LIB_DIR.DS.'AkActionWebService.php');
2577 require_once(AK_LIB_DIR.DS.'AkActionWebService'.DS.'AkActionWebServiceServer.php');
2578 $Server =& new AkActionWebServiceServer($protocol);
2579 foreach ($web_services as $web_service){
2580 $Server->addService($web_service);
2582 $Server->init();
2583 $Server->serve();
2584 exit;
2585 }else{
2586 die(Ak::t('There is not any webservice configured at this endpoint'));
2593 * Function for getting the singleton controller;
2595 * @return unknown
2597 function &AkActionController()
2599 $params = func_num_args() == 0 ? null : func_get_args();
2600 $AkActionController =& Ak::singleton('AkActionController', $params);
2601 return $AkActionController;