controller.php 33 KB

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