PageRenderTime 59ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/AkActionController.php

http://akelosframework.googlecode.com/
PHP | 2533 lines | 1167 code | 266 blank | 1100 comment | 140 complexity | 185aefb13d635a2b29f4c8b9bebdf7e4 MD5 | raw file
Possible License(s): LGPL-2.1

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

Large files files are truncated, but you can click here to view the full file