PageRenderTime 29ms CodeModel.GetById 7ms 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
  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
  1064. * <tt><?php echo $$this->content_for_layout ?></tt>. This layout can itself depend on instance variables assigned during action
  1065. * performance and have access to them as any normal template would.
  1066. */
  1067. function setLayout($template_name, $conditions = array())
  1068. {
  1069. $this->_addLayoutConditions($conditions);
  1070. $this->layout = $template_name;
  1071. }
  1072. function getLayoutConditions()
  1073. {
  1074. return empty($this->_layout_conditions) ? array() : $this->_layout_conditions;
  1075. }
  1076. function _addLayoutConditions($conditions)
  1077. {
  1078. $this->_layout_conditions = $conditions;
  1079. }
  1080. /**
  1081. * Returns the name of the active layout. If the layout was specified as a method reference, this method
  1082. * is called and the return value is used. Likewise if( the layout was specified as an inline method (through a method
  1083. * object). If the layout was defined without a directory, layouts is assumed. So <tt>setLayout('weblog/standard')</tt> will return
  1084. * weblog/standard, but <tt>setLayout('standard')</tt> will return layouts/standard.
  1085. */
  1086. function getActiveLayout($passed_layout = null)
  1087. {
  1088. if(empty($passed_layout)){
  1089. $layout = !isset($this->layout) ? AkInflector::underscore($this->getControllerName()) : $this->layout;
  1090. }else{
  1091. $layout =& $passed_layout;
  1092. }
  1093. if(is_array($layout) && is_object($layout[0]) && method_exists($layout[0], $layout[1])){
  1094. $this->active_layout = $layout[0]->{$layout[1]}();
  1095. }elseif(method_exists($this,$layout) && strtolower(get_class($this)) !== strtolower($layout)){
  1096. $this->active_layout = $this->$layout();
  1097. }else{
  1098. $this->active_layout = $layout;
  1099. }
  1100. if(!empty($this->active_layout)){
  1101. return strstr($this->active_layout,DS) ? $this->active_layout : 'layouts'.DS.$this->active_layout;
  1102. }
  1103. }
  1104. function renderWithALayout($options = null, $status = null, $layout = null)
  1105. {
  1106. $template_with_options = !empty($options) && is_array($options);
  1107. if($this->_canApplyLayout($template_with_options, $options) && ($layout = $this->_pickLayout($template_with_options, $options, $layout))){
  1108. $options = $template_with_options? array_merge((array)$options,array('layout'=>false)) : $options;
  1109. $this->content_for_layout = $this->render($options, $status);
  1110. if($template_with_options){
  1111. $status = empty($options['status']) ? $status : $options['status'];
  1112. }
  1113. $this->eraseRenderResults();
  1114. $this->_addVariablesToAssigns();
  1115. return $this->renderText($this->Template->renderFile($layout, true, &$this->_assigns), $status);
  1116. }else{
  1117. return $this->render($options, $status, &$this->_assigns);
  1118. }
  1119. }
  1120. function _canApplyLayout($template_with_options, $options)
  1121. {
  1122. return !empty($template_with_options) ? $this->_isCandidateForLayout($options) : !$this->_isTemplateExemptFromLayout();
  1123. }
  1124. function _isCandidateForLayout($options)
  1125. {
  1126. return !empty($options['layout']) ||
  1127. (empty($options['text']) && empty($options['file']) && empty($options['inline']) && empty($options['partial']) && empty($options['nothing'])) &&
  1128. !$this->_isTemplateExemptFromLayout($this->_getDefaultTemplateName(empty($options['action']) ? $options['template'] : $options['action']));
  1129. }
  1130. function _pickLayout($template_with_options, $options, $layout = null)
  1131. {
  1132. if(!empty($template_with_options)){
  1133. $layout = empty($options['layout']) ? ($this->_doesActionHasLayout() ? $this->getActiveLayout(): false) : $this->getActiveLayout($options['layout']);
  1134. }elseif(empty($layout) || $layout === true){
  1135. $layout = $this->_doesActionHasLayout() ? $this->getActiveLayout() : false;
  1136. }
  1137. if(!empty($layout)){
  1138. $layout = strstr($layout,'/') || strstr($layout,DS) ? $layout : 'layouts'.DS.$layout;
  1139. $layout = substr($layout,0,7) === 'layouts' ? AK_VIEWS_DIR.DS.$layout.'.tpl' : $layout.'.tpl';
  1140. if (file_exists($layout)) {
  1141. return $layout;
  1142. }
  1143. $layout = null;
  1144. }
  1145. if(empty($layout) && $layout !== false && defined('AK_DEFAULT_LAYOUT')){
  1146. $layout = AK_VIEWS_DIR.DS.'layouts'.DS.AK_DEFAULT_LAYOUT.'.tpl';
  1147. }
  1148. return file_exists($layout) ? $layout : false;
  1149. }
  1150. function _doesActionHasLayout()
  1151. {
  1152. $conditions = $this->getLayoutConditions();
  1153. $action_name = $this->Request->getAction();
  1154. if(!empty($conditions['only']) && ((is_array($conditions['only']) && in_array($action_name,$conditions['only'])) ||
  1155. (is_string($conditions['only']) && $action_name == $conditions['only']))){
  1156. return true;
  1157. }elseif (!empty($conditions['only'])){
  1158. return false;
  1159. }
  1160. if(!empty($conditions['except']) && ((is_array($conditions['except']) && in_array($action_name,$conditions['except'])) ||
  1161. (is_string($conditions['except']) && $action_name == $conditions['except']))){
  1162. return false;
  1163. }
  1164. return true;
  1165. }
  1166. /**
  1167. * Filters enable controllers to run shared pre and post processing code for its actions. These filters can be used to do
  1168. * authentication, caching, or auditing before the intended action is performed. Or to do localization or output
  1169. * compression after the action has been performed.
  1170. *
  1171. * Filters have access to the request, response, and all the instance variables set by other filters in the chain
  1172. * or by the action (in the case of after filters). Additionally, it's possible for a pre-processing <tt>beforeFilter</tt>
  1173. * to halt the processing before the intended action is processed by returning false or performing a redirect or render.
  1174. * This is especially useful for filters like authentication where you're not interested in allowing the action to be
  1175. * performed if the proper credentials are not in order.
  1176. *
  1177. * == Filter inheritance
  1178. *
  1179. * Controller inheritance hierarchies share filters downwards, but subclasses can also add new filters without
  1180. * affecting the superclass. For example:
  1181. *
  1182. * class BankController extends AkActionController
  1183. * {
  1184. * function __construct()
  1185. * {
  1186. * $this->beforeFilter('_audit');
  1187. * }
  1188. *
  1189. * function _audit(&$controller)
  1190. * {
  1191. * // record the action and parameters in an audit log
  1192. * }
  1193. * }
  1194. *
  1195. * class VaultController extends BankController
  1196. * {
  1197. * function __construct()
  1198. * {
  1199. * $this->beforeFilter('_verifyCredentials');
  1200. * }
  1201. *
  1202. * function _verifyCredentials(&$controller)
  1203. * {
  1204. * // make sure the user is allowed into the vault
  1205. * }
  1206. * }
  1207. *
  1208. * Now any actions performed on the BankController will have the audit method called before. On the VaultController,
  1209. * first the audit method is called, then the _verifyCredentials method. If the _audit method returns false, then
  1210. * _verifyCredentials and the intended action are never called.
  1211. *
  1212. * == Filter types
  1213. *
  1214. * A filter can take one of three forms: method reference, external class, or inline method. The first
  1215. * is the most common and works by referencing a method somewhere in the inheritance hierarchy of
  1216. * the controller by use of a method name. In the bank example above, both BankController and VaultController use this form.
  1217. *
  1218. * Using an external class makes for more easily reused generic filters, such as output compression. External filter classes
  1219. * are implemented by having a static +filter+ method on any class and then passing this class to the filter method. Example:
  1220. *
  1221. * class OutputCompressionFilter
  1222. * {
  1223. * function filter(&$controller)
  1224. * {
  1225. * $controller->response->body = compress($controller->response->body);
  1226. * }
  1227. * }
  1228. *
  1229. * class NewspaperController extends AkActionController
  1230. * {
  1231. * function __construct()
  1232. * {
  1233. * $this->afterFilter(new OutputCompressionFilter());
  1234. * }
  1235. * }
  1236. *
  1237. * The filter method is passed the controller instance and is hence granted access to all aspects of the controller and can
  1238. * manipulate them as it sees fit.
  1239. *
  1240. *
  1241. * == Filter chain ordering
  1242. *
  1243. * Using <tt>beforeFilter</tt> and <tt>afterFilter</tt> appends the specified filters to the existing chain. That's usually
  1244. * just fine, but some times you care more about the order in which the filters are executed. When that's the case, you
  1245. * can use <tt>prependBeforeFilter</tt> and <tt>prependAfterFilter</tt>. Filters added by these methods will be put at the
  1246. * beginning of their respective chain and executed before the rest. For example:
  1247. *
  1248. * class ShoppingController extends AkActionController
  1249. * {
  1250. * function __construct()
  1251. * {
  1252. * $this->beforeFilter('verifyOpenShop');
  1253. * }
  1254. * }
  1255. *
  1256. *
  1257. * class CheckoutController extends AkActionController
  1258. * {
  1259. * function __construct()
  1260. * {
  1261. * $this->prependBeforeFilter('ensureItemsInCart', 'ensureItemsInStock');
  1262. * }
  1263. * }
  1264. *
  1265. * The filter chain for the CheckoutController is now <tt>ensureItemsInCart, ensureItemsInStock,</tt>
  1266. * <tt>verifyOpenShop</tt>. So if either of the ensure filters return false, we'll never get around to see if the shop
  1267. * is open or not.
  1268. *
  1269. * You may pass multiple filter arguments of each type.
  1270. *
  1271. * == Around filters
  1272. *
  1273. * In addition to the individual before and after filters, it's also possible to specify that a single object should handle
  1274. * both the before and after call. That's especially useful when you need to keep state active between the before and after,
  1275. * such as the example of a benchmark filter below:
  1276. *
  1277. * class WeblogController extends AkActionController
  1278. * {
  1279. * function __construct()
  1280. * {
  1281. * $this->aroundFilter(new BenchmarkingFilter());
  1282. * }
  1283. *
  1284. * // Before this action is performed, BenchmarkingFilter->before($controller) is executed
  1285. * function index()
  1286. * {
  1287. * }
  1288. * // After this action has been performed, BenchmarkingFilter->after($controller) is executed
  1289. * }
  1290. *
  1291. * class BenchmarkingFilter
  1292. * {
  1293. * function before(&$controller)
  1294. * {
  1295. * start_timer();
  1296. * }
  1297. *
  1298. * function after(&$controller)
  1299. * {
  1300. * stop_timer();
  1301. * report_result();
  1302. * }
  1303. * }
  1304. *
  1305. * == Filter chain skipping
  1306. *
  1307. * Some times its convenient to specify a filter chain in a superclass that'll hold true for the majority of the
  1308. * subclasses, but not necessarily all of them. The subclasses that behave in exception can then specify which filters
  1309. * they would like to be relieved of. Examples
  1310. *
  1311. * class ApplicationController extends AkActionController
  1312. * {
  1313. * function __construct()
  1314. * {
  1315. * $this->beforeFilter('authenticate');
  1316. * }
  1317. * }
  1318. *
  1319. * class WeblogController extends ApplicationController
  1320. * {
  1321. * // will run the authenticate filter
  1322. * }
  1323. *
  1324. * class SignupController extends AkActionController
  1325. * {
  1326. * function __construct()
  1327. * {
  1328. * $this->skipBeforeFilter('authenticate');
  1329. * }
  1330. * // will not run the authenticate filter
  1331. * }
  1332. *
  1333. * == Filter conditions
  1334. *
  1335. * Filters can be limited to run for only specific actions. This can be expressed either by listing the actions to
  1336. * exclude or the actions to include when executing the filter. Available conditions are +only+ or +except+, both
  1337. * of which accept an arbitrary number of method references. For example:
  1338. *
  1339. * class Journal extends AkActionController
  1340. * {
  1341. * function __construct()
  1342. * { // only require authentication if the current action is edit or delete
  1343. * $this->beforeFilter(array('_authorize'=>array('only'=>array('edit','delete')));
  1344. * }
  1345. *
  1346. * function _authorize(&$controller)
  1347. * {
  1348. * // redirect to login unless authenticated
  1349. * }
  1350. * }
  1351. */
  1352. var $_includedActions = array(), $_beforeFilters = array(), $_afterFilters = array(), $_excludedActions = array();
  1353. /**
  1354. * The passed <tt>filters</tt> will be appended to the array of filters that's run _before_ actions
  1355. * on this controller are performed.
  1356. */
  1357. function appendBeforeFilter()
  1358. {
  1359. $filters = array_reverse(func_get_args());
  1360. foreach (array_keys($filters) as $k){
  1361. $conditions = $this->_extractConditions(&$filters[$k]);
  1362. $this->_addActionConditions($filters[$k], $conditions);
  1363. $this->_appendFilterToChain('before', $filters[$k]);
  1364. }
  1365. }
  1366. /**
  1367. * The passed <tt>filters</tt> will be prepended to the array of filters that's run _before_ actions
  1368. * on this controller are performed.
  1369. */
  1370. function prependBeforeFilter()
  1371. {
  1372. $filters = array_reverse(func_get_args());
  1373. foreach (array_keys($filters) as $k){
  1374. $conditions = $this->_extractConditions(&$filters[$k]);
  1375. $this->_addActionConditions($filters[$k], $conditions);
  1376. $this->_prependFilterToChain('before', $filters[$k]);
  1377. }
  1378. }
  1379. /**
  1380. * Short-hand for appendBeforeFilter since that's the most common of the two.
  1381. */
  1382. function beforeFilter()
  1383. {
  1384. $filters = func_get_args();
  1385. foreach (array_keys($filters) as $k){
  1386. $this->appendBeforeFilter($filters[$k]);
  1387. }
  1388. }
  1389. /**
  1390. * The passed <tt>filters</tt> will be appended to the array of filters that's run _after_ actions
  1391. * on this controller are performed.
  1392. */
  1393. function appendAfterFilter()
  1394. {
  1395. $filters = array_reverse(func_get_args());
  1396. foreach (array_keys($filters) as $k){
  1397. $conditions = $this->_extractConditions(&$filters[$k]);
  1398. $this->_addActionConditions(&$filters[$k], $conditions);
  1399. $this->_appendFilterToChain('after', &$filters[$k]);
  1400. }
  1401. }
  1402. /**
  1403. * The passed <tt>filters</tt> will be prepended to the array of filters that's run _after_ actions
  1404. * on this controller are performed.
  1405. */
  1406. function prependAfterFilter()
  1407. {
  1408. $filters = array_reverse(func_get_args());
  1409. foreach (array_keys($filters) as $k){
  1410. $conditions = $this->_extractConditions(&$filters[$k]);
  1411. $this->_addActionConditions(&$filters[$k], $conditions);
  1412. $this->_prependFilterToChain('after', &$filters[$k]);
  1413. }
  1414. }
  1415. /**
  1416. * Short-hand for appendAfterFilter since that's the most common of the two.
  1417. * */
  1418. function afterFilter()
  1419. {
  1420. $filters = func_get_args();
  1421. foreach (array_keys($filters) as $k){
  1422. $this->appendAfterFilter($filters[$k]);
  1423. }
  1424. }
  1425. /**
  1426. * The passed <tt>filters</tt> will have their +before+ method appended to the array of filters that's run both before actions
  1427. * on this controller are performed and have their +after+ method prepended to the after actions. The filter objects must all
  1428. * respond to both +before+ and +after+. So if you do appendAroundFilter(new A(), new B()), the callstack will look like:
  1429. *
  1430. * B::before()
  1431. * A::before()
  1432. * A::after()
  1433. * B::after()
  1434. */
  1435. function appendAroundFilter()
  1436. {
  1437. $filters = func_get_args();
  1438. foreach (array_keys($filters) as $k){
  1439. $this->_ensureFilterRespondsToBeforeAndAfter(&$filters[$k]);
  1440. $this->appendBeforeFilter(array(&$filters[$k],'before'));
  1441. }
  1442. $filters = array_reverse($filters);
  1443. foreach (array_keys($filters) as $k){
  1444. $this->prependAfterFilter(array(&$filters[$k],'after'));
  1445. }
  1446. }
  1447. /**
  1448. * The passed <tt>filters</tt> will have their +before+ method prepended to the array of filters that's run both before actions
  1449. * on this controller are performed and have their +after+ method appended to the after actions. The filter objects must all
  1450. * respond to both +before+ and +after+. So if you do appendAroundFilter(new A(), new B()), the callstack will look like:
  1451. *
  1452. * A::before()
  1453. * B::before()
  1454. * B::after()
  1455. * A::after()
  1456. */
  1457. function prependAroundFilter()
  1458. {
  1459. $filters = func_get_args();
  1460. foreach (array_keys($filters) as $k){
  1461. $this->_ensureFilterRespondsToBeforeAndAfter(&$filters[$k]);
  1462. $this->prependBeforeFilter(array(&$filters[$k],'before'));
  1463. }
  1464. $filters = array_reverse($filters);
  1465. foreach (array_keys($filters) as $k){
  1466. $this->appendAfterFilter(array(&$filters[$k],'after'));
  1467. }
  1468. }
  1469. /**
  1470. * Short-hand for appendAroundFilter since that's the most common of the two.
  1471. */
  1472. function aroundFilter()
  1473. {
  1474. $filters = func_get_args();
  1475. call_user_func_array(array(&$this,'appendAroundFilter'), $filters);
  1476. }
  1477. /**
  1478. * Removes the specified filters from the +before+ filter chain.
  1479. * This is especially useful for managing the chain in inheritance hierarchies where only one out
  1480. * of many sub-controllers need a different hierarchy.
  1481. */
  1482. function skipBeforeFilter($filters)
  1483. {
  1484. $filters = func_get_args();
  1485. $this->_skipFilter($filters, 'before');
  1486. }
  1487. /**
  1488. * Removes the specified filters from the +after+ filter chain. Note that this only works for skipping method-reference
  1489. * filters, not instances. This is especially useful for managing the chain in inheritance hierarchies where only one out
  1490. * of many sub-controllers need a different hierarchy.
  1491. */
  1492. function skipAfterFilter($filters)
  1493. {
  1494. $filters = func_get_args();
  1495. $this->_skipFilter($filters, 'after');
  1496. }
  1497. function _skipFilter(&$filters, $type)
  1498. {
  1499. $_filters =& $this->{'_'.$type.'Filters'};
  1500. // array_diff doesn't play nice with some PHP5 releases when it comes to
  1501. // Objects as it only diff equal references, not object types
  1502. foreach (array_keys($filters) as $k){
  1503. if(AK_PHP5){
  1504. if(is_object($filters[$k])){
  1505. foreach (array_keys($_filters) as $k2){
  1506. if(is_object($_filters[$k2]) && get_class($_filters[$k2]) == get_class($filters[$k])){
  1507. $pos = $k2;
  1508. break;
  1509. }
  1510. }
  1511. }else{
  1512. $pos = array_search($filters[$k], $_filters);
  1513. }
  1514. array_splice($_filters, $pos, 1, null);
  1515. return ;
  1516. }
  1517. $_filters = array_diff($_filters,array($filters[$k]));
  1518. }
  1519. }
  1520. /**
  1521. * Returns all the before filters for this class.
  1522. */
  1523. function beforeFilters()
  1524. {
  1525. return $this->_beforeFilters;
  1526. }
  1527. /**
  1528. * Returns all the after filters for this class and all its ancestors.
  1529. */
  1530. function afterFilters()
  1531. {
  1532. return $this->_afterFilters;
  1533. }
  1534. /**
  1535. * Returns a mapping between filters and the actions that may run them.
  1536. */
  1537. function includedActions()
  1538. {
  1539. return $this->_includedActions;
  1540. }
  1541. /**
  1542. * Returns a mapping between filters and actions that may not run them.
  1543. */
  1544. function excludedActions()
  1545. {
  1546. return $this->_excludedActions;
  1547. }
  1548. function _appendFilterToChain($condition, $filters)
  1549. {
  1550. $this->{"_{$condition}Filters"}[] =& $filters;
  1551. }
  1552. function _prependFilterToChain($condition, $filters)
  1553. {
  1554. array_unshift($this->{"_{$condition}Filters"}, $filters);
  1555. }
  1556. function _ensureFilterRespondsToBeforeAndAfter(&$filter_object)
  1557. {
  1558. if(!method_exists(&$filter_object,'before') && !method_exists(&$filter_object,'after')){
  1559. trigger_error(Ak::t('Filter object must respond to both before and after'), E_USER_ERROR);
  1560. }
  1561. }
  1562. function _extractConditions(&$filters)
  1563. {
  1564. if(is_array($filters) && !isset($filters[0])){
  1565. $keys = array_keys($filters);
  1566. $conditions = $filters[$keys[0]];
  1567. $filters = $keys[0];
  1568. return $conditions;
  1569. }
  1570. }
  1571. function _addActionConditions($filters, $conditions)
  1572. {
  1573. if(!empty($conditions['only'])){
  1574. $this->_includedActions[$this->_filterId($filters)] = $this->_conditionArray($this->_includedActions, $conditions['only']);
  1575. }
  1576. if(!empty($conditions['except'])){
  1577. $this->_excludedActions[$this->_filterId($filters)] = $this->_conditionArray($this->_excludedActions, $conditions['except']);
  1578. }
  1579. }
  1580. function _conditionArray($actions, $filter_actions)
  1581. {
  1582. $filter_actions = is_array($filter_actions) ? $filter_actions : array($filter_actions);
  1583. $filter_actions = array_map(array(&$this,'_filterId'),$filter_actions);
  1584. return array_unique(array_merge($actions, $filter_actions));
  1585. }
  1586. function _filterId($filters)
  1587. {
  1588. return is_string($filters) ? $filters : md5(serialize($filters));
  1589. }
  1590. function performActionWithoutFilters($action)
  1591. {
  1592. if(method_exists(&$this, $action)){
  1593. call_user_func_array(array(&$this, $action), @(array)$this->passed_args);
  1594. }
  1595. }
  1596. function performActionWithFilters($method = '')
  1597. {
  1598. if ($this->beforeAction($method) !== false || empty($this->_performed)){
  1599. $this->performActionWithoutFilters($method);
  1600. $this->afterAction($method);
  1601. return true;
  1602. }
  1603. return $this->performActionWithoutFilters($method);
  1604. }
  1605. function performAction($method = '')
  1606. {
  1607. $this->performActionWithFilters($method);
  1608. }
  1609. /**
  1610. * Calls all the defined before-filter filters, which are added by using "beforeFilter($method)".
  1611. * If any of the filters return false, no more filters will be executed and the action is aborted.
  1612. */
  1613. function beforeAction($method = '')
  1614. {
  1615. Ak::profile('Running before controller action filters '.__CLASS__.'::'.__FUNCTION__.' '.__LINE__);
  1616. return $this->_callFilters($this->_beforeFilters, $method);
  1617. }
  1618. /**
  1619. * Calls all the defined after-filter filters, which are added by using "afterFilter($method)".
  1620. * If any of the filters return false, no more filters will be executed.
  1621. */
  1622. function afterAction($method = '')
  1623. {
  1624. Ak::profile('Running after controller action filters '.__CLASS__.'::'.__FUNCTION__.' '.__LINE__);
  1625. return $this->_callFilters(&$this->_afterFilters, $method);
  1626. }
  1627. function _callFilters(&$filters, $method = '')
  1628. {
  1629. $filter_result = null;
  1630. foreach (array_keys($filters) as $k){
  1631. $filter =& $filters[$k];
  1632. if(!$this->_actionIsExempted($filter, $method)){
  1633. if(is_array($filter) && is_object($filter[0]) && method_exists($filter[0], $filter[1])){
  1634. $filter_result = $filter[0]->$filter[1]($this);
  1635. }elseif(!is_object($filter) && method_exists($this, $filter)){
  1636. $filter_result = $this->$filter($this);
  1637. }elseif(is_object($filter) && method_exists($filter, 'filter')){
  1638. $filter_result = $filter->filter($this);
  1639. }else{
  1640. trigger_error(Ak::t('Filters need to be a method name, or class implementing a static filter method'), E_USER_WARNING);
  1641. }
  1642. }
  1643. if($filter_result === false){
  1644. !empty($this->_Logger) ? $this->_Logger->info(Ak::t('Filter chain halted as '.$filter.' returned false')) : null;
  1645. return false;
  1646. }
  1647. }
  1648. return $filter_result;
  1649. }
  1650. function _actionIsExempted($filter, $method = '')
  1651. {
  1652. $method_id = is_string($method) ? $method : $this->_filterId($method);
  1653. $filter_id = $this->_filterId($filter);
  1654. if((!empty($this->_includedActions[$filter_id]) && !in_array($method_id, $this->_includedActions[$filter_id])) ||
  1655. (!empty($this->_excludedActions[$filter_id]) && in_array($method_id, $this->_excludedActions[$filter_id]))){
  1656. return true;
  1657. }
  1658. return false;
  1659. }
  1660. /**
  1661. * The flash provides a way to pass temporary objects between actions. Anything you place in the flash will be exposed
  1662. * to the very next action and then cleared out. This is a great way of doing notices and alerts, such as a create action
  1663. * that sets <tt>flash['notice] = 'Successfully created'</tt> before redirecting to a display action that can then expose
  1664. * the flash to its template. Actually, that exposure is automatically done. Example:
  1665. *
  1666. * class WeblogController extends ActionController
  1667. * {
  1668. * function create()
  1669. * {
  1670. * // save post
  1671. * $this->flash['notice] = 'Successfully created post';
  1672. * $this->redirectTo(array('action'=>'display','params' => array('id' =>$Post->id)));
  1673. * }
  1674. *
  1675. * function display()
  1676. * {
  1677. * // doesn't need to assign the flash notice to the template, that's done automatically
  1678. * }
  1679. * }
  1680. *
  1681. * display.tpl
  1682. * <?php if($flash['notice']) : ?><div class='notice'><?php echo $flash['notice'] ?></div><?php endif; ?>
  1683. *
  1684. * This example just places a string in the flash, but you can put any object in there. And of course, you can put as many
  1685. * as you like at a time too. Just remember: They'll be gone by the time the next action has been performed.
  1686. *
  1687. * ==flash_now
  1688. *
  1689. * Sets a flash that will not be available to the next action, only to the current.
  1690. *
  1691. * $this->flash_now['message] = 'Hello current action';
  1692. *
  1693. * This method enables you to use the flash as a central messaging system in your app.
  1694. * When you need to pass an object to the next action, you use the standard flash assign (<tt>[]=</tt>).
  1695. * When you need to pass an object to the current action, you use <tt>now</tt>, and your object will
  1696. * vanish when the current action is done.
  1697. *
  1698. * Entries set via <tt>flash_now</tt> are accessed the same way as standard entries: <tt>flash['my-key']</tt>.
  1699. */
  1700. var $flash = array();
  1701. var $flash_now = array();
  1702. var $flash_options = array();
  1703. var $_flash_handled = false;
  1704. function _handleFlashAttribute()
  1705. {
  1706. $this->_flash_handled = true;
  1707. $next_flash = empty($this->flash) ? false : $this->flash;
  1708. $this->flash = array();
  1709. if(isset($_SESSION['__flash'])){
  1710. $this->flash = $_SESSION['__flash'];
  1711. }
  1712. $_SESSION['__flash'] = $next_flash;
  1713. if(!empty($this->flash_now)){
  1714. $this->flash = array_merge((array)$this->flash,(array)$this->flash_now);
  1715. }
  1716. $this->_handleFlashOptions();
  1717. }
  1718. function _handleFlashOptions()
  1719. {
  1720. $next_flash_options = empty($this->flash_options) ? false : $this->flash_options;
  1721. $this->flash_options = array();
  1722. if(isset($_SESSION['__flash_options'])){
  1723. $this->flash_options = $_SESSION['__flash_options'];
  1724. }
  1725. $_SESSION['__flash_options'] = $next_flash_options;
  1726. if(!empty($this->flash_now_options)){
  1727. $this->flash_options = array_merge((array)$this->flash_options,(array)$this->flash_now_options);
  1728. }
  1729. }
  1730. function _mergeFlashOnFlashNow()
  1731. {
  1732. $this->flash_now = array_merge($this->flash_now,$this->flash);
  1733. }
  1734. /**
  1735. * This methods are used before triggering an Application Controller
  1736. */
  1737. function __connectToDatabase()
  1738. {
  1739. global $dsn;
  1740. if(!empty($dsn)){
  1741. Ak::db($dsn);
  1742. $this->__database_connection_available = AK_DATABASE_CONNECTION_AVAILABLE;
  1743. }
  1744. }
  1745. function __startSession()
  1746. {
  1747. if($this->__session_available === false){
  1748. if($this->__session_handler == 1 && $this->__database_connection_available){
  1749. require_once(AK_LIB_DIR.DS.'AkDbSession.php');
  1750. $AkDbSession = new AkDbSession();
  1751. $AkDbSession->session_life = AK_SESSION_EXPIRE;
  1752. session_set_save_handler (
  1753. array(&$AkDbSession, '_open'),
  1754. array(&$AkDbSession, '_close'),
  1755. array(&$AkDbSession, '_read'),
  1756. array(&$AkDbSession, '_write'),
  1757. array(&$AkDbSession, '_destroy'),
  1758. array(&$AkDbSession, '_gc')
  1759. );
  1760. }
  1761. @session_start();
  1762. }
  1763. $this->__session_available = isset($_SESSION);
  1764. if($this->__session_available){
  1765. $this->session =& $_SESSION;
  1766. }
  1767. }
  1768. function __enableInternationalizationSupport()
  1769. {
  1770. require_once(AK_LIB_DIR.DS.'AkLocaleManager.php');
  1771. $LocaleManager = new AkLocaleManager();
  1772. $LocaleManager->init();
  1773. $LocaleManager->initApplicationInternationalization($this->Request);
  1774. $this->__internationalization_support_enabled = true;
  1775. }
  1776. function __mapRoutes()
  1777. {
  1778. require_once(AK_LIB_DIR.DS.'AkRouter.php');
  1779. if(is_file(AK_ROUTES_MAPPING_FILE)){
  1780. $Map =& AkRouter();
  1781. include(AK_ROUTES_MAPPING_FILE);
  1782. // Set this routes for being used via Ak::toUrl
  1783. Ak::toUrl($Map,true);
  1784. $this->Request->checkForRoutedRequests($Map);
  1785. }
  1786. }
  1787. /**
  1788. * === Pagination for Active Record collections
  1789. *
  1790. * The Pagination module aids in the process of paging large collections of
  1791. * Active Record objects. It offers macro-style automatic fetching of your
  1792. * model for multiple views, or explicit fetching for single actions. And if
  1793. * the magic isn't flexible enough for your needs, you can create your own
  1794. * paginators with a minimal amount of code.
  1795. *
  1796. * The Pagination module can handle as much or as little as you wish. In the
  1797. * controller, have it automatically query your model for pagination; or,
  1798. * if you prefer, create Paginator objects yourself
  1799. *
  1800. * Pagination is included automatically for all controllers.
  1801. *
  1802. * For help rendering pagination links, see
  1803. * Helpers/PaginationHelper.
  1804. *
  1805. * ==== Automatic pagination for every action in a controller
  1806. *
  1807. * class PersonController extends ApplicationController
  1808. * {
  1809. * var $model = 'person';
  1810. * var $paginate = array('people'=>array('order' => 'last_name, first_name',
  1811. * 'per_page' => 20));
  1812. * }
  1813. *
  1814. * Each action in this controller now has access to a <tt>$this->people</tt>
  1815. * instance variable, which is an ordered collection of model objects for the
  1816. * current page (at most 20, sorted by last name and first name), and a
  1817. * <tt>$this->person_pages</tt> Paginator instance. The current page is determined
  1818. * by the <tt>$params['page']</tt> variable.
  1819. *
  1820. * ==== Pagination for a single action
  1821. *
  1822. * function show_all()
  1823. * {
  1824. * list($this->person_pages, $this->people) =
  1825. * $this->paginate('people', array('order' => 'last_name, first_name'));
  1826. * }
  1827. *
  1828. * Like the previous example, but explicitly creates <tt>$this->person_pages</tt>
  1829. * and <tt>$this->people</tt> for a single action, and uses the default of 10 items
  1830. * per page.
  1831. *
  1832. * ==== Custom/"classic" pagination
  1833. *
  1834. * function list()
  1835. * {
  1836. * $this->person_pages = new AkPaginator(&$this, $Person->count(), 10, $params['page']);
  1837. * $this->people = $this->Person->find('all', array(
  1838. * 'order'=> 'last_name, first_name',
  1839. * 'limit' => $this->person_pages->items_per_page,
  1840. * 'offset' => $this->person_pages->getOffset()));
  1841. * }
  1842. *
  1843. * Explicitly creates the paginator from the previous example and uses
  1844. * AkPaginator::toSql to retrieve <tt>$this->people</tt> from the model.
  1845. */
  1846. // An array holding options for controllers using macro-style pagination
  1847. var $_pagination_options = array(
  1848. 'class_name' => null,
  1849. 'singular_name' => null,
  1850. 'per_page' => 10,
  1851. 'conditions' => null,
  1852. 'order_by' => null,
  1853. 'order' => null,
  1854. 'join' => null,
  1855. 'joins' => null,
  1856. 'include' => null,
  1857. 'select' => null,
  1858. 'parameter' => 'page'
  1859. );
  1860. // The default options for pagination
  1861. var $_pagination_default_options = array(
  1862. 'class_name' => null,
  1863. 'singular_name' => null,
  1864. 'per_page' => 10,
  1865. 'conditions' => null,
  1866. 'order_by' => null,
  1867. 'order' => null,
  1868. 'join' => null,
  1869. 'joins' => null,
  1870. 'include' => null,
  1871. 'select' => null,
  1872. 'parameter' => 'page'
  1873. );
  1874. var $_pagination_actions = array();
  1875. function _paginationValidateOptions($collection_id, $options = array(), $in_action)
  1876. {
  1877. $this->_pagination_options = array_merge($this->_pagination_default_options, $this->_pagination_options);
  1878. $valid_options = array_keys($this->_pagination_default_options);
  1879. $valid_options = !in_array($in_action, $valid_options) ? array_merge($valid_options, $this->_pagination_actions) : $valid_options;
  1880. $unknown_option_keys = array_diff(array_keys($this->_pagination_options) , $valid_options);
  1881. if(!empty($unknown_option_keys)){
  1882. trigger_error(Ak::t('Unknown options for pagination: %unknown_option',array('%unknown_option'=>join(', ',$unknown_option_keys))), E_USER_WARNING);
  1883. }
  1884. $this->_pagination_options['singular_name'] = !empty($this->_pagination_options['singular_name']) ? $this->_pagination_options['singular_name'] : AkInflector::singularize($collection_id);
  1885. $this->_pagination_options['class_name'] = !empty($this->_pagination_options['class_name']) ? $this->_pagination_options['class_name'] : AkInflector::camelize($this->_pagination_options['singular_name']);
  1886. }
  1887. /**
  1888. * Returns a paginator and a collection of Active Record model instances
  1889. * for the paginator's current page. This is designed to be used in a
  1890. * single action.
  1891. *
  1892. * +options+ are:
  1893. * <tt>singular_name</tt>:: the singular name to use, if it can't be inferred by
  1894. * singularizing the collection name
  1895. * <tt>class_name</tt>:: the class name to use, if it can't be inferred by
  1896. * camelizing the singular name
  1897. * <tt>per_page</tt>:: the maximum number of items to include in a
  1898. * single page. Defaults to 10
  1899. * <tt>conditions</tt>:: optional conditions passed to Model::find('all', $this->params); and
  1900. * Model::count()
  1901. * <tt>order</tt>:: optional order parameter passed to Model::find('all', $this->params);
  1902. * <tt>order_by</tt>:: (deprecated, used :order) optional order parameter passed to Model::find('all', $this->params)
  1903. * <tt>joins</tt>:: optional joins parameter passed to Model::find('all', $this->params)
  1904. * and Model::count()
  1905. * <tt>join</tt>:: (deprecated, used :joins or :include) optional join parameter passed to Model::find('all', $this->params)
  1906. * and Model::count()
  1907. * <tt>include</tt>:: optional eager loading parameter passed to Model::find('all', $this->params)
  1908. * and Model::count()
  1909. *
  1910. * Creates a +before_filter+ which automatically paginates an Active
  1911. * Record model for all actions in a controller (or certain actions if
  1912. * specified with the <tt>actions</tt> option).
  1913. *
  1914. * +options+ are the same as PaginationHelper::paginate, with the addition
  1915. * of:
  1916. * <tt>actions</tt>:: an array of actions for which the pagination is
  1917. * active. Defaults to +null+ (i.e., every action)
  1918. */
  1919. function paginate($collection_id, $options = array())
  1920. {
  1921. $this->_paginationValidateOptions($collection_id, $options, true);
  1922. $this->_paginationLoadPaginatorAndCollection($collection_id, $this->_pagination_options);
  1923. $this->beforeFilter('_paginationCreateAndRetrieveCollections');
  1924. }
  1925. function _paginationCreateAndRetrieveCollections()
  1926. {
  1927. foreach($this->_pagination_options[$this->class] as $collection_id=>$options){
  1928. if(!empty($options['actions']) && in_array($options['actions'], $action_name)){
  1929. continue;
  1930. }
  1931. list($paginator, $collection) = $this->_paginationLoadPaginatorAndCollection($collection_id, $this->_pagination_options);
  1932. $this->{$options['singular_name'].'_pages'} =& $paginator;
  1933. $this->$collection_name =& $collection;
  1934. }
  1935. }
  1936. /**
  1937. * Returns the total number of items in the collection to be paginated for
  1938. * the +model+ and given +conditions+. Override this method to implement a
  1939. * custom counter.
  1940. */
  1941. function _paginationCountCollection(&$model, $conditions, $joins)
  1942. {
  1943. return $model->count($conditions, $joins);
  1944. }
  1945. /**
  1946. * Returns a collection of items for the given +$model+ and +$options['conditions']+,
  1947. * ordered by +$options['order']+, for the current page in the given +$paginator+.
  1948. * Override this method to implement a custom finder.
  1949. */
  1950. function _paginationFindCollection(&$model, $options, &$paginator)
  1951. {
  1952. return $model->find('all', array(
  1953. 'conditions' => $this->_pagination_options['conditions'],
  1954. 'order' => !empty($options['order_by']) ? $options['order_by'] : $options['order'],
  1955. 'joins' => !empty($options['join']) ? $options['join'] : $options['joins'],
  1956. 'include' => $this->_pagination_options['include'],
  1957. 'select' => $this->_pagination_options['select'],
  1958. 'limit' => $this->_pagination_options['per_page'],
  1959. 'offset' => $paginator->getOffset()));
  1960. }
  1961. /**
  1962. * @todo Fix this function
  1963. */
  1964. function _paginationLoadPaginatorAndCollection($collection_id, $options)
  1965. {
  1966. $page = $this->params[$options['parameter']];
  1967. $count = $this->_paginationCountCollection($klass, $options['conditions'],
  1968. empty($options['join']) ? $options['join'] : $options['joins']);
  1969. require_once(AK_LIB_DIR.DS.'AkActionController'.DS.'AkPaginator.php');
  1970. $paginator =& new AkPaginator($this, $count, $options['per_page'], $page);
  1971. $collection =& $this->_paginationFindCollection($options['class_name'], $options, $paginator);
  1972. return array(&$paginator, &$collection);
  1973. }
  1974. /**
  1975. * Specifies that the named actions requires an SSL connection to be performed (which is enforced by ensure_proper_protocol).
  1976. */
  1977. function setSslRequiredActions($actions)
  1978. {
  1979. $this->_ssl_required_actions = empty($this->_ssl_required_actions) ?
  1980. (is_string($actions) ? Ak::stringToArray($actions) : $actions) :
  1981. array_merge($this->_ssl_required_actions, (is_string($actions) ? Ak::stringToArray($actions) : $actions));
  1982. }
  1983. function setSslAllowedActions($actions)
  1984. {
  1985. $this->_ssl_allowed_actions = empty($this->_ssl_allowed_actions) ?
  1986. (is_string($actions) ? Ak::stringToArray($actions) : $actions) :
  1987. array_merge($this->_ssl_allowed_actions, (is_string($actions) ? Ak::stringToArray($actions) : $actions));
  1988. }
  1989. /**
  1990. * Returns true if the current action is supposed to run as SSL
  1991. */
  1992. function _isSslRequired()
  1993. {
  1994. return !empty($this->_ssl_required_actions) && is_array($this->_ssl_required_actions) && isset($this->_action_name) ?
  1995. in_array($this->_action_name, $this->_ssl_required_actions) : false;
  1996. }
  1997. function _isSslAllowed()
  1998. {
  1999. return !empty($this->_ssl_allowed_actions) && is_array($this->_ssl_allowed_actions) && isset($this->_action_name) ?
  2000. in_array($this->_action_name, $this->_ssl_allowed_actions) : false;
  2001. }
  2002. function _ensureProperProtocol()
  2003. {
  2004. if($this->_isSslAllowed()){
  2005. return true;
  2006. }
  2007. if ($this->_isSslRequired() && !$this->Request->isSsl()){
  2008. $this->redirectTo(substr_replace(AK_CURRENT_URL,'s:',4,1));
  2009. return false;
  2010. }elseif($this->Request->isSsl() && !$this->_isSslRequired()){
  2011. $this->redirectTo(substr_replace(AK_CURRENT_URL,'',4,1));
  2012. return false;
  2013. }
  2014. }
  2015. /**
  2016. * Account Location
  2017. * ================
  2018. *
  2019. * Account location is a set of methods that supports the account-key-as-subdomain
  2020. * way of identifying the current scope. These methods allow you to easily produce URLs that
  2021. * match this style and to get the current account key from the subdomain.
  2022. *
  2023. * The methods are: getAccountUrl, getAccountHost, and getAccountDomain.
  2024. *
  2025. * Example:
  2026. *
  2027. * include_once('AkAccountLocation.php');
  2028. *
  2029. * class ApplicationController extends AkActiveRecord
  2030. * {
  2031. * var $before_filter = '_findAccount';
  2032. *
  2033. * function _findAccount()
  2034. * {
  2035. * $this->account = Account::find(array('conditions'=>array('username = ?', $this->account_domain)));
  2036. * }
  2037. *
  2038. * class AccountController extends ApplicationController
  2039. * {
  2040. * function new_account()
  2041. * {
  2042. * $this->new_account = Account::create($this->params['new_account']);
  2043. * $this->redirectTo(array('host' => $this->accountHost($this->new_account->username), 'controller' => 'weblog'));
  2044. * }
  2045. *
  2046. * function _authenticate()
  2047. * {
  2048. * $this->session[$this->account_domain] = 'authenticated';
  2049. * $this->redirectTo(array('controller => 'weblog'));
  2050. * }
  2051. *
  2052. * function _isAuthenticated()
  2053. * {
  2054. * return !empty($this->session['account_domain']) ? $this->session['account_domain'] == 'authenticated' : false;
  2055. * }
  2056. * }
  2057. *
  2058. * // The view:
  2059. * Your domain: {account_url?}
  2060. *
  2061. * By default, all the methods will query for $this->account->username as the account key, but you can
  2062. * specialize that by overwriting defaultAccountSubdomain. You can of course also pass it in
  2063. * as the first argument to all the methods.
  2064. */
  2065. function defaultAccountSubdomain()
  2066. {
  2067. if(!empty($this->account)){
  2068. return $this->account->respondsTo('username');
  2069. }
  2070. }
  2071. function accountUrl($account_subdomain = null, $use_ssl = null)
  2072. {
  2073. $account_subdomain = empty($account_subdomain) ? 'default_account_subdomain' : $account_subdomain;
  2074. $use_ssl = empty($use_ssl) ? $use_ssl : $this->Request->isSsl();
  2075. return ($use_ssl ? 'https://' : 'http://') . $this->accountHost($account_subdomain);
  2076. }
  2077. function accountHost($account_subdomain = null)
  2078. {
  2079. $account_subdomain = empty($account_subdomain) ? 'default_account_subdomain' : $account_subdomain;
  2080. $account_host = '';
  2081. $account_host .= $account_subdomain . '.';
  2082. $account_host .= $this->accountDomain();
  2083. return $account_host;
  2084. }
  2085. function accountDomain()
  2086. {
  2087. $account_domain = '';
  2088. if(count($this->Request->getSubdomains()) > 1){
  2089. $account_domain .= join('.',$this->Request->getSubdomains()) . '.';
  2090. }
  2091. $account_domain .= $this->Request->getDomain() . $this->Request->getPortString();
  2092. return $account_domain;
  2093. }
  2094. function getAccountSubdomain()
  2095. {
  2096. return array_shift($this->Request->getSubdomains());
  2097. }
  2098. /**
  2099. * Methods for sending files and streams to the browser instead of rendering.
  2100. */
  2101. var $default_send_file_options = array(
  2102. 'type' => 'application/octet-stream',
  2103. 'disposition' => 'attachment',
  2104. 'stream' => true,
  2105. 'buffer_size' => 4096
  2106. );
  2107. /**
  2108. * Sends the file by streaming it 4096 bytes at a time. This way the
  2109. * whole file doesn't need to be read into memory at once. This makes
  2110. * it feasible to send even large files.
  2111. *
  2112. * Be careful to sanitize the path parameter if it coming from a web
  2113. * page. sendFile($params['path']) allows a malicious user to
  2114. * download any file on your server.
  2115. *
  2116. * Options:
  2117. * * <tt>filename</tt> - suggests a filename for the browser to use.
  2118. * Defaults to realpath($path).
  2119. * * <tt>type</tt> - specifies an HTTP content type.
  2120. * Defaults to 'application/octet-stream'.
  2121. * * <tt>disposition</tt> - specifies whether the file will be shown inline or downloaded.
  2122. * Valid values are 'inline' and 'attachment' (default).
  2123. * * <tt>stream</tt> - whether to send the file to the user agent as it is read (true)
  2124. * or to read the entire file before sending (false). Defaults to true.
  2125. * * <tt>buffer_size</tt> - specifies size (in bytes) of the buffer used to stream the file.
  2126. * Defaults to 4096.
  2127. *
  2128. * The default Content-Type and Content-Disposition headers are
  2129. * set to download arbitrary binary files in as many browsers as
  2130. * possible. IE versions 4, 5, 5.5, and 6 are all known to have
  2131. * a variety of quirks (especially when downloading over SSL).
  2132. *
  2133. * Simple download:
  2134. * sendFile('/path/to.zip');
  2135. *
  2136. * Show a JPEG in browser:
  2137. * sendFile('/path/to.jpeg', 'type' => 'image/jpeg', 'disposition' => 'inline');
  2138. *
  2139. * Read about the other Content-* HTTP headers if you'd like to
  2140. * provide the user with more information (such as Content-Description).
  2141. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11
  2142. *
  2143. * Also be aware that the document may be cached by proxies and browsers.
  2144. * The Pragma and Cache-Control headers declare how the file may be cached
  2145. * by intermediaries. They default to require clients to validate with
  2146. * the server before releasing cached responses. See
  2147. * http://www.mnot.net/cache_docs/ for an overview of web caching and
  2148. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9
  2149. * for the Cache-Control header spec.
  2150. */
  2151. function sendFile($path, $options = array())
  2152. {
  2153. $path = realpath($path);
  2154. if(!file_exists($path)){
  2155. trigger_error(Ak::t('Cannot read file %path',array('%path'=>$path)), E_USER_NOTICE);
  2156. return false;
  2157. }
  2158. $options['length'] = empty($options['length']) ? filesize($path) : $options['length'];
  2159. $options['filename'] = empty($options['filename']) ? basename($path) : $options['filename'];
  2160. $options['type'] = empty($options['type']) ? Ak::mime_content_type($path) : $options['type'];
  2161. $this->performed_render = false;
  2162. $this->_sendFileHeaders($options);
  2163. if(!empty($options['stream'])){
  2164. require_once(AK_LIB_DIR.DS.'AkStream.php');
  2165. $this->render(array('text'=> new AkStream($path,$options['buffer_size'])));
  2166. }else{
  2167. $this->render(array('text'=> Ak::file_get_contents($path)));
  2168. }
  2169. }
  2170. /**
  2171. * Send binary data to the user as a file download. May set content type, apparent file name,
  2172. * and specify whether to show data inline or download as an attachment.
  2173. *
  2174. * Options:
  2175. * * <tt>filename</tt> - Suggests a filename for the browser to use.
  2176. * * <tt>type</tt> - specifies an HTTP content type.
  2177. * Defaults to 'application/octet-stream'.
  2178. * * <tt>disposition</tt> - specifies whether the file will be shown inline or downloaded.
  2179. * Valid values are 'inline' and 'attachment' (default).
  2180. *
  2181. * Generic data download:
  2182. * sendData($buffer)
  2183. *
  2184. * Download a dynamically-generated tarball:
  2185. * sendData(Ak::compress('dir','tgz'), array('filename' => 'dir.tgz'));
  2186. *
  2187. * Display an image Active Record in the browser:
  2188. * sendData($image_data, array('type' =>Ak::mime_content_type('image_name.png'), 'disposition' => 'inline'));
  2189. *
  2190. * See +sendFile+ for more information on HTTP Content-* headers and caching.
  2191. */
  2192. function sendData($data, $options = array())
  2193. {
  2194. $options['length'] = empty($options['length']) ? Ak::size($data) : $options['length'];
  2195. $this->_sendFileHeaders($options);
  2196. $this->performed_render = false;
  2197. $this->renderText($data);
  2198. }
  2199. /**
  2200. * Creates a file for streaming from a file.
  2201. * This way you might free memory usage is file is too large
  2202. */
  2203. function sendDataAsStream($data, $options)
  2204. {
  2205. $temp_file_name = tempnam(AK_CACHE_DIR, Ak::randomString());
  2206. $fp = fopen($temp_file_name, 'w');
  2207. fwrite($fp, $data);
  2208. fclose($fp);
  2209. $this->sendFile($temp_file_name, $options);
  2210. }
  2211. function _sendFileHeaders(&$options)
  2212. {
  2213. $options = array_merge($this->default_send_file_options,$options);
  2214. foreach (array('length', 'type', 'disposition') as $arg){
  2215. empty($options[$arg]) ? trigger_error(Ak::t('%arg option required', array('%arg'=>$arg)), E_USER_ERROR) : null;
  2216. }
  2217. $disposition = empty($options['disposition']) ? 'attachment' : $options['disposition'];
  2218. $disposition .= !empty($options['filename']) ? '; filename="'.$options['filename'].'"' : '';
  2219. $this->Response->addHeader(array(
  2220. 'Content-Length' => $options['length'],
  2221. 'Content-Type' => trim($options['type']), // fixes a problem with extra '\r' with some browsers
  2222. 'Content-Disposition' => $disposition,
  2223. 'Content-Transfer-Encoding' => 'binary'
  2224. ));
  2225. }
  2226. function redirectToLocale($locale)
  2227. {
  2228. if($this->__internationalization_support_enabled){
  2229. $lang = isset($this->params['lang']) ? $this->params['lang'] : $locale;
  2230. if($locale != $lang){
  2231. $this->redirectTo(array_merge($this->Request->getParams(),array('lang'=>$locale)));
  2232. return true;
  2233. }
  2234. }
  2235. return false;
  2236. }
  2237. function api($protocol = 'xml_rpc')
  2238. {
  2239. $web_services = array_merge(Ak::toArray($this->web_services), Ak::toArray($this->web_service));
  2240. if(!empty($web_services)){
  2241. $web_services = array_unique($web_services);
  2242. require_once(AK_LIB_DIR.DS.'AkActionWebService.php');
  2243. require_once(AK_LIB_DIR.DS.'AkActionWebService'.DS.'AkActionWebServiceServer.php');
  2244. $Server =& new AkActionWebServiceServer($protocol);
  2245. foreach ($web_services as $web_service){
  2246. $Server->addService($web_service);
  2247. }
  2248. $Server->init();
  2249. $Server->serve();
  2250. exit;
  2251. }else{
  2252. die(Ak::t('There is not any webservice configured at this endpoint'));
  2253. }
  2254. }
  2255. }
  2256. /**
  2257. * Function for getting the singleton controller;
  2258. *
  2259. * @return unknown
  2260. */
  2261. function &AkActionController()
  2262. {
  2263. $params = func_num_args() == 0 ? null : func_get_args();
  2264. $AkActionController =& Ak::singleton('AkActionController', $params);
  2265. return $AkActionController;
  2266. }
  2267. ?>