Controller.php 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235
  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) {
  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 (!empty($request->params['return']) && $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. $merge = array('components', 'helpers');
  505. $this->_mergeVars($merge, $this->_mergeParent, true);
  506. }
  507. if ($this->uses === null) {
  508. $this->uses = false;
  509. }
  510. if ($this->uses === true) {
  511. $this->uses = array($pluginDot . $this->modelClass);
  512. }
  513. if (isset($appVars['uses']) && $appVars['uses'] === $this->uses) {
  514. array_unshift($this->uses, $pluginDot . $this->modelClass);
  515. }
  516. if ($pluginController) {
  517. $pluginVars = get_class_vars($pluginController);
  518. }
  519. if ($this->uses !== false) {
  520. $this->_mergeUses($pluginVars);
  521. $this->_mergeUses($appVars);
  522. } else {
  523. $this->uses = array();
  524. $this->modelClass = '';
  525. }
  526. }
  527. /**
  528. * Helper method for merging the $uses property together.
  529. *
  530. * Merges the elements not already in $this->uses into
  531. * $this->uses.
  532. *
  533. * @param array $merge The data to merge in.
  534. * @return void
  535. */
  536. protected function _mergeUses($merge) {
  537. if (!isset($merge['uses'])) {
  538. return;
  539. }
  540. if ($merge['uses'] === true) {
  541. return;
  542. }
  543. $this->uses = array_merge(
  544. $this->uses,
  545. array_diff($merge['uses'], $this->uses)
  546. );
  547. }
  548. /**
  549. * Returns a list of all events that will fire in the controller during it's lifecycle.
  550. * You can override this function to add you own listener callbacks
  551. *
  552. * @return array
  553. */
  554. public function implementedEvents() {
  555. return array(
  556. 'Controller.initialize' => 'beforeFilter',
  557. 'Controller.beforeRender' => 'beforeRender',
  558. 'Controller.beforeRedirect' => array('callable' => 'beforeRedirect', 'passParams' => true),
  559. 'Controller.shutdown' => 'afterFilter'
  560. );
  561. }
  562. /**
  563. * Loads Model classes based on the uses property
  564. * see Controller::loadModel(); for more info.
  565. * Loads Components and prepares them for initialization.
  566. *
  567. * @return mixed true if models found and instance created.
  568. * @see Controller::loadModel()
  569. * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::constructClasses
  570. * @throws MissingModelException
  571. */
  572. public function constructClasses() {
  573. $this->_mergeControllerVars();
  574. $this->Components->init($this);
  575. if ($this->uses) {
  576. $this->uses = (array)$this->uses;
  577. list(, $this->modelClass) = pluginSplit(current($this->uses));
  578. }
  579. return true;
  580. }
  581. /**
  582. * Returns the CakeEventManager manager instance that is handling any callbacks.
  583. * You can use this instance to register any new listeners or callbacks to the
  584. * controller events, or create your own events and trigger them at will.
  585. *
  586. * @return CakeEventManager
  587. */
  588. public function getEventManager() {
  589. if (empty($this->_eventManager)) {
  590. $this->_eventManager = new CakeEventManager();
  591. $this->_eventManager->attach($this->Components);
  592. $this->_eventManager->attach($this);
  593. }
  594. return $this->_eventManager;
  595. }
  596. /**
  597. * Perform the startup process for this controller.
  598. * Fire the Components and Controller callbacks in the correct order.
  599. *
  600. * - Initializes components, which fires their `initialize` callback
  601. * - Calls the controller `beforeFilter`.
  602. * - triggers Component `startup` methods.
  603. *
  604. * @return void
  605. */
  606. public function startupProcess() {
  607. $this->getEventManager()->dispatch(new CakeEvent('Controller.initialize', $this));
  608. $this->getEventManager()->dispatch(new CakeEvent('Controller.startup', $this));
  609. }
  610. /**
  611. * Perform the various shutdown processes for this controller.
  612. * Fire the Components and Controller callbacks in the correct order.
  613. *
  614. * - triggers the component `shutdown` callback.
  615. * - calls the Controller's `afterFilter` method.
  616. *
  617. * @return void
  618. */
  619. public function shutdownProcess() {
  620. $this->getEventManager()->dispatch(new CakeEvent('Controller.shutdown', $this));
  621. }
  622. /**
  623. * Queries & sets valid HTTP response codes & messages.
  624. *
  625. * @param integer|array $code If $code is an integer, then the corresponding code/message is
  626. * returned if it exists, null if it does not exist. If $code is an array,
  627. * then the 'code' and 'message' keys of each nested array are added to the default
  628. * HTTP codes. Example:
  629. *
  630. * httpCodes(404); // returns array(404 => 'Not Found')
  631. *
  632. * httpCodes(array(
  633. * 701 => 'Unicorn Moved',
  634. * 800 => 'Unexpected Minotaur'
  635. * )); // sets these new values, and returns true
  636. *
  637. * @return array Associative array of the HTTP codes as keys, and the message
  638. * strings as values, or null of the given $code does not exist.
  639. * @deprecated Use CakeResponse::httpCodes();
  640. */
  641. public function httpCodes($code = null) {
  642. return $this->response->httpCodes($code);
  643. }
  644. /**
  645. * Loads and instantiates models required by this controller.
  646. * If the model is non existent, it will throw a missing database table error, as Cake generates
  647. * dynamic models for the time being.
  648. *
  649. * @param string $modelClass Name of model class to load
  650. * @param integer|string $id Initial ID the instanced model class should have
  651. * @return mixed true when single model found and instance created, error returned if model not found.
  652. * @throws MissingModelException if the model class cannot be found.
  653. */
  654. public function loadModel($modelClass = null, $id = null) {
  655. if ($modelClass === null) {
  656. $modelClass = $this->modelClass;
  657. }
  658. $this->uses = ($this->uses) ? (array)$this->uses : array();
  659. if (!in_array($modelClass, $this->uses)) {
  660. $this->uses[] = $modelClass;
  661. }
  662. list($plugin, $modelClass) = pluginSplit($modelClass, true);
  663. $this->{$modelClass} = ClassRegistry::init(array(
  664. 'class' => $plugin . $modelClass, 'alias' => $modelClass, 'id' => $id
  665. ));
  666. if (!$this->{$modelClass}) {
  667. throw new MissingModelException($modelClass);
  668. }
  669. return true;
  670. }
  671. /**
  672. * Redirects to given $url, after turning off $this->autoRender.
  673. * Script execution is halted after the redirect.
  674. *
  675. * @param string|array $url A string or array-based URL pointing to another location within the app,
  676. * or an absolute URL
  677. * @param integer $status Optional HTTP status code (eg: 404)
  678. * @param boolean $exit If true, exit() will be called after the redirect
  679. * @return void
  680. * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::redirect
  681. */
  682. public function redirect($url, $status = null, $exit = true) {
  683. $this->autoRender = false;
  684. if (is_array($status)) {
  685. extract($status, EXTR_OVERWRITE);
  686. }
  687. $event = new CakeEvent('Controller.beforeRedirect', $this, array($url, $status, $exit));
  688. list($event->break, $event->breakOn, $event->collectReturn) = array(true, false, true);
  689. $this->getEventManager()->dispatch($event);
  690. if ($event->isStopped()) {
  691. return;
  692. }
  693. $response = $event->result;
  694. extract($this->_parseBeforeRedirect($response, $url, $status, $exit), EXTR_OVERWRITE);
  695. if ($url !== null) {
  696. $this->response->header('Location', Router::url($url, true));
  697. }
  698. if (is_string($status)) {
  699. $codes = array_flip($this->response->httpCodes());
  700. if (isset($codes[$status])) {
  701. $status = $codes[$status];
  702. }
  703. }
  704. if ($status) {
  705. $this->response->statusCode($status);
  706. }
  707. if ($exit) {
  708. $this->response->send();
  709. $this->_stop();
  710. }
  711. }
  712. /**
  713. * Parse beforeRedirect Response
  714. *
  715. * @param mixed $response Response from beforeRedirect callback
  716. * @param string|array $url The same value of beforeRedirect
  717. * @param integer $status The same value of beforeRedirect
  718. * @param boolean $exit The same value of beforeRedirect
  719. * @return array Array with keys url, status and exit
  720. */
  721. protected function _parseBeforeRedirect($response, $url, $status, $exit) {
  722. if (is_array($response) && array_key_exists(0, $response)) {
  723. foreach ($response as $resp) {
  724. if (is_array($resp) && isset($resp['url'])) {
  725. extract($resp, EXTR_OVERWRITE);
  726. } elseif ($resp !== null) {
  727. $url = $resp;
  728. }
  729. }
  730. } elseif (is_array($response)) {
  731. extract($response, EXTR_OVERWRITE);
  732. }
  733. return compact('url', 'status', 'exit');
  734. }
  735. /**
  736. * Convenience and object wrapper method for CakeResponse::header().
  737. *
  738. * @param string $status The header message that is being set.
  739. * @return void
  740. * @deprecated Use CakeResponse::header()
  741. */
  742. public function header($status) {
  743. $this->response->header($status);
  744. }
  745. /**
  746. * Saves a variable for use inside a view template.
  747. *
  748. * @param string|array $one A string or an array of data.
  749. * @param string|array $two Value in case $one is a string (which then works as the key).
  750. * Unused if $one is an associative array, otherwise serves as the values to $one's keys.
  751. * @return void
  752. * @link http://book.cakephp.org/2.0/en/controllers.html#interacting-with-views
  753. */
  754. public function set($one, $two = null) {
  755. if (is_array($one)) {
  756. if (is_array($two)) {
  757. $data = array_combine($one, $two);
  758. } else {
  759. $data = $one;
  760. }
  761. } else {
  762. $data = array($one => $two);
  763. }
  764. $this->viewVars = $data + $this->viewVars;
  765. }
  766. /**
  767. * Internally redirects one action to another. Does not perform another HTTP request unlike Controller::redirect()
  768. *
  769. * Examples:
  770. *
  771. * {{{
  772. * setAction('another_action');
  773. * setAction('action_with_parameters', $parameter1);
  774. * }}}
  775. *
  776. * @param string $action The new action to be 'redirected' to.
  777. * Any other parameters passed to this method will be passed as parameters to the new action.
  778. * @return mixed Returns the return value of the called action
  779. */
  780. public function setAction($action) {
  781. $this->request->params['action'] = $action;
  782. $this->view = $action;
  783. $args = func_get_args();
  784. unset($args[0]);
  785. return call_user_func_array(array(&$this, $action), $args);
  786. }
  787. /**
  788. * Returns number of errors in a submitted FORM.
  789. *
  790. * @return integer Number of errors
  791. */
  792. public function validate() {
  793. $args = func_get_args();
  794. $errors = call_user_func_array(array(&$this, 'validateErrors'), $args);
  795. if ($errors === false) {
  796. return 0;
  797. }
  798. return count($errors);
  799. }
  800. /**
  801. * Validates models passed by parameters. Example:
  802. *
  803. * `$errors = $this->validateErrors($this->Article, $this->User);`
  804. *
  805. * @param mixed A list of models as a variable argument
  806. * @return array Validation errors, or false if none
  807. */
  808. public function validateErrors() {
  809. $objects = func_get_args();
  810. if (empty($objects)) {
  811. return false;
  812. }
  813. $errors = array();
  814. foreach ($objects as $object) {
  815. if (isset($this->{$object->alias})) {
  816. $object = $this->{$object->alias};
  817. }
  818. $object->set($object->data);
  819. $errors = array_merge($errors, $object->invalidFields());
  820. }
  821. return $this->validationErrors = (!empty($errors) ? $errors : false);
  822. }
  823. /**
  824. * Instantiates the correct view class, hands it its data, and uses it to render the view output.
  825. *
  826. * @param string $view View to use for rendering
  827. * @param string $layout Layout to use
  828. * @return CakeResponse A response object containing the rendered view.
  829. * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::render
  830. */
  831. public function render($view = null, $layout = null) {
  832. $event = new CakeEvent('Controller.beforeRender', $this);
  833. $this->getEventManager()->dispatch($event);
  834. if ($event->isStopped()) {
  835. $this->autoRender = false;
  836. return $this->response;
  837. }
  838. if (!empty($this->uses) && is_array($this->uses)) {
  839. foreach ($this->uses as $model) {
  840. list($plugin, $className) = pluginSplit($model);
  841. $this->request->params['models'][$className] = compact('plugin', 'className');
  842. }
  843. }
  844. $this->View = $this->_getViewObject();
  845. $models = ClassRegistry::keys();
  846. foreach ($models as $currentModel) {
  847. $currentObject = ClassRegistry::getObject($currentModel);
  848. if (is_a($currentObject, 'Model')) {
  849. $className = get_class($currentObject);
  850. list($plugin) = pluginSplit(App::location($className));
  851. $this->request->params['models'][$currentObject->alias] = compact('plugin', 'className');
  852. $this->View->validationErrors[$currentObject->alias] =& $currentObject->validationErrors;
  853. }
  854. }
  855. $this->autoRender = false;
  856. $this->response->body($this->View->render($view, $layout));
  857. return $this->response;
  858. }
  859. /**
  860. * Returns the referring URL for this request.
  861. *
  862. * @param string $default Default URL to use if HTTP_REFERER cannot be read from headers
  863. * @param boolean $local If true, restrict referring URLs to local server
  864. * @return string Referring URL
  865. * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::referer
  866. */
  867. public function referer($default = null, $local = false) {
  868. if (!$this->request) {
  869. return '/';
  870. }
  871. $referer = $this->request->referer($local);
  872. if ($referer == '/' && $default) {
  873. return Router::url($default, true);
  874. }
  875. return $referer;
  876. }
  877. /**
  878. * Forces the user's browser not to cache the results of the current request.
  879. *
  880. * @return void
  881. * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::disableCache
  882. * @deprecated Use CakeResponse::disableCache()
  883. */
  884. public function disableCache() {
  885. $this->response->disableCache();
  886. }
  887. /**
  888. * Shows a message to the user for $pause seconds, then redirects to $url.
  889. * Uses flash.ctp as the default layout for the message.
  890. * Does not work if the current debug level is higher than 0.
  891. *
  892. * @param string $message Message to display to the user
  893. * @param string|array $url Relative string or array-based URL to redirect to after the time expires
  894. * @param integer $pause Time to show the message
  895. * @param string $layout Layout you want to use, defaults to 'flash'
  896. * @return void
  897. * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::flash
  898. */
  899. public function flash($message, $url, $pause = 1, $layout = 'flash') {
  900. $this->autoRender = false;
  901. $this->set('url', Router::url($url));
  902. $this->set('message', $message);
  903. $this->set('pause', $pause);
  904. $this->set('page_title', $message);
  905. $this->render(false, $layout);
  906. }
  907. /**
  908. * Converts POST'ed form data to a model conditions array, suitable for use in a Model::find() call.
  909. *
  910. * @param array $data POST'ed data organized by model and field
  911. * @param string|array $op A string containing an SQL comparison operator, or an array matching operators
  912. * to fields
  913. * @param string $bool SQL boolean operator: AND, OR, XOR, etc.
  914. * @param boolean $exclusive If true, and $op is an array, fields not included in $op will not be
  915. * included in the returned conditions
  916. * @return array An array of model conditions
  917. * @deprecated
  918. */
  919. public function postConditions($data = array(), $op = null, $bool = 'AND', $exclusive = false) {
  920. if (!is_array($data) || empty($data)) {
  921. if (!empty($this->request->data)) {
  922. $data = $this->request->data;
  923. } else {
  924. return null;
  925. }
  926. }
  927. $cond = array();
  928. if ($op === null) {
  929. $op = '';
  930. }
  931. $arrayOp = is_array($op);
  932. foreach ($data as $model => $fields) {
  933. foreach ($fields as $field => $value) {
  934. $key = $model . '.' . $field;
  935. $fieldOp = $op;
  936. if ($arrayOp) {
  937. if (array_key_exists($key, $op)) {
  938. $fieldOp = $op[$key];
  939. } elseif (array_key_exists($field, $op)) {
  940. $fieldOp = $op[$field];
  941. } else {
  942. $fieldOp = false;
  943. }
  944. }
  945. if ($exclusive && $fieldOp === false) {
  946. continue;
  947. }
  948. $fieldOp = strtoupper(trim($fieldOp));
  949. if ($fieldOp === 'LIKE') {
  950. $key = $key . ' LIKE';
  951. $value = '%' . $value . '%';
  952. } elseif ($fieldOp && $fieldOp != '=') {
  953. $key = $key . ' ' . $fieldOp;
  954. }
  955. $cond[$key] = $value;
  956. }
  957. }
  958. if ($bool && strtoupper($bool) != 'AND') {
  959. $cond = array($bool => $cond);
  960. }
  961. return $cond;
  962. }
  963. /**
  964. * Handles automatic pagination of model records.
  965. *
  966. * @param Model|string $object Model to paginate (e.g: model instance, or 'Model', or 'Model.InnerModel')
  967. * @param string|array $scope Conditions to use while paginating
  968. * @param array $whitelist List of allowed options for paging
  969. * @return array Model query results
  970. * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::paginate
  971. * @deprecated Use PaginatorComponent instead
  972. */
  973. public function paginate($object = null, $scope = array(), $whitelist = array()) {
  974. return $this->Components->load('Paginator', $this->paginate)->paginate($object, $scope, $whitelist);
  975. }
  976. /**
  977. * Called before the controller action. You can use this method to configure and customize components
  978. * or perform logic that needs to happen before each controller action.
  979. *
  980. * @return void
  981. * @link http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks
  982. */
  983. public function beforeFilter() {
  984. }
  985. /**
  986. * Called after the controller action is run, but before the view is rendered. You can use this method
  987. * to perform logic or set view variables that are required on every request.
  988. *
  989. * @return void
  990. * @link http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks
  991. */
  992. public function beforeRender() {
  993. }
  994. /**
  995. * The beforeRedirect method is invoked when the controller's redirect method is called but before any
  996. * further action. If this method returns false the controller will not continue on to redirect the request.
  997. * The $url, $status and $exit variables have same meaning as for the controller's method. You can also
  998. * return a string which will be interpreted as the url to redirect to or return associative array with
  999. * key 'url' and optionally 'status' and 'exit'.
  1000. *
  1001. * @param string|array $url A string or array-based URL pointing to another location within the app,
  1002. * or an absolute URL
  1003. * @param integer $status Optional HTTP status code (eg: 404)
  1004. * @param boolean $exit If true, exit() will be called after the redirect
  1005. * @return mixed
  1006. * false to stop redirection event,
  1007. * string controllers a new redirection url or
  1008. * array with the keys url, status and exit to be used by the redirect method.
  1009. * @link http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks
  1010. */
  1011. public function beforeRedirect($url, $status = null, $exit = true) {
  1012. }
  1013. /**
  1014. * Called after the controller action is run and rendered.
  1015. *
  1016. * @return void
  1017. * @link http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks
  1018. */
  1019. public function afterFilter() {
  1020. }
  1021. /**
  1022. * This method should be overridden in child classes.
  1023. *
  1024. * @param string $method name of method called example index, edit, etc.
  1025. * @return boolean Success
  1026. * @link http://book.cakephp.org/2.0/en/controllers.html#callbacks
  1027. */
  1028. public function beforeScaffold($method) {
  1029. return true;
  1030. }
  1031. /**
  1032. * Alias to beforeScaffold()
  1033. *
  1034. * @param string $method
  1035. * @return boolean
  1036. * @see Controller::beforeScaffold()
  1037. * @deprecated
  1038. */
  1039. protected function _beforeScaffold($method) {
  1040. return $this->beforeScaffold($method);
  1041. }
  1042. /**
  1043. * This method should be overridden in child classes.
  1044. *
  1045. * @param string $method name of method called either edit or update.
  1046. * @return boolean Success
  1047. * @link http://book.cakephp.org/2.0/en/controllers.html#callbacks
  1048. */
  1049. public function afterScaffoldSave($method) {
  1050. return true;
  1051. }
  1052. /**
  1053. * Alias to afterScaffoldSave()
  1054. *
  1055. * @param string $method
  1056. * @return boolean
  1057. * @see Controller::afterScaffoldSave()
  1058. * @deprecated
  1059. */
  1060. protected function _afterScaffoldSave($method) {
  1061. return $this->afterScaffoldSave($method);
  1062. }
  1063. /**
  1064. * This method should be overridden in child classes.
  1065. *
  1066. * @param string $method name of method called either edit or update.
  1067. * @return boolean Success
  1068. * @link http://book.cakephp.org/2.0/en/controllers.html#callbacks
  1069. */
  1070. public function afterScaffoldSaveError($method) {
  1071. return true;
  1072. }
  1073. /**
  1074. * Alias to afterScaffoldSaveError()
  1075. *
  1076. * @param string $method
  1077. * @return boolean
  1078. * @see Controller::afterScaffoldSaveError()
  1079. * @deprecated
  1080. */
  1081. protected function _afterScaffoldSaveError($method) {
  1082. return $this->afterScaffoldSaveError($method);
  1083. }
  1084. /**
  1085. * This method should be overridden in child classes.
  1086. * If not it will render a scaffold error.
  1087. * Method MUST return true in child classes
  1088. *
  1089. * @param string $method name of method called example index, edit, etc.
  1090. * @return boolean Success
  1091. * @link http://book.cakephp.org/2.0/en/controllers.html#callbacks
  1092. */
  1093. public function scaffoldError($method) {
  1094. return false;
  1095. }
  1096. /**
  1097. * Alias to scaffoldError()
  1098. *
  1099. * @param string $method
  1100. * @return boolean
  1101. * @see Controller::scaffoldError()
  1102. * @deprecated
  1103. */
  1104. protected function _scaffoldError($method) {
  1105. return $this->scaffoldError($method);
  1106. }
  1107. /**
  1108. * Constructs the view class instance based on the controller property
  1109. *
  1110. * @return View
  1111. */
  1112. protected function _getViewObject() {
  1113. $viewClass = $this->viewClass;
  1114. if ($this->viewClass !== 'View') {
  1115. list($plugin, $viewClass) = pluginSplit($viewClass, true);
  1116. $viewClass = $viewClass . 'View';
  1117. App::uses($viewClass, $plugin . 'View');
  1118. }
  1119. return new $viewClass($this);
  1120. }
  1121. }