Controller.php 35 KB

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