PageRenderTime 44ms CodeModel.GetById 13ms RepoModel.GetById 1ms app.codeStats 0ms

/cake/libs/controller/controller.php

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