PageRenderTime 53ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/cake/libs/controller/controller.php

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