Controller.php 35 KB

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