PageRenderTime 998ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 1ms

/code/ryzom/tools/server/www/webtt/cake/libs/controller/controller.php

https://bitbucket.org/mattraykowski/ryzomcore_demoshard
PHP | 1321 lines | 651 code | 128 blank | 542 comment | 164 complexity | 5607c6305bdce53a827c948ad4c0d140 MD5 | raw file
Possible License(s): AGPL-3.0, GPL-3.0, LGPL-2.1
  1. <?php
  2. /**
  3. * Base controller class.
  4. *
  5. * PHP versions 4 and 5
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
  9. *
  10. * Licensed under The MIT License
  11. * Redistributions of files must retain the above copyright notice.
  12. *
  13. * @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
  14. * @link http://cakephp.org CakePHP(tm) Project
  15. * @package cake
  16. * @subpackage cake.cake.libs.controller
  17. * @since CakePHP(tm) v 0.2.9
  18. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  19. */
  20. /**
  21. * Include files
  22. */
  23. App::import('Controller', 'Component', false);
  24. App::import('View', 'View', false);
  25. /**
  26. * Controller
  27. *
  28. * Application controller class for organization of business logic.
  29. * Provides basic functionality, such as rendering views inside layouts,
  30. * automatic model availability, redirection, callbacks, and more.
  31. *
  32. * @package cake
  33. * @subpackage cake.cake.libs.controller
  34. * @link http://book.cakephp.org/view/956/Introduction
  35. */
  36. class Controller extends Object {
  37. /**
  38. * The name of this controller. Controller names are plural, named after the model they manipulate.
  39. *
  40. * @var string
  41. * @access public
  42. * @link http://book.cakephp.org/view/959/Controller-Attributes
  43. */
  44. var $name = null;
  45. /**
  46. * Stores the current URL, relative to the webroot of the application.
  47. *
  48. * @var string
  49. * @access public
  50. */
  51. var $here = null;
  52. /**
  53. * The webroot of the application.
  54. *
  55. * @var string
  56. * @access public
  57. */
  58. var $webroot = null;
  59. /**
  60. * The name of the currently requested controller action.
  61. *
  62. * @var string
  63. * @access public
  64. */
  65. var $action = null;
  66. /**
  67. * An array containing the class names of models this controller uses.
  68. *
  69. * Example: `var $uses = array('Product', 'Post', 'Comment');`
  70. *
  71. * Can be set to array() to use no models. Can be set to false to
  72. * use no models and prevent the merging of $uses with AppController
  73. *
  74. * @var mixed A single name as a string or a list of names as an array.
  75. * @access protected
  76. * @link http://book.cakephp.org/view/961/components-helpers-and-uses
  77. */
  78. var $uses = false;
  79. /**
  80. * An array containing the names of helpers this controller uses. The array elements should
  81. * not contain the "Helper" part of the classname.
  82. *
  83. * Example: `var $helpers = array('Html', 'Javascript', 'Time', 'Ajax');`
  84. *
  85. * @var mixed A single name as a string or a list of names as an array.
  86. * @access protected
  87. * @link http://book.cakephp.org/view/961/components-helpers-and-uses
  88. */
  89. var $helpers = array('Session', 'Html', 'Form');
  90. /**
  91. * Parameters received in the current request: GET and POST data, information
  92. * about the request, etc.
  93. *
  94. * @var array
  95. * @access public
  96. * @link http://book.cakephp.org/view/963/The-Parameters-Attribute-params
  97. */
  98. var $params = array();
  99. /**
  100. * Data POSTed to the controller using the HtmlHelper. Data here is accessible
  101. * using the `$this->data['ModelName']['fieldName']` pattern.
  102. *
  103. * @var array
  104. * @access public
  105. */
  106. var $data = array();
  107. /**
  108. * Holds pagination defaults for controller actions. The keys that can be included
  109. * in this array are: 'conditions', 'fields', 'order', 'limit', 'page', and 'recursive',
  110. * similar to the keys in the second parameter of Model::find().
  111. *
  112. * Pagination defaults can also be supplied in a model-by-model basis by using
  113. * the name of the model as a key for a pagination array:
  114. *
  115. * {{{
  116. * var $paginate = array(
  117. * 'Post' => array(...),
  118. * 'Comment' => array(...)
  119. * );
  120. * }}}
  121. *
  122. * @var array
  123. * @access public
  124. * @link http://book.cakephp.org/view/1231/Pagination
  125. */
  126. var $paginate = array('limit' => 20, 'page' => 1);
  127. /**
  128. * The name of the views subfolder containing views for this controller.
  129. *
  130. * @var string
  131. * @access public
  132. */
  133. var $viewPath = null;
  134. /**
  135. * The name of the layouts subfolder containing layouts for this controller.
  136. *
  137. * @var string
  138. * @access public
  139. */
  140. var $layoutPath = null;
  141. /**
  142. * Contains variables to be handed to the view.
  143. *
  144. * @var array
  145. * @access public
  146. */
  147. var $viewVars = array();
  148. /**
  149. * An array containing the class names of the models this controller uses.
  150. *
  151. * @var array Array of model objects.
  152. * @access public
  153. */
  154. var $modelNames = array();
  155. /**
  156. * Base URL path.
  157. *
  158. * @var string
  159. * @access public
  160. */
  161. var $base = null;
  162. /**
  163. * The name of the layout file to render the view inside of. The name specified
  164. * is the filename of the layout in /app/views/layouts without the .ctp
  165. * extension.
  166. *
  167. * @var string
  168. * @access public
  169. * @link http://book.cakephp.org/view/962/Page-related-Attributes-layout-and-pageTitle
  170. */
  171. var $layout = 'default';
  172. /**
  173. * Set to true to automatically render the view
  174. * after action logic.
  175. *
  176. * @var boolean
  177. * @access public
  178. */
  179. var $autoRender = true;
  180. /**
  181. * Set to true to automatically render the layout around views.
  182. *
  183. * @var boolean
  184. * @access public
  185. */
  186. var $autoLayout = true;
  187. /**
  188. * Instance of Component used to handle callbacks.
  189. *
  190. * @var string
  191. * @access public
  192. */
  193. var $Component = null;
  194. /**
  195. * Array containing the names of components this controller uses. Component names
  196. * should not contain the "Component" portion of the classname.
  197. *
  198. * Example: `var $components = array('Session', 'RequestHandler', 'Acl');`
  199. *
  200. * @var array
  201. * @access public
  202. * @link http://book.cakephp.org/view/961/components-helpers-and-uses
  203. */
  204. var $components = array('Session');
  205. /**
  206. * The name of the View class this controller sends output to.
  207. *
  208. * @var string
  209. * @access public
  210. */
  211. var $view = 'View';
  212. /**
  213. * File extension for view templates. Defaults to Cake's conventional ".ctp".
  214. *
  215. * @var string
  216. * @access public
  217. */
  218. var $ext = '.ctp';
  219. /**
  220. * The output of the requested action. Contains either a variable
  221. * returned from the action, or the data of the rendered view;
  222. * You can use this var in child controllers' afterFilter() callbacks to alter output.
  223. *
  224. * @var string
  225. * @access public
  226. */
  227. var $output = null;
  228. /**
  229. * Automatically set to the name of a plugin.
  230. *
  231. * @var string
  232. * @access public
  233. */
  234. var $plugin = null;
  235. /**
  236. * Used to define methods a controller that will be cached. To cache a
  237. * single action, the value is set to an array containing keys that match
  238. * action names and values that denote cache expiration times (in seconds).
  239. *
  240. * Example:
  241. *
  242. * {{{
  243. * var $cacheAction = array(
  244. * 'view/23/' => 21600,
  245. * 'recalled/' => 86400
  246. * );
  247. * }}}
  248. *
  249. * $cacheAction can also be set to a strtotime() compatible string. This
  250. * marks all the actions in the controller for view caching.
  251. *
  252. * @var mixed
  253. * @access public
  254. * @link http://book.cakephp.org/view/1380/Caching-in-the-Controller
  255. */
  256. var $cacheAction = false;
  257. /**
  258. * Used to create cached instances of models a controller uses.
  259. * When set to true, all models related to the controller will be cached.
  260. * This can increase performance in many cases.
  261. *
  262. * @var boolean
  263. * @access public
  264. */
  265. var $persistModel = false;
  266. /**
  267. * Holds all params passed and named.
  268. *
  269. * @var mixed
  270. * @access public
  271. */
  272. var $passedArgs = array();
  273. /**
  274. * Triggers Scaffolding
  275. *
  276. * @var mixed
  277. * @access public
  278. * @link http://book.cakephp.org/view/1103/Scaffolding
  279. */
  280. var $scaffold = false;
  281. /**
  282. * Holds current methods of the controller
  283. *
  284. * @var array
  285. * @access public
  286. * @link
  287. */
  288. var $methods = array();
  289. /**
  290. * This controller's primary model class name, the Inflector::classify()'ed version of
  291. * the controller's $name property.
  292. *
  293. * Example: For a controller named 'Comments', the modelClass would be 'Comment'
  294. *
  295. * @var string
  296. * @access public
  297. */
  298. var $modelClass = null;
  299. /**
  300. * This controller's model key name, an underscored version of the controller's $modelClass property.
  301. *
  302. * Example: For a controller named 'ArticleComments', the modelKey would be 'article_comment'
  303. *
  304. * @var string
  305. * @access public
  306. */
  307. var $modelKey = null;
  308. /**
  309. * Holds any validation errors produced by the last call of the validateErrors() method/
  310. *
  311. * @var array Validation errors, or false if none
  312. * @access public
  313. */
  314. var $validationErrors = null;
  315. /**
  316. * Contains a list of the HTTP codes that CakePHP recognizes. These may be
  317. * queried and/or modified through Controller::httpCodes(), which is also
  318. * tasked with their lazy-loading.
  319. *
  320. * @var array Associative array of HTTP codes and their associated messages.
  321. * @access private
  322. */
  323. var $__httpCodes = null;
  324. /**
  325. * Constructor.
  326. *
  327. */
  328. function __construct() {
  329. if ($this->name === null) {
  330. $r = null;
  331. if (!preg_match('/(.*)Controller/i', get_class($this), $r)) {
  332. __("Controller::__construct() : Can not get or parse my own class name, exiting.");
  333. $this->_stop();
  334. }
  335. $this->name = $r[1];
  336. }
  337. if ($this->viewPath == null) {
  338. $this->viewPath = Inflector::underscore($this->name);
  339. }
  340. $this->modelClass = Inflector::classify($this->name);
  341. $this->modelKey = Inflector::underscore($this->modelClass);
  342. $this->Component =& new Component();
  343. $childMethods = get_class_methods($this);
  344. $parentMethods = get_class_methods('Controller');
  345. foreach ($childMethods as $key => $value) {
  346. $childMethods[$key] = strtolower($value);
  347. }
  348. foreach ($parentMethods as $key => $value) {
  349. $parentMethods[$key] = strtolower($value);
  350. }
  351. $this->methods = array_diff($childMethods, $parentMethods);
  352. parent::__construct();
  353. }
  354. /**
  355. * Merge components, helpers, and uses vars from AppController and PluginAppController.
  356. *
  357. * @return void
  358. * @access protected
  359. */
  360. function __mergeVars() {
  361. $pluginName = Inflector::camelize($this->plugin);
  362. $pluginController = $pluginName . 'AppController';
  363. if (is_subclass_of($this, 'AppController') || is_subclass_of($this, $pluginController)) {
  364. $appVars = get_class_vars('AppController');
  365. $uses = $appVars['uses'];
  366. $merge = array('components', 'helpers');
  367. $plugin = null;
  368. if (!empty($this->plugin)) {
  369. $plugin = $pluginName . '.';
  370. if (!is_subclass_of($this, $pluginController)) {
  371. $pluginController = null;
  372. }
  373. } else {
  374. $pluginController = null;
  375. }
  376. if ($uses == $this->uses && !empty($this->uses)) {
  377. if (!in_array($plugin . $this->modelClass, $this->uses)) {
  378. array_unshift($this->uses, $plugin . $this->modelClass);
  379. } elseif ($this->uses[0] !== $plugin . $this->modelClass) {
  380. $this->uses = array_flip($this->uses);
  381. unset($this->uses[$plugin . $this->modelClass]);
  382. $this->uses = array_flip($this->uses);
  383. array_unshift($this->uses, $plugin . $this->modelClass);
  384. }
  385. } elseif ($this->uses !== null || $this->uses !== false) {
  386. $merge[] = 'uses';
  387. }
  388. foreach ($merge as $var) {
  389. if (!empty($appVars[$var]) && is_array($this->{$var})) {
  390. if ($var !== 'uses') {
  391. $normal = Set::normalize($this->{$var});
  392. $app = Set::normalize($appVars[$var]);
  393. if ($app !== $normal) {
  394. $this->{$var} = Set::merge($app, $normal);
  395. }
  396. } else {
  397. $this->{$var} = array_merge($this->{$var}, array_diff($appVars[$var], $this->{$var}));
  398. }
  399. }
  400. }
  401. }
  402. if ($pluginController && $pluginName != null) {
  403. $appVars = get_class_vars($pluginController);
  404. $uses = $appVars['uses'];
  405. $merge = array('components', 'helpers');
  406. if ($this->uses !== null || $this->uses !== false) {
  407. $merge[] = 'uses';
  408. }
  409. foreach ($merge as $var) {
  410. if (isset($appVars[$var]) && !empty($appVars[$var]) && is_array($this->{$var})) {
  411. if ($var !== 'uses') {
  412. $normal = Set::normalize($this->{$var});
  413. $app = Set::normalize($appVars[$var]);
  414. if ($app !== $normal) {
  415. $this->{$var} = Set::merge($app, $normal);
  416. }
  417. } else {
  418. $this->{$var} = array_merge($this->{$var}, array_diff($appVars[$var], $this->{$var}));
  419. }
  420. }
  421. }
  422. }
  423. }
  424. /**
  425. * Loads Model classes based on the uses property
  426. * see Controller::loadModel(); for more info.
  427. * Loads Components and prepares them for initialization.
  428. *
  429. * @return mixed true if models found and instance created, or cakeError if models not found.
  430. * @access public
  431. * @see Controller::loadModel()
  432. * @link http://book.cakephp.org/view/977/Controller-Methods#constructClasses-986
  433. */
  434. function constructClasses() {
  435. $this->__mergeVars();
  436. $this->Component->init($this);
  437. if ($this->uses !== null || ($this->uses !== array())) {
  438. if (empty($this->passedArgs) || !isset($this->passedArgs['0'])) {
  439. $id = false;
  440. } else {
  441. $id = $this->passedArgs['0'];
  442. }
  443. if ($this->uses === false) {
  444. $this->loadModel($this->modelClass, $id);
  445. } elseif ($this->uses) {
  446. $uses = is_array($this->uses) ? $this->uses : array($this->uses);
  447. $modelClassName = $uses[0];
  448. if (strpos($uses[0], '.') !== false) {
  449. list($plugin, $modelClassName) = explode('.', $uses[0]);
  450. }
  451. $this->modelClass = $modelClassName;
  452. foreach ($uses as $modelClass) {
  453. $this->loadModel($modelClass);
  454. }
  455. }
  456. }
  457. return true;
  458. }
  459. /**
  460. * Perform the startup process for this controller.
  461. * Fire the Component and Controller callbacks in the correct order.
  462. *
  463. * - Initializes components, which fires their `initialize` callback
  464. * - Calls the controller `beforeFilter`.
  465. * - triggers Component `startup` methods.
  466. *
  467. * @return void
  468. * @access public
  469. */
  470. function startupProcess() {
  471. $this->Component->initialize($this);
  472. $this->beforeFilter();
  473. $this->Component->triggerCallback('startup', $this);
  474. }
  475. /**
  476. * Perform the various shutdown processes for this controller.
  477. * Fire the Component and Controller callbacks in the correct order.
  478. *
  479. * - triggers the component `shutdown` callback.
  480. * - calls the Controller's `afterFilter` method.
  481. *
  482. * @return void
  483. * @access public
  484. */
  485. function shutdownProcess() {
  486. $this->Component->triggerCallback('shutdown', $this);
  487. $this->afterFilter();
  488. }
  489. /**
  490. * Queries & sets valid HTTP response codes & messages.
  491. *
  492. * @param mixed $code If $code is an integer, then the corresponding code/message is
  493. * returned if it exists, null if it does not exist. If $code is an array,
  494. * then the 'code' and 'message' keys of each nested array are added to the default
  495. * HTTP codes. Example:
  496. *
  497. * httpCodes(404); // returns array(404 => 'Not Found')
  498. *
  499. * httpCodes(array(
  500. * 701 => 'Unicorn Moved',
  501. * 800 => 'Unexpected Minotaur'
  502. * )); // sets these new values, and returns true
  503. *
  504. * @return mixed Associative array of the HTTP codes as keys, and the message
  505. * strings as values, or null of the given $code does not exist.
  506. */
  507. function httpCodes($code = null) {
  508. if (empty($this->__httpCodes)) {
  509. $this->__httpCodes = array(
  510. 100 => 'Continue', 101 => 'Switching Protocols',
  511. 200 => 'OK', 201 => 'Created', 202 => 'Accepted',
  512. 203 => 'Non-Authoritative Information', 204 => 'No Content',
  513. 205 => 'Reset Content', 206 => 'Partial Content',
  514. 300 => 'Multiple Choices', 301 => 'Moved Permanently',
  515. 302 => 'Found', 303 => 'See Other',
  516. 304 => 'Not Modified', 305 => 'Use Proxy', 307 => 'Temporary Redirect',
  517. 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required',
  518. 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed',
  519. 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required',
  520. 408 => 'Request Time-out', 409 => 'Conflict', 410 => 'Gone',
  521. 411 => 'Length Required', 412 => 'Precondition Failed',
  522. 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Large',
  523. 415 => 'Unsupported Media Type', 416 => 'Requested range not satisfiable',
  524. 417 => 'Expectation Failed', 500 => 'Internal Server Error',
  525. 501 => 'Not Implemented', 502 => 'Bad Gateway',
  526. 503 => 'Service Unavailable', 504 => 'Gateway Time-out'
  527. );
  528. }
  529. if (empty($code)) {
  530. return $this->__httpCodes;
  531. }
  532. if (is_array($code)) {
  533. $this->__httpCodes = $code + $this->__httpCodes;
  534. return true;
  535. }
  536. if (!isset($this->__httpCodes[$code])) {
  537. return null;
  538. }
  539. return array($code => $this->__httpCodes[$code]);
  540. }
  541. /**
  542. * Loads and instantiates models required by this controller.
  543. * If Controller::$persistModel; is true, controller will cache model instances on first request,
  544. * additional request will used cached models.
  545. * If the model is non existent, it will throw a missing database table error, as Cake generates
  546. * dynamic models for the time being.
  547. *
  548. * @param string $modelClass Name of model class to load
  549. * @param mixed $id Initial ID the instanced model class should have
  550. * @return mixed true when single model found and instance created, error returned if model not found.
  551. * @access public
  552. */
  553. function loadModel($modelClass = null, $id = null) {
  554. if ($modelClass === null) {
  555. $modelClass = $this->modelClass;
  556. }
  557. $cached = false;
  558. $object = null;
  559. $plugin = null;
  560. if ($this->uses === false) {
  561. if ($this->plugin) {
  562. $plugin = $this->plugin . '.';
  563. }
  564. }
  565. list($plugin, $modelClass) = pluginSplit($modelClass, true, $plugin);
  566. if ($this->persistModel === true) {
  567. $cached = $this->_persist($modelClass, null, $object);
  568. }
  569. if (($cached === false)) {
  570. $this->modelNames[] = $modelClass;
  571. if (!PHP5) {
  572. $this->{$modelClass} =& ClassRegistry::init(array(
  573. 'class' => $plugin . $modelClass, 'alias' => $modelClass, 'id' => $id
  574. ));
  575. } else {
  576. $this->{$modelClass} = ClassRegistry::init(array(
  577. 'class' => $plugin . $modelClass, 'alias' => $modelClass, 'id' => $id
  578. ));
  579. }
  580. if (!$this->{$modelClass}) {
  581. return $this->cakeError('missingModel', array(array(
  582. 'className' => $modelClass, 'webroot' => '', 'base' => $this->base
  583. )));
  584. }
  585. if ($this->persistModel === true) {
  586. $this->_persist($modelClass, true, $this->{$modelClass});
  587. $registry =& ClassRegistry::getInstance();
  588. $this->_persist($modelClass . 'registry', true, $registry->__objects, 'registry');
  589. }
  590. } else {
  591. $this->_persist($modelClass . 'registry', true, $object, 'registry');
  592. $this->_persist($modelClass, true, $object);
  593. $this->modelNames[] = $modelClass;
  594. }
  595. return true;
  596. }
  597. /**
  598. * Redirects to given $url, after turning off $this->autoRender.
  599. * Script execution is halted after the redirect.
  600. *
  601. * @param mixed $url A string or array-based URL pointing to another location within the app,
  602. * or an absolute URL
  603. * @param integer $status Optional HTTP status code (eg: 404)
  604. * @param boolean $exit If true, exit() will be called after the redirect
  605. * @return mixed void if $exit = false. Terminates script if $exit = true
  606. * @access public
  607. * @link http://book.cakephp.org/view/982/redirect
  608. */
  609. function redirect($url, $status = null, $exit = true) {
  610. $this->autoRender = false;
  611. if (is_array($status)) {
  612. extract($status, EXTR_OVERWRITE);
  613. }
  614. $response = $this->Component->beforeRedirect($this, $url, $status, $exit);
  615. if ($response === false) {
  616. return;
  617. }
  618. if (is_array($response)) {
  619. foreach ($response as $resp) {
  620. if (is_array($resp) && isset($resp['url'])) {
  621. extract($resp, EXTR_OVERWRITE);
  622. } elseif ($resp !== null) {
  623. $url = $resp;
  624. }
  625. }
  626. }
  627. if (function_exists('session_write_close')) {
  628. session_write_close();
  629. }
  630. if (!empty($status)) {
  631. $codes = $this->httpCodes();
  632. if (is_string($status)) {
  633. $codes = array_flip($codes);
  634. }
  635. if (isset($codes[$status])) {
  636. $code = $msg = $codes[$status];
  637. if (is_numeric($status)) {
  638. $code = $status;
  639. }
  640. if (is_string($status)) {
  641. $msg = $status;
  642. }
  643. $status = "HTTP/1.1 {$code} {$msg}";
  644. } else {
  645. $status = null;
  646. }
  647. $this->header($status);
  648. }
  649. if ($url !== null) {
  650. $this->header('Location: ' . Router::url($url, true));
  651. }
  652. if (!empty($status) && ($status >= 300 && $status < 400)) {
  653. $this->header($status);
  654. }
  655. if ($exit) {
  656. $this->_stop();
  657. }
  658. }
  659. /**
  660. * Convenience and object wrapper method for header(). Useful when doing tests and
  661. * asserting that particular headers have been set.
  662. *
  663. * @param string $status The header message that is being set.
  664. * @return void
  665. * @access public
  666. */
  667. function header($status) {
  668. header($status);
  669. }
  670. /**
  671. * Saves a variable for use inside a view template.
  672. *
  673. * @param mixed $one A string or an array of data.
  674. * @param mixed $two Value in case $one is a string (which then works as the key).
  675. * Unused if $one is an associative array, otherwise serves as the values to $one's keys.
  676. * @return void
  677. * @access public
  678. * @link http://book.cakephp.org/view/979/set
  679. */
  680. function set($one, $two = null) {
  681. $data = array();
  682. if (is_array($one)) {
  683. if (is_array($two)) {
  684. $data = array_combine($one, $two);
  685. } else {
  686. $data = $one;
  687. }
  688. } else {
  689. $data = array($one => $two);
  690. }
  691. $this->viewVars = $data + $this->viewVars;
  692. }
  693. /**
  694. * Internally redirects one action to another. Does not perform another HTTP request unlike Controller::redirect()
  695. *
  696. * Examples:
  697. *
  698. * {{{
  699. * setAction('another_action');
  700. * setAction('action_with_parameters', $parameter1);
  701. * }}}
  702. *
  703. * @param string $action The new action to be 'redirected' to
  704. * @param mixed Any other parameters passed to this method will be passed as
  705. * parameters to the new action.
  706. * @return mixed Returns the return value of the called action
  707. * @access public
  708. */
  709. function setAction($action) {
  710. $this->action = $action;
  711. $args = func_get_args();
  712. unset($args[0]);
  713. return call_user_func_array(array(&$this, $action), $args);
  714. }
  715. /**
  716. * Controller callback to tie into Auth component.
  717. * Only called when AuthComponent::$authorize is set to 'controller'.
  718. *
  719. * @return bool true if authorized, false otherwise
  720. * @access public
  721. * @link http://book.cakephp.org/view/1275/authorize
  722. */
  723. function isAuthorized() {
  724. trigger_error(sprintf(
  725. __('%sController::isAuthorized() is not defined.', true), $this->name
  726. ), E_USER_WARNING);
  727. return false;
  728. }
  729. /**
  730. * Returns number of errors in a submitted FORM.
  731. *
  732. * @return integer Number of errors
  733. * @access public
  734. */
  735. function validate() {
  736. $args = func_get_args();
  737. $errors = call_user_func_array(array(&$this, 'validateErrors'), $args);
  738. if ($errors === false) {
  739. return 0;
  740. }
  741. return count($errors);
  742. }
  743. /**
  744. * Validates models passed by parameters. Example:
  745. *
  746. * `$errors = $this->validateErrors($this->Article, $this->User);`
  747. *
  748. * @param mixed A list of models as a variable argument
  749. * @return array Validation errors, or false if none
  750. * @access public
  751. */
  752. function validateErrors() {
  753. $objects = func_get_args();
  754. if (empty($objects)) {
  755. return false;
  756. }
  757. $errors = array();
  758. foreach ($objects as $object) {
  759. if (isset($this->{$object->alias})) {
  760. $object =& $this->{$object->alias};
  761. }
  762. $object->set($object->data);
  763. $errors = array_merge($errors, (array)$object->invalidFields());
  764. }
  765. return $this->validationErrors = (!empty($errors) ? $errors : false);
  766. }
  767. /**
  768. * Instantiates the correct view class, hands it its data, and uses it to render the view output.
  769. *
  770. * @param string $action Action name to render
  771. * @param string $layout Layout to use
  772. * @param string $file File to use for rendering
  773. * @return string Full output string of view contents
  774. * @access public
  775. * @link http://book.cakephp.org/view/980/render
  776. */
  777. function render($action = null, $layout = null, $file = null) {
  778. $this->beforeRender();
  779. $this->Component->triggerCallback('beforeRender', $this);
  780. $viewClass = $this->view;
  781. if ($this->view != 'View') {
  782. list($plugin, $viewClass) = pluginSplit($viewClass);
  783. $viewClass = $viewClass . 'View';
  784. App::import('View', $this->view);
  785. }
  786. $this->params['models'] = $this->modelNames;
  787. if (Configure::read() > 2) {
  788. $this->set('cakeDebug', $this);
  789. }
  790. $View =& new $viewClass($this);
  791. if (!empty($this->modelNames)) {
  792. $models = array();
  793. foreach ($this->modelNames as $currentModel) {
  794. if (isset($this->$currentModel) && is_a($this->$currentModel, 'Model')) {
  795. $models[] = Inflector::underscore($currentModel);
  796. }
  797. $isValidModel = (
  798. isset($this->$currentModel) && is_a($this->$currentModel, 'Model') &&
  799. !empty($this->$currentModel->validationErrors)
  800. );
  801. if ($isValidModel) {
  802. $View->validationErrors[Inflector::camelize($currentModel)] =&
  803. $this->$currentModel->validationErrors;
  804. }
  805. }
  806. $models = array_diff(ClassRegistry::keys(), $models);
  807. foreach ($models as $currentModel) {
  808. if (ClassRegistry::isKeySet($currentModel)) {
  809. $currentObject =& ClassRegistry::getObject($currentModel);
  810. if (is_a($currentObject, 'Model') && !empty($currentObject->validationErrors)) {
  811. $View->validationErrors[Inflector::camelize($currentModel)] =&
  812. $currentObject->validationErrors;
  813. }
  814. }
  815. }
  816. }
  817. $this->autoRender = false;
  818. $this->output .= $View->render($action, $layout, $file);
  819. return $this->output;
  820. }
  821. /**
  822. * Returns the referring URL for this request.
  823. *
  824. * @param string $default Default URL to use if HTTP_REFERER cannot be read from headers
  825. * @param boolean $local If true, restrict referring URLs to local server
  826. * @return string Referring URL
  827. * @access public
  828. * @link http://book.cakephp.org/view/987/referer
  829. */
  830. function referer($default = null, $local = false) {
  831. $ref = env('HTTP_REFERER');
  832. if (!empty($ref) && defined('FULL_BASE_URL')) {
  833. $base = FULL_BASE_URL . $this->webroot;
  834. if (strpos($ref, $base) === 0) {
  835. $return = substr($ref, strlen($base));
  836. if ($return[0] != '/') {
  837. $return = '/'.$return;
  838. }
  839. return $return;
  840. } elseif (!$local) {
  841. return $ref;
  842. }
  843. }
  844. if ($default != null) {
  845. $url = Router::url($default, true);
  846. return $url;
  847. }
  848. return '/';
  849. }
  850. /**
  851. * Forces the user's browser not to cache the results of the current request.
  852. *
  853. * @return void
  854. * @access public
  855. * @link http://book.cakephp.org/view/988/disableCache
  856. */
  857. function disableCache() {
  858. header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
  859. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  860. header("Cache-Control: no-store, no-cache, must-revalidate");
  861. header("Cache-Control: post-check=0, pre-check=0", false);
  862. header("Pragma: no-cache");
  863. }
  864. /**
  865. * Shows a message to the user for $pause seconds, then redirects to $url.
  866. * Uses flash.ctp as the default layout for the message.
  867. * Does not work if the current debug level is higher than 0.
  868. *
  869. * @param string $message Message to display to the user
  870. * @param mixed $url Relative string or array-based URL to redirect to after the time expires
  871. * @param integer $pause Time to show the message
  872. * @param string $layout Layout you want to use, defaults to 'flash'
  873. * @return void Renders flash layout
  874. * @access public
  875. * @link http://book.cakephp.org/view/983/flash
  876. */
  877. function flash($message, $url, $pause = 1, $layout = 'flash') {
  878. $this->autoRender = false;
  879. $this->set('url', Router::url($url));
  880. $this->set('message', $message);
  881. $this->set('pause', $pause);
  882. $this->set('page_title', $message);
  883. $this->render(false, $layout);
  884. }
  885. /**
  886. * Converts POST'ed form data to a model conditions array, suitable for use in a Model::find() call.
  887. *
  888. * @param array $data POST'ed data organized by model and field
  889. * @param mixed $op A string containing an SQL comparison operator, or an array matching operators
  890. * to fields
  891. * @param string $bool SQL boolean operator: AND, OR, XOR, etc.
  892. * @param boolean $exclusive If true, and $op is an array, fields not included in $op will not be
  893. * included in the returned conditions
  894. * @return array An array of model conditions
  895. * @access public
  896. * @link http://book.cakephp.org/view/989/postConditions
  897. */
  898. function postConditions($data = array(), $op = null, $bool = 'AND', $exclusive = false) {
  899. if (!is_array($data) || empty($data)) {
  900. if (!empty($this->data)) {
  901. $data = $this->data;
  902. } else {
  903. return null;
  904. }
  905. }
  906. $cond = array();
  907. if ($op === null) {
  908. $op = '';
  909. }
  910. $arrayOp = is_array($op);
  911. foreach ($data as $model => $fields) {
  912. foreach ($fields as $field => $value) {
  913. $key = $model.'.'.$field;
  914. $fieldOp = $op;
  915. if ($arrayOp) {
  916. if (array_key_exists($key, $op)) {
  917. $fieldOp = $op[$key];
  918. } elseif (array_key_exists($field, $op)) {
  919. $fieldOp = $op[$field];
  920. } else {
  921. $fieldOp = false;
  922. }
  923. }
  924. if ($exclusive && $fieldOp === false) {
  925. continue;
  926. }
  927. $fieldOp = strtoupper(trim($fieldOp));
  928. if ($fieldOp === 'LIKE') {
  929. $key = $key.' LIKE';
  930. $value = '%'.$value.'%';
  931. } elseif ($fieldOp && $fieldOp != '=') {
  932. $key = $key.' '.$fieldOp;
  933. }
  934. $cond[$key] = $value;
  935. }
  936. }
  937. if ($bool != null && strtoupper($bool) != 'AND') {
  938. $cond = array($bool => $cond);
  939. }
  940. return $cond;
  941. }
  942. /**
  943. * Handles automatic pagination of model records.
  944. *
  945. * @param mixed $object Model to paginate (e.g: model instance, or 'Model', or 'Model.InnerModel')
  946. * @param mixed $scope Conditions to use while paginating
  947. * @param array $whitelist List of allowed options for paging
  948. * @return array Model query results
  949. * @access public
  950. * @link http://book.cakephp.org/view/1232/Controller-Setup
  951. */
  952. function paginate($object = null, $scope = array(), $whitelist = array()) {
  953. if (is_array($object)) {
  954. $whitelist = $scope;
  955. $scope = $object;
  956. $object = null;
  957. }
  958. $assoc = null;
  959. if (is_string($object)) {
  960. $assoc = null;
  961. if (strpos($object, '.') !== false) {
  962. list($object, $assoc) = pluginSplit($object);
  963. }
  964. if ($assoc && isset($this->{$object}->{$assoc})) {
  965. $object =& $this->{$object}->{$assoc};
  966. } elseif (
  967. $assoc && isset($this->{$this->modelClass}) &&
  968. isset($this->{$this->modelClass}->{$assoc}
  969. )) {
  970. $object =& $this->{$this->modelClass}->{$assoc};
  971. } elseif (isset($this->{$object})) {
  972. $object =& $this->{$object};
  973. } elseif (
  974. isset($this->{$this->modelClass}) && isset($this->{$this->modelClass}->{$object}
  975. )) {
  976. $object =& $this->{$this->modelClass}->{$object};
  977. }
  978. } elseif (empty($object) || $object === null) {
  979. if (isset($this->{$this->modelClass})) {
  980. $object =& $this->{$this->modelClass};
  981. } else {
  982. $className = null;
  983. $name = $this->uses[0];
  984. if (strpos($this->uses[0], '.') !== false) {
  985. list($name, $className) = explode('.', $this->uses[0]);
  986. }
  987. if ($className) {
  988. $object =& $this->{$className};
  989. } else {
  990. $object =& $this->{$name};
  991. }
  992. }
  993. }
  994. if (!is_object($object)) {
  995. trigger_error(sprintf(
  996. __('Controller::paginate() - can\'t find model %1$s in controller %2$sController',
  997. true
  998. ), $object, $this->name
  999. ), E_USER_WARNING);
  1000. return array();
  1001. }
  1002. $options = array_merge($this->params, $this->params['url'], $this->passedArgs);
  1003. if (isset($this->paginate[$object->alias])) {
  1004. $defaults = $this->paginate[$object->alias];
  1005. } else {
  1006. $defaults = $this->paginate;
  1007. }
  1008. if (isset($options['show'])) {
  1009. $options['limit'] = $options['show'];
  1010. }
  1011. if (isset($options['sort'])) {
  1012. $direction = null;
  1013. if (isset($options['direction'])) {
  1014. $direction = strtolower($options['direction']);
  1015. }
  1016. if ($direction != 'asc' && $direction != 'desc') {
  1017. $direction = 'asc';
  1018. }
  1019. $options['order'] = array($options['sort'] => $direction);
  1020. }
  1021. if (!empty($options['order']) && is_array($options['order'])) {
  1022. $alias = $object->alias ;
  1023. $key = $field = key($options['order']);
  1024. if (strpos($key, '.') !== false) {
  1025. list($alias, $field) = explode('.', $key);
  1026. }
  1027. $value = $options['order'][$key];
  1028. unset($options['order'][$key]);
  1029. if ($object->hasField($field)) {
  1030. $options['order'][$alias . '.' . $field] = $value;
  1031. } elseif ($object->hasField($field, true)) {
  1032. $options['order'][$field] = $value;
  1033. } elseif (isset($object->{$alias}) && $object->{$alias}->hasField($field)) {
  1034. $options['order'][$alias . '.' . $field] = $value;
  1035. }
  1036. }
  1037. $vars = array('fields', 'order', 'limit', 'page', 'recursive');
  1038. $keys = array_keys($options);
  1039. $count = count($keys);
  1040. for ($i = 0; $i < $count; $i++) {
  1041. if (!in_array($keys[$i], $vars, true)) {
  1042. unset($options[$keys[$i]]);
  1043. }
  1044. if (empty($whitelist) && ($keys[$i] === 'fields' || $keys[$i] === 'recursive')) {
  1045. unset($options[$keys[$i]]);
  1046. } elseif (!empty($whitelist) && !in_array($keys[$i], $whitelist)) {
  1047. unset($options[$keys[$i]]);
  1048. }
  1049. }
  1050. $conditions = $fields = $order = $limit = $page = $recursive = null;
  1051. if (!isset($defaults['conditions'])) {
  1052. $defaults['conditions'] = array();
  1053. }
  1054. $type = 'all';
  1055. if (isset($defaults[0])) {
  1056. $type = $defaults[0];
  1057. unset($defaults[0]);
  1058. }
  1059. $options = array_merge(array('page' => 1, 'limit' => 20), $defaults, $options);
  1060. $options['limit'] = (int) $options['limit'];
  1061. if (empty($options['limit']) || $options['limit'] < 1) {
  1062. $options['limit'] = 1;
  1063. }
  1064. extract($options);
  1065. if (is_array($scope) && !empty($scope)) {
  1066. $conditions = array_merge($conditions, $scope);
  1067. } elseif (is_string($scope)) {
  1068. $conditions = array($conditions, $scope);
  1069. }
  1070. if ($recursive === null) {
  1071. $recursive = $object->recursive;
  1072. }
  1073. $extra = array_diff_key($defaults, compact(
  1074. 'conditions', 'fields', 'order', 'limit', 'page', 'recursive'
  1075. ));
  1076. if ($type !== 'all') {
  1077. $extra['type'] = $type;
  1078. }
  1079. if (method_exists($object, 'paginateCount')) {
  1080. $count = $object->paginateCount($conditions, $recursive, $extra);
  1081. } else {
  1082. $parameters = compact('conditions');
  1083. if ($recursive != $object->recursive) {
  1084. $parameters['recursive'] = $recursive;
  1085. }
  1086. $count = $object->find('count', array_merge($parameters, $extra));
  1087. // var_dump(array_merge($parameters, $extra));
  1088. }
  1089. $pageCount = intval(ceil($count / $limit));
  1090. if ($page === 'last' || $page >= $pageCount) {
  1091. $options['page'] = $page = $pageCount;
  1092. } elseif (intval($page) < 1) {
  1093. $options['page'] = $page = 1;
  1094. }
  1095. $page = $options['page'] = (integer)$page;
  1096. if (method_exists($object, 'paginate')) {
  1097. $results = $object->paginate(
  1098. $conditions, $fields, $order, $limit, $page, $recursive, $extra
  1099. );
  1100. } else {
  1101. $parameters = compact('conditions', 'fields', 'order', 'limit', 'page');
  1102. if ($recursive != $object->recursive) {
  1103. $parameters['recursive'] = $recursive;
  1104. }
  1105. $results = $object->find($type, array_merge($parameters, $extra));
  1106. }
  1107. $paging = array(
  1108. 'page' => $page,
  1109. 'current' => count($results),
  1110. 'count' => $count,
  1111. 'prevPage' => ($page > 1),
  1112. 'nextPage' => ($count > ($page * $limit)),
  1113. 'pageCount' => $pageCount,
  1114. 'defaults' => array_merge(array('limit' => 20, 'step' => 1), $defaults),
  1115. 'options' => $options
  1116. );
  1117. $this->params['paging'][$object->alias] = $paging;
  1118. if (!in_array('Paginator', $this->helpers) && !array_key_exists('Paginator', $this->helpers)) {
  1119. $this->helpers[] = 'Paginator';
  1120. }
  1121. return $results;
  1122. }
  1123. /**
  1124. * Called before the controller action.
  1125. *
  1126. * @access public
  1127. * @link http://book.cakephp.org/view/984/Callbacks
  1128. */
  1129. function beforeFilter() {
  1130. }
  1131. /**
  1132. * Called after the controller action is run, but before the view is rendered.
  1133. *
  1134. * @access public
  1135. * @link http://book.cakephp.org/view/984/Callbacks
  1136. */
  1137. function beforeRender() {
  1138. }
  1139. /**
  1140. * Called after the controller action is run and rendered.
  1141. *
  1142. * @access public
  1143. * @link http://book.cakephp.org/view/984/Callbacks
  1144. */
  1145. function afterFilter() {
  1146. }
  1147. /**
  1148. * This method should be overridden in child classes.
  1149. *
  1150. * @param string $method name of method called example index, edit, etc.
  1151. * @return boolean Success
  1152. * @access protected
  1153. * @link http://book.cakephp.org/view/984/Callbacks
  1154. */
  1155. function _beforeScaffold($method) {
  1156. return true;
  1157. }
  1158. /**
  1159. * This method should be overridden in child classes.
  1160. *
  1161. * @param string $method name of method called either edit or update.
  1162. * @return boolean Success
  1163. * @access protected
  1164. * @link http://book.cakephp.org/view/984/Callbacks
  1165. */
  1166. function _afterScaffoldSave($method) {
  1167. return true;
  1168. }
  1169. /**
  1170. * This method should be overridden in child classes.
  1171. *
  1172. * @param string $method name of method called either edit or update.
  1173. * @return boolean Success
  1174. * @access protected
  1175. * @link http://book.cakephp.org/view/984/Callbacks
  1176. */
  1177. function _afterScaffoldSaveError($method) {
  1178. return true;
  1179. }
  1180. /**
  1181. * This method should be overridden in child classes.
  1182. * If not it will render a scaffold error.
  1183. * Method MUST return true in child classes
  1184. *
  1185. * @param string $method name of method called example index, edit, etc.
  1186. * @return boolean Success
  1187. * @access protected
  1188. * @link http://book.cakephp.org/view/984/Callbacks
  1189. */
  1190. function _scaffoldError($method) {
  1191. return false;
  1192. }
  1193. }