PageRenderTime 72ms CodeModel.GetById 39ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/Cake/Controller/Controller.php

https://bitbucket.org/udeshika/fake_twitter
PHP | 1169 lines | 483 code | 110 blank | 576 comment | 97 complexity | 47ebafeb56544419d41b7217445e4a89 MD5 | raw file
  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/2.0/en/controllers.html
  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/2.0/en/controllers.html#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/2.0/en/controllers.html#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/2.0/en/controllers.html#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. */
  132. public $view = null;
  133. /**
  134. * The name of the layout file to render the view inside of. The name specified
  135. * is the filename of the layout in /app/View/Layouts without the .ctp
  136. * extension.
  137. *
  138. * @var string
  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 ComponentCollection
  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. * Holds all params passed and named.
  217. *
  218. * @var mixed
  219. */
  220. public $passedArgs = array();
  221. /**
  222. * Triggers Scaffolding
  223. *
  224. * @var mixed
  225. * @link http://book.cakephp.org/view/1103/Scaffolding
  226. */
  227. public $scaffold = false;
  228. /**
  229. * Holds current methods of the controller. This is a list of all the methods reachable
  230. * via url. Modifying this array, will allow you to change which methods can be reached.
  231. *
  232. * @var array
  233. */
  234. public $methods = array();
  235. /**
  236. * This controller's primary model class name, the Inflector::classify()'ed version of
  237. * the controller's $name property.
  238. *
  239. * Example: For a controller named 'Comments', the modelClass would be 'Comment'
  240. *
  241. * @var string
  242. */
  243. public $modelClass = null;
  244. /**
  245. * This controller's model key name, an underscored version of the controller's $modelClass property.
  246. *
  247. * Example: For a controller named 'ArticleComments', the modelKey would be 'article_comment'
  248. *
  249. * @var string
  250. */
  251. public $modelKey = null;
  252. /**
  253. * Holds any validation errors produced by the last call of the validateErrors() method/
  254. *
  255. * @var array Validation errors, or false if none
  256. */
  257. public $validationErrors = null;
  258. /**
  259. * The class name of the parent class you wish to merge with.
  260. * Typically this is AppController, but you may wish to merge vars with a different
  261. * parent class.
  262. *
  263. * @var string
  264. */
  265. protected $_mergeParent = 'AppController';
  266. /**
  267. * Constructor.
  268. *
  269. * @param CakeRequest $request Request object for this controller. Can be null for testing,
  270. * but expect that features that use the request parameters will not work.
  271. * @param CakeResponse $response Response object for this controller.
  272. */
  273. public function __construct($request = null, $response = null) {
  274. if ($this->name === null) {
  275. $this->name = substr(get_class($this), 0, strlen(get_class($this)) -10);
  276. }
  277. if ($this->viewPath == null) {
  278. $this->viewPath = $this->name;
  279. }
  280. $this->modelClass = Inflector::singularize($this->name);
  281. $this->modelKey = Inflector::underscore($this->modelClass);
  282. $this->Components = new ComponentCollection();
  283. $childMethods = get_class_methods($this);
  284. $parentMethods = get_class_methods('Controller');
  285. $this->methods = array_diff($childMethods, $parentMethods);
  286. if ($request instanceof CakeRequest) {
  287. $this->setRequest($request);
  288. }
  289. if ($response instanceof CakeResponse) {
  290. $this->response = $response;
  291. }
  292. parent::__construct();
  293. }
  294. /**
  295. * Provides backwards compatibility to avoid problems with empty and isset to alias properties.
  296. * Lazy loads models using the loadModel() method if declared in $uses
  297. *
  298. * @param string $name
  299. * @return void
  300. */
  301. public function __isset($name) {
  302. switch ($name) {
  303. case 'base':
  304. case 'here':
  305. case 'webroot':
  306. case 'data':
  307. case 'action':
  308. case 'params':
  309. return true;
  310. }
  311. if (is_array($this->uses)) {
  312. foreach ($this->uses as $modelClass) {
  313. list($plugin, $class) = pluginSplit($modelClass, true);
  314. if ($name === $class) {
  315. if (!$plugin) {
  316. $plugin = $this->plugin ? $this->plugin . '.' : null;
  317. }
  318. return $this->loadModel($modelClass);
  319. }
  320. }
  321. }
  322. if ($name === $this->modelClass) {
  323. list($plugin, $class) = pluginSplit($name, true);
  324. if (!$plugin) {
  325. $plugin = $this->plugin ? $this->plugin . '.' : null;
  326. }
  327. return $this->loadModel($plugin . $this->modelClass);
  328. }
  329. return false;
  330. }
  331. /**
  332. * Provides backwards compatibility access to the request object properties.
  333. * Also provides the params alias.
  334. *
  335. * @param string $name
  336. * @return void
  337. */
  338. public function __get($name) {
  339. switch ($name) {
  340. case 'base':
  341. case 'here':
  342. case 'webroot':
  343. case 'data':
  344. return $this->request->{$name};
  345. case 'action':
  346. return isset($this->request->params['action']) ? $this->request->params['action'] : '';
  347. case 'params':
  348. return $this->request;
  349. case 'paginate':
  350. return $this->Components->load('Paginator')->settings;
  351. }
  352. if (isset($this->{$name})) {
  353. return $this->{$name};
  354. }
  355. return null;
  356. }
  357. /**
  358. * Provides backwards compatibility access for setting values to the request object.
  359. *
  360. * @param string $name
  361. * @param mixed $value
  362. * @return void
  363. */
  364. public function __set($name, $value) {
  365. switch ($name) {
  366. case 'base':
  367. case 'here':
  368. case 'webroot':
  369. case 'data':
  370. return $this->request->{$name} = $value;
  371. case 'action':
  372. return $this->request->params['action'] = $value;
  373. case 'params':
  374. return $this->request->params = $value;
  375. case 'paginate':
  376. return $this->Components->load('Paginator')->settings = $value;
  377. }
  378. return $this->{$name} = $value;
  379. }
  380. /**
  381. * Sets the request objects and configures a number of controller properties
  382. * based on the contents of the request. The properties that get set are
  383. *
  384. * - $this->request - To the $request parameter
  385. * - $this->plugin - To the $request->params['plugin']
  386. * - $this->view - To the $request->params['action']
  387. * - $this->autoLayout - To the false if $request->params['bare']; is set.
  388. * - $this->autoRender - To false if $request->params['return'] == 1
  389. * - $this->passedArgs - The the combined results of params['named'] and params['pass]
  390. *
  391. * @param CakeRequest $request
  392. * @return void
  393. */
  394. public function setRequest(CakeRequest $request) {
  395. $this->request = $request;
  396. $this->plugin = isset($request->params['plugin']) ? Inflector::camelize($request->params['plugin']) : null;
  397. $this->view = isset($request->params['action']) ? $request->params['action'] : null;
  398. if (isset($request->params['pass']) && isset($request->params['named'])) {
  399. $this->passedArgs = array_merge($request->params['pass'], $request->params['named']);
  400. }
  401. if (array_key_exists('return', $request->params) && $request->params['return'] == 1) {
  402. $this->autoRender = false;
  403. }
  404. if (!empty($request->params['bare'])) {
  405. $this->autoLayout = false;
  406. }
  407. }
  408. /**
  409. * Dispatches the controller action. Checks that the action
  410. * exists and isn't private.
  411. *
  412. * @param CakeRequest $request
  413. * @return mixed The resulting response.
  414. * @throws PrivateActionException, MissingActionException
  415. */
  416. public function invokeAction(CakeRequest $request) {
  417. try {
  418. $method = new ReflectionMethod($this, $request->params['action']);
  419. if ($this->_isPrivateAction($method, $request)) {
  420. throw new PrivateActionException(array(
  421. 'controller' => $this->name . "Controller",
  422. 'action' => $request->params['action']
  423. ));
  424. }
  425. return $method->invokeArgs($this, $request->params['pass']);
  426. } catch (ReflectionException $e) {
  427. if ($this->scaffold !== false) {
  428. return $this->_getScaffold($request);
  429. }
  430. throw new MissingActionException(array(
  431. 'controller' => $this->name . "Controller",
  432. 'action' => $request->params['action']
  433. ));
  434. }
  435. }
  436. /**
  437. * Check if the request's action is marked as private, with an underscore,
  438. * or if the request is attempting to directly accessing a prefixed action.
  439. *
  440. * @param ReflectionMethod $method The method to be invoked.
  441. * @param CakeRequest $request The request to check.
  442. * @return boolean
  443. */
  444. protected function _isPrivateAction(ReflectionMethod $method, CakeRequest $request) {
  445. $privateAction = (
  446. $method->name[0] === '_' ||
  447. !$method->isPublic() ||
  448. !in_array($method->name, $this->methods)
  449. );
  450. $prefixes = Router::prefixes();
  451. if (!$privateAction && !empty($prefixes)) {
  452. if (empty($request->params['prefix']) && strpos($request->params['action'], '_') > 0) {
  453. list($prefix) = explode('_', $request->params['action']);
  454. $privateAction = in_array($prefix, $prefixes);
  455. }
  456. }
  457. return $privateAction;
  458. }
  459. /**
  460. * Returns a scaffold object to use for dynamically scaffolded controllers.
  461. *
  462. * @param CakeRequest $request
  463. * @return Scaffold
  464. */
  465. protected function _getScaffold(CakeRequest $request) {
  466. return new Scaffold($this, $request);
  467. }
  468. /**
  469. * Merge components, helpers, and uses vars from Controller::$_mergeParent and PluginAppController.
  470. *
  471. * @return void
  472. */
  473. protected function _mergeControllerVars() {
  474. $pluginController = $pluginDot = null;
  475. if (!empty($this->plugin)) {
  476. $pluginController = $this->plugin . 'AppController';
  477. if (!is_subclass_of($this, $pluginController)) {
  478. $pluginController = null;
  479. }
  480. $pluginDot = $this->plugin . '.';
  481. }
  482. if ($pluginController && $this->plugin != null) {
  483. $merge = array('components', 'helpers');
  484. $appVars = get_class_vars($pluginController);
  485. if (
  486. ($this->uses !== null || $this->uses !== false) &&
  487. is_array($this->uses) && !empty($appVars['uses'])
  488. ) {
  489. $this->uses = array_merge($this->uses, array_diff($appVars['uses'], $this->uses));
  490. }
  491. $this->_mergeVars($merge, $pluginController);
  492. }
  493. if (is_subclass_of($this, $this->_mergeParent) || !empty($pluginController)) {
  494. $appVars = get_class_vars($this->_mergeParent);
  495. $uses = $appVars['uses'];
  496. $merge = array('components', 'helpers');
  497. if ($uses == $this->uses && !empty($this->uses)) {
  498. if (!in_array($pluginDot . $this->modelClass, $this->uses)) {
  499. array_unshift($this->uses, $pluginDot . $this->modelClass);
  500. } elseif ($this->uses[0] !== $pluginDot . $this->modelClass) {
  501. $this->uses = array_flip($this->uses);
  502. unset($this->uses[$pluginDot . $this->modelClass]);
  503. $this->uses = array_flip($this->uses);
  504. array_unshift($this->uses, $pluginDot . $this->modelClass);
  505. }
  506. } elseif (
  507. ($this->uses !== null || $this->uses !== false) &&
  508. is_array($this->uses) && !empty($appVars['uses'])
  509. ) {
  510. $this->uses = array_merge($this->uses, array_diff($appVars['uses'], $this->uses));
  511. }
  512. $this->_mergeVars($merge, $this->_mergeParent, true);
  513. }
  514. }
  515. /**
  516. * Loads Model classes based on the uses property
  517. * see Controller::loadModel(); for more info.
  518. * Loads Components and prepares them for initialization.
  519. *
  520. * @return mixed true if models found and instance created.
  521. * @see Controller::loadModel()
  522. * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::constructClasses
  523. * @throws MissingModelException
  524. */
  525. public function constructClasses() {
  526. $this->_mergeControllerVars();
  527. $this->Components->init($this);
  528. if ($this->uses) {
  529. $this->uses = (array) $this->uses;
  530. list(, $this->modelClass) = pluginSplit(current($this->uses));
  531. }
  532. return true;
  533. }
  534. /**
  535. * Perform the startup process for this controller.
  536. * Fire the Components and Controller callbacks in the correct order.
  537. *
  538. * - Initializes components, which fires their `initialize` callback
  539. * - Calls the controller `beforeFilter`.
  540. * - triggers Component `startup` methods.
  541. *
  542. * @return void
  543. */
  544. public function startupProcess() {
  545. $this->Components->trigger('initialize', array(&$this));
  546. $this->beforeFilter();
  547. $this->Components->trigger('startup', array(&$this));
  548. }
  549. /**
  550. * Perform the various shutdown processes for this controller.
  551. * Fire the Components and Controller callbacks in the correct order.
  552. *
  553. * - triggers the component `shutdown` callback.
  554. * - calls the Controller's `afterFilter` method.
  555. *
  556. * @return void
  557. */
  558. public function shutdownProcess() {
  559. $this->Components->trigger('shutdown', array(&$this));
  560. $this->afterFilter();
  561. }
  562. /**
  563. * Queries & sets valid HTTP response codes & messages.
  564. *
  565. * @param mixed $code If $code is an integer, then the corresponding code/message is
  566. * returned if it exists, null if it does not exist. If $code is an array,
  567. * then the 'code' and 'message' keys of each nested array are added to the default
  568. * HTTP codes. Example:
  569. *
  570. * httpCodes(404); // returns array(404 => 'Not Found')
  571. *
  572. * httpCodes(array(
  573. * 701 => 'Unicorn Moved',
  574. * 800 => 'Unexpected Minotaur'
  575. * )); // sets these new values, and returns true
  576. *
  577. * @return mixed Associative array of the HTTP codes as keys, and the message
  578. * strings as values, or null of the given $code does not exist.
  579. * @deprecated Use CakeResponse::httpCodes();
  580. */
  581. public function httpCodes($code = null) {
  582. return $this->response->httpCodes($code);
  583. }
  584. /**
  585. * Loads and instantiates models required by this controller.
  586. * If the model is non existent, it will throw a missing database table error, as Cake generates
  587. * dynamic models for the time being.
  588. *
  589. * @param string $modelClass Name of model class to load
  590. * @param mixed $id Initial ID the instanced model class should have
  591. * @return mixed true when single model found and instance created, error returned if model not found.
  592. * @throws MissingModelException if the model class cannot be found.
  593. */
  594. public function loadModel($modelClass = null, $id = null) {
  595. if ($modelClass === null) {
  596. $modelClass = $this->modelClass;
  597. }
  598. $this->uses = ($this->uses) ? $this->uses : array();
  599. if (!in_array($modelClass, $this->uses)) {
  600. $this->uses[] = $modelClass;
  601. }
  602. list($plugin, $modelClass) = pluginSplit($modelClass, true);
  603. $this->{$modelClass} = ClassRegistry::init(array(
  604. 'class' => $plugin . $modelClass, 'alias' => $modelClass, 'id' => $id
  605. ));
  606. if (!$this->{$modelClass}) {
  607. throw new MissingModelException($modelClass);
  608. }
  609. return true;
  610. }
  611. /**
  612. * Redirects to given $url, after turning off $this->autoRender.
  613. * Script execution is halted after the redirect.
  614. *
  615. * @param mixed $url A string or array-based URL pointing to another location within the app,
  616. * or an absolute URL
  617. * @param integer $status Optional HTTP status code (eg: 404)
  618. * @param boolean $exit If true, exit() will be called after the redirect
  619. * @return mixed void if $exit = false. Terminates script if $exit = true
  620. * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::redirect
  621. */
  622. public function redirect($url, $status = null, $exit = true) {
  623. $this->autoRender = false;
  624. if (is_array($status)) {
  625. extract($status, EXTR_OVERWRITE);
  626. }
  627. $response = $this->Components->trigger(
  628. 'beforeRedirect',
  629. array(&$this, $url, $status, $exit),
  630. array('break' => true, 'breakOn' => false, 'collectReturn' => true)
  631. );
  632. if ($response === false) {
  633. return;
  634. }
  635. extract($this->_parseBeforeRedirect($response, $url, $status, $exit), EXTR_OVERWRITE);
  636. $response = $this->beforeRedirect($url, $status, $exit);
  637. if ($response === false) {
  638. return;
  639. }
  640. extract($this->_parseBeforeRedirect($response, $url, $status, $exit), EXTR_OVERWRITE);
  641. if (function_exists('session_write_close')) {
  642. session_write_close();
  643. }
  644. if (!empty($status) && is_string($status)) {
  645. $codes = array_flip($this->response->httpCodes());
  646. if (isset($codes[$status])) {
  647. $status = $codes[$status];
  648. }
  649. }
  650. if ($url !== null) {
  651. $this->response->header('Location', Router::url($url, true));
  652. }
  653. if (!empty($status) && ($status >= 300 && $status < 400)) {
  654. $this->response->statusCode($status);
  655. }
  656. if ($exit) {
  657. $this->response->send();
  658. $this->_stop();
  659. }
  660. }
  661. /**
  662. * Parse beforeRedirect Response
  663. *
  664. * @param mixed $response Response from beforeRedirect callback
  665. * @param mixed $url The same value of beforeRedirect
  666. * @param integer $status The same value of beforeRedirect
  667. * @param boolean $exit The same value of beforeRedirect
  668. * @return array Array with keys url, status and exit
  669. */
  670. protected function _parseBeforeRedirect($response, $url, $status, $exit) {
  671. if (is_array($response)) {
  672. foreach ($response as $resp) {
  673. if (is_array($resp) && isset($resp['url'])) {
  674. extract($resp, EXTR_OVERWRITE);
  675. } elseif ($resp !== null) {
  676. $url = $resp;
  677. }
  678. }
  679. }
  680. return compact('url', 'status', 'exit');
  681. }
  682. /**
  683. * Convenience and object wrapper method for CakeResponse::header().
  684. *
  685. * @param string $status The header message that is being set.
  686. * @return void
  687. * @deprecated Use CakeResponse::header()
  688. */
  689. public function header($status) {
  690. $this->response->header($status);
  691. }
  692. /**
  693. * Saves a variable for use inside a view template.
  694. *
  695. * @param mixed $one A string or an array of data.
  696. * @param mixed $two Value in case $one is a string (which then works as the key).
  697. * Unused if $one is an associative array, otherwise serves as the values to $one's keys.
  698. * @return void
  699. * @link http://book.cakephp.org/2.0/en/controllers.html#interacting-with-views
  700. */
  701. public function set($one, $two = null) {
  702. if (is_array($one)) {
  703. if (is_array($two)) {
  704. $data = array_combine($one, $two);
  705. } else {
  706. $data = $one;
  707. }
  708. } else {
  709. $data = array($one => $two);
  710. }
  711. $this->viewVars = $data + $this->viewVars;
  712. }
  713. /**
  714. * Internally redirects one action to another. Does not perform another HTTP request unlike Controller::redirect()
  715. *
  716. * Examples:
  717. *
  718. * {{{
  719. * setAction('another_action');
  720. * setAction('action_with_parameters', $parameter1);
  721. * }}}
  722. *
  723. * @param string $action The new action to be 'redirected' to
  724. * @param mixed Any other parameters passed to this method will be passed as
  725. * parameters to the new action.
  726. * @return mixed Returns the return value of the called action
  727. */
  728. public function setAction($action) {
  729. $this->request->action = $action;
  730. $this->view = $action;
  731. $args = func_get_args();
  732. unset($args[0]);
  733. return call_user_func_array(array(&$this, $action), $args);
  734. }
  735. /**
  736. * Returns number of errors in a submitted FORM.
  737. *
  738. * @return integer Number of errors
  739. */
  740. public function validate() {
  741. $args = func_get_args();
  742. $errors = call_user_func_array(array(&$this, 'validateErrors'), $args);
  743. if ($errors === false) {
  744. return 0;
  745. }
  746. return count($errors);
  747. }
  748. /**
  749. * Validates models passed by parameters. Example:
  750. *
  751. * `$errors = $this->validateErrors($this->Article, $this->User);`
  752. *
  753. * @param mixed A list of models as a variable argument
  754. * @return array Validation errors, or false if none
  755. */
  756. public function validateErrors() {
  757. $objects = func_get_args();
  758. if (empty($objects)) {
  759. return false;
  760. }
  761. $errors = array();
  762. foreach ($objects as $object) {
  763. if (isset($this->{$object->alias})) {
  764. $object = $this->{$object->alias};
  765. }
  766. $object->set($object->data);
  767. $errors = array_merge($errors, $object->invalidFields());
  768. }
  769. return $this->validationErrors = (!empty($errors) ? $errors : false);
  770. }
  771. /**
  772. * Instantiates the correct view class, hands it its data, and uses it to render the view output.
  773. *
  774. * @param string $view View to use for rendering
  775. * @param string $layout Layout to use
  776. * @return CakeResponse A response object containing the rendered view.
  777. * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::render
  778. */
  779. public function render($view = null, $layout = null) {
  780. $this->beforeRender();
  781. $this->Components->trigger('beforeRender', array(&$this));
  782. $viewClass = $this->viewClass;
  783. if ($this->viewClass != 'View') {
  784. list($plugin, $viewClass) = pluginSplit($viewClass, true);
  785. $viewClass = $viewClass . 'View';
  786. App::uses($viewClass, $plugin . 'View');
  787. }
  788. $View = new $viewClass($this);
  789. if (!empty($this->uses)) {
  790. foreach ($this->uses as $model) {
  791. list($plugin, $className) = pluginSplit($model);
  792. $this->request->params['models'][$className] = compact('plugin', 'className');
  793. }
  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/2.0/en/controllers.html#Controller::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/2.0/en/controllers.html#Controller::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/2.0/en/controllers.html#Controller::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. * @deprecated
  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/2.0/en/controllers.html#Controller::paginate
  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/2.0/en/controllers.html#request-life-cycle-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/2.0/en/controllers.html#request-life-cycle-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. * @link http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks
  961. */
  962. public function beforeRedirect($url, $status = null, $exit = true) {
  963. return true;
  964. }
  965. /**
  966. * Called after the controller action is run and rendered.
  967. *
  968. * @return void
  969. * @link http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks
  970. */
  971. public function afterFilter() {
  972. }
  973. /**
  974. * This method should be overridden in child classes.
  975. *
  976. * @param string $method name of method called example index, edit, etc.
  977. * @return boolean Success
  978. * @link http://book.cakephp.org/2.0/en/controllers.html#callbacks
  979. */
  980. public function beforeScaffold($method) {
  981. return true;
  982. }
  983. /**
  984. * Alias to beforeScaffold()
  985. *
  986. * @param string $method
  987. * @return boolean
  988. * @see Controller::beforeScaffold()
  989. * @deprecated
  990. */
  991. protected function _beforeScaffold($method) {
  992. return $this->beforeScaffold($method);
  993. }
  994. /**
  995. * This method should be overridden in child classes.
  996. *
  997. * @param string $method name of method called either edit or update.
  998. * @return boolean Success
  999. * @link http://book.cakephp.org/2.0/en/controllers.html#callbacks
  1000. */
  1001. public function afterScaffoldSave($method) {
  1002. return true;
  1003. }
  1004. /**
  1005. * Alias to afterScaffoldSave()
  1006. *
  1007. * @param string $method
  1008. * @return boolean
  1009. * @see Controller::afterScaffoldSave()
  1010. * @deprecated
  1011. */
  1012. protected function _afterScaffoldSave($method) {
  1013. return $this->afterScaffoldSave($method);
  1014. }
  1015. /**
  1016. * This method should be overridden in child classes.
  1017. *
  1018. * @param string $method name of method called either edit or update.
  1019. * @return boolean Success
  1020. * @link http://book.cakephp.org/2.0/en/controllers.html#callbacks
  1021. */
  1022. public function afterScaffoldSaveError($method) {
  1023. return true;
  1024. }
  1025. /**
  1026. * Alias to afterScaffoldSaveError()
  1027. *
  1028. * @param string $method
  1029. * @return boolean
  1030. * @see Controller::afterScaffoldSaveError()
  1031. * @deprecated
  1032. */
  1033. protected function _afterScaffoldSaveError($method) {
  1034. return $this->afterScaffoldSaveError($method);
  1035. }
  1036. /**
  1037. * This method should be overridden in child classes.
  1038. * If not it will render a scaffold error.
  1039. * Method MUST return true in child classes
  1040. *
  1041. * @param string $method name of method called example index, edit, etc.
  1042. * @return boolean Success
  1043. * @link http://book.cakephp.org/2.0/en/controllers.html#callbacks
  1044. */
  1045. public function scaffoldError($method) {
  1046. return false;
  1047. }
  1048. /**
  1049. * Alias to scaffoldError()
  1050. *
  1051. * @param string $method
  1052. * @return boolean
  1053. * @see Controller::scaffoldError()
  1054. * @deprecated
  1055. */
  1056. protected function _scaffoldError($method) {
  1057. return $this->scaffoldError($method);
  1058. }
  1059. }