Controller.php 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228
  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. App::uses('CakeResponse', 'Network');
  16. App::uses('ClassRegistry', 'Utility');
  17. App::uses('ComponentCollection', 'Controller');
  18. App::uses('View', 'View');
  19. App::uses('CakeEvent', 'Event');
  20. App::uses('CakeEventListener', 'Event');
  21. App::uses('CakeEventManager', 'Event');
  22. /**
  23. * Application controller class for organization of business logic.
  24. * Provides basic functionality, such as rendering views inside layouts,
  25. * automatic model availability, redirection, callbacks, and more.
  26. *
  27. * Controllers should provide a number of 'action' methods. These are public methods on the controller
  28. * that are not prefixed with a '_' and not part of Controller. Each action serves as an endpoint for
  29. * performing a specific action on a resource or collection of resources. For example adding or editing a new
  30. * object, or listing a set of objects.
  31. *
  32. * You can access request parameters, using `$this->request`. The request object contains all the POST, GET and FILES
  33. * that were part of the request.
  34. *
  35. * After performing the required actions, controllers are responsible for creating a response. This usually
  36. * takes the form of a generated View, or possibly a redirection to another controller action. In either case
  37. * `$this->response` allows you to manipulate all aspects of the response.
  38. *
  39. * Controllers are created by Dispatcher based on request parameters and routing. By default controllers and actions
  40. * use conventional names. For example `/posts/index` maps to `PostsController::index()`. You can re-map urls
  41. * using Router::connect().
  42. *
  43. * @package Cake.Controller
  44. * @property AclComponent $Acl
  45. * @property AuthComponent $Auth
  46. * @property CookieComponent $Cookie
  47. * @property EmailComponent $Email
  48. * @property PaginatorComponent $Paginator
  49. * @property RequestHandlerComponent $RequestHandler
  50. * @property SecurityComponent $Security
  51. * @property SessionComponent $Session
  52. * @link http://book.cakephp.org/2.0/en/controllers.html
  53. */
  54. class Controller extends Object implements CakeEventListener {
  55. /**
  56. * The name of this controller. Controller names are plural, named after the model they manipulate.
  57. *
  58. * @var string
  59. * @link http://book.cakephp.org/2.0/en/controllers.html#controller-attributes
  60. */
  61. public $name = null;
  62. /**
  63. * An array containing the class names of models this controller uses.
  64. *
  65. * Example: `public $uses = array('Product', 'Post', 'Comment');`
  66. *
  67. * Can be set to several values to express different options:
  68. *
  69. * - `true` Use the default inflected model name.
  70. * - `array()` Use only models defined in the parent class.
  71. * - `false` Use no models at all, do not merge with parent class either.
  72. * - `array('Post', 'Comment')` Use only the Post and Comment models. Models
  73. * Will also be merged with the parent class.
  74. *
  75. * The default value is `true`.
  76. *
  77. * @var mixed A single name as a string or a list of names as an array.
  78. * @link http://book.cakephp.org/2.0/en/controllers.html#components-helpers-and-uses
  79. */
  80. public $uses = true;
  81. /**
  82. * An array containing the names of helpers this controller uses. The array elements should
  83. * not contain the "Helper" part of the classname.
  84. *
  85. * Example: `public $helpers = array('Html', 'Javascript', 'Time', 'Ajax');`
  86. *
  87. * @var mixed A single name as a string or a list of names as an array.
  88. * @link http://book.cakephp.org/2.0/en/controllers.html#components-helpers-and-uses
  89. */
  90. public $helpers = array();
  91. /**
  92. * An instance of a CakeRequest object that contains information about the current request.
  93. * This object contains all the information about a request and several methods for reading
  94. * additional information about the request.
  95. *
  96. * @var CakeRequest
  97. * @link http://book.cakephp.org/2.0/en/controllers/request-response.html#cakerequest
  98. */
  99. public $request;
  100. /**
  101. * An instance of a CakeResponse object that contains information about the impending response
  102. *
  103. * @var CakeResponse
  104. * @link http://book.cakephp.org/2.0/en/controllers/request-response.html#cakeresponse
  105. */
  106. public $response;
  107. /**
  108. * The classname to use for creating the response object.
  109. *
  110. * @var string
  111. */
  112. protected $_responseClass = 'CakeResponse';
  113. /**
  114. * The name of the views subfolder containing views for this controller.
  115. *
  116. * @var string
  117. */
  118. public $viewPath = null;
  119. /**
  120. * The name of the layouts subfolder containing layouts for this controller.
  121. *
  122. * @var string
  123. */
  124. public $layoutPath = null;
  125. /**
  126. * Contains variables to be handed to the view.
  127. *
  128. * @var array
  129. */
  130. public $viewVars = array();
  131. /**
  132. * The name of the view file to render. The name specified
  133. * is the filename in /app/View/<SubFolder> without the .ctp extension.
  134. *
  135. * @var string
  136. */
  137. public $view = null;
  138. /**
  139. * The name of the layout file to render the view inside of. The name specified
  140. * is the filename of the layout in /app/View/Layouts without the .ctp
  141. * extension.
  142. *
  143. * @var string
  144. */
  145. public $layout = 'default';
  146. /**
  147. * Set to true to automatically render the view
  148. * after action logic.
  149. *
  150. * @var boolean
  151. */
  152. public $autoRender = true;
  153. /**
  154. * Set to true to automatically render the layout around views.
  155. *
  156. * @var boolean
  157. */
  158. public $autoLayout = true;
  159. /**
  160. * Instance of ComponentCollection used to handle callbacks.
  161. *
  162. * @var ComponentCollection
  163. */
  164. public $Components = null;
  165. /**
  166. * Array containing the names of components this controller uses. Component names
  167. * should not contain the "Component" portion of the classname.
  168. *
  169. * Example: `public $components = array('Session', 'RequestHandler', 'Acl');`
  170. *
  171. * @var array
  172. * @link http://book.cakephp.org/2.0/en/controllers/components.html
  173. */
  174. public $components = array('Session');
  175. /**
  176. * The name of the View class this controller sends output to.
  177. *
  178. * @var string
  179. */
  180. public $viewClass = 'View';
  181. /**
  182. * Instance of the View created during rendering. Won't be set until after
  183. * 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/2.0/en/core-libraries/helpers/cache.html#additional-configuration-options
  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/2.0/en/controllers/scaffolding.html
  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, -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 array $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 integer|array $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 array 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 integer|string $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 string|array $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 ($url !== null) {
  698. $this->response->header('Location', Router::url($url, true));
  699. }
  700. if (is_string($status)) {
  701. $codes = array_flip($this->response->httpCodes());
  702. if (isset($codes[$status])) {
  703. $status = $codes[$status];
  704. }
  705. }
  706. if ($status) {
  707. $this->response->statusCode($status);
  708. }
  709. if ($exit) {
  710. $this->response->send();
  711. $this->_stop();
  712. }
  713. }
  714. /**
  715. * Parse beforeRedirect Response
  716. *
  717. * @param mixed $response Response from beforeRedirect callback
  718. * @param string|array $url The same value of beforeRedirect
  719. * @param integer $status The same value of beforeRedirect
  720. * @param boolean $exit The same value of beforeRedirect
  721. * @return array Array with keys url, status and exit
  722. */
  723. protected function _parseBeforeRedirect($response, $url, $status, $exit) {
  724. if (is_array($response) && isset($response[0])) {
  725. foreach ($response as $resp) {
  726. if (is_array($resp) && isset($resp['url'])) {
  727. extract($resp, EXTR_OVERWRITE);
  728. } elseif ($resp !== null) {
  729. $url = $resp;
  730. }
  731. }
  732. } elseif (is_array($response)) {
  733. extract($response, EXTR_OVERWRITE);
  734. }
  735. return compact('url', 'status', 'exit');
  736. }
  737. /**
  738. * Convenience and object wrapper method for CakeResponse::header().
  739. *
  740. * @param string $status The header message that is being set.
  741. * @return void
  742. * @deprecated Use CakeResponse::header()
  743. */
  744. public function header($status) {
  745. $this->response->header($status);
  746. }
  747. /**
  748. * Saves a variable for use inside a view template.
  749. *
  750. * @param string|array $one A string or an array of data.
  751. * @param string|array $two Value in case $one is a string (which then works as the key).
  752. * Unused if $one is an associative array, otherwise serves as the values to $one's keys.
  753. * @return void
  754. * @link http://book.cakephp.org/2.0/en/controllers.html#interacting-with-views
  755. */
  756. public function set($one, $two = null) {
  757. if (is_array($one)) {
  758. if (is_array($two)) {
  759. $data = array_combine($one, $two);
  760. } else {
  761. $data = $one;
  762. }
  763. } else {
  764. $data = array($one => $two);
  765. }
  766. $this->viewVars = $data + $this->viewVars;
  767. }
  768. /**
  769. * Internally redirects one action to another. Does not perform another HTTP request unlike Controller::redirect()
  770. *
  771. * Examples:
  772. *
  773. * {{{
  774. * setAction('another_action');
  775. * setAction('action_with_parameters', $parameter1);
  776. * }}}
  777. *
  778. * @param string $action The new action to be 'redirected' to
  779. * @param mixed Any other parameters passed to this method will be passed as
  780. * parameters to the new action.
  781. * @return mixed Returns the return value of the called action
  782. */
  783. public function setAction($action) {
  784. $this->request->params['action'] = $action;
  785. $this->view = $action;
  786. $args = func_get_args();
  787. unset($args[0]);
  788. return call_user_func_array(array(&$this, $action), $args);
  789. }
  790. /**
  791. * Returns number of errors in a submitted FORM.
  792. *
  793. * @return integer Number of errors
  794. */
  795. public function validate() {
  796. $args = func_get_args();
  797. $errors = call_user_func_array(array(&$this, 'validateErrors'), $args);
  798. if ($errors === false) {
  799. return 0;
  800. }
  801. return count($errors);
  802. }
  803. /**
  804. * Validates models passed by parameters. Example:
  805. *
  806. * `$errors = $this->validateErrors($this->Article, $this->User);`
  807. *
  808. * @param mixed A list of models as a variable argument
  809. * @return array Validation errors, or false if none
  810. */
  811. public function validateErrors() {
  812. $objects = func_get_args();
  813. if (empty($objects)) {
  814. return false;
  815. }
  816. $errors = array();
  817. foreach ($objects as $object) {
  818. if (isset($this->{$object->alias})) {
  819. $object = $this->{$object->alias};
  820. }
  821. $object->set($object->data);
  822. $errors = array_merge($errors, $object->invalidFields());
  823. }
  824. return $this->validationErrors = (!empty($errors) ? $errors : false);
  825. }
  826. /**
  827. * Instantiates the correct view class, hands it its data, and uses it to render the view output.
  828. *
  829. * @param string $view View to use for rendering
  830. * @param string $layout Layout to use
  831. * @return CakeResponse A response object containing the rendered view.
  832. * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::render
  833. */
  834. public function render($view = null, $layout = null) {
  835. $event = new CakeEvent('Controller.beforeRender', $this);
  836. $this->getEventManager()->dispatch($event);
  837. if ($event->isStopped()) {
  838. $this->autoRender = false;
  839. return $this->response;
  840. }
  841. if (!empty($this->uses) && is_array($this->uses)) {
  842. foreach ($this->uses as $model) {
  843. list($plugin, $className) = pluginSplit($model);
  844. $this->request->params['models'][$className] = compact('plugin', 'className');
  845. }
  846. }
  847. $viewClass = $this->viewClass;
  848. if ($this->viewClass != 'View') {
  849. list($plugin, $viewClass) = pluginSplit($viewClass, true);
  850. $viewClass = $viewClass . 'View';
  851. App::uses($viewClass, $plugin . 'View');
  852. }
  853. $View = new $viewClass($this);
  854. $models = ClassRegistry::keys();
  855. foreach ($models as $currentModel) {
  856. $currentObject = ClassRegistry::getObject($currentModel);
  857. if (is_a($currentObject, 'Model')) {
  858. $className = get_class($currentObject);
  859. list($plugin) = pluginSplit(App::location($className));
  860. $this->request->params['models'][$currentObject->alias] = compact('plugin', 'className');
  861. $View->validationErrors[$currentObject->alias] =& $currentObject->validationErrors;
  862. }
  863. }
  864. $this->autoRender = false;
  865. $this->View = $View;
  866. $this->response->body($View->render($view, $layout));
  867. return $this->response;
  868. }
  869. /**
  870. * Returns the referring URL for this request.
  871. *
  872. * @param string $default Default URL to use if HTTP_REFERER cannot be read from headers
  873. * @param boolean $local If true, restrict referring URLs to local server
  874. * @return string Referring URL
  875. * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::referer
  876. */
  877. public function referer($default = null, $local = false) {
  878. if ($this->request) {
  879. $referer = $this->request->referer($local);
  880. if ($referer == '/' && $default != null) {
  881. return Router::url($default, true);
  882. }
  883. return $referer;
  884. }
  885. return '/';
  886. }
  887. /**
  888. * Forces the user's browser not to cache the results of the current request.
  889. *
  890. * @return void
  891. * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::disableCache
  892. * @deprecated Use CakeResponse::disableCache()
  893. */
  894. public function disableCache() {
  895. $this->response->disableCache();
  896. }
  897. /**
  898. * Shows a message to the user for $pause seconds, then redirects to $url.
  899. * Uses flash.ctp as the default layout for the message.
  900. * Does not work if the current debug level is higher than 0.
  901. *
  902. * @param string $message Message to display to the user
  903. * @param string|array $url Relative string or array-based URL to redirect to after the time expires
  904. * @param integer $pause Time to show the message
  905. * @param string $layout Layout you want to use, defaults to 'flash'
  906. * @return void Renders flash layout
  907. * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::flash
  908. */
  909. public function flash($message, $url, $pause = 1, $layout = 'flash') {
  910. $this->autoRender = false;
  911. $this->set('url', Router::url($url));
  912. $this->set('message', $message);
  913. $this->set('pause', $pause);
  914. $this->set('page_title', $message);
  915. $this->render(false, $layout);
  916. }
  917. /**
  918. * Converts POST'ed form data to a model conditions array, suitable for use in a Model::find() call.
  919. *
  920. * @param array $data POST'ed data organized by model and field
  921. * @param string|array $op A string containing an SQL comparison operator, or an array matching operators
  922. * to fields
  923. * @param string $bool SQL boolean operator: AND, OR, XOR, etc.
  924. * @param boolean $exclusive If true, and $op is an array, fields not included in $op will not be
  925. * included in the returned conditions
  926. * @return array An array of model conditions
  927. * @deprecated
  928. */
  929. public function postConditions($data = array(), $op = null, $bool = 'AND', $exclusive = false) {
  930. if (!is_array($data) || empty($data)) {
  931. if (!empty($this->request->data)) {
  932. $data = $this->request->data;
  933. } else {
  934. return null;
  935. }
  936. }
  937. $cond = array();
  938. if ($op === null) {
  939. $op = '';
  940. }
  941. $arrayOp = is_array($op);
  942. foreach ($data as $model => $fields) {
  943. foreach ($fields as $field => $value) {
  944. $key = $model . '.' . $field;
  945. $fieldOp = $op;
  946. if ($arrayOp) {
  947. if (array_key_exists($key, $op)) {
  948. $fieldOp = $op[$key];
  949. } elseif (array_key_exists($field, $op)) {
  950. $fieldOp = $op[$field];
  951. } else {
  952. $fieldOp = false;
  953. }
  954. }
  955. if ($exclusive && $fieldOp === false) {
  956. continue;
  957. }
  958. $fieldOp = strtoupper(trim($fieldOp));
  959. if ($fieldOp === 'LIKE') {
  960. $key = $key . ' LIKE';
  961. $value = '%' . $value . '%';
  962. } elseif ($fieldOp && $fieldOp != '=') {
  963. $key = $key . ' ' . $fieldOp;
  964. }
  965. $cond[$key] = $value;
  966. }
  967. }
  968. if ($bool != null && strtoupper($bool) != 'AND') {
  969. $cond = array($bool => $cond);
  970. }
  971. return $cond;
  972. }
  973. /**
  974. * Handles automatic pagination of model records.
  975. *
  976. * @param Model|string $object Model to paginate (e.g: model instance, or 'Model', or 'Model.InnerModel')
  977. * @param string|array $scope Conditions to use while paginating
  978. * @param array $whitelist List of allowed options for paging
  979. * @return array Model query results
  980. * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::paginate
  981. * @deprecated Use PaginatorComponent instead
  982. */
  983. public function paginate($object = null, $scope = array(), $whitelist = array()) {
  984. return $this->Components->load('Paginator', $this->paginate)->paginate($object, $scope, $whitelist);
  985. }
  986. /**
  987. * Called before the controller action. You can use this method to configure and customize components
  988. * or perform logic that needs to happen before each controller action.
  989. *
  990. * @return void
  991. * @link http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks
  992. */
  993. public function beforeFilter() {
  994. }
  995. /**
  996. * Called after the controller action is run, but before the view is rendered. You can use this method
  997. * to perform logic or set view variables that are required on every request.
  998. *
  999. * @return void
  1000. * @link http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks
  1001. */
  1002. public function beforeRender() {
  1003. }
  1004. /**
  1005. * The beforeRedirect method is invoked when the controller's redirect method is called but before any
  1006. * further action. If this method returns false the controller will not continue on to redirect the request.
  1007. * The $url, $status and $exit variables have same meaning as for the controller's method. You can also
  1008. * return a string which will be interpreted as the url to redirect to or return associative array with
  1009. * key 'url' and optionally 'status' and 'exit'.
  1010. *
  1011. * @param string|array $url A string or array-based URL pointing to another location within the app,
  1012. * or an absolute URL
  1013. * @param integer $status Optional HTTP status code (eg: 404)
  1014. * @param boolean $exit If true, exit() will be called after the redirect
  1015. * @return mixed
  1016. * false to stop redirection event,
  1017. * string controllers a new redirection url or
  1018. * array with the keys url, status and exit to be used by the redirect method.
  1019. * @link http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks
  1020. */
  1021. public function beforeRedirect($url, $status = null, $exit = true) {
  1022. }
  1023. /**
  1024. * Called after the controller action is run and rendered.
  1025. *
  1026. * @return void
  1027. * @link http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks
  1028. */
  1029. public function afterFilter() {
  1030. }
  1031. /**
  1032. * This method should be overridden in child classes.
  1033. *
  1034. * @param string $method name of method called example index, edit, etc.
  1035. * @return boolean Success
  1036. * @link http://book.cakephp.org/2.0/en/controllers.html#callbacks
  1037. */
  1038. public function beforeScaffold($method) {
  1039. return true;
  1040. }
  1041. /**
  1042. * Alias to beforeScaffold()
  1043. *
  1044. * @param string $method
  1045. * @return boolean
  1046. * @see Controller::beforeScaffold()
  1047. * @deprecated
  1048. */
  1049. protected function _beforeScaffold($method) {
  1050. return $this->beforeScaffold($method);
  1051. }
  1052. /**
  1053. * This method should be overridden in child classes.
  1054. *
  1055. * @param string $method name of method called either edit or update.
  1056. * @return boolean Success
  1057. * @link http://book.cakephp.org/2.0/en/controllers.html#callbacks
  1058. */
  1059. public function afterScaffoldSave($method) {
  1060. return true;
  1061. }
  1062. /**
  1063. * Alias to afterScaffoldSave()
  1064. *
  1065. * @param string $method
  1066. * @return boolean
  1067. * @see Controller::afterScaffoldSave()
  1068. * @deprecated
  1069. */
  1070. protected function _afterScaffoldSave($method) {
  1071. return $this->afterScaffoldSave($method);
  1072. }
  1073. /**
  1074. * This method should be overridden in child classes.
  1075. *
  1076. * @param string $method name of method called either edit or update.
  1077. * @return boolean Success
  1078. * @link http://book.cakephp.org/2.0/en/controllers.html#callbacks
  1079. */
  1080. public function afterScaffoldSaveError($method) {
  1081. return true;
  1082. }
  1083. /**
  1084. * Alias to afterScaffoldSaveError()
  1085. *
  1086. * @param string $method
  1087. * @return boolean
  1088. * @see Controller::afterScaffoldSaveError()
  1089. * @deprecated
  1090. */
  1091. protected function _afterScaffoldSaveError($method) {
  1092. return $this->afterScaffoldSaveError($method);
  1093. }
  1094. /**
  1095. * This method should be overridden in child classes.
  1096. * If not it will render a scaffold error.
  1097. * Method MUST return true in child classes
  1098. *
  1099. * @param string $method name of method called example index, edit, etc.
  1100. * @return boolean Success
  1101. * @link http://book.cakephp.org/2.0/en/controllers.html#callbacks
  1102. */
  1103. public function scaffoldError($method) {
  1104. return false;
  1105. }
  1106. /**
  1107. * Alias to scaffoldError()
  1108. *
  1109. * @param string $method
  1110. * @return boolean
  1111. * @see Controller::scaffoldError()
  1112. * @deprecated
  1113. */
  1114. protected function _scaffoldError($method) {
  1115. return $this->scaffoldError($method);
  1116. }
  1117. }