controller.php 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141
  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. foreach($uses as $modelClass) {
  371. $id = false;
  372. $cached = false;
  373. $object = null;
  374. $modelKey = Inflector::underscore($modelClass);
  375. if(!class_exists($modelClass)){
  376. loadModel($modelClass);
  377. }
  378. if (class_exists($modelClass)) {
  379. if ($this->persistModel === true) {
  380. $cached = $this->_persist($modelClass, null, $object);
  381. }
  382. if (($cached === false)) {
  383. $model =& new $modelClass($id);
  384. $this->modelNames[] = $modelClass;
  385. $this->{$modelClass} =& $model;
  386. if ($this->persistModel === true) {
  387. $this->_persist($modelClass, true, $model);
  388. $registry = ClassRegistry::getInstance();
  389. $this->_persist($modelClass . 'registry', true, $registry->_objects, 'registry');
  390. }
  391. } else {
  392. $this->_persist($modelClass . 'registry', true, $object, 'registry');
  393. $this->_persist($modelClass, true, $object);
  394. $this->modelNames[] = $modelClass;
  395. }
  396. } else {
  397. return $this->cakeError('missingModel', array(array('className' => $modelClass, 'webroot' => '', 'base' => $this->base)));
  398. }
  399. }
  400. return true;
  401. }
  402. }
  403. /**
  404. * Redirects to given $url, after turning off $this->autoRender.
  405. * Please notice that the script execution is not stopped after the redirect.
  406. *
  407. * @param mixed $url A string or array-based URL pointing to another location
  408. * within the app, or an absolute URL
  409. * @param integer $status Optional HTTP status code
  410. * @param boolean $exit If true, exit() will be called after the redirect
  411. * @access public
  412. */
  413. function redirect($url, $status = null, $exit = false) {
  414. $this->autoRender = false;
  415. if (is_array($status)) {
  416. extract($status, EXTR_OVERWRITE);
  417. }
  418. if (function_exists('session_write_close')) {
  419. session_write_close();
  420. }
  421. if (!empty($status)) {
  422. $codes = array(
  423. 100 => "Continue",
  424. 101 => "Switching Protocols",
  425. 200 => "OK",
  426. 201 => "Created",
  427. 202 => "Accepted",
  428. 203 => "Non-Authoritative Information",
  429. 204 => "No Content",
  430. 205 => "Reset Content",
  431. 206 => "Partial Content",
  432. 300 => "Multiple Choices",
  433. 301 => "Moved Permanently",
  434. 302 => "Found",
  435. 303 => "See Other",
  436. 304 => "Not Modified",
  437. 305 => "Use Proxy",
  438. 307 => "Temporary Redirect",
  439. 400 => "Bad Request",
  440. 401 => "Unauthorized",
  441. 402 => "Payment Required",
  442. 403 => "Forbidden",
  443. 404 => "Not Found",
  444. 405 => "Method Not Allowed",
  445. 406 => "Not Acceptable",
  446. 407 => "Proxy Authentication Required",
  447. 408 => "Request Time-out",
  448. 409 => "Conflict",
  449. 410 => "Gone",
  450. 411 => "Length Required",
  451. 412 => "Precondition Failed",
  452. 413 => "Request Entity Too Large",
  453. 414 => "Request-URI Too Large",
  454. 415 => "Unsupported Media Type",
  455. 416 => "Requested range not satisfiable",
  456. 417 => "Expectation Failed",
  457. 500 => "Internal Server Error",
  458. 501 => "Not Implemented",
  459. 502 => "Bad Gateway",
  460. 503 => "Service Unavailable",
  461. 504 => "Gateway Time-out"
  462. );
  463. if (is_string($status)) {
  464. $codes = array_combine(array_values($codes), array_keys($codes));
  465. }
  466. if (isset($codes[$status])) {
  467. $code = ife(is_numeric($status), $status, $codes[$status]);
  468. $msg = ife(is_string($status), $status, $codes[$status]);
  469. $status = "HTTP/1.1 {$code} {$msg}";
  470. } else {
  471. $status = null;
  472. }
  473. }
  474. if (!empty($status)) {
  475. header($status);
  476. }
  477. if ($url !== null) {
  478. header('Location: ' . Router::url($url, true));
  479. }
  480. if (!empty($status)) {
  481. header($status);
  482. }
  483. if ($exit) {
  484. exit();
  485. }
  486. }
  487. /**
  488. * Saves a variable to use inside a template.
  489. *
  490. * @param mixed $one A string or an array of data.
  491. * @param mixed $two Value in case $one is a string (which then works as the key).
  492. * Unused if $one is an associative array, otherwise serves as the values to $one's keys.
  493. * @return void
  494. */
  495. function set($one, $two = null) {
  496. $data = array();
  497. if (is_array($one)) {
  498. if (is_array($two)) {
  499. $data = array_combine($one, $two);
  500. } else {
  501. $data = $one;
  502. }
  503. } else {
  504. $data = array($one => $two);
  505. }
  506. foreach($data as $name => $value) {
  507. if ($name == 'title') {
  508. $this->pageTitle = $value;
  509. } else {
  510. $this->viewVars[$name] = $value;
  511. }
  512. }
  513. }
  514. /**
  515. * Internally redirects one action to another
  516. *
  517. * @param string $action The new action to be redirected to
  518. * @param mixed Any other parameters passed to this method will be passed as
  519. * parameters to the new action.
  520. */
  521. function setAction($action) {
  522. $this->action = $action;
  523. $args = func_get_args();
  524. unset($args[0]);
  525. call_user_func_array(array(&$this, $action), $args);
  526. }
  527. /**
  528. * Returns number of errors in a submitted FORM.
  529. *
  530. * @return int Number of errors
  531. */
  532. function validate() {
  533. $args = func_get_args();
  534. $errors = call_user_func_array(array(&$this, 'validateErrors'), $args);
  535. if ($errors === false) {
  536. return 0;
  537. }
  538. return count($errors);
  539. }
  540. /**
  541. * Validates a FORM according to the rules set up in the Model.
  542. *
  543. * @return int Number of errors
  544. */
  545. function validateErrors() {
  546. $objects = func_get_args();
  547. if (!count($objects)) {
  548. return false;
  549. }
  550. $errors = array();
  551. foreach($objects as $object) {
  552. $this->{$object->name}->set($object->data);
  553. $errors = array_merge($errors, $this->{$object->name}->invalidFields());
  554. }
  555. return $this->validationErrors = (count($errors) ? $errors : false);
  556. }
  557. /**
  558. * Gets an instance of the view object & prepares it for rendering the output, then
  559. * asks the view to actualy do the job.
  560. *
  561. * @param unknown_type $action
  562. * @param unknown_type $layout
  563. * @param unknown_type $file
  564. * @return unknown
  565. */
  566. function render($action = null, $layout = null, $file = null) {
  567. $viewClass = $this->view;
  568. if ($this->view != 'View') {
  569. $viewClass = $this->view . 'View';
  570. loadView($this->view);
  571. }
  572. $this->beforeRender();
  573. $this->params['models'] = $this->modelNames;
  574. $this->__viewClass =& new $viewClass($this);
  575. if (!empty($this->modelNames)) {
  576. $count = count($this->modelNames);
  577. for ($i = 0; $i < $count; $i++) {
  578. $model = $this->modelNames[$i];
  579. if (!empty($this->{$model}->validationErrors)) {
  580. $this->__viewClass->validationErrors[$model] = &$this->{$model}->validationErrors;
  581. }
  582. }
  583. }
  584. $this->autoRender = false;
  585. return $this->__viewClass->render($action, $layout, $file);
  586. }
  587. /**
  588. * Gets the referring URL of this request
  589. *
  590. * @param string $default Default URL to use if HTTP_REFERER cannot be read from headers
  591. * @param boolean $local If true, restrict referring URLs to local server
  592. * @access public
  593. */
  594. function referer($default = null, $local = false) {
  595. $ref = env('HTTP_REFERER');
  596. $base = FULL_BASE_URL . $this->webroot;
  597. if ($ref != null && defined('FULL_BASE_URL')) {
  598. if (strpos($ref, $base) === 0) {
  599. return substr($ref, strlen($base) - 1);
  600. } elseif(!$local) {
  601. return $ref;
  602. }
  603. }
  604. if ($default != null) {
  605. return $default;
  606. } else {
  607. return '/';
  608. }
  609. }
  610. /**
  611. * Tells the browser not to cache the results of the current request
  612. *
  613. * @return void
  614. * @access public
  615. */
  616. function disableCache() {
  617. header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
  618. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  619. header("Cache-Control: no-store, no-cache, must-revalidate");
  620. header("Cache-Control: post-check=0, pre-check=0", false);
  621. header("Pragma: no-cache");
  622. }
  623. /**
  624. * @deprecated
  625. * @see Controller::set
  626. */
  627. function _setTitle($pageTitle) {
  628. trigger_error(__('Deprecated: Use Controller::set("title", "...") instead'), E_USER_WARNING);
  629. $this->pageTitle = $pageTitle;
  630. }
  631. /**
  632. * Shows a message to the user $time seconds, then redirects to $url
  633. * Uses flash.thtml as a layout for the messages
  634. *
  635. * @param string $message Message to display to the user
  636. * @param string $url Relative URL to redirect to after the time expires
  637. * @param int $time Time to show the message
  638. */
  639. function flash($message, $url, $pause = 1) {
  640. $this->autoRender = false;
  641. $this->autoLayout = false;
  642. $this->set('url', Router::url($url));
  643. $this->set('message', $message);
  644. $this->set('pause', $pause);
  645. $this->set('page_title', $message);
  646. if (file_exists(VIEWS . 'layouts' . DS . 'flash.ctp')) {
  647. $flash = VIEWS . 'layouts' . DS . 'flash.ctp';
  648. } elseif (file_exists(VIEWS . 'layouts' . DS . 'flash.thtml')) {
  649. $flash = VIEWS . 'layouts' . DS . 'flash.thtml';
  650. } elseif ($flash = fileExistsInPath(LIBS . 'view' . DS . 'templates' . DS . "layouts" . DS . 'flash.ctp')) {
  651. }
  652. $this->render(null, false, $flash);
  653. }
  654. /**
  655. * This function creates a $fieldNames array for the view to use.
  656. * @todo Map more database field types to html form fields.
  657. * @todo View the database field types from all the supported databases.
  658. *
  659. */
  660. function generateFieldNames($data = null, $doCreateOptions = true) {
  661. $fieldNames = array();
  662. $model = $this->modelClass;
  663. $modelKey = $this->modelKey;
  664. $modelObj =& ClassRegistry::getObject($modelKey);
  665. foreach($modelObj->_tableInfo->value as $column) {
  666. if ($modelObj->isForeignKey($column['name'])) {
  667. foreach($modelObj->belongsTo as $associationName => $assoc) {
  668. if($column['name'] == $assoc['foreignKey']) {
  669. $fkNames = $modelObj->keyToTable[$column['name']];
  670. $fieldNames[$column['name']]['table'] = $fkNames[0];
  671. $fieldNames[$column['name']]['label'] = Inflector::humanize($associationName);
  672. $fieldNames[$column['name']]['prompt'] = $fieldNames[$column['name']]['label'];
  673. $fieldNames[$column['name']]['model'] = Inflector::classify($associationName);
  674. $fieldNames[$column['name']]['modelKey'] = Inflector::underscore($modelObj->tableToModel[$fieldNames[$column['name']]['table']]);
  675. $fieldNames[$column['name']]['controller'] = Inflector::pluralize($fieldNames[$column['name']]['modelKey']);
  676. $fieldNames[$column['name']]['foreignKey'] = true;
  677. break;
  678. }
  679. }
  680. } else {
  681. $fieldNames[$column['name']]['label'] = Inflector::humanize($column['name']);
  682. $fieldNames[$column['name']]['prompt'] = $fieldNames[$column['name']]['label'];
  683. }
  684. $fieldNames[$column['name']]['tagName'] = $model . '/' . $column['name'];
  685. $fieldNames[$column['name']]['name'] = $column['name'];
  686. $fieldNames[$column['name']]['class'] = 'optional';
  687. $validationFields = $modelObj->validate;
  688. if (isset($validationFields[$column['name']])) {
  689. if (VALID_NOT_EMPTY == $validationFields[$column['name']]) {
  690. $fieldNames[$column['name']]['required'] = true;
  691. $fieldNames[$column['name']]['class'] = 'required';
  692. $fieldNames[$column['name']]['error'] = "Required Field";
  693. }
  694. }
  695. $lParenPos = strpos($column['type'], '(');
  696. $rParenPos = strpos($column['type'], ')');
  697. if (false != $lParenPos) {
  698. $type = substr($column['type'], 0, $lParenPos);
  699. $fieldLength = substr($column['type'], $lParenPos + 1, $rParenPos - $lParenPos - 1);
  700. } else {
  701. $type = $column['type'];
  702. }
  703. switch($type) {
  704. case "text":
  705. $fieldNames[$column['name']]['type'] = 'textarea';
  706. $fieldNames[$column['name']]['cols'] = '30';
  707. $fieldNames[$column['name']]['rows'] = '10';
  708. break;
  709. case "string":
  710. if (isset($fieldNames[$column['name']]['foreignKey'])) {
  711. $fieldNames[$column['name']]['type'] = 'select';
  712. $fieldNames[$column['name']]['options'] = array();
  713. $otherModelObj =& ClassRegistry::getObject($fieldNames[$column['name']]['modelKey']);
  714. if (is_object($otherModelObj)) {
  715. if ($doCreateOptions) {
  716. $fieldNames[$column['name']]['options'] = $otherModelObj->generateList();
  717. }
  718. $fieldNames[$column['name']]['selected'] = $data[$model][$column['name']];
  719. }
  720. } else {
  721. $fieldNames[$column['name']]['type'] = 'text';
  722. }
  723. break;
  724. case "boolean":
  725. $fieldNames[$column['name']]['type'] = 'checkbox';
  726. break;
  727. case "integer":
  728. case "float":
  729. if (strcmp($column['name'], $this->$model->primaryKey) == 0) {
  730. $fieldNames[$column['name']]['type'] = 'hidden';
  731. } else if(isset($fieldNames[$column['name']]['foreignKey'])) {
  732. $fieldNames[$column['name']]['type'] = 'select';
  733. $fieldNames[$column['name']]['options'] = array();
  734. $otherModelObj =& ClassRegistry::getObject($fieldNames[$column['name']]['modelKey']);
  735. if (is_object($otherModelObj)) {
  736. if ($doCreateOptions) {
  737. $fieldNames[$column['name']]['options'] = $otherModelObj->generateList();
  738. }
  739. $fieldNames[$column['name']]['selected'] = $data[$model][$column['name']];
  740. }
  741. } else {
  742. $fieldNames[$column['name']]['type'] = 'text';
  743. }
  744. break;
  745. case "enum":
  746. $fieldNames[$column['name']]['type'] = 'select';
  747. $fieldNames[$column['name']]['options'] = array();
  748. $enumValues = split(',', $fieldLength);
  749. foreach($enumValues as $enum) {
  750. $enum = trim($enum, "'");
  751. $fieldNames[$column['name']]['options'][$enum] = $enum;
  752. }
  753. $fieldNames[$column['name']]['selected'] = $data[$model][$column['name']];
  754. break;
  755. case "date":
  756. case "datetime":
  757. case "time":
  758. case "year":
  759. if (0 != strncmp("created", $column['name'], 7) && 0 != strncmp("modified", $column['name'], 8) && 0 != strncmp("updated", $column['name'], 7)) {
  760. $fieldNames[$column['name']]['type'] = $type;
  761. if (isset($data[$model][$column['name']])) {
  762. $fieldNames[$column['name']]['selected'] = $data[$model][$column['name']];
  763. } else {
  764. $fieldNames[$column['name']]['selected'] = null;
  765. }
  766. } else {
  767. unset($fieldNames[$column['name']]);
  768. }
  769. break;
  770. default:
  771. break;
  772. }
  773. }
  774. foreach($modelObj->hasAndBelongsToMany as $associationName => $assocData) {
  775. $otherModelKey = Inflector::underscore($assocData['className']);
  776. $otherModelObj = &ClassRegistry::getObject($otherModelKey);
  777. if ($doCreateOptions) {
  778. $fieldNames[$otherModelKey]['model'] = $associationName;
  779. $fieldNames[$otherModelKey]['label'] = "Related " . Inflector::humanize(Inflector::pluralize($associationName));
  780. $fieldNames[$otherModelKey]['prompt'] = $fieldNames[$otherModelKey]['label'];
  781. $fieldNames[$otherModelKey]['type'] = "select";
  782. $fieldNames[$otherModelKey]['multiple'] = "multiple";
  783. $fieldNames[$otherModelKey]['tagName'] = $associationName . '/' . $associationName;
  784. $fieldNames[$otherModelKey]['name'] = $associationName;
  785. $fieldNames[$otherModelKey]['class'] = 'optional';
  786. $fieldNames[$otherModelKey]['options'] = $otherModelObj->generateList();
  787. if (isset($data[$associationName])) {
  788. $fieldNames[$otherModelKey]['selected'] = $this->_selectedArray($data[$associationName], $otherModelObj->primaryKey);
  789. }
  790. }
  791. }
  792. return $fieldNames;
  793. }
  794. /**
  795. * Converts POST'ed model data to a model conditions array, suitable for a find
  796. * or findAll Model query
  797. *
  798. * @param array $data POST'ed data organized by model and field
  799. * @param mixed $op A string containing an SQL comparison operator, or an array matching operators to fields
  800. * @param string $bool SQL boolean operator: AND, OR, XOR, etc.
  801. * @param boolean $exclusive If true, and $op is an array, fields not included in $op will not be included in the returned conditions
  802. * @return array An array of model conditions
  803. */
  804. function postConditions($data = array(), $op = null, $bool = 'AND', $exclusive = false) {
  805. if ((!is_array($data) || empty($data)) && empty($this->data)) {
  806. return null;
  807. } elseif (!empty($this->data)) {
  808. $data = $this->data;
  809. }
  810. $cond = array();
  811. if ($op === null) {
  812. $op = '';
  813. }
  814. foreach($data as $model => $fields) {
  815. foreach($fields as $field => $value) {
  816. $key = $model . '.' . $field;
  817. if (is_string($op)) {
  818. $cond[$key] = $this->__postConditionMatch($op, $value);
  819. } elseif (is_array($op)) {
  820. $opFields = array_keys($op);
  821. if (in_array($key, $opFields) || in_array($field, $opFields)) {
  822. if (in_array($key, $opFields)) {
  823. $cond[$key] = $this->__postConditionMatch($op[$key], $value);
  824. } else {
  825. $cond[$key] = $this->__postConditionMatch($op[$field], $value);
  826. }
  827. } elseif (!$exclusive) {
  828. $cond[$key] = $this->__postConditionMatch(null, $value);
  829. }
  830. }
  831. }
  832. }
  833. if ($bool != null && up($bool) != 'AND') {
  834. $cond = array($bool => $cond);
  835. }
  836. return $cond;
  837. }
  838. /**
  839. * Private method used by postConditions
  840. *
  841. */
  842. function __postConditionMatch($op, $value) {
  843. if (is_string($op)) {
  844. $op = up(trim($op));
  845. }
  846. switch($op) {
  847. case '':
  848. case '=':
  849. case null:
  850. return $value;
  851. break;
  852. case 'LIKE':
  853. return 'LIKE %' . $value . '%';
  854. break;
  855. default:
  856. return $op . ' ' . $value;
  857. break;
  858. }
  859. }
  860. /**
  861. * Cleans up the date fields of current Model.
  862. *
  863. */
  864. function cleanUpFields($modelClass = null) {
  865. if ($modelClass == null) {
  866. $modelClass = $this->modelClass;
  867. }
  868. foreach($this->{$modelClass}->_tableInfo->value as $field) {
  869. $dateFields = array('Y'=>'_year', 'm'=>'_month', 'd'=>'_day', 'H'=>'_hour', 'i'=>'_min', 's'=>'_sec');
  870. foreach ($dateFields as $default => $var) {
  871. if(isset($this->data[$modelClass][$field['name'] . $var])) {
  872. ${$var} = $this->data[$modelClass][$field['name'] . $var];
  873. unset($this->data[$modelClass][$field['name'] . $var]);
  874. } else {
  875. ${$var} = date($default);
  876. }
  877. }
  878. if ($_hour != 12 && (isset($this->data[$modelClass][$field['name'] . '_meridian']) && 'pm' == $this->data[$modelClass][$field['name'] . '_meridian'])) {
  879. $_hour = $_hour + 12;
  880. }
  881. $newDate = null;
  882. if ('datetime' == $field['type'] && isset($this->data[$modelClass][$field['name'].'_year'])) {
  883. $newDate = "{$_year}-{$_month}-{$_day}:{$_hour}:{$_min}:{$_sec}";
  884. } else if ('date' == $field['type'] && isset($this->data[$modelClass][$field['name'].'_year'])) {
  885. $newDate = "{$_year}-{$_month}-{$_day}";
  886. } else if ('time' == $field['type'] && isset($this->data[$modelClass][$field['name'].'_hour'])) {
  887. $newDate = "{$_hour}:{$_min}:{$_sec}";
  888. }
  889. if($newDate && !in_array($field['name'], array('created', 'updated', 'modified'))) {
  890. $this->data[$modelClass][$field['name']] = $newDate;
  891. }
  892. }
  893. }
  894. /**
  895. * Handles automatic pagination of model records
  896. *
  897. * @param mixed $object
  898. * @param mixed $scope
  899. * @param array $whitelist
  900. * @return array Model query results
  901. */
  902. function paginate($object = null, $scope = array(), $whitelist = array()) {
  903. if (is_array($object)) {
  904. $whitelist = $scope;
  905. $scope = $object;
  906. $object = null;
  907. }
  908. if (is_string($object)) {
  909. if (isset($this->{$object})) {
  910. $object = $this->{$object};
  911. } elseif (isset($this->{$this->modelClass}) && isset($this->{$this->modelClass}->{$object})) {
  912. $object = $this->{$this->modelClass}->{$object};
  913. } elseif (!empty($this->uses)) {
  914. for ($i = 0; $i < count($this->uses); $i++) {
  915. $model = $this->uses[$i];
  916. if (isset($this->{$model}->{$object})) {
  917. $object = $this->{$model}->{$object};
  918. break;
  919. }
  920. }
  921. }
  922. } elseif (empty($object) || $object == null) {
  923. if (isset($this->{$this->modelClass})) {
  924. $object = $this->{$this->modelClass};
  925. } else {
  926. $object = $this->{$this->uses[0]};
  927. }
  928. }
  929. if (!is_object($object)) {
  930. // Error: can't find object
  931. return array();
  932. }
  933. $options = am($this->params, $this->params['url'], $this->passedArgs);
  934. if (isset($this->paginate[$object->name])) {
  935. $defaults = $this->paginate[$object->name];
  936. } else {
  937. $defaults = $this->paginate;
  938. }
  939. if (isset($options['show'])) {
  940. $options['limit'] = $options['show'];
  941. }
  942. if (isset($options['sort']) && isset($options['direction'])) {
  943. $options['order'] = array($options['sort'] => $options['direction']);
  944. } elseif (isset($options['sort'])) {
  945. $options['order'] = array($options['sort'] => 'asc');
  946. }
  947. if (!empty($options['order']) && is_array($options['order'])) {
  948. $key = key($options['order']);
  949. if (strpos($key, '.') === false && $object->hasField($key)) {
  950. $options['order'][$object->name . '.' . $key] = $options['order'][$key];
  951. unset($options['order'][$key]);
  952. }
  953. }
  954. $vars = array('fields', 'order', 'limit', 'page', 'recursive');
  955. $keys = array_keys($options);
  956. $count = count($keys);
  957. for($i = 0; $i < $count; $i++) {
  958. if (!in_array($keys[$i], $vars)) {
  959. unset($options[$keys[$i]]);
  960. }
  961. if (empty($whitelist) && ($keys[$i] == 'fields' || $keys[$i] == 'recursive')) {
  962. unset($options[$keys[$i]]);
  963. } elseif (!empty($whitelist) && !in_array($keys[$i], $whitelist)) {
  964. unset($options[$keys[$i]]);
  965. }
  966. }
  967. $conditions = $fields = $order = $limit = $page = $recursive = null;
  968. $options = am($defaults, $options);
  969. if (isset($this->paginate[$object->name])) {
  970. $defaults = $this->paginate[$object->name];
  971. } else {
  972. $defaults = $this->paginate;
  973. }
  974. if (!isset($defaults['conditions'])) {
  975. $defaults['conditions'] = array();
  976. }
  977. extract(am(array('page' => 1, 'limit' => 20), $defaults, $options));
  978. if (is_array($scope) && !empty($scope)) {
  979. $conditions = am($conditions, $scope);
  980. } elseif (is_string($scope)) {
  981. $conditions = array($conditions, $scope);
  982. }
  983. $results = $object->findAll($conditions, $fields, $order, $limit, $page, $recursive);
  984. $count = $object->findCount($conditions);
  985. $paging = array(
  986. 'page' => $page,
  987. 'current' => count($results),
  988. 'count' => $count,
  989. 'prevPage' => ($page > 1),
  990. 'nextPage' => ($count > ($page * $limit)),
  991. 'pageCount' => ceil($count / $limit),
  992. 'defaults' => am(array('limit' => 20, 'step' => 1), $defaults),
  993. 'options' => $options
  994. );
  995. $this->params['paging'][$object->name] = $paging;
  996. if (!in_array('Paginator', $this->helpers) && !array_key_exists('Paginator', $this->helpers)) {
  997. $this->helpers[] = 'Paginator';
  998. }
  999. return $results;
  1000. }
  1001. /**
  1002. * Called before the controller action. Overridden in subclasses.
  1003. *
  1004. */
  1005. function beforeFilter() {
  1006. }
  1007. /**
  1008. * Called after the controller action is run, but before the view is rendered. Overridden in subclasses.
  1009. *
  1010. */
  1011. function beforeRender() {
  1012. }
  1013. /**
  1014. * Called after the controller action is run and rendered. Overridden in subclasses.
  1015. *
  1016. */
  1017. function afterFilter() {
  1018. }
  1019. /**
  1020. * This method should be overridden in child classes.
  1021. *
  1022. * @param string $method name of method called example index, edit, etc.
  1023. * @return boolean
  1024. */
  1025. function _beforeScaffold($method) {
  1026. return true;
  1027. }
  1028. /**
  1029. * This method should be overridden in child classes.
  1030. *
  1031. * @param string $method name of method called either edit or update.
  1032. * @return boolean
  1033. */
  1034. function _afterScaffoldSave($method) {
  1035. return true;
  1036. }
  1037. /**
  1038. * This method should be overridden in child classes.
  1039. *
  1040. * @param string $method name of method called either edit or update.
  1041. * @return boolean
  1042. */
  1043. function _afterScaffoldSaveError($method) {
  1044. return true;
  1045. }
  1046. /**
  1047. * This method should be overridden in child classes.
  1048. * If not it will render a scaffold error.
  1049. * Method MUST return true in child classes
  1050. *
  1051. * @param string $method name of method called example index, edit, etc.
  1052. * @return boolean
  1053. */
  1054. function _scaffoldError($method) {
  1055. return false;
  1056. }
  1057. /**
  1058. * Enter description here...
  1059. *
  1060. * @param unknown_type $data
  1061. * @param unknown_type $key
  1062. * @return unknown
  1063. */
  1064. function _selectedArray($data, $key = 'id') {
  1065. if(!is_array($data)) {
  1066. $model = $data;
  1067. if(!empty($this->data[$model][$model])) {
  1068. return $this->data[$model][$model];
  1069. }
  1070. if(!empty($this->data[$model])) {
  1071. $data = $this->data[$model];
  1072. }
  1073. }
  1074. $array = array();
  1075. if(!empty($data)) {
  1076. foreach($data as $var) {
  1077. $array[$var[$key]] = $var[$key];
  1078. }
  1079. }
  1080. return $array;
  1081. }
  1082. }
  1083. ?>