Controller.php 36 KB

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