Controller.php 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111
  1. <?php
  2. /**
  3. * Base controller class.
  4. *
  5. * PHP 5
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright 2005-2011, 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-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  14. * @link http://cakephp.org CakePHP(tm) Project
  15. * @package Cake.Controller
  16. * @since CakePHP(tm) v 0.2.9
  17. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  18. */
  19. /**
  20. * Include files
  21. */
  22. App::uses('CakeResponse', 'Network');
  23. App::uses('ClassRegistry', 'Utility');
  24. App::uses('ComponentCollection', 'Controller');
  25. App::uses('View', 'View');
  26. /**
  27. * Application controller class for organization of business logic.
  28. * Provides basic functionality, such as rendering views inside layouts,
  29. * automatic model availability, redirection, callbacks, and more.
  30. *
  31. * Controllers should provide a number of 'action' methods. These are public methods on the controller
  32. * that are not prefixed with a '_' and not part of Controller. Each action serves as an endpoint for
  33. * performing a specific action on a resource or collection of resources. For example adding or editing a new
  34. * object, or listing a set of objects.
  35. *
  36. * You can access request parameters, using `$this->request`. The request object contains all the POST, GET and FILES
  37. * that were part of the request.
  38. *
  39. * After performing the required actions, controllers are responsible for creating a response. This usually
  40. * takes the form of a generated View, or possibly a redirection to another controller action. In either case
  41. * `$this->response` allows you to manipulate all aspects of the response.
  42. *
  43. * Controllers are created by Dispatcher based on request parameters and routing. By default controllers and actions
  44. * use conventional names. For example `/posts/index` maps to `PostsController::index()`. You can re-map urls
  45. * using Router::connect().
  46. *
  47. * @package Cake.Controller
  48. * @link http://book.cakephp.org/view/956/Introduction
  49. */
  50. class Controller extends Object {
  51. /**
  52. * The name of this controller. Controller names are plural, named after the model they manipulate.
  53. *
  54. * @var string
  55. * @link http://book.cakephp.org/view/959/Controller-Attributes
  56. */
  57. public $name = null;
  58. /**
  59. * An array containing the class names of models this controller uses.
  60. *
  61. * Example: `public $uses = array('Product', 'Post', 'Comment');`
  62. *
  63. * Can be set to array() to use no models. Can be set to false to
  64. * use no models and prevent the merging of $uses with AppController
  65. *
  66. * @var mixed A single name as a string or a list of names as an array.
  67. * @link http://book.cakephp.org/view/961/components-helpers-and-uses
  68. */
  69. public $uses = false;
  70. /**
  71. * An array containing the names of helpers this controller uses. The array elements should
  72. * not contain the "Helper" part of the classname.
  73. *
  74. * Example: `public $helpers = array('Html', 'Javascript', 'Time', 'Ajax');`
  75. *
  76. * @var mixed A single name as a string or a list of names as an array.
  77. * @link http://book.cakephp.org/view/961/components-helpers-and-uses
  78. */
  79. public $helpers = array('Session', 'Html', 'Form');
  80. /**
  81. * An instance of a CakeRequest object that contains information about the current request.
  82. * This object contains all the information about a request and several methods for reading
  83. * additional information about the request.
  84. *
  85. * @var CakeRequest
  86. */
  87. public $request;
  88. /**
  89. * An instance of a CakeResponse object that contains information about the impending response
  90. *
  91. * @var CakeResponse
  92. */
  93. public $response;
  94. /**
  95. * The classname to use for creating the response object.
  96. *
  97. * @var string
  98. */
  99. protected $_responseClass = 'CakeResponse';
  100. /**
  101. * The name of the views subfolder containing views for this controller.
  102. *
  103. * @var string
  104. */
  105. public $viewPath = null;
  106. /**
  107. * The name of the layouts subfolder containing layouts for this controller.
  108. *
  109. * @var string
  110. */
  111. public $layoutPath = null;
  112. /**
  113. * Contains variables to be handed to the view.
  114. *
  115. * @var array
  116. */
  117. public $viewVars = array();
  118. /**
  119. * The name of the view file to render. The name specified
  120. * is the filename in /app/View/<SubFolder> without the .ctp extension.
  121. *
  122. * @var string
  123. * @link http://book.cakephp.org/view/962/Page-related-Attributes-layout-and-pageTitle
  124. */
  125. public $view = null;
  126. /**
  127. * The name of the layout file to render the view inside of. The name specified
  128. * is the filename of the layout in /app/View/Layouts without the .ctp
  129. * extension.
  130. *
  131. * @var string
  132. * @link http://book.cakephp.org/view/962/Page-related-Attributes-layout-and-pageTitle
  133. */
  134. public $layout = 'default';
  135. /**
  136. * Set to true to automatically render the view
  137. * after action logic.
  138. *
  139. * @var boolean
  140. */
  141. public $autoRender = true;
  142. /**
  143. * Set to true to automatically render the layout around views.
  144. *
  145. * @var boolean
  146. */
  147. public $autoLayout = true;
  148. /**
  149. * Instance of ComponentCollection used to handle callbacks.
  150. *
  151. * @var string
  152. */
  153. public $Components = null;
  154. /**
  155. * Array containing the names of components this controller uses. Component names
  156. * should not contain the "Component" portion of the classname.
  157. *
  158. * Example: `public $components = array('Session', 'RequestHandler', 'Acl');`
  159. *
  160. * @var array
  161. * @link http://book.cakephp.org/view/961/components-helpers-and-uses
  162. */
  163. public $components = array('Session');
  164. /**
  165. * The name of the View class this controller sends output to.
  166. *
  167. * @var string
  168. */
  169. public $viewClass = 'View';
  170. /**
  171. * Instance of the View created during rendering. Won't be set until after Controller::render() is called.
  172. *
  173. * @var View
  174. */
  175. public $View;
  176. /**
  177. * File extension for view templates. Defaults to Cake's conventional ".ctp".
  178. *
  179. * @var string
  180. */
  181. public $ext = '.ctp';
  182. /**
  183. * Automatically set to the name of a plugin.
  184. *
  185. * @var string
  186. */
  187. public $plugin = null;
  188. /**
  189. * Used to define methods a controller that will be cached. To cache a
  190. * single action, the value is set to an array containing keys that match
  191. * action names and values that denote cache expiration times (in seconds).
  192. *
  193. * Example:
  194. *
  195. * {{{
  196. * public $cacheAction = array(
  197. * 'view/23/' => 21600,
  198. * 'recalled/' => 86400
  199. * );
  200. * }}}
  201. *
  202. * $cacheAction can also be set to a strtotime() compatible string. This
  203. * marks all the actions in the controller for view caching.
  204. *
  205. * @var mixed
  206. * @link http://book.cakephp.org/view/1380/Caching-in-the-Controller
  207. */
  208. public $cacheAction = false;
  209. /**
  210. * Holds all params passed and named.
  211. *
  212. * @var mixed
  213. */
  214. public $passedArgs = array();
  215. /**
  216. * Triggers Scaffolding
  217. *
  218. * @var mixed
  219. * @link http://book.cakephp.org/view/1103/Scaffolding
  220. */
  221. public $scaffold = false;
  222. /**
  223. * Holds current methods of the controller. This is a list of all the methods reachable
  224. * via url. Modifying this array, will allow you to change which methods can be reached.
  225. *
  226. * @var array
  227. */
  228. public $methods = array();
  229. /**
  230. * This controller's primary model class name, the Inflector::classify()'ed version of
  231. * the controller's $name property.
  232. *
  233. * Example: For a controller named 'Comments', the modelClass would be 'Comment'
  234. *
  235. * @var string
  236. */
  237. public $modelClass = null;
  238. /**
  239. * This controller's model key name, an underscored version of the controller's $modelClass property.
  240. *
  241. * Example: For a controller named 'ArticleComments', the modelKey would be 'article_comment'
  242. *
  243. * @var string
  244. */
  245. public $modelKey = null;
  246. /**
  247. * Holds any validation errors produced by the last call of the validateErrors() method/
  248. *
  249. * @var array Validation errors, or false if none
  250. */
  251. public $validationErrors = null;
  252. /**
  253. * The class name of the parent class you wish to merge with.
  254. * Typically this is AppController, but you may wish to merge vars with a different
  255. * parent class.
  256. *
  257. * @var string
  258. */
  259. protected $_mergeParent = 'AppController';
  260. /**
  261. * Constructor.
  262. *
  263. * @param CakeRequest $request Request object for this controller. Can be null for testing,
  264. * but expect that features that use the request parameters will not work.
  265. * @param CakeResponse $response Response object for this controller.
  266. */
  267. public function __construct($request = null, $response = null) {
  268. if ($this->name === null) {
  269. $this->name = substr(get_class($this), 0, strlen(get_class($this)) -10);
  270. }
  271. if ($this->viewPath == null) {
  272. $this->viewPath = $this->name;
  273. }
  274. $this->modelClass = Inflector::singularize($this->name);
  275. $this->modelKey = Inflector::underscore($this->modelClass);
  276. $this->Components = new ComponentCollection();
  277. $childMethods = get_class_methods($this);
  278. $parentMethods = get_class_methods('Controller');
  279. $this->methods = array_diff($childMethods, $parentMethods);
  280. if ($request instanceof CakeRequest) {
  281. $this->setRequest($request);
  282. }
  283. if ($response instanceof CakeResponse) {
  284. $this->response = $response;
  285. }
  286. parent::__construct();
  287. }
  288. /**
  289. * Provides backwards compatibility to avoid problems with empty and isset to alias properties.
  290. * Lazy loads models using the loadModel() method if declared in $uses
  291. *
  292. * @param string $name
  293. * @return void
  294. */
  295. public function __isset($name) {
  296. switch ($name) {
  297. case 'base':
  298. case 'here':
  299. case 'webroot':
  300. case 'data':
  301. case 'action':
  302. case 'params':
  303. return true;
  304. }
  305. if (is_array($this->uses)) {
  306. foreach ($this->uses as $modelClass) {
  307. list($plugin, $class) = pluginSplit($modelClass, true);
  308. if ($name === $class) {
  309. if (!$plugin) {
  310. $plugin = $this->plugin ? $this->plugin . '.' : null;
  311. }
  312. return $this->loadModel($modelClass);
  313. }
  314. }
  315. }
  316. if ($name === $this->modelClass) {
  317. list($plugin, $class) = pluginSplit($name, true);
  318. if (!$plugin) {
  319. $plugin = $this->plugin ? $this->plugin . '.' : null;
  320. }
  321. return $this->loadModel($plugin . $this->modelClass);
  322. }
  323. return false;
  324. }
  325. /**
  326. * Provides backwards compatibility access to the request object properties.
  327. * Also provides the params alias.
  328. *
  329. * @param string $name
  330. * @return void
  331. */
  332. public function __get($name) {
  333. switch ($name) {
  334. case 'base':
  335. case 'here':
  336. case 'webroot':
  337. case 'data':
  338. return $this->request->{$name};
  339. case 'action':
  340. return isset($this->request->params['action']) ? $this->request->params['action'] : '';
  341. case 'params':
  342. return $this->request;
  343. case 'paginate':
  344. return $this->Components->load('Paginator')->settings;
  345. }
  346. if (isset($this->{$name})) {
  347. return $this->{$name};
  348. }
  349. return null;
  350. }
  351. /**
  352. * Provides backwards compatibility access for setting values to the request object.
  353. *
  354. * @param string $name
  355. * @param mixed $value
  356. * @return void
  357. */
  358. public function __set($name, $value) {
  359. switch ($name) {
  360. case 'base':
  361. case 'here':
  362. case 'webroot':
  363. case 'data':
  364. return $this->request->{$name} = $value;
  365. case 'action':
  366. return $this->request->params['action'] = $value;
  367. case 'params':
  368. return $this->request->params = $value;
  369. case 'paginate':
  370. return $this->Components->load('Paginator')->settings = $value;
  371. }
  372. return $this->{$name} = $value;
  373. }
  374. /**
  375. * Sets the request objects and configures a number of controller properties
  376. * based on the contents of the request. The properties that get set are
  377. *
  378. * - $this->request - To the $request parameter
  379. * - $this->plugin - To the $request->params['plugin']
  380. * - $this->view - To the $request->params['action']
  381. * - $this->autoLayout - To the false if $request->params['bare']; is set.
  382. * - $this->autoRender - To false if $request->params['return'] == 1
  383. * - $this->passedArgs - The the combined results of params['named'] and params['pass]
  384. *
  385. * @param CakeRequest $request
  386. * @return void
  387. */
  388. public function setRequest(CakeRequest $request) {
  389. $this->request = $request;
  390. $this->plugin = isset($request->params['plugin']) ? Inflector::camelize($request->params['plugin']) : null;
  391. $this->view = isset($request->params['action']) ? $request->params['action'] : null;
  392. if (isset($request->params['pass']) && isset($request->params['named'])) {
  393. $this->passedArgs = array_merge($request->params['pass'], $request->params['named']);
  394. }
  395. if (array_key_exists('return', $request->params) && $request->params['return'] == 1) {
  396. $this->autoRender = false;
  397. }
  398. if (!empty($request->params['bare'])) {
  399. $this->autoLayout = false;
  400. }
  401. }
  402. /**
  403. * Dispatches the controller action. Checks that the action
  404. * exists and isn't private.
  405. *
  406. * @param CakeRequest $request
  407. * @return The resulting response.
  408. */
  409. public function invokeAction(CakeRequest $request) {
  410. $reflection = new ReflectionClass($this);
  411. try {
  412. $method = $reflection->getMethod($request->params['action']);
  413. if ($this->_isPrivateAction($method, $request)) {
  414. throw new PrivateActionException(array(
  415. 'controller' => $this->name . "Controller",
  416. 'action' => $request->params['action']
  417. ));
  418. }
  419. return $method->invokeArgs($this, $request->params['pass']);
  420. } catch (ReflectionException $e) {
  421. if ($this->scaffold !== false) {
  422. return $this->_getScaffold($request);
  423. }
  424. throw new MissingActionException(array(
  425. 'controller' => $this->name . "Controller",
  426. 'action' => $request->params['action']
  427. ));
  428. }
  429. }
  430. /**
  431. * Check if the request's action is marked as private, with an underscore,
  432. * or if the request is attempting to directly accessing a prefixed action.
  433. *
  434. * @param ReflectionMethod $method The method to be invoked.
  435. * @param CakeRequest $request The request to check.
  436. * @return boolean
  437. */
  438. protected function _isPrivateAction(ReflectionMethod $method, CakeRequest $request) {
  439. $privateAction = (
  440. $method->name[0] === '_' ||
  441. !$method->isPublic() ||
  442. !in_array($method->name, $this->methods)
  443. );
  444. $prefixes = Router::prefixes();
  445. if (!$privateAction && !empty($prefixes)) {
  446. if (empty($request->params['prefix']) && strpos($request->params['action'], '_') > 0) {
  447. list($prefix, $action) = explode('_', $request->params['action']);
  448. $privateAction = in_array($prefix, $prefixes);
  449. }
  450. }
  451. return $privateAction;
  452. }
  453. /**
  454. * Returns a scaffold object to use for dynamically scaffolded controllers.
  455. *
  456. * @param CakeRequest $request
  457. * @return Scaffold
  458. */
  459. protected function _getScaffold(CakeRequest $request) {
  460. return new Scaffold($this, $request);
  461. }
  462. /**
  463. * Merge components, helpers, and uses vars from Controller::$_mergeParent and PluginAppController.
  464. *
  465. * @return void
  466. */
  467. protected function __mergeVars() {
  468. $pluginController = $pluginDot = null;
  469. if (!empty($this->plugin)) {
  470. $pluginController = $this->plugin . 'AppController';
  471. if (!is_subclass_of($this, $pluginController)) {
  472. $pluginController = null;
  473. }
  474. $pluginDot = $this->plugin . '.';
  475. }
  476. if (is_subclass_of($this, $this->_mergeParent) || !empty($pluginController)) {
  477. $appVars = get_class_vars($this->_mergeParent);
  478. $uses = $appVars['uses'];
  479. $merge = array('components', 'helpers');
  480. if ($uses == $this->uses && !empty($this->uses)) {
  481. if (!in_array($pluginDot . $this->modelClass, $this->uses)) {
  482. array_unshift($this->uses, $pluginDot . $this->modelClass);
  483. } elseif ($this->uses[0] !== $pluginDot . $this->modelClass) {
  484. $this->uses = array_flip($this->uses);
  485. unset($this->uses[$pluginDot . $this->modelClass]);
  486. $this->uses = array_flip($this->uses);
  487. array_unshift($this->uses, $pluginDot . $this->modelClass);
  488. }
  489. } elseif (
  490. ($this->uses !== null || $this->uses !== false) &&
  491. is_array($this->uses) && !empty($appVars['uses'])
  492. ) {
  493. $this->uses = array_merge($this->uses, array_diff($appVars['uses'], $this->uses));
  494. }
  495. $this->_mergeVars($merge, $this->_mergeParent, true);
  496. }
  497. if ($pluginController && $this->plugin != null) {
  498. $merge = array('components', 'helpers');
  499. $appVars = get_class_vars($pluginController);
  500. if (
  501. ($this->uses !== null || $this->uses !== false) &&
  502. is_array($this->uses) && !empty($appVars['uses'])
  503. ) {
  504. $this->uses = array_merge($this->uses, array_diff($appVars['uses'], $this->uses));
  505. }
  506. $this->_mergeVars($merge, $pluginController);
  507. }
  508. }
  509. /**
  510. * Loads Model classes based on the uses property
  511. * see Controller::loadModel(); for more info.
  512. * Loads Components and prepares them for initialization.
  513. *
  514. * @return mixed true if models found and instance created.
  515. * @see Controller::loadModel()
  516. * @link http://book.cakephp.org/view/977/Controller-Methods#constructClasses-986
  517. * @throws MissingModelException
  518. */
  519. public function constructClasses() {
  520. $this->__mergeVars();
  521. $this->Components->init($this);
  522. if ($this->uses) {
  523. $this->uses = (array) $this->uses;
  524. list(, $this->modelClass) = pluginSplit(current($this->uses));
  525. }
  526. return true;
  527. }
  528. /**
  529. * Perform the startup process for this controller.
  530. * Fire the Components and Controller callbacks in the correct order.
  531. *
  532. * - Initializes components, which fires their `initialize` callback
  533. * - Calls the controller `beforeFilter`.
  534. * - triggers Component `startup` methods.
  535. *
  536. * @return void
  537. */
  538. public function startupProcess() {
  539. $this->Components->trigger('initialize', array(&$this));
  540. $this->beforeFilter();
  541. $this->Components->trigger('startup', array(&$this));
  542. }
  543. /**
  544. * Perform the various shutdown processes for this controller.
  545. * Fire the Components and Controller callbacks in the correct order.
  546. *
  547. * - triggers the component `shutdown` callback.
  548. * - calls the Controller's `afterFilter` method.
  549. *
  550. * @return void
  551. */
  552. public function shutdownProcess() {
  553. $this->Components->trigger('shutdown', array(&$this));
  554. $this->afterFilter();
  555. }
  556. /**
  557. * Queries & sets valid HTTP response codes & messages.
  558. *
  559. * @param mixed $code If $code is an integer, then the corresponding code/message is
  560. * returned if it exists, null if it does not exist. If $code is an array,
  561. * then the 'code' and 'message' keys of each nested array are added to the default
  562. * HTTP codes. Example:
  563. *
  564. * httpCodes(404); // returns array(404 => 'Not Found')
  565. *
  566. * httpCodes(array(
  567. * 701 => 'Unicorn Moved',
  568. * 800 => 'Unexpected Minotaur'
  569. * )); // sets these new values, and returns true
  570. *
  571. * @return mixed Associative array of the HTTP codes as keys, and the message
  572. * strings as values, or null of the given $code does not exist.
  573. * @deprecated Use CakeResponse::httpCodes();
  574. */
  575. public function httpCodes($code = null) {
  576. return $this->response->httpCodes($code);
  577. }
  578. /**
  579. * Loads and instantiates models required by this controller.
  580. * If the model is non existent, it will throw a missing database table error, as Cake generates
  581. * dynamic models for the time being.
  582. *
  583. * @param string $modelClass Name of model class to load
  584. * @param mixed $id Initial ID the instanced model class should have
  585. * @return mixed true when single model found and instance created, error returned if model not found.
  586. * @throws MissingModelException if the model class cannot be found.
  587. */
  588. public function loadModel($modelClass = null, $id = null) {
  589. if ($modelClass === null) {
  590. $modelClass = $this->modelClass;
  591. }
  592. $this->uses = ($this->uses) ? $this->uses : array();
  593. if (!in_array($modelClass, $this->uses)) {
  594. $this->uses[] = $modelClass;
  595. }
  596. list($plugin, $modelClass) = pluginSplit($modelClass, true);
  597. $this->{$modelClass} = ClassRegistry::init(array(
  598. 'class' => $plugin . $modelClass, 'alias' => $modelClass, 'id' => $id
  599. ));
  600. if (!$this->{$modelClass}) {
  601. throw new MissingModelException($modelClass);
  602. }
  603. return true;
  604. }
  605. /**
  606. * Redirects to given $url, after turning off $this->autoRender.
  607. * Script execution is halted after the redirect.
  608. *
  609. * @param mixed $url A string or array-based URL pointing to another location within the app,
  610. * or an absolute URL
  611. * @param integer $status Optional HTTP status code (eg: 404)
  612. * @param boolean $exit If true, exit() will be called after the redirect
  613. * @return mixed void if $exit = false. Terminates script if $exit = true
  614. * @link http://book.cakephp.org/view/982/redirect
  615. */
  616. public function redirect($url, $status = null, $exit = true) {
  617. $this->autoRender = false;
  618. if (is_array($status)) {
  619. extract($status, EXTR_OVERWRITE);
  620. }
  621. $response = $this->Components->trigger(
  622. 'beforeRedirect',
  623. array(&$this, $url, $status, $exit),
  624. array('break' => true, 'breakOn' => false, 'collectReturn' => true)
  625. );
  626. if ($response === false) {
  627. return;
  628. }
  629. extract($this->_parseBeforeRedirect($response, $url, $status, $exit), EXTR_OVERWRITE);
  630. $response = $this->beforeRedirect($url, $status, $exit);
  631. if ($response === false) {
  632. return;
  633. }
  634. extract($this->_parseBeforeRedirect($response, $url, $status, $exit), EXTR_OVERWRITE);
  635. if (function_exists('session_write_close')) {
  636. session_write_close();
  637. }
  638. if (!empty($status) && is_string($status)) {
  639. $codes = array_flip($this->response->httpCodes());
  640. if (isset($codes[$status])) {
  641. $status = $codes[$status];
  642. }
  643. }
  644. if ($url !== null) {
  645. $this->response->header('Location', Router::url($url, true));
  646. }
  647. if (!empty($status) && ($status >= 300 && $status < 400)) {
  648. $this->response->statusCode($status);
  649. }
  650. if ($exit) {
  651. $this->response->send();
  652. $this->_stop();
  653. }
  654. }
  655. /**
  656. * Parse beforeRedirect Response
  657. *
  658. * @param mixed $response Response from beforeRedirect callback
  659. * @param mixed $url The same value of beforeRedirect
  660. * @param integer $status The same value of beforeRedirect
  661. * @param boolean $exit The same value of beforeRedirect
  662. * @return array Array with keys url, status and exit
  663. */
  664. protected function _parseBeforeRedirect($response, $url, $status, $exit) {
  665. if (is_array($response)) {
  666. foreach ($response as $resp) {
  667. if (is_array($resp) && isset($resp['url'])) {
  668. extract($resp, EXTR_OVERWRITE);
  669. } elseif ($resp !== null) {
  670. $url = $resp;
  671. }
  672. }
  673. }
  674. return compact('url', 'status', 'exit');
  675. }
  676. /**
  677. * Convenience and object wrapper method for CakeResponse::header().
  678. *
  679. * @param string $status The header message that is being set.
  680. * @return void
  681. * @deprecated Use CakeResponse::header()
  682. */
  683. public function header($status) {
  684. $this->response->header($status);
  685. }
  686. /**
  687. * Saves a variable for use inside a view template.
  688. *
  689. * @param mixed $one A string or an array of data.
  690. * @param mixed $two Value in case $one is a string (which then works as the key).
  691. * Unused if $one is an associative array, otherwise serves as the values to $one's keys.
  692. * @return void
  693. * @link http://book.cakephp.org/view/979/set
  694. */
  695. public function set($one, $two = null) {
  696. if (is_array($one)) {
  697. if (is_array($two)) {
  698. $data = array_combine($one, $two);
  699. } else {
  700. $data = $one;
  701. }
  702. } else {
  703. $data = array($one => $two);
  704. }
  705. $this->viewVars = $data + $this->viewVars;
  706. }
  707. /**
  708. * Internally redirects one action to another. Does not perform another HTTP request unlike Controller::redirect()
  709. *
  710. * Examples:
  711. *
  712. * {{{
  713. * setAction('another_action');
  714. * setAction('action_with_parameters', $parameter1);
  715. * }}}
  716. *
  717. * @param string $action The new action to be 'redirected' to
  718. * @param mixed Any other parameters passed to this method will be passed as
  719. * parameters to the new action.
  720. * @return mixed Returns the return value of the called action
  721. */
  722. public function setAction($action) {
  723. $this->request->action = $action;
  724. $args = func_get_args();
  725. unset($args[0]);
  726. return call_user_func_array(array(&$this, $action), $args);
  727. }
  728. /**
  729. * Returns number of errors in a submitted FORM.
  730. *
  731. * @return integer Number of errors
  732. */
  733. public function validate() {
  734. $args = func_get_args();
  735. $errors = call_user_func_array(array(&$this, 'validateErrors'), $args);
  736. if ($errors === false) {
  737. return 0;
  738. }
  739. return count($errors);
  740. }
  741. /**
  742. * Validates models passed by parameters. Example:
  743. *
  744. * `$errors = $this->validateErrors($this->Article, $this->User);`
  745. *
  746. * @param mixed A list of models as a variable argument
  747. * @return array Validation errors, or false if none
  748. */
  749. public function validateErrors() {
  750. $objects = func_get_args();
  751. if (empty($objects)) {
  752. return false;
  753. }
  754. $errors = array();
  755. foreach ($objects as $object) {
  756. if (isset($this->{$object->alias})) {
  757. $object = $this->{$object->alias};
  758. }
  759. $object->set($object->data);
  760. $errors = array_merge($errors, $object->invalidFields());
  761. }
  762. return $this->validationErrors = (!empty($errors) ? $errors : false);
  763. }
  764. /**
  765. * Instantiates the correct view class, hands it its data, and uses it to render the view output.
  766. *
  767. * @param string $view View to use for rendering
  768. * @param string $layout Layout to use
  769. * @return CakeResponse A response object containing the rendered view.
  770. * @link http://book.cakephp.org/view/980/render
  771. */
  772. public function render($view = null, $layout = null) {
  773. $this->beforeRender();
  774. $this->Components->trigger('beforeRender', array(&$this));
  775. $viewClass = $this->viewClass;
  776. if ($this->viewClass != 'View') {
  777. list($plugin, $viewClass) = pluginSplit($viewClass, true);
  778. $viewClass = $viewClass . 'View';
  779. App::uses($viewClass, $plugin . 'View');
  780. }
  781. $View = new $viewClass($this);
  782. if (!empty($this->uses)) {
  783. foreach ($this->uses as $model) {
  784. list($plugin, $className) = pluginSplit($model);
  785. $this->request->params['models'][$className] = compact('plugin', 'className');
  786. }
  787. } if (!empty($this->modelClass) && ($this->uses === false || $this->uses === array())) {
  788. $this->request->params['models'][$this->modelClass] = array('plugin' => $this->plugin, 'className' => $this->modelClass);
  789. }
  790. $models = ClassRegistry::keys();
  791. foreach ($models as $currentModel) {
  792. $currentObject = ClassRegistry::getObject($currentModel);
  793. if (is_a($currentObject, 'Model')) {
  794. $className = get_class($currentObject);
  795. list($plugin, $package) = pluginSplit(App::location($className));
  796. $this->request->params['models'][$currentObject->alias] = compact('plugin', 'className');
  797. $View->validationErrors[$currentObject->alias] =& $currentObject->validationErrors;
  798. }
  799. }
  800. $this->autoRender = false;
  801. $this->View = $View;
  802. $this->response->body($View->render($view, $layout));
  803. return $this->response;
  804. }
  805. /**
  806. * Returns the referring URL for this request.
  807. *
  808. * @param string $default Default URL to use if HTTP_REFERER cannot be read from headers
  809. * @param boolean $local If true, restrict referring URLs to local server
  810. * @return string Referring URL
  811. * @link http://book.cakephp.org/view/987/referer
  812. */
  813. public function referer($default = null, $local = false) {
  814. if ($this->request) {
  815. $referer = $this->request->referer($local);
  816. if ($referer == '/' && $default != null) {
  817. return Router::url($default, true);
  818. }
  819. return $referer;
  820. }
  821. return '/';
  822. }
  823. /**
  824. * Forces the user's browser not to cache the results of the current request.
  825. *
  826. * @return void
  827. * @link http://book.cakephp.org/view/988/disableCache
  828. * @deprecated Use CakeResponse::disableCache()
  829. */
  830. public function disableCache() {
  831. $this->response->disableCache();
  832. }
  833. /**
  834. * Shows a message to the user for $pause seconds, then redirects to $url.
  835. * Uses flash.ctp as the default layout for the message.
  836. * Does not work if the current debug level is higher than 0.
  837. *
  838. * @param string $message Message to display to the user
  839. * @param mixed $url Relative string or array-based URL to redirect to after the time expires
  840. * @param integer $pause Time to show the message
  841. * @param string $layout Layout you want to use, defaults to 'flash'
  842. * @return void Renders flash layout
  843. * @link http://book.cakephp.org/view/983/flash
  844. */
  845. public function flash($message, $url, $pause = 1, $layout = 'flash') {
  846. $this->autoRender = false;
  847. $this->set('url', Router::url($url));
  848. $this->set('message', $message);
  849. $this->set('pause', $pause);
  850. $this->set('page_title', $message);
  851. $this->render(false, $layout);
  852. }
  853. /**
  854. * Converts POST'ed form data to a model conditions array, suitable for use in a Model::find() call.
  855. *
  856. * @param array $data POST'ed data organized by model and field
  857. * @param mixed $op A string containing an SQL comparison operator, or an array matching operators
  858. * to fields
  859. * @param string $bool SQL boolean operator: AND, OR, XOR, etc.
  860. * @param boolean $exclusive If true, and $op is an array, fields not included in $op will not be
  861. * included in the returned conditions
  862. * @return array An array of model conditions
  863. * @link http://book.cakephp.org/view/989/postConditions
  864. */
  865. public function postConditions($data = array(), $op = null, $bool = 'AND', $exclusive = false) {
  866. if (!is_array($data) || empty($data)) {
  867. if (!empty($this->request->data)) {
  868. $data = $this->request->data;
  869. } else {
  870. return null;
  871. }
  872. }
  873. $cond = array();
  874. if ($op === null) {
  875. $op = '';
  876. }
  877. $arrayOp = is_array($op);
  878. foreach ($data as $model => $fields) {
  879. foreach ($fields as $field => $value) {
  880. $key = $model.'.'.$field;
  881. $fieldOp = $op;
  882. if ($arrayOp) {
  883. if (array_key_exists($key, $op)) {
  884. $fieldOp = $op[$key];
  885. } elseif (array_key_exists($field, $op)) {
  886. $fieldOp = $op[$field];
  887. } else {
  888. $fieldOp = false;
  889. }
  890. }
  891. if ($exclusive && $fieldOp === false) {
  892. continue;
  893. }
  894. $fieldOp = strtoupper(trim($fieldOp));
  895. if ($fieldOp === 'LIKE') {
  896. $key = $key.' LIKE';
  897. $value = '%'.$value.'%';
  898. } elseif ($fieldOp && $fieldOp != '=') {
  899. $key = $key.' '.$fieldOp;
  900. }
  901. $cond[$key] = $value;
  902. }
  903. }
  904. if ($bool != null && strtoupper($bool) != 'AND') {
  905. $cond = array($bool => $cond);
  906. }
  907. return $cond;
  908. }
  909. /**
  910. * Handles automatic pagination of model records.
  911. *
  912. * @param mixed $object Model to paginate (e.g: model instance, or 'Model', or 'Model.InnerModel')
  913. * @param mixed $scope Conditions to use while paginating
  914. * @param array $whitelist List of allowed options for paging
  915. * @return array Model query results
  916. * @link http://book.cakephp.org/view/1232/Controller-Setup
  917. * @deprecated Use PaginatorComponent instead
  918. */
  919. public function paginate($object = null, $scope = array(), $whitelist = array()) {
  920. return $this->Components->load('Paginator', $this->paginate)->paginate($object, $scope, $whitelist);
  921. }
  922. /**
  923. * Called before the controller action. You can use this method to configure and customize components
  924. * or perform logic that needs to happen before each controller action.
  925. *
  926. * @return void
  927. * @link http://book.cakephp.org/view/984/Callbacks
  928. */
  929. public function beforeFilter() {
  930. }
  931. /**
  932. * Called after the controller action is run, but before the view is rendered. You can use this method
  933. * to perform logic or set view variables that are required on every request.
  934. *
  935. * @return void
  936. * @link http://book.cakephp.org/view/984/Callbacks
  937. */
  938. public function beforeRender() {
  939. }
  940. /**
  941. * The beforeRedirect method is invoked when the controller's redirect method is called but before any
  942. * further action. If this method returns false the controller will not continue on to redirect the request.
  943. * The $url, $status and $exit variables have same meaning as for the controller's method. You can also
  944. * return a string which will be interpreted as the url to redirect to or return associative array with
  945. * key 'url' and optionally 'status' and 'exit'.
  946. *
  947. * @param mixed $url A string or array-based URL pointing to another location within the app,
  948. * or an absolute URL
  949. * @param integer $status Optional HTTP status code (eg: 404)
  950. * @param boolean $exit If true, exit() will be called after the redirect
  951. * @return boolean
  952. */
  953. public function beforeRedirect($url, $status = null, $exit = true) {
  954. return true;
  955. }
  956. /**
  957. * Called after the controller action is run and rendered.
  958. *
  959. * @return void
  960. * @link http://book.cakephp.org/view/984/Callbacks
  961. */
  962. public function afterFilter() {
  963. }
  964. /**
  965. * This method should be overridden in child classes.
  966. *
  967. * @param string $method name of method called example index, edit, etc.
  968. * @return boolean Success
  969. * @link http://book.cakephp.org/view/984/Callbacks
  970. */
  971. public function _beforeScaffold($method) {
  972. return true;
  973. }
  974. /**
  975. * This method should be overridden in child classes.
  976. *
  977. * @param string $method name of method called either edit or update.
  978. * @return boolean Success
  979. * @link http://book.cakephp.org/view/984/Callbacks
  980. */
  981. public function _afterScaffoldSave($method) {
  982. return true;
  983. }
  984. /**
  985. * This method should be overridden in child classes.
  986. *
  987. * @param string $method name of method called either edit or update.
  988. * @return boolean Success
  989. * @link http://book.cakephp.org/view/984/Callbacks
  990. */
  991. public function _afterScaffoldSaveError($method) {
  992. return true;
  993. }
  994. /**
  995. * This method should be overridden in child classes.
  996. * If not it will render a scaffold error.
  997. * Method MUST return true in child classes
  998. *
  999. * @param string $method name of method called example index, edit, etc.
  1000. * @return boolean Success
  1001. * @link http://book.cakephp.org/view/984/Callbacks
  1002. */
  1003. public function _scaffoldError($method) {
  1004. return false;
  1005. }
  1006. }