Controller.php 34 KB

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