Controller.php 32 KB

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