Controller.php 36 KB

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