PageRenderTime 72ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/Cake/Controller/Controller.php

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