PageRenderTime 54ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/cake/libs/controller/controller.php

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