Controller.php 36 KB

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