PageRenderTime 61ms CodeModel.GetById 20ms RepoModel.GetById 13ms app.codeStats 0ms

/lib/Cake/Controller/Controller.php

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