Controller.php 34 KB

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