Controller.php 32 KB

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