Controller.php 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
  10. * @link http://cakephp.org CakePHP(tm) Project
  11. * @package Cake.Controller
  12. * @since CakePHP(tm) v 0.2.9
  13. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  14. */
  15. App::uses('CakeResponse', 'Network');
  16. App::uses('ClassRegistry', 'Utility');
  17. App::uses('ComponentCollection', 'Controller');
  18. App::uses('View', 'View');
  19. App::uses('CakeEvent', 'Event');
  20. App::uses('CakeEventListener', 'Event');
  21. App::uses('CakeEventManager', 'Event');
  22. /**
  23. * Application controller class for organization of business logic.
  24. * Provides basic functionality, such as rendering views inside layouts,
  25. * automatic model availability, redirection, callbacks, and more.
  26. *
  27. * Controllers should provide a number of 'action' methods. These are public methods on the controller
  28. * that are not prefixed with a '_' and not part of Controller. Each action serves as an endpoint for
  29. * performing a specific action on a resource or collection of resources. For example adding or editing a new
  30. * object, or listing a set of objects.
  31. *
  32. * You can access request parameters, using `$this->request`. The request object contains all the POST, GET and FILES
  33. * that were part of the request.
  34. *
  35. * After performing the required actions, controllers are responsible for creating a response. This usually
  36. * takes the form of a generated View, or possibly a redirection to another controller action. In either case
  37. * `$this->response` allows you to manipulate all aspects of the response.
  38. *
  39. * Controllers are created by Dispatcher based on request parameters and routing. By default controllers and actions
  40. * use conventional names. For example `/posts/index` maps to `PostsController::index()`. You can re-map urls
  41. * using Router::connect().
  42. *
  43. * @package Cake.Controller
  44. * @property AclComponent $Acl
  45. * @property AuthComponent $Auth
  46. * @property CookieComponent $Cookie
  47. * @property EmailComponent $Email
  48. * @property PaginatorComponent $Paginator
  49. * @property RequestHandlerComponent $RequestHandler
  50. * @property SecurityComponent $Security
  51. * @property SessionComponent $Session
  52. * @link http://book.cakephp.org/2.0/en/controllers.html
  53. */
  54. class Controller extends Object implements CakeEventListener {
  55. /**
  56. * The name of this controller. Controller names are plural, named after the model they manipulate.
  57. *
  58. * @var string
  59. * @link http://book.cakephp.org/2.0/en/controllers.html#controller-attributes
  60. */
  61. public $name = null;
  62. /**
  63. * An array containing the class names of models this controller uses.
  64. *
  65. * Example: `public $uses = array('Product', 'Post', 'Comment');`
  66. *
  67. * Can be set to several values to express different options:
  68. *
  69. * - `true` Use the default inflected model name.
  70. * - `array()` Use only models defined in the parent class.
  71. * - `false` Use no models at all, do not merge with parent class either.
  72. * - `array('Post', 'Comment')` Use only the Post and Comment models. Models
  73. * Will also be merged with the parent class.
  74. *
  75. * The default value is `true`.
  76. *
  77. * @var mixed A single name as a string or a list of names as an array.
  78. * @link http://book.cakephp.org/2.0/en/controllers.html#components-helpers-and-uses
  79. */
  80. public $uses = true;
  81. /**
  82. * An array containing the names of helpers this controller uses. The array elements should
  83. * not contain the "Helper" part of the classname.
  84. *
  85. * Example: `public $helpers = array('Html', 'Javascript', 'Time', 'Ajax');`
  86. *
  87. * @var mixed A single name as a string or a list of names as an array.
  88. * @link http://book.cakephp.org/2.0/en/controllers.html#components-helpers-and-uses
  89. */
  90. public $helpers = array('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::singularize()'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, -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. return $this->loadModel($modelClass);
  326. }
  327. }
  328. }
  329. if ($name === $this->modelClass) {
  330. list($plugin, $class) = pluginSplit($name, true);
  331. if (!$plugin) {
  332. $plugin = $this->plugin ? $this->plugin . '.' : null;
  333. }
  334. return $this->loadModel($plugin . $this->modelClass);
  335. }
  336. return false;
  337. }
  338. /**
  339. * Provides backwards compatibility access to the request object properties.
  340. * Also provides the params alias.
  341. *
  342. * @param string $name
  343. * @return void
  344. */
  345. public function __get($name) {
  346. switch ($name) {
  347. case 'base':
  348. case 'here':
  349. case 'webroot':
  350. case 'data':
  351. return $this->request->{$name};
  352. case 'action':
  353. return isset($this->request->params['action']) ? $this->request->params['action'] : '';
  354. case 'params':
  355. return $this->request;
  356. case 'paginate':
  357. return $this->Components->load('Paginator')->settings;
  358. }
  359. if (isset($this->{$name})) {
  360. return $this->{$name};
  361. }
  362. return null;
  363. }
  364. /**
  365. * Provides backwards compatibility access for setting values to the request object.
  366. *
  367. * @param string $name
  368. * @param mixed $value
  369. * @return void
  370. */
  371. public function __set($name, $value) {
  372. switch ($name) {
  373. case 'base':
  374. case 'here':
  375. case 'webroot':
  376. case 'data':
  377. return $this->request->{$name} = $value;
  378. case 'action':
  379. return $this->request->params['action'] = $value;
  380. case 'params':
  381. return $this->request->params = $value;
  382. case 'paginate':
  383. return $this->Components->load('Paginator')->settings = $value;
  384. }
  385. return $this->{$name} = $value;
  386. }
  387. /**
  388. * Sets the request objects and configures a number of controller properties
  389. * based on the contents of the request. The properties that get set are
  390. *
  391. * - $this->request - To the $request parameter
  392. * - $this->plugin - To the $request->params['plugin']
  393. * - $this->view - To the $request->params['action']
  394. * - $this->autoLayout - To the false if $request->params['bare']; is set.
  395. * - $this->autoRender - To false if $request->params['return'] == 1
  396. * - $this->passedArgs - The the combined results of params['named'] and params['pass]
  397. *
  398. * @param CakeRequest $request
  399. * @return void
  400. */
  401. public function setRequest(CakeRequest $request) {
  402. $this->request = $request;
  403. $this->plugin = isset($request->params['plugin']) ? Inflector::camelize($request->params['plugin']) : null;
  404. $this->view = isset($request->params['action']) ? $request->params['action'] : null;
  405. if (isset($request->params['pass']) && isset($request->params['named'])) {
  406. $this->passedArgs = array_merge($request->params['pass'], $request->params['named']);
  407. }
  408. if (array_key_exists('return', $request->params) && $request->params['return'] == 1) {
  409. $this->autoRender = false;
  410. }
  411. if (!empty($request->params['bare'])) {
  412. $this->autoLayout = false;
  413. }
  414. }
  415. /**
  416. * Dispatches the controller action. Checks that the action
  417. * exists and isn't private.
  418. *
  419. * @param CakeRequest $request
  420. * @return mixed The resulting response.
  421. * @throws PrivateActionException When actions are not public or prefixed by _
  422. * @throws MissingActionException When actions are not defined and scaffolding is
  423. * not enabled.
  424. */
  425. public function invokeAction(CakeRequest $request) {
  426. try {
  427. $method = new ReflectionMethod($this, $request->params['action']);
  428. if ($this->_isPrivateAction($method, $request)) {
  429. throw new PrivateActionException(array(
  430. 'controller' => $this->name . "Controller",
  431. 'action' => $request->params['action']
  432. ));
  433. }
  434. return $method->invokeArgs($this, $request->params['pass']);
  435. } catch (ReflectionException $e) {
  436. if ($this->scaffold !== false) {
  437. return $this->_getScaffold($request);
  438. }
  439. throw new MissingActionException(array(
  440. 'controller' => $this->name . "Controller",
  441. 'action' => $request->params['action']
  442. ));
  443. }
  444. }
  445. /**
  446. * Check if the request's action is marked as private, with an underscore,
  447. * or if the request is attempting to directly accessing a prefixed action.
  448. *
  449. * @param ReflectionMethod $method The method to be invoked.
  450. * @param CakeRequest $request The request to check.
  451. * @return boolean
  452. */
  453. protected function _isPrivateAction(ReflectionMethod $method, CakeRequest $request) {
  454. $privateAction = (
  455. $method->name[0] === '_' ||
  456. !$method->isPublic() ||
  457. !in_array($method->name, $this->methods)
  458. );
  459. $prefixes = Router::prefixes();
  460. if (!$privateAction && !empty($prefixes)) {
  461. if (empty($request->params['prefix']) && strpos($request->params['action'], '_') > 0) {
  462. list($prefix) = explode('_', $request->params['action']);
  463. $privateAction = in_array($prefix, $prefixes);
  464. }
  465. }
  466. return $privateAction;
  467. }
  468. /**
  469. * Returns a scaffold object to use for dynamically scaffolded controllers.
  470. *
  471. * @param CakeRequest $request
  472. * @return Scaffold
  473. */
  474. protected function _getScaffold(CakeRequest $request) {
  475. return new Scaffold($this, $request);
  476. }
  477. /**
  478. * Merge components, helpers, and uses vars from
  479. * Controller::$_mergeParent and PluginAppController.
  480. *
  481. * @return void
  482. */
  483. protected function _mergeControllerVars() {
  484. $pluginController = $pluginDot = null;
  485. $mergeParent = is_subclass_of($this, $this->_mergeParent);
  486. $pluginVars = array();
  487. $appVars = array();
  488. if (!empty($this->plugin)) {
  489. $pluginController = $this->plugin . 'AppController';
  490. if (!is_subclass_of($this, $pluginController)) {
  491. $pluginController = null;
  492. }
  493. $pluginDot = $this->plugin . '.';
  494. }
  495. if ($pluginController) {
  496. $merge = array('components', 'helpers');
  497. $this->_mergeVars($merge, $pluginController);
  498. }
  499. if ($mergeParent || !empty($pluginController)) {
  500. $appVars = get_class_vars($this->_mergeParent);
  501. $uses = $appVars['uses'];
  502. $merge = array('components', 'helpers');
  503. $this->_mergeVars($merge, $this->_mergeParent, true);
  504. }
  505. if ($this->uses === null) {
  506. $this->uses = false;
  507. }
  508. if ($this->uses === true) {
  509. $this->uses = array($pluginDot . $this->modelClass);
  510. }
  511. if (isset($appVars['uses']) && $appVars['uses'] === $this->uses) {
  512. array_unshift($this->uses, $pluginDot . $this->modelClass);
  513. }
  514. if ($pluginController) {
  515. $pluginVars = get_class_vars($pluginController);
  516. }
  517. if ($this->uses !== false) {
  518. $this->_mergeUses($pluginVars);
  519. $this->_mergeUses($appVars);
  520. } else {
  521. $this->uses = array();
  522. $this->modelClass = '';
  523. }
  524. }
  525. /**
  526. * Helper method for merging the $uses property together.
  527. *
  528. * Merges the elements not already in $this->uses into
  529. * $this->uses.
  530. *
  531. * @param mixed $merge The data to merge in.
  532. * @return void
  533. */
  534. protected function _mergeUses($merge) {
  535. if (!isset($merge['uses'])) {
  536. return;
  537. }
  538. if ($merge['uses'] === true) {
  539. return;
  540. }
  541. $this->uses = array_merge(
  542. $this->uses,
  543. array_diff($merge['uses'], $this->uses)
  544. );
  545. }
  546. /**
  547. * Returns a list of all events that will fire in the controller during it's lifecycle.
  548. * You can override this function to add you own listener callbacks
  549. *
  550. * @return array
  551. */
  552. public function implementedEvents() {
  553. return array(
  554. 'Controller.initialize' => 'beforeFilter',
  555. 'Controller.beforeRender' => 'beforeRender',
  556. 'Controller.beforeRedirect' => array('callable' => 'beforeRedirect', 'passParams' => true),
  557. 'Controller.shutdown' => 'afterFilter'
  558. );
  559. }
  560. /**
  561. * Loads Model classes based on the uses property
  562. * see Controller::loadModel(); for more info.
  563. * Loads Components and prepares them for initialization.
  564. *
  565. * @return mixed true if models found and instance created.
  566. * @see Controller::loadModel()
  567. * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::constructClasses
  568. * @throws MissingModelException
  569. */
  570. public function constructClasses() {
  571. $this->_mergeControllerVars();
  572. $this->Components->init($this);
  573. if ($this->uses) {
  574. $this->uses = (array)$this->uses;
  575. list(, $this->modelClass) = pluginSplit(current($this->uses));
  576. }
  577. return true;
  578. }
  579. /**
  580. * Returns the CakeEventManager manager instance that is handling any callbacks.
  581. * You can use this instance to register any new listeners or callbacks to the
  582. * controller events, or create your own events and trigger them at will.
  583. *
  584. * @return CakeEventManager
  585. */
  586. public function getEventManager() {
  587. if (empty($this->_eventManager)) {
  588. $this->_eventManager = new CakeEventManager();
  589. $this->_eventManager->attach($this->Components);
  590. $this->_eventManager->attach($this);
  591. }
  592. return $this->_eventManager;
  593. }
  594. /**
  595. * Perform the startup process for this controller.
  596. * Fire the Components and Controller callbacks in the correct order.
  597. *
  598. * - Initializes components, which fires their `initialize` callback
  599. * - Calls the controller `beforeFilter`.
  600. * - triggers Component `startup` methods.
  601. *
  602. * @return void
  603. */
  604. public function startupProcess() {
  605. $this->getEventManager()->dispatch(new CakeEvent('Controller.initialize', $this));
  606. $this->getEventManager()->dispatch(new CakeEvent('Controller.startup', $this));
  607. }
  608. /**
  609. * Perform the various shutdown processes for this controller.
  610. * Fire the Components and Controller callbacks in the correct order.
  611. *
  612. * - triggers the component `shutdown` callback.
  613. * - calls the Controller's `afterFilter` method.
  614. *
  615. * @return void
  616. */
  617. public function shutdownProcess() {
  618. $this->getEventManager()->dispatch(new CakeEvent('Controller.shutdown', $this));
  619. }
  620. /**
  621. * Queries & sets valid HTTP response codes & messages.
  622. *
  623. * @param mixed $code If $code is an integer, then the corresponding code/message is
  624. * returned if it exists, null if it does not exist. If $code is an array,
  625. * then the 'code' and 'message' keys of each nested array are added to the default
  626. * HTTP codes. Example:
  627. *
  628. * httpCodes(404); // returns array(404 => 'Not Found')
  629. *
  630. * httpCodes(array(
  631. * 701 => 'Unicorn Moved',
  632. * 800 => 'Unexpected Minotaur'
  633. * )); // sets these new values, and returns true
  634. *
  635. * @return mixed Associative array of the HTTP codes as keys, and the message
  636. * strings as values, or null of the given $code does not exist.
  637. * @deprecated Use CakeResponse::httpCodes();
  638. */
  639. public function httpCodes($code = null) {
  640. return $this->response->httpCodes($code);
  641. }
  642. /**
  643. * Loads and instantiates models required by this controller.
  644. * If the model is non existent, it will throw a missing database table error, as Cake generates
  645. * dynamic models for the time being.
  646. *
  647. * @param string $modelClass Name of model class to load
  648. * @param mixed $id Initial ID the instanced model class should have
  649. * @return mixed true when single model found and instance created, error returned if model not found.
  650. * @throws MissingModelException if the model class cannot be found.
  651. */
  652. public function loadModel($modelClass = null, $id = null) {
  653. if ($modelClass === null) {
  654. $modelClass = $this->modelClass;
  655. }
  656. $this->uses = ($this->uses) ? (array)$this->uses : array();
  657. if (!in_array($modelClass, $this->uses)) {
  658. $this->uses[] = $modelClass;
  659. }
  660. list($plugin, $modelClass) = pluginSplit($modelClass, true);
  661. $this->{$modelClass} = ClassRegistry::init(array(
  662. 'class' => $plugin . $modelClass, 'alias' => $modelClass, 'id' => $id
  663. ));
  664. if (!$this->{$modelClass}) {
  665. throw new MissingModelException($modelClass);
  666. }
  667. return true;
  668. }
  669. /**
  670. * Redirects to given $url, after turning off $this->autoRender.
  671. * Script execution is halted after the redirect.
  672. *
  673. * @param mixed $url A string or array-based URL pointing to another location within the app,
  674. * or an absolute URL
  675. * @param integer $status Optional HTTP status code (eg: 404)
  676. * @param boolean $exit If true, exit() will be called after the redirect
  677. * @return mixed void if $exit = false. Terminates script if $exit = true
  678. * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::redirect
  679. */
  680. public function redirect($url, $status = null, $exit = true) {
  681. $this->autoRender = false;
  682. if (is_array($status)) {
  683. extract($status, EXTR_OVERWRITE);
  684. }
  685. $event = new CakeEvent('Controller.beforeRedirect', $this, array($url, $status, $exit));
  686. //TODO: Remove the following line when the events are fully migrated to the CakeEventManager
  687. list($event->break, $event->breakOn, $event->collectReturn) = array(true, false, true);
  688. $this->getEventManager()->dispatch($event);
  689. if ($event->isStopped()) {
  690. return;
  691. }
  692. $response = $event->result;
  693. extract($this->_parseBeforeRedirect($response, $url, $status, $exit), EXTR_OVERWRITE);
  694. if (function_exists('session_write_close')) {
  695. session_write_close();
  696. }
  697. if (!empty($status) && is_string($status)) {
  698. $codes = array_flip($this->response->httpCodes());
  699. if (isset($codes[$status])) {
  700. $status = $codes[$status];
  701. }
  702. }
  703. if ($url !== null) {
  704. $this->response->header('Location', Router::url($url, true));
  705. }
  706. if (!empty($status) && ($status >= 300 && $status < 400)) {
  707. $this->response->statusCode($status);
  708. }
  709. if ($exit) {
  710. $this->response->send();
  711. $this->_stop();
  712. }
  713. }
  714. /**
  715. * Parse beforeRedirect Response
  716. *
  717. * @param mixed $response Response from beforeRedirect callback
  718. * @param mixed $url The same value of beforeRedirect
  719. * @param integer $status The same value of beforeRedirect
  720. * @param boolean $exit The same value of beforeRedirect
  721. * @return array Array with keys url, status and exit
  722. */
  723. protected function _parseBeforeRedirect($response, $url, $status, $exit) {
  724. if (is_array($response)) {
  725. foreach ($response as $resp) {
  726. if (is_array($resp) && isset($resp['url'])) {
  727. extract($resp, EXTR_OVERWRITE);
  728. } elseif ($resp !== null) {
  729. $url = $resp;
  730. }
  731. }
  732. }
  733. return compact('url', 'status', 'exit');
  734. }
  735. /**
  736. * Convenience and object wrapper method for CakeResponse::header().
  737. *
  738. * @param string $status The header message that is being set.
  739. * @return void
  740. * @deprecated Use CakeResponse::header()
  741. */
  742. public function header($status) {
  743. $this->response->header($status);
  744. }
  745. /**
  746. * Saves a variable for use inside a view template.
  747. *
  748. * @param mixed $one A string or an array of data.
  749. * @param mixed $two Value in case $one is a string (which then works as the key).
  750. * Unused if $one is an associative array, otherwise serves as the values to $one's keys.
  751. * @return void
  752. * @link http://book.cakephp.org/2.0/en/controllers.html#interacting-with-views
  753. */
  754. public function set($one, $two = null) {
  755. if (is_array($one)) {
  756. if (is_array($two)) {
  757. $data = array_combine($one, $two);
  758. } else {
  759. $data = $one;
  760. }
  761. } else {
  762. $data = array($one => $two);
  763. }
  764. $this->viewVars = $data + $this->viewVars;
  765. }
  766. /**
  767. * Internally redirects one action to another. Does not perform another HTTP request unlike Controller::redirect()
  768. *
  769. * Examples:
  770. *
  771. * {{{
  772. * setAction('another_action');
  773. * setAction('action_with_parameters', $parameter1);
  774. * }}}
  775. *
  776. * @param string $action The new action to be 'redirected' to
  777. * @param mixed Any other parameters passed to this method will be passed as
  778. * 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. $viewClass = $this->viewClass;
  846. if ($this->viewClass != 'View') {
  847. list($plugin, $viewClass) = pluginSplit($viewClass, true);
  848. $viewClass = $viewClass . 'View';
  849. App::uses($viewClass, $plugin . 'View');
  850. }
  851. $View = new $viewClass($this);
  852. $models = ClassRegistry::keys();
  853. foreach ($models as $currentModel) {
  854. $currentObject = ClassRegistry::getObject($currentModel);
  855. if (is_a($currentObject, 'Model')) {
  856. $className = get_class($currentObject);
  857. list($plugin) = pluginSplit(App::location($className));
  858. $this->request->params['models'][$currentObject->alias] = compact('plugin', 'className');
  859. $View->validationErrors[$currentObject->alias] =& $currentObject->validationErrors;
  860. }
  861. }
  862. $this->autoRender = false;
  863. $this->View = $View;
  864. $this->response->body($View->render($view, $layout));
  865. return $this->response;
  866. }
  867. /**
  868. * Returns the referring URL for this request.
  869. *
  870. * @param string $default Default URL to use if HTTP_REFERER cannot be read from headers
  871. * @param boolean $local If true, restrict referring URLs to local server
  872. * @return string Referring URL
  873. * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::referer
  874. */
  875. public function referer($default = null, $local = false) {
  876. if ($this->request) {
  877. $referer = $this->request->referer($local);
  878. if ($referer == '/' && $default != null) {
  879. return Router::url($default, true);
  880. }
  881. return $referer;
  882. }
  883. return '/';
  884. }
  885. /**
  886. * Forces the user's browser not to cache the results of the current request.
  887. *
  888. * @return void
  889. * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::disableCache
  890. * @deprecated Use CakeResponse::disableCache()
  891. */
  892. public function disableCache() {
  893. $this->response->disableCache();
  894. }
  895. /**
  896. * Shows a message to the user for $pause seconds, then redirects to $url.
  897. * Uses flash.ctp as the default layout for the message.
  898. * Does not work if the current debug level is higher than 0.
  899. *
  900. * @param string $message Message to display to the user
  901. * @param mixed $url Relative string or array-based URL to redirect to after the time expires
  902. * @param integer $pause Time to show the message
  903. * @param string $layout Layout you want to use, defaults to 'flash'
  904. * @return void Renders flash layout
  905. * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::flash
  906. */
  907. public function flash($message, $url, $pause = 1, $layout = 'flash') {
  908. $this->autoRender = false;
  909. $this->set('url', Router::url($url));
  910. $this->set('message', $message);
  911. $this->set('pause', $pause);
  912. $this->set('page_title', $message);
  913. $this->render(false, $layout);
  914. }
  915. /**
  916. * Converts POST'ed form data to a model conditions array, suitable for use in a Model::find() call.
  917. *
  918. * @param array $data POST'ed data organized by model and field
  919. * @param mixed $op A string containing an SQL comparison operator, or an array matching operators
  920. * to fields
  921. * @param string $bool SQL boolean operator: AND, OR, XOR, etc.
  922. * @param boolean $exclusive If true, and $op is an array, fields not included in $op will not be
  923. * included in the returned conditions
  924. * @return array An array of model conditions
  925. * @deprecated
  926. */
  927. public function postConditions($data = array(), $op = null, $bool = 'AND', $exclusive = false) {
  928. if (!is_array($data) || empty($data)) {
  929. if (!empty($this->request->data)) {
  930. $data = $this->request->data;
  931. } else {
  932. return null;
  933. }
  934. }
  935. $cond = array();
  936. if ($op === null) {
  937. $op = '';
  938. }
  939. $arrayOp = is_array($op);
  940. foreach ($data as $model => $fields) {
  941. foreach ($fields as $field => $value) {
  942. $key = $model . '.' . $field;
  943. $fieldOp = $op;
  944. if ($arrayOp) {
  945. if (array_key_exists($key, $op)) {
  946. $fieldOp = $op[$key];
  947. } elseif (array_key_exists($field, $op)) {
  948. $fieldOp = $op[$field];
  949. } else {
  950. $fieldOp = false;
  951. }
  952. }
  953. if ($exclusive && $fieldOp === false) {
  954. continue;
  955. }
  956. $fieldOp = strtoupper(trim($fieldOp));
  957. if ($fieldOp === 'LIKE') {
  958. $key = $key . ' LIKE';
  959. $value = '%' . $value . '%';
  960. } elseif ($fieldOp && $fieldOp != '=') {
  961. $key = $key . ' ' . $fieldOp;
  962. }
  963. $cond[$key] = $value;
  964. }
  965. }
  966. if ($bool != null && strtoupper($bool) != 'AND') {
  967. $cond = array($bool => $cond);
  968. }
  969. return $cond;
  970. }
  971. /**
  972. * Handles automatic pagination of model records.
  973. *
  974. * @param mixed $object Model to paginate (e.g: model instance, or 'Model', or 'Model.InnerModel')
  975. * @param mixed $scope Conditions to use while paginating
  976. * @param array $whitelist List of allowed options for paging
  977. * @return array Model query results
  978. * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::paginate
  979. * @deprecated Use PaginatorComponent instead
  980. */
  981. public function paginate($object = null, $scope = array(), $whitelist = array()) {
  982. return $this->Components->load('Paginator', $this->paginate)->paginate($object, $scope, $whitelist);
  983. }
  984. /**
  985. * Called before the controller action. You can use this method to configure and customize components
  986. * or perform logic that needs to happen before each controller action.
  987. *
  988. * @return void
  989. * @link http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks
  990. */
  991. public function beforeFilter() {
  992. }
  993. /**
  994. * Called after the controller action is run, but before the view is rendered. You can use this method
  995. * to perform logic or set view variables that are required on every request.
  996. *
  997. * @return void
  998. * @link http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks
  999. */
  1000. public function beforeRender() {
  1001. }
  1002. /**
  1003. * The beforeRedirect method is invoked when the controller's redirect method is called but before any
  1004. * further action. If this method returns false the controller will not continue on to redirect the request.
  1005. * The $url, $status and $exit variables have same meaning as for the controller's method. You can also
  1006. * return a string which will be interpreted as the url to redirect to or return associative array with
  1007. * key 'url' and optionally 'status' and 'exit'.
  1008. *
  1009. * @param mixed $url A string or array-based URL pointing to another location within the app,
  1010. * or an absolute URL
  1011. * @param integer $status Optional HTTP status code (eg: 404)
  1012. * @param boolean $exit If true, exit() will be called after the redirect
  1013. * @return mixed
  1014. * false to stop redirection event,
  1015. * string controllers a new redirection url or
  1016. * array with the keys url, status and exit to be used by the redirect method.
  1017. * @link http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks
  1018. */
  1019. public function beforeRedirect($url, $status = null, $exit = true) {
  1020. }
  1021. /**
  1022. * Called after the controller action is run and rendered.
  1023. *
  1024. * @return void
  1025. * @link http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks
  1026. */
  1027. public function afterFilter() {
  1028. }
  1029. /**
  1030. * This method should be overridden in child classes.
  1031. *
  1032. * @param string $method name of method called example index, edit, etc.
  1033. * @return boolean Success
  1034. * @link http://book.cakephp.org/2.0/en/controllers.html#callbacks
  1035. */
  1036. public function beforeScaffold($method) {
  1037. return true;
  1038. }
  1039. /**
  1040. * Alias to beforeScaffold()
  1041. *
  1042. * @param string $method
  1043. * @return boolean
  1044. * @see Controller::beforeScaffold()
  1045. * @deprecated
  1046. */
  1047. protected function _beforeScaffold($method) {
  1048. return $this->beforeScaffold($method);
  1049. }
  1050. /**
  1051. * This method should be overridden in child classes.
  1052. *
  1053. * @param string $method name of method called either edit or update.
  1054. * @return boolean Success
  1055. * @link http://book.cakephp.org/2.0/en/controllers.html#callbacks
  1056. */
  1057. public function afterScaffoldSave($method) {
  1058. return true;
  1059. }
  1060. /**
  1061. * Alias to afterScaffoldSave()
  1062. *
  1063. * @param string $method
  1064. * @return boolean
  1065. * @see Controller::afterScaffoldSave()
  1066. * @deprecated
  1067. */
  1068. protected function _afterScaffoldSave($method) {
  1069. return $this->afterScaffoldSave($method);
  1070. }
  1071. /**
  1072. * This method should be overridden in child classes.
  1073. *
  1074. * @param string $method name of method called either edit or update.
  1075. * @return boolean Success
  1076. * @link http://book.cakephp.org/2.0/en/controllers.html#callbacks
  1077. */
  1078. public function afterScaffoldSaveError($method) {
  1079. return true;
  1080. }
  1081. /**
  1082. * Alias to afterScaffoldSaveError()
  1083. *
  1084. * @param string $method
  1085. * @return boolean
  1086. * @see Controller::afterScaffoldSaveError()
  1087. * @deprecated
  1088. */
  1089. protected function _afterScaffoldSaveError($method) {
  1090. return $this->afterScaffoldSaveError($method);
  1091. }
  1092. /**
  1093. * This method should be overridden in child classes.
  1094. * If not it will render a scaffold error.
  1095. * Method MUST return true in child classes
  1096. *
  1097. * @param string $method name of method called example index, edit, etc.
  1098. * @return boolean Success
  1099. * @link http://book.cakephp.org/2.0/en/controllers.html#callbacks
  1100. */
  1101. public function scaffoldError($method) {
  1102. return false;
  1103. }
  1104. /**
  1105. * Alias to scaffoldError()
  1106. *
  1107. * @param string $method
  1108. * @return boolean
  1109. * @see Controller::scaffoldError()
  1110. * @deprecated
  1111. */
  1112. protected function _scaffoldError($method) {
  1113. return $this->scaffoldError($method);
  1114. }
  1115. }