Controller.php 36 KB

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