/lib/AkActionController.php
PHP | 2846 lines | 1355 code | 290 blank | 1201 comment | 177 complexity | d9d05d2b37031605d95621cb9c8f3024 MD5 | raw file
Large files files are truncated, but you can click here to view the full file
1<?php 2/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ 3 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// +----------------------------------------------------------------------+ 10 11require_once(AK_LIB_DIR.DS.'AkObject.php'); 12 13defined('AK_HIGH_LOAD_MODE') ? null : define('AK_HIGH_LOAD_MODE', false); 14defined('AK_APP_NAME') ? null : define('AK_APP_NAME', 'Application'); 15 16/** 17 * @package ActionController 18 * @subpackage Base 19 * @author Bermi Ferrer <bermi a.t akelos c.om> 20 * @copyright Copyright (c) 2002-2006, Akelos Media, S.L. http://www.akelos.org 21 * @license GNU Lesser General Public License <http://www.gnu.org/copyleft/lesser.html> 22 */ 23 24class AkActionController extends AkObject 25{ 26 var $_high_load_mode = AK_HIGH_LOAD_MODE; 27 var $_enable_plugins = true; 28 var $_auto_instantiate_models = true; 29 var $validate_output = false; 30 31 var $_ssl_requirement = false; 32 var $_ssl_allowed_actions = array(); 33 var $ssl_for_all_actions = true; 34 35 /** 36 * Determines whether the view has access to controller internals $this->Request, $this->Response, $this->session, and $this->Template. 37 * By default, it does. 38 */ 39 var $_view_controller_internals = true; 40 41 /** 42 * Protected instance variable cache 43 */ 44 var $_protected_variables_cache = array(); 45 46 /** 47 * Prepends all the URL-generating helpers from AssetHelper. 48 * This makes it possible to easily move javascripts, stylesheets, 49 * and images to a dedicated asset server away from the main web server. 50 * Example: 51 * $this->_asset_host = 'http://assets.example.com'; 52 */ 53 var $asset_host = AK_ASSET_HOST; 54 55 56 var $_Logger; 57 58 /** 59 * Determines which template class should be used by AkActionController. 60 */ 61 var $TemplateClass; 62 63 /** 64 * Turn on +_ignore_missing_templates+ if you want to unit test actions without 65 * making the associated templates. 66 */ 67 var $_ignore_missing_templates; 68 69 /** 70 * Holds the Request object that's primarily used to get environment variables 71 */ 72 var $Request; 73 74 /** 75 * Holds an array of all the GET, POST, and Url parameters passed to the action. 76 * Accessed like <tt>$this->params['post_id'];</tt> 77 * to get the post_id. 78 */ 79 var $params = array(); 80 81 /** 82 * Holds the Response object that's primarily used to set additional HTTP _headers 83 * through access like <tt>$this->Response->_headers['Cache-Control'] = 'no-cache';</tt>. 84 * Can also be used to access the final body HTML after a template 85 * has been rendered through $this->Response->body -- useful for <tt>after_filter</tt>s 86 * that wants to manipulate the output, such as a OutputCompressionFilter. 87 */ 88 var $Response; 89 90 /** 91 * Holds an array of objects in the session. Accessed like <tt>$this->session['person']</tt> 92 * to get the object tied to the 'person' key. The session will hold any type of object 93 * as values, but the key should be a string. 94 */ 95 var $session; 96 97 /** 98 * Holds an array of header names and values. Accessed like <tt>$this->_headers['Cache-Control']</tt> 99 * to get the value of the Cache-Control directive. Values should always be specified as strings. 100 */ 101 var $_headers = array(); 102 103 /** 104 * Holds the array of variables that are passed on to the template class to be 105 * made available to the view. This array is generated by taking a snapshot of 106 * all the instance variables in the current scope just before a template is rendered. 107 */ 108 var $_assigns = array(); 109 110 /** 111 * Holds the name of the action this controller is processing. 112 */ 113 var $_action_name; 114 115 var $cookies; 116 117 var $helpers = 'default'; 118 119 var $app_helpers; 120 var $plugin_helpers = 'all'; 121 122 var $web_service; 123 var $web_services = array(); 124 125 var $web_service_api; 126 var $web_service_apis = array(); 127 128 var $module_name; 129 var $_module_path; 130 131 /** 132 * Old fashioned way of dispatching requests. Please use AkDispatcher or roll your own. 133 * 134 * @deprecated 135 */ 136 function handleRequest() 137 { 138 AK_LOG_EVENTS && empty($this->_Logger) ? ($this->_Logger =& Ak::getLogger()) : null; 139 AK_LOG_EVENTS && !empty($this->_Logger) ? $this->_Logger->warning('Using deprecated request dispatcher AkActionController::handleRequest. Use to AkDispatcher + AkDispatcher::dispatch instead.') : null; 140 require_once(AK_LIB_DIR.DS.'AkDispatcher.php'); 141 $Dispatcher =& new AkDispatcher(); 142 $Dispatcher->dispatch(); 143 } 144 145 function process(&$Request, &$Response) 146 { 147 AK_LOG_EVENTS && empty($this->_Logger) ? ($this->_Logger =& Ak::getLogger()) : null; 148 149 $this->Request =& $Request; 150 $this->Response =& $Response; 151 $this->params = $this->Request->getParams(); 152 $this->_action_name = $this->Request->getAction(); 153 154 $this->_ensureActionExists(); 155 156 Ak::t('Akelos'); // We need to get locales ready 157 158 if($this->_high_load_mode !== true){ 159 if(!empty($this->_auto_instantiate_models)){ 160 $this->instantiateIncludedModelClasses(); 161 } 162 if(!empty($this->_enable_plugins)){ 163 $this->loadPlugins(); 164 } 165 if(!empty($this->helpers)){ 166 $this->instantiateHelpers(); 167 } 168 }else{ 169 $this->_enableLayoutOnRender = false; 170 } 171 172 $this->_ensureProperProtocol(); 173 174 // After filters 175 $this->afterFilter('_handleFlashAttribute'); 176 177 $this->_loadActionView(); 178 179 if(isset($this->api)){ 180 require_once(AK_LIB_DIR.DS.'AkActionWebService.php'); 181 $this->aroundFilter(new AkActionWebService($this)); 182 } 183 184 $this->performActionWithFilters($this->_action_name); 185 186 if (!$this->_hasPerformed()){ 187 $this->_enableLayoutOnRender ? $this->renderWithLayout() : $this->renderWithoutLayout(); 188 } 189 190 if(!empty($this->validate_output)){ 191 $this->_validateGeneratedXhtml(); 192 } 193 194 $this->Response->outputResults(); 195 } 196 197 function _loadActionView() 198 { 199 empty($this->_assigns) ? ($this->_assigns = array()) : null; 200 empty($this->_default_render_status_code) ? ($this->_default_render_status_code = 200) : null; 201 $this->_enableLayoutOnRender = !isset($this->_enableLayoutOnRender) ? true : $this->_enableLayoutOnRender; 202 $this->passed_args = !isset($this->Request->pass)? array() : $this->Request->pass; 203 empty($this->cookies) && isset($_COOKIE) ? ($this->cookies =& $_COOKIE) : null; 204 205 if(empty($this->Template)){ 206 require_once(AK_LIB_DIR.DS.'AkActionView.php'); 207 require_once(AK_LIB_DIR.DS.'AkActionView'.DS.'AkPhpTemplateHandler.php'); 208 $this->Template =& new AkActionView($this->_getTemplateBasePath(), 209 $this->Request->getParameters(),$this->Request->getController()); 210 211 $this->Template->_controllerInstance =& $this; 212 $this->Template->_registerTemplateHandler('tpl','AkPhpTemplateHandler'); 213 } 214 } 215 216 function loadPlugins() 217 { 218 Ak::loadPlugins(); 219 } 220 221 /** 222 * Creates an instance of each available helper and links it into into current controller. 223 * 224 * Per example, if a helper TextHelper is located into the file text_helper.php. 225 * An instance is created on current controller 226 * at $this->text_helper. This instance is also available on the view by calling $text_helper. 227 * 228 * Helpers can be found at lib/AkActionView/helpers (this might change in a future) 229 */ 230 function instantiateHelpers() 231 { 232 $helpers = $this->getDefaultHelpers(); 233 $helpers = array_merge($helpers, $this->getApplicationHelpers()); 234 $helpers = array_merge($helpers, $this->getPluginHelpers()); 235 $helpers = array_merge($helpers, $this->getModuleHelper()); 236 $helpers = array_merge($helpers, $this->getCurrentControllerHelper()); 237 238 require_once(AK_LIB_DIR.DS.'AkActionView'.DS.'AkActionViewHelper.php'); 239 240 $available_helpers = array(); 241 foreach ($helpers as $file=>$helper){ 242 $helper_class_name = AkInflector::camelize(AkInflector::demodulize(strstr($helper, 'Helper') ? $helper : $helper.'Helper')); 243 $full_path = preg_match('/[\\\\\/]+/',$file); 244 $file_path = $full_path ? $file : AK_LIB_DIR.DS.'AkActionView'.DS.'helpers'.DS.$file; 245 include_once($file_path); 246 247 if(class_exists($helper_class_name)){ 248 $attribute_name = $full_path ? AkInflector::underscore($helper_class_name) : substr($file,0,-4); 249 $available_helpers[] = $attribute_name; 250 $this->$attribute_name =& new $helper_class_name(&$this); 251 if(method_exists($this->$attribute_name,'setController')){ 252 $this->$attribute_name->setController(&$this); 253 } 254 if(method_exists($this->$attribute_name,'init')){ 255 $this->$attribute_name->init(); 256 } 257 } 258 } 259 defined('AK_ACTION_CONTROLLER_AVAILABLE_HELPERS') ? null : define('AK_ACTION_CONTROLLER_AVAILABLE_HELPERS', join(',',$available_helpers)); 260 } 261 262 function getCurrentControllerHelper() 263 { 264 $helper = $this->getControllerName(); 265 $helper = AkInflector::is_plural($helper)?AkInflector::singularize($helper):$helper; 266 $helper_file_name = AK_HELPERS_DIR.DS.$this->_module_path.AkInflector::underscore($helper).'_helper.php'; 267 268 if(file_exists($helper_file_name)){ 269 return array($helper_file_name => $helper); 270 } 271 return array(); 272 } 273 274 function getModuleHelper() 275 { 276 $this->getControllerName(); // module name is set when we first retrieve the controller name 277 if(!empty($this->module_name)){ 278 $helper_file_name = AK_HELPERS_DIR.DS.AkInflector::underscore($this->module_name).'_helper.php'; 279 if(file_exists($helper_file_name)){ 280 return array($helper_file_name => $this->module_name); 281 } 282 } 283 return array(); 284 } 285 286 function getDefaultHelpers() 287 { 288 if($this->helpers == 'default'){ 289 $available_helpers = Ak::dir(AK_LIB_DIR.DS.'AkActionView'.DS.'helpers',array('dirs'=>false)); 290 $helper_names = array(); 291 foreach ($available_helpers as $available_helper){ 292 $helper_names[$available_helper] = AkInflector::classify(substr($available_helper,0,-10)); 293 } 294 return $helper_names; 295 }else{ 296 $this->helpers = Ak::toArray($this->helpers); 297 } 298 return $this->helpers; 299 } 300 301 function getApplicationHelpers() 302 { 303 $helper_names = array(); 304 if ($this->app_helpers == 'all'){ 305 $available_helpers = Ak::dir(AK_HELPERS_DIR,array('dirs'=>false)); 306 $helper_names = array(); 307 foreach ($available_helpers as $available_helper){ 308 $helper_names[AK_HELPERS_DIR.DS.$available_helper] = AkInflector::classify(substr($available_helper,0,-10)); 309 } 310 311 } elseif (!empty($this->app_helpers)){ 312 foreach (Ak::toArray($this->app_helpers) as $helper_name){ 313 $helper_names[AK_HELPERS_DIR.DS.AkInflector::underscore($helper_name).'_helper.php'] = AkInflector::camelize($helper_name); 314 } 315 } 316 return $helper_names; 317 } 318 319 function getPluginHelpers() 320 { 321 $helper_names = AkActionController::addPluginHelper(false); // Trick for getting helper names set by AkPlugin::addHelper 322 if(empty($helper_names)){ 323 return array(); 324 }elseif ($this->plugin_helpers == 'all'){ 325 return $helper_names; 326 }else { 327 $selected_helper_names = array(); 328 foreach (Ak::toArray($this->plugin_helpers) as $helper_name){ 329 $helper_name = AkInflector::camelize($helper_name); 330 if($path = array_shift(array_keys($helper_names, AkInflector::camelize($helper_name)))){ 331 $selected_helper_names[$path] = $helper_names[$path]; 332 } 333 } 334 return $selected_helper_names; 335 } 336 } 337 338 /** 339 * Used for adding helpers to the base class like those added by the plugins engine. 340 * 341 * @param string $helper_name Helper class name like CalendarHelper 342 * @param array $options - path: Path to the helper class, defaults to AK_PLUGINS_DIR/helper_name/lib/helper_name.php 343 */ 344 function addPluginHelper($helper_name, $options = array()) 345 { 346 static $helpers = array(); 347 if($helper_name === false){ 348 return $helpers; 349 } 350 $underscored_helper_name = AkInflector::underscore($helper_name); 351 $default_options = array( 352 'path' => AK_PLUGINS_DIR.DS.$underscored_helper_name.DS.'lib'.DS.$underscored_helper_name.'.php' 353 ); 354 $options = array_merge($default_options, $options); 355 $helpers[$options['path']] = $helper_name; 356 } 357 358 function _validateGeneratedXhtml() 359 { 360 require_once(AK_LIB_DIR.DS.'AkXhtmlValidator.php'); 361 $XhtmlValidator = new AkXhtmlValidator(); 362 if($XhtmlValidator->validate($this->Response->body) === false){ 363 $this->Response->sendHeaders(); 364 echo '<h1>'.Ak::t('Ooops! There are some errors on current XHTML page').'</h1>'; 365 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"; 366 $XhtmlValidator->showErrors(); 367 echo "<hr /><h2>".Ak::t('Showing XHTML code')."</h2><hr /><div style='border:5px solid red;margin:5px;padding:15px;'>".$this->Response->body."</pre>"; 368 die(); 369 } 370 } 371 372 373 /** 374 * Methods for loading desired models into this controller 375 */ 376 function setModel($model) 377 { 378 $this->instantiateIncludedModelClasses(array($model)); 379 } 380 381 function setModels($models) 382 { 383 $this->instantiateIncludedModelClasses($models); 384 } 385 386 function instantiateIncludedModelClasses($models = array()) 387 { 388 require_once(AK_LIB_DIR.DS.'AkActiveRecord.php'); 389 require_once(AK_APP_DIR.DS.'shared_model.php'); 390 391 empty($this->model) ? ($this->model = $this->params['controller']) : null; 392 empty($this->models) ? ($this->models = array()) : null; 393 394 $models = array_unique(array_merge(Ak::import($this->model), Ak::import($this->models), Ak::import($models), (empty($this->app_models)?array(): Ak::import($this->app_models)))); 395 396 foreach ($models as $model){ 397 $this->instantiateModelClass($model, (empty($this->finder_options[$model])?array():$this->finder_options[$model])); 398 } 399 } 400 401 function instantiateModelClass($model_class_name, $finder_options = array()) 402 { 403 $underscored_model_class_name = AkInflector::underscore($model_class_name); 404 $controller_name = $this->getControllerName(); 405 $id = empty($this->params[$underscored_model_class_name]['id']) ? 406 (empty($this->params['id']) ? false : 407 (($model_class_name == $controller_name || $model_class_name == AkInflector::singularize($controller_name)) ? $this->params['id'] : false)) : 408 $this->params[$underscored_model_class_name]['id']; 409 410 if(class_exists($model_class_name)){ 411 $underscored_model_class_name = AkInflector::underscore($model_class_name); 412 413 if(!isset($this->$model_class_name) || !isset($this->$underscored_model_class_name)){ 414 if($finder_options !== false && is_numeric($id)){ 415 $model =& new $model_class_name(); 416 if(empty($finder_options)){ 417 $model =& $model->find($id); 418 }else{ 419 $model =& $model->find($id, $finder_options); 420 } 421 }else{ 422 $model =& new $model_class_name(); 423 } 424 if(!isset($this->$model_class_name)){ 425 $this->$model_class_name =& $model; 426 } 427 if(!isset($this->$underscored_model_class_name)){ 428 $this->$underscored_model_class_name =& $model; 429 } 430 } 431 } 432 } 433 434 435 436 /** 437 Rendering content 438 ==================================================================== 439 */ 440 441 /** 442 * Renders the content that will be returned to the browser as the Response body. 443 * 444 * === Rendering an action 445 * 446 * Action rendering is the most common form and the type used automatically by 447 * Action Controller when nothing else is specified. By default, actions are 448 * rendered within the current layout (if one exists). 449 * 450 * * Renders the template for the action "goal" within the current controller 451 * 452 * $this->render(array('action'=>'goal')); 453 * 454 * * Renders the template for the action "short_goal" within the current controller, 455 * but without the current active layout 456 * 457 * $this->render(array('action'=>'short_goal','layout'=>false)); 458 * 459 * * Renders the template for the action "long_goal" within the current controller, 460 * but with a custom layout 461 * 462 * $this->render(array('action'=>'long_goal','layout'=>'spectacular')); 463 * 464 * === Rendering partials 465 * 466 * Partial rendering is most commonly used together with Ajax calls that only update 467 * one or a few elements on a page without reloading. Rendering of partials from 468 * the controller makes it possible to use the same partial template in 469 * both the full-page rendering (by calling it from within the template) and when 470 * sub-page updates happen (from the controller action responding to Ajax calls). 471 * By default, the current layout is not used. 472 * 473 * * Renders the partial located at app/views/controller/_win.tpl 474 * 475 * $this->render(array('partial'=>'win')); 476 * 477 * * Renders the partial with a status code of 500 (internal error) 478 * 479 * $this->render(array('partial'=>'broken','status'=>500)); 480 * 481 * * Renders the same partial but also makes a local variable available to it 482 * 483 * $this->render(array('partial' => 'win', 'locals' => array('name'=>'david'))); 484 * 485 * * Renders a collection of the same partial by making each element of $wins available through 486 * the local variable "win" as it builds the complete Response 487 * 488 * $this->render(array('partial'=>'win','collection'=>$wins)); 489 * 490 * * Renders the same collection of partials, but also renders the win_divider partial in between 491 * each win partial. 492 * 493 * $this->render(array('partial'=>'win','collection'=>$wins,'spacer_template'=>'win_divider')); 494 * 495 * === Rendering a template 496 * 497 * Template rendering works just like action rendering except that it takes a 498 * path relative to the template root. 499 * The current layout is automatically applied. 500 * 501 * * Renders the template located in app/views/weblog/show.tpl 502 * $this->render(array('template'=>'weblog/show')); 503 * 504 * === Rendering a file 505 * 506 * File rendering works just like action rendering except that it takes a 507 * filesystem path. By default, the path is assumed to be absolute, and the 508 * current layout is not applied. 509 * 510 * * Renders the template located at the absolute filesystem path 511 * $this->render(array('file'=>'/path/to/some/template.tpl')); 512 * $this->render(array('file'=>'c:/path/to/some/template.tpl')); 513 * 514 * * Renders a template within the current layout, and with a 404 status code 515 * $this->render(array('file' => '/path/to/some/template.tpl', 'layout' => true, 'status' => 404)); 516 * $this->render(array('file' => 'c:/path/to/some/template.tpl', 'layout' => true, 'status' => 404)); 517 * 518 * * Renders a template relative to the template root and chooses the proper file extension 519 * $this->render(array('file' => 'some/template', 'use_full_path' => true)); 520 * 521 * 522 * === Rendering text 523 * 524 * Rendering of text is usually used for tests or for rendering prepared content, 525 * such as a cache. By default, text 526 * rendering is not done within the active layout. 527 * 528 * * Renders the clear text "hello world" with status code 200 529 * $this->render(array('text' => 'hello world!')); 530 * 531 * * Renders the clear text "Explosion!" with status code 500 532 * $this->render(array('text' => "Explosion!", 'status' => 500 )); 533 * 534 * * Renders the clear text "Hi there!" within the current active layout (if one exists) 535 * $this->render(array('text' => "Explosion!", 'layout' => true)); 536 * 537 * * Renders the clear text "Hi there!" within the layout 538 * * placed in "app/views/layouts/special.tpl" 539 * $this->render(array('text' => "Explosion!", 'layout => "special")); 540 * 541 * 542 * === Rendering an inline template 543 * 544 * Rendering of an inline template works as a cross between text and action 545 * rendering where the source for the template 546 * is supplied inline, like text, but its evaled by PHP, like action. By default, 547 * PHP is used for rendering and the current layout is not used. 548 * 549 * * Renders "hello, hello, hello, again" 550 * $this->render(array('inline' => "<?php echo str_repeat('hello, ', 3).'again'?>" )); 551 * 552 * * Renders "hello david" 553 * $this->render(array('inline' => "<?php echo 'hello ' . $name ?>", 'locals' => array('name' => 'david'))); 554 * 555 * 556 * === Rendering nothing 557 * 558 * Rendering nothing is often convenient in combination with Ajax calls that 559 * perform their effect client-side or 560 * when you just want to communicate a status code. Due to a bug in Safari, nothing 561 * actually means a single space. 562 * 563 * * Renders an empty Response with status code 200 564 * $this->render(array('nothing' => true)); 565 * 566 * * Renders an empty Response with status code 401 (access denied) 567 * $this->render(array('nothing' => true, 'status' => 401)); 568 */ 569 function render($options = null, $status = 200) 570 { 571 if(empty($options['partial']) && $this->_hasPerformed()){ 572 $this->_doubleRenderError(Ak::t("Can only render or redirect once per action")); 573 return false; 574 } 575 576 $this->_flash_handled ? null : $this->_handleFlashAttribute(); 577 578 if(!is_array($options)){ 579 return $this->renderFile(empty($options) ? $this->getDefaultTemplateName() : $options, $status, true); 580 } 581 582 if(!empty($options['text'])){ 583 return $this->renderText($options['text'], @$options['status']); 584 }else{ 585 586 if(!empty($options['file'])){ 587 return $this->renderFile($options['file'], @$options['status'], @$options['use_full_path'], @(array)$options['locals']); 588 }elseif(!empty($options['template'])){ 589 return $this->renderFile($options['template'], @$options['status'], true); 590 }elseif(!empty($options['inline'])){ 591 return $this->renderTemplate($options['inline'], @$options['status'], @$options['type'], @(array)$options['locals']); 592 }elseif(!empty($options['action'])){ 593 return $this->renderAction($options['action'], @$options['status'], @$options['layout']); 594 }elseif(!empty($options['partial'])){ 595 if($options['partial'] === true){ 596 $options['partial'] = !empty($options['template']) ? $options['template'] : $this->getDefaultTemplateName(); 597 } 598 if(!empty($options['collection'])){ 599 return $this->renderPartialCollection($options['partial'], $options['collection'], @$options['spacer_template'], @$options['locals'], @$options['status']); 600 }else{ 601 return $this->renderPartial($options['partial'], @$options['object'], @$options['locals'], @$options['status']); 602 } 603 }elseif(!empty($options['nothing'])){ 604 // Safari doesn't pass the _headers of the return if the Response is zero length 605 return $this->renderText(' ', @$options['status']); 606 }else{ 607 return $this->renderFile($this->getDefaultTemplateName(), @$options['status'], true); 608 } 609 return true; 610 } 611 } 612 613 /** 614 * Renders according to the same rules as <tt>render</tt>, but returns the result in a string instead 615 * of sending it as the Response body to the browser. 616 */ 617 function renderToString($options = null) 618 { 619 $result = $this->render($options); 620 $this->eraseRenderResults(); 621 $this->variables_added = null; 622 $this->Template->_assigns_added = null; 623 return $result; 624 } 625 626 function renderAction($_action_name, $status = null, $with_layout = true) 627 { 628 $template = $this->getDefaultTemplateName($_action_name); 629 if(!empty($with_layout) && !$this->_isTemplateExemptFromLayout($template)){ 630 return $this->renderWithLayout($template, $status, $with_layout); 631 }else{ 632 return $this->renderWithoutLayout($template, $status); 633 } 634 } 635 636 function renderFile($template_path, $status = null, $use_full_path = false, $locals = array()) 637 { 638 $this->_addVariablesToAssigns(); 639 $locals = array_merge($locals,$this->_assigns); 640 641 if($use_full_path){ 642 $this->_assertExistanceOfTemplateFile($template_path); 643 } 644 645 AK_LOG_EVENTS && !empty($this->_Logger) ? $this->_Logger->message("Rendering $this->full_template_path" . (!empty($status) ? " ($status)":'')) : null; 646 return $this->renderText($this->Template->renderFile($template_path, $use_full_path, $locals), $status); 647 } 648 649 function renderTemplate($template, $status = null, $type = 'tpl', $local_assigns = array()) 650 { 651 $this->_addVariablesToAssigns(); 652 $local_assigns = array_merge($local_assigns,$this->_assigns); 653 return $this->renderText($this->Template->renderTemplate($type, $template, null, $local_assigns), $status); 654 } 655 656 function renderText($text = null, $status = null) 657 { 658 $this->performed_render = true; 659 $this->Response->_headers['Status'] = !empty($status) ? $status : $this->_default_render_status_code; 660 $this->Response->body = $text; 661 return $text; 662 } 663 664 function renderNothing($status = null) 665 { 666 return $this->renderText(' ', $status); 667 } 668 669 function renderPartial($partial_path = null, $object = null, $local_assigns = null, $status = null) 670 { 671 $partial_path = empty($partial_path) ? $this->getDefaultTemplateName() : $partial_path; 672 $this->variables_added = false; 673 $this->performed_render = false; 674 $this->_addVariablesToAssigns(); 675 $this->Template->controller =& $this; 676 $this->$partial_path = $this->renderText($this->Template->renderPartial($partial_path, $object, array_merge($this->_assigns, (array)$local_assigns)), $status); 677 return $this->$partial_path; 678 } 679 680 function renderPartialCollection($partial_name, $collection, $partial_spacer_template = null, $local_assigns = null, $status = null) 681 { 682 $this->_addVariablesToAssigns(); 683 $collection_name = AkInflector::pluralize($partial_name).'_collection'; 684 $result = $this->Template->renderPartialCollection($partial_name, $collection, $partial_spacer_template, $local_assigns); 685 if(empty($this->$collection_name)){ 686 $this->$collection_name = $result; 687 } 688 $this->variables_added = false; 689 $this->performed_render = false; 690 691 return $result; 692 } 693 694 function renderWithLayout($template_name = null, $status = null, $layout = null) 695 { 696 $template_name = empty($template_name) ? $this->getDefaultTemplateName() : $template_name; 697 return $this->renderWithALayout($template_name, $status, $layout); 698 } 699 700 function renderWithoutLayout($template_name = null, $status = null) 701 { 702 $template_name = empty($template_name) ? $this->getDefaultTemplateName() : $template_name; 703 return $this->render($template_name, $status); 704 } 705 706 /** 707 * Clears the rendered results, allowing for another render to be performed. 708 */ 709 function eraseRenderResults() 710 { 711 $this->Response->body = ''; 712 $this->performed_render = false; 713 $this->variables_added = false; 714 } 715 716 function _addVariablesToAssigns() 717 { 718 if(empty($this->variables_added)){ 719 $this->_addInstanceVariablesToAssigns(); 720 $this->variables_added = true; 721 } 722 } 723 724 function _addInstanceVariablesToAssigns() 725 { 726 $this->_protected_variables_cache = array_merge($this->_protected_variables_cache, $this->_getProtectedInstanceVariables()); 727 728 foreach (array_diff(array_keys(get_object_vars($this)), $this->_protected_variables_cache) as $attribute){ 729 if($attribute[0] != '_'){ 730 $this->_assigns[$attribute] =& $this->$attribute; 731 } 732 } 733 } 734 735 function _getProtectedInstanceVariables() 736 { 737 return !empty($this->_view_controller_internals) ? 738 array('_assigns', 'performed_redirect', 'performed_render','db') : 739 array('_assigns', 'performed_redirect', 'performed_render', 'session', 'cookies', 740 'Template','db','helpers','models','layout','Response','Request', 741 'params','passed_args'); 742 } 743 744 745 /** 746 * Use this to translate strings in the scope of your controller 747 * 748 * @see Ak::t 749 */ 750 function t($string, $array = null) 751 { 752 return Ak::t($string, $array, AkInflector::underscore($this->getControllerName())); 753 } 754 755 756 757 /** 758 Redirects 759 ==================================================================== 760 */ 761 762 /** 763 * Redirects the browser to the target specified in +options+. This parameter can take one of three forms: 764 * 765 * * <tt>Array</tt>: The URL will be generated by calling $this->UrlFor with the +options+. 766 * * <tt>String starting with protocol:// (like http://)</tt>: Is passed straight through 767 * as the target for redirection. 768 * * <tt>String not containing a protocol</tt>: The current protocol and host is prepended to the string. 769 * * <tt>back</tt>: Back to the page that issued the Request-> Useful for forms that are 770 * triggered from multiple places. 771 * Short-hand for redirectTo(Request->env["HTTP_REFERER"]) 772 * 773 * Examples: 774 * redirectTo(array('action' => 'show', 'id' => 5)); 775 * redirectTo('http://www.akelos.com'); 776 * redirectTo('/images/screenshot.jpg'); 777 * redirectTo('back'); 778 * 779 * The redirection happens as a "302 Moved" header. 780 */ 781 function redirectTo($options = array(), $parameters_for_method_reference = null) 782 { 783 if(is_string($options)) { 784 if(preg_match('/^\w+:\/\/.*/',$options)){ 785 if($this->_hasPerformed()){ 786 $this->_doubleRenderError(); 787 } 788 AK_LOG_EVENTS && !empty($this->_Logger) ? $this->_Logger->message('Redirected to '.$options) : null; 789 $this->_handleFlashAttribute(); 790 $this->Response->redirect($options); 791 $this->Response->redirected_to = $options; 792 $this->performed_redirect = true; 793 }elseif ($options == 'back'){ 794 $this->redirectTo($this->Request->env['HTTP_REFERER']); 795 }else{ 796 $this->redirectTo($this->Request->getProtocol(). $this->Request->getHostWithPort(). $options); 797 } 798 }else{ 799 if(empty($parameters_for_method_reference)){ 800 $this->redirectTo($this->UrlFor($options)); 801 $this->Response->redirected_to = $options; 802 }else{ 803 $this->redirectTo($this->UrlFor($options, $parameters_for_method_reference)); 804 $this->Response->redirected_to = $options; 805 $this->Response->redirected_to_method_params = $parameters_for_method_reference; 806 } 807 } 808 } 809 810 function redirectToAction($action, $options = array()) 811 { 812 $this->redirectTo(array_merge(array('action'=>$action), $options)); 813 } 814 815 816 /** 817 * This methods are required for retrieving available controllers for URL Routing 818 */ 819 function rewriteOptions($options) 820 { 821 $defaults = $this->defaultUrlOptions($options); 822 if(!empty($this->module_name)){ 823 $defaults['module'] = $this->getModuleName(); 824 } 825 if(!empty($options['controller']) && strstr($options['controller'], '/')){ 826 $defaults['module'] = substr($options['controller'], 0, strrpos($options['controller'], '/')); 827 $options['controller'] = substr($options['controller'], strrpos($options['controller'], '/') + 1); 828 } 829 $options = !empty($defaults) ? array_merge($defaults, $options) : $options; 830 $options['controller'] = empty($options['controller']) ? AkInflector::underscore($this->getControllerName()) : $options['controller']; 831 return $options; 832 } 833 834 function getControllerName() 835 { 836 if(!isset($this->controller_name)){ 837 $current_class_name = str_replace('_', '::', get_class($this)); 838 if (!AK_PHP5){ 839 $current_class_name = $this->__getControllerName_PHP4_fix($current_class_name); 840 } 841 $controller_name = substr($current_class_name,0,-10); 842 $this->controller_name = $this->_removeModuleNameFromControllerName($controller_name); 843 } 844 return $this->controller_name; 845 } 846 847 function __getControllerName_PHP4_fix($class_name) 848 { 849 $included_controllers = $this->_getIncludedControllerNames(); 850 $lowercase_included_controllers = array_map('strtolower', $included_controllers); 851 $key = array_search(strtolower($class_name), $lowercase_included_controllers, true); 852 return $included_controllers[$key]; 853 } 854 855 function getModuleName() 856 { 857 return $this->module_name; 858 } 859 860 function setModuleName($module_name) 861 { 862 return $this->module_name = $module_name; 863 } 864 865 /** 866 * Removes the modules name from the controller if exists and sets it. 867 * 868 * @return $controller_name 869 */ 870 function _removeModuleNameFromControllerName($controller_name) 871 { 872 if(strstr($controller_name, '::')){ 873 $module_parts = explode ('::',$controller_name); 874 $controller_name = array_pop($module_parts); 875 $this->setModuleName(join('/', array_map(array('AkInflector','underscore'), $module_parts))); 876 } 877 return $controller_name; 878 } 879 880 function _getTemplateBasePath() 881 { 882 return AK_APP_DIR.DS.'views'.DS.(empty($this->_module_path)?'':$this->_module_path).$this->Request->getController(); 883 } 884 885 function _getIncludedControllerNames() 886 { 887 $controllers = array(); 888 foreach (get_included_files() as $file_name){ 889 if(strstr($file_name,AK_CONTROLLERS_DIR)){ 890 $controllers[] = AkInflector::classify(str_replace(array(AK_CONTROLLERS_DIR.DS,'.php', DS, '//'),array('','','/', '/'),$file_name)); 891 } 892 } 893 return $controllers; 894 } 895 896 897 898 899 /** 900 URL generation/rewriting 901 ==================================================================== 902 */ 903 904 905 /** 906 * Overwrite to implement a number of default options that all urlFor-based methods will use. 907 * The default options should come in 908 * the form of a an array, just like the one you would use for $this->UrlFor directly. Example: 909 * 910 * function defaultUrlOptions($options) 911 * { 912 * return array('project' => ($this->Project->isActive() ? $this->Project->url_name : 'unknown')); 913 * } 914 * 915 * As you can infer from the example, this is mostly useful for situations where you want to 916 * centralize dynamic decisions about the urls as they stem from the business domain. 917 * Please note that any individual $this->UrlFor call can always override the defaults set 918 * by this method. 919 */ 920 function defaultUrlOptions($options) 921 { 922 } 923 924 925 /** 926 * Returns a URL that has been rewritten according to the options array and the defined Routes. 927 * (For doing a complete redirect, use redirectTo). 928 * 929 * <tt>$this->UrlFor</tt> is used to: 930 * 931 * All keys given to $this->UrlFor are forwarded to the Route module, save for the following: 932 * * <tt>anchor</tt> -- specifies the anchor name to be appended to the path. For example, 933 * <tt>$this->UrlFor(array('controller' => 'posts', 'action' => 'show', 'id' => 10, 'anchor' => 'comments'</tt> 934 * will produce "/posts/show/10#comments". 935 * * <tt>only_path</tt> -- if true, returns the absolute URL (omitting the protocol, host name, and port) 936 * * <tt>trailing_slash</tt> -- if true, adds a trailing slash, as in "/archive/2005/". Note that this 937 * is currently not recommended since it breaks caching. 938 * * <tt>host</tt> -- overrides the default (current) host if provided 939 * * <tt>protocol</tt> -- overrides the default (current) protocol if provided 940 * 941 * The URL is generated from the remaining keys in the array. A URL contains two key parts: the <base> and a query string. 942 * Routes composes a query string as the key/value pairs not included in the <base>. 943 * 944 * The default Routes setup supports a typical Akelos Framework path of "controller/action/id" 945 * where action and id are optional, with 946 * action defaulting to 'index' when not given. Here are some typical $this->UrlFor statements 947 * and their corresponding URLs: 948 * 949 * $this->UrlFor(array('controller'=>'posts','action'=>'recent')); // 'proto://host.com/posts/recent' 950 * $this->UrlFor(array('controller'=>'posts','action'=>'index')); // 'proto://host.com/posts' 951 * $this->UrlFor(array('controller'=>'posts','action'=>'show','id'=>10)); // 'proto://host.com/posts/show/10' 952 * 953 * When generating a new URL, missing values may be filled in from the current 954 * Request's parameters. For example, 955 * <tt>$this->UrlFor(array('action'=>'some_action'));</tt> will retain the current controller, 956 * as expected. This behavior extends to other parameters, including <tt>controller</tt>, 957 * <tt>id</tt>, and any other parameters that are placed into a Route's path. 958 * 959 * The URL helpers such as <tt>$this->UrlFor</tt> have a limited form of memory: 960 * when generating a new URL, they can look for missing values in the current Request's parameters. 961 * Routes attempts to guess when a value should and should not be 962 * taken from the defaults. There are a few simple rules on how this is performed: 963 * 964 * * If the controller name begins with a slash, no defaults are used: <tt>$this->UrlFor(array('controller'=>'/home'));</tt> 965 * * If the controller changes, the action will default to index unless provided 966 * 967 * The final rule is applied while the URL is being generated and is best illustrated by an example. Let us consider the 968 * route given by <tt>map->connect('people/:last/:first/:action', array('action' => 'bio', 'controller' => 'people'))</tt>. 969 * 970 * Suppose that the current URL is "people/hh/david/contacts". Let's consider a few 971 * different cases of URLs which are generated from this page. 972 * 973 * * <tt>$this->UrlFor(array('action'=>'bio'));</tt> -- During the generation of this URL, 974 * default values will be used for the first and 975 * last components, and the action shall change. The generated URL will be, "people/hh/david/bio". 976 * * <tt>$this->UrlFor(array('first'=>'davids-little-brother'));</tt> This 977 * generates the URL 'people/hh/davids-little-brother' -- note 978 * that this URL leaves out the assumed action of 'bio'. 979 * 980 * However, you might ask why the action from the current Request, 'contacts', isn't 981 * carried over into the new URL. The answer has to do with the order in which 982 * the parameters appear in the generated path. In a nutshell, since the 983 * value that appears in the slot for <tt>first</tt> is not equal to default value 984 * for <tt>first</tt> we stop using defaults. On it's own, this rule can account 985 * for much of the typical Akelos Framework URL behavior. 986 * 987 * Although a convienence, defaults can occasionaly get in your way. In some cases 988 * a default persists longer than desired. 989 * The default may be cleared by adding <tt>'name' => null</tt> to <tt>$this->UrlFor</tt>'s options. 990 * This is often required when writing form helpers, since the defaults in play 991 * may vary greatly depending upon where the helper is used from. The following line 992 * will redirect to PostController's default action, regardless of the page it is 993 * displayed on: 994 * 995 * $this->UrlFor(array('controller' => 'posts', 'action' => null)); 996 * 997 * If you explicitly want to create a URL that's almost the same as the current URL, you can do so using the 998 * overwrite_params options. Say for your posts you have different views for showing and printing them. 999 * Then, in the show view, you get the URL for the print view like this 1000 * 1001 * $this->UrlFor(array('overwrite_params' => array('action' => 'print'))); 1002 * 1003 * This takes the current URL as is and only exchanges the action. In contrast, 1004 * <tt>$this->UrlFor(array('action'=>'print'));</tt> 1005 * would have slashed-off the path components after the changed action. 1006 */ 1007 function urlFor($options = array(), $parameters_for_method_reference = null) 1008 { 1009 return $this->rewrite($this->rewriteOptions($options)); 1010 } 1011 1012 function addToUrl($options = array(), $options_to_exclude = array()) 1013 { 1014 $options_to_exclude = array_merge(array('ak','lang',AK_SESSION_NAME,'AK_SESSID','PHPSESSID'), $options_to_exclude); 1015 $options = array_merge(array_merge(array('action'=>$this->Request->getAction()),$this->params),$options); 1016 foreach ($options_to_exclude as $option_to_exclude){ 1017 unset($options[$option_to_exclude]); 1018 } 1019 return $this->urlFor($options); 1020 } 1021 1022 function getActionName() 1023 { 1024 return $this->Request->getAction(); 1025 } 1026 1027 1028 function _doubleRenderError($message = null) 1029 { 1030 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); 1031 } 1032 1033 function _hasPerformed() 1034 { 1035 return !empty($this->performed_render) || !empty($this->performed_redirect); 1036 } 1037 1038 function _getRequestOrigin() 1039 { 1040 return $this->Request->remote_ip.' at '.Ak::getDate(); 1041 } 1042 1043 function _getCompleteRequestUri() 1044 { 1045 return $this->Request->protocol . $this->Request->host . $this->Request->request_uri; 1046 } 1047 1048 function _closeSession() 1049 { 1050 !empty($this->session) ? session_write_close() : null; 1051 } 1052 1053 1054 function _hasTemplate($template_name = null) 1055 { 1056 return file_exists(empty($template_name) ? $this->getDefaultTemplateName() : $template_name); 1057 } 1058 1059 function _templateIsPublic($template_name = null) 1060 { 1061 $template_name = empty($template_name) ? $this->getDefaultTemplateName() : $template_name; 1062 return $this->Template->fileIsPublic($template_name); 1063 } 1064 1065 function _isTemplateExemptFromLayout($template_name = null) 1066 { 1067 $template_name = empty($template_name) ? $this->getDefaultTemplateName() : $template_name; 1068 return $this->Template->_javascriptTemplateExists($template_name); 1069 } 1070 1071 function _assertExistanceOfTemplateFile($template_name) 1072 { 1073 $extension = $this->Template->delegateTemplateExists($template_name); 1074 $this->full_template_path = $this->Template->getFullTemplatePath($template_name, $extension ? $extension : 'tpl'); 1075 if(!$this->_hasTemplate($this->full_template_path)){ 1076 if(!empty($this->_ignore_missing_templates) && $this->_ignore_missing_templates === true){ 1077 return; 1078 } 1079 $template_type = strstr($template_name,'layouts') ? 'layout' : 'template'; 1080 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); 1081 } 1082 } 1083 1084 function getDefaultTemplateName($default_action_name = null) 1085 { 1086 return empty($default_action_name) ? (empty($this->_default_template_name) ? $this->_action_name : $this->_default_template_name) : $default_action_name; 1087 } 1088 1089 function setDefaultTemplateName($template_name) 1090 { 1091 $this->_default_template_name = $template_name; 1092 } 1093 1094 1095 1096 function rewrite($options = array()) 1097 { 1098 return $this->_rewriteUrl($this->_rewritePath($options), $options); 1099 } 1100 1101 1102 function toString() 1103 { 1104 return $this->Request->getProtocol().$this->Request->getHostWithPort(). 1105 $this->Request->getPath().@$this->parameters['controller']. 1106 @$this->parameters['action'].@$this->parameters['inspect']; 1107 } 1108 1109 /** 1110 * Given a path and options, returns a rewritten URL string 1111 */ 1112 function _rewriteUrl($path, $options) 1113 { 1114 $rewritten_url = ''; 1115 if(empty($options['only_path'])){ 1116 $rewritten_url .= !empty($options['protocol']) ? $options['protocol'] : $this->Request->getProtocol(); 1117 $rewritten_url .= empty($rewritten_url) || strpos($rewritten_url,'://') ? '' : '://'; 1118 $rewritten_url .= $this->_rewriteAuthentication($options); 1119 $rewritten_url .= !empty($options['host']) ? $options['host'] : $this->Request->getHostWithPort(); 1120 $options = Ak::delete($options, array('user','password','host','protocol')); 1121 } 1122 1123 $rewritten_url .= empty($options['skip_relative_url_root']) ? $this->Request->getRelativeUrlRoot() : ''; 1124 1125 if(empty($options['skip_url_locale'])){ 1126 $locale = $this->Request->getLocaleFromUrl(); 1127 if(empty($options['lang'])){ 1128 $rewritten_url .= (empty($locale) ? '' : '/').$locale; 1129 } 1130 1131 } 1132 1133 $rewritten_url .= (substr($rewritten_url,-1) == '/' ? '' : (AK_URL_REWRITE_ENABLED ? '' : (!empty($path[0]) && $path[0] != '/' ? '/' : ''))); 1134 $rewritten_url .= $path; 1135 $rewritten_url .= empty($options['trailing_slash']) ? '' : '/'; 1136 $rewritten_url .= empty($options['anchor']) ? '' : '#'.$options['anchor']; 1137 1138 return $rewritten_url; 1139 } 1140 1141 function _rewriteAuthentication($options) 1142 { 1143 if(!isset($options['user']) && isset($options['password'])){ 1144 return urlencode($options['user']).':'.urlencode($options['password']).'@'; 1145 }else{ 1146 return ''; 1147 } 1148 } 1149 1150 function _rewritePath($options) 1151 { 1152 if(!empty($options['params'])){ 1153 foreach ($options['params'] as $k=>$v){ 1154 $options[$k] = $v; 1155 } 1156 unset($options['params']); 1157 } 1158 if(!empty($options['overwrite_params'])){ 1159 foreach ($options['overwrite_params'] as $k=>$v){ 1160 $options[$k] = $v; 1161 } 1162 unset($options['overwrite_params']); 1163 } 1164 foreach (array('anchor', 'params', 'only_path', 'host', 'protocol', 'trailing_slash', 'skip_relative_url_root') as $k){ 1165 unset($options[$k]); 1166 } 1167 $path = Ak::toUrl($options); 1168 return $path; 1169 } 1170 1171 /** 1172 * Returns a query string with escaped keys and values from the passed array. If the passed 1173 * array contains an 'id' it'll 1174 * be added as a path element instead of a regular parameter pair. 1175 */ 1176 function buildQueryString($array, $only_keys = null) 1177 { 1178 $array = !empty($only_keys) ? array_keys($array) : $array; 1179 return Ak::toUrl($array); 1180 } 1181 1182 1183 1184 1185 /** 1186 Layouts 1187 ==================================================================== 1188 * 1189 * Layouts reverse the common pattern of including shared headers and footers in many templates 1190 * to isolate changes in repeated setups. The inclusion pattern has pages that look like this: 1191 * 1192 * <?php echo $controller->render('shared/header') ?> 1193 * Hello World 1194 * <?php echo $controller->render('shared/footer') ?> 1195 * 1196 * This approach is a decent way of keeping common structures isolated from the 1197 * changing content, but it's verbose and if( you ever want to change the structure 1198 * of these two includes, you'll have to change all the templates. 1199 * 1200 * With layouts, you can flip it around and have the common structure know where 1201 * to insert changing …
Large files files are truncated, but you can click here to view the full file