PageRenderTime 37ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/cake/libs/model/model.php

https://github.com/msadouni/cakephp2x
PHP | 3107 lines | 1862 code | 293 blank | 952 comment | 517 complexity | 57ec65b152476aabc33723ecfbee02e0 MD5 | raw file
  1. <?php
  2. /**
  3. * Object-relational mapper.
  4. *
  5. * DBO-backed object data model, for mapping database tables to Cake objects.
  6. *
  7. * PHP versions 5
  8. *
  9. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  10. * Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. *
  12. * Licensed under The MIT License
  13. * Redistributions of files must retain the above copyright notice.
  14. *
  15. * @copyright Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
  16. * @link http://cakephp.org CakePHP(tm) Project
  17. * @package cake
  18. * @subpackage cake.cake.libs.model
  19. * @since CakePHP(tm) v 0.10.0.0
  20. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  21. */
  22. /**
  23. * Included libs
  24. */
  25. App::import('Core', array('ClassRegistry', 'Validation', 'Set', 'String'));
  26. App::import('Model', 'ModelBehavior', false);
  27. App::import('Model', 'ConnectionManager', false);
  28. if (!class_exists('Overloadable')) {
  29. require LIBS . 'overloadable.php';
  30. }
  31. /**
  32. * Object-relational mapper.
  33. *
  34. * DBO-backed object data model.
  35. * Automatically selects a database table name based on a pluralized lowercase object class name
  36. * (i.e. class 'User' => table 'users'; class 'Man' => table 'men')
  37. * The table is required to have at least 'id auto_increment' primary key.
  38. *
  39. * @package cake
  40. * @subpackage cake.cake.libs.model
  41. * @link http://book.cakephp.org/view/66/Models
  42. */
  43. class Model extends Overloadable {
  44. /**
  45. * The name of the DataSource connection that this Model uses
  46. *
  47. * @var string
  48. * @access public
  49. * @link http://book.cakephp.org/view/435/useDbConfig
  50. */
  51. public $useDbConfig = 'default';
  52. /**
  53. * Custom database table name, or null/false if no table association is desired.
  54. *
  55. * @var string
  56. * @access public
  57. * @link http://book.cakephp.org/view/436/useTable
  58. */
  59. public $useTable = null;
  60. /**
  61. * Custom display field name. Display fields are used by Scaffold, in SELECT boxes' OPTION elements.
  62. *
  63. * @var string
  64. * @access public
  65. * @link http://book.cakephp.org/view/438/displayField
  66. */
  67. public $displayField = null;
  68. /**
  69. * Value of the primary key ID of the record that this model is currently pointing to.
  70. * Automatically set after database insertions.
  71. *
  72. * @var mixed
  73. * @access public
  74. */
  75. public $id = false;
  76. /**
  77. * Container for the data that this model gets from persistent storage (usually, a database).
  78. *
  79. * @var array
  80. * @access public
  81. * @link http://book.cakephp.org/view/441/data
  82. */
  83. public $data = array();
  84. /**
  85. * Table name for this Model.
  86. *
  87. * @var string
  88. * @access public
  89. */
  90. public $table = false;
  91. /**
  92. * The name of the primary key field for this model.
  93. *
  94. * @var string
  95. * @access public
  96. * @link http://book.cakephp.org/view/437/primaryKey
  97. */
  98. public $primaryKey = null;
  99. /**
  100. * Field-by-field table metadata.
  101. *
  102. * @var array
  103. * @access protected
  104. * @link http://book.cakephp.org/view/442/_schema
  105. */
  106. protected $_schema = null;
  107. /**
  108. * List of validation rules. Append entries for validation as ('field_name' => '/^perl_compat_regexp$/')
  109. * that have to match with preg_match(). Use these rules with Model::validate()
  110. *
  111. * @var array
  112. * @access public
  113. * @link http://book.cakephp.org/view/443/validate
  114. * @link http://book.cakephp.org/view/125/Data-Validation
  115. */
  116. public $validate = array();
  117. /**
  118. * List of validation errors.
  119. *
  120. * @var array
  121. * @access public
  122. * @link http://book.cakephp.org/view/410/Validating-Data-from-the-Controller
  123. */
  124. public $validationErrors = array();
  125. /**
  126. * Database table prefix for tables in model.
  127. *
  128. * @var string
  129. * @access public
  130. * @link http://book.cakephp.org/view/475/tablePrefix
  131. */
  132. public $tablePrefix = null;
  133. /**
  134. * Name of the model.
  135. *
  136. * @var string
  137. * @access public
  138. * @link http://book.cakephp.org/view/444/name
  139. */
  140. public $name = null;
  141. /**
  142. * Alias name for model.
  143. *
  144. * @var string
  145. * @access public
  146. */
  147. public $alias = null;
  148. /**
  149. * List of table names included in the model description. Used for associations.
  150. *
  151. * @var array
  152. * @access public
  153. */
  154. public $tableToModel = array();
  155. /**
  156. * Whether or not to log transactions for this model.
  157. *
  158. * @var boolean
  159. * @access public
  160. */
  161. public $logTransactions = false;
  162. /**
  163. * Whether or not to enable transactions for this model (i.e. BEGIN/COMMIT/ROLLBACK statements)
  164. *
  165. * @var boolean
  166. * @access public
  167. */
  168. public $transactional = false;
  169. /**
  170. * Whether or not to cache queries for this model. This enables in-memory
  171. * caching only, the results are not stored beyond the current request.
  172. *
  173. * @var boolean
  174. * @access public
  175. * @link http://book.cakephp.org/view/445/cacheQueries
  176. */
  177. public $cacheQueries = false;
  178. /**
  179. * Detailed list of belongsTo associations.
  180. *
  181. * @var array
  182. * @access public
  183. * @link http://book.cakephp.org/view/81/belongsTo
  184. */
  185. public $belongsTo = array();
  186. /**
  187. * Detailed list of hasOne associations.
  188. *
  189. * @var array
  190. * @access public
  191. * @link http://book.cakephp.org/view/80/hasOne
  192. */
  193. public $hasOne = array();
  194. /**
  195. * Detailed list of hasMany associations.
  196. *
  197. * @var array
  198. * @access public
  199. * @link http://book.cakephp.org/view/82/hasMany
  200. */
  201. public $hasMany = array();
  202. /**
  203. * Detailed list of hasAndBelongsToMany associations.
  204. *
  205. * @var array
  206. * @access public
  207. * @link http://book.cakephp.org/view/83/hasAndBelongsToMany-HABTM
  208. */
  209. public $hasAndBelongsToMany = array();
  210. /**
  211. * List of behaviors to load when the model object is initialized. Settings can be
  212. * passed to behaviors by using the behavior name as index. Eg:
  213. *
  214. * var $actsAs = array('Translate', 'MyBehavior' => array('setting1' => 'value1'))
  215. *
  216. * @var array
  217. * @access public
  218. * @link http://book.cakephp.org/view/90/Using-Behaviors
  219. */
  220. public $actsAs = null;
  221. /**
  222. * Holds the Behavior objects currently bound to this model.
  223. *
  224. * @var BehaviorCollection
  225. * @access public
  226. */
  227. public $Behaviors = null;
  228. /**
  229. * Whitelist of fields allowed to be saved.
  230. *
  231. * @var array
  232. * @access public
  233. */
  234. public $whitelist = array();
  235. /**
  236. * Whether or not to cache sources for this model.
  237. *
  238. * @var boolean
  239. * @access public
  240. */
  241. public $cacheSources = true;
  242. /**
  243. * Type of find query currently executing.
  244. *
  245. * @var string
  246. * @access public
  247. */
  248. public $findQueryType = null;
  249. /**
  250. * Number of associations to recurse through during find calls. Fetches only
  251. * the first level by default.
  252. *
  253. * @var integer
  254. * @access public
  255. * @link http://book.cakephp.org/view/439/recursive
  256. */
  257. public $recursive = 1;
  258. /**
  259. * The column name(s) and direction(s) to order find results by default.
  260. *
  261. * var $order = "Post.created DESC";
  262. * var $order = array("Post.view_count DESC", "Post.rating DESC");
  263. *
  264. * @var string
  265. * @access public
  266. * @link http://book.cakephp.org/view/440/order
  267. */
  268. public $order = null;
  269. /**
  270. * Whether or not the model record exists, set by Model::exists().
  271. *
  272. * @var bool
  273. * @access private
  274. */
  275. public $__exists = null;
  276. /**
  277. * Default list of association keys.
  278. *
  279. * @var array
  280. * @access private
  281. */
  282. public $__associationKeys = array(
  283. 'belongsTo' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'counterCache'),
  284. 'hasOne' => array('className', 'foreignKey','conditions', 'fields','order', 'dependent'),
  285. 'hasMany' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'dependent', 'exclusive', 'finderQuery', 'counterQuery'),
  286. 'hasAndBelongsToMany' => array('className', 'joinTable', 'with', 'foreignKey', 'associationForeignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'unique', 'finderQuery', 'deleteQuery', 'insertQuery')
  287. );
  288. /**
  289. * Holds provided/generated association key names and other data for all associations.
  290. *
  291. * @var array
  292. * @access private
  293. */
  294. public $__associations = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
  295. /**
  296. * Holds model associations temporarily to allow for dynamic (un)binding.
  297. *
  298. * @var array
  299. * @access private
  300. */
  301. public $__backAssociation = array();
  302. /**
  303. * The ID of the model record that was last inserted.
  304. *
  305. * @var integer
  306. * @access private
  307. */
  308. public $__insertID = null;
  309. /**
  310. * The number of records returned by the last query.
  311. *
  312. * @var integer
  313. * @access private
  314. */
  315. public $__numRows = null;
  316. /**
  317. * The number of records affected by the last query.
  318. *
  319. * @var integer
  320. * @access private
  321. */
  322. public $__affectedRows = null;
  323. /**
  324. * List of valid finder method options, supplied as the first parameter to find().
  325. *
  326. * @var array
  327. * @access protected
  328. */
  329. public $_findMethods = array(
  330. 'all' => true, 'first' => true, 'count' => true,
  331. 'neighbors' => true, 'list' => true, 'threaded' => true
  332. );
  333. /**
  334. * Constructor. Binds the model's database table to the object.
  335. *
  336. * @param integer $id Set this ID for this model on startup
  337. * @param string $table Name of database table to use.
  338. * @param object $ds DataSource connection object.
  339. */
  340. public function __construct($id = false, $table = null, $ds = null) {
  341. parent::__construct();
  342. if (is_array($id)) {
  343. extract(array_merge(
  344. array(
  345. 'id' => $this->id, 'table' => $this->useTable, 'ds' => $this->useDbConfig,
  346. 'name' => $this->name, 'alias' => $this->alias
  347. ),
  348. $id
  349. ));
  350. }
  351. if ($this->name === null) {
  352. $this->name = (isset($name) ? $name : get_class($this));
  353. }
  354. if ($this->alias === null) {
  355. $this->alias = (isset($alias) ? $alias : $this->name);
  356. }
  357. if ($this->primaryKey === null) {
  358. $this->primaryKey = 'id';
  359. }
  360. ClassRegistry::addObject($this->alias, $this);
  361. $this->id = $id;
  362. unset($id);
  363. if ($table === false) {
  364. $this->useTable = false;
  365. } elseif ($table) {
  366. $this->useTable = $table;
  367. }
  368. if ($ds !== null) {
  369. $this->useDbConfig = $ds;
  370. }
  371. if (is_subclass_of($this, 'AppModel')) {
  372. $appVars = get_class_vars('AppModel');
  373. $merge = array('_findMethods');
  374. if ($this->actsAs !== null || $this->actsAs !== false) {
  375. $merge[] = 'actsAs';
  376. }
  377. $parentClass = get_parent_class($this);
  378. if (strtolower($parentClass) !== 'appmodel') {
  379. $parentVars = get_class_vars($parentClass);
  380. foreach ($merge as $var) {
  381. if (isset($parentVars[$var]) && !empty($parentVars[$var])) {
  382. $appVars[$var] = Set::merge($appVars[$var], $parentVars[$var]);
  383. }
  384. }
  385. }
  386. foreach ($merge as $var) {
  387. if (isset($appVars[$var]) && !empty($appVars[$var]) && is_array($this->{$var})) {
  388. $this->{$var} = Set::merge($appVars[$var], $this->{$var});
  389. }
  390. }
  391. }
  392. $this->Behaviors = new BehaviorCollection();
  393. if ($this->useTable !== false) {
  394. $this->setDataSource($ds);
  395. if ($this->useTable === null) {
  396. $this->useTable = Inflector::tableize($this->name);
  397. }
  398. if (method_exists($this, 'setTablePrefix')) {
  399. $this->setTablePrefix();
  400. }
  401. $this->setSource($this->useTable);
  402. if ($this->displayField == null) {
  403. $this->displayField = $this->hasField(array('title', 'name', $this->primaryKey));
  404. }
  405. } elseif ($this->table === false) {
  406. $this->table = Inflector::tableize($this->name);
  407. }
  408. ModelAssociation::create($this);
  409. $this->Behaviors->init($this->alias, $this->actsAs);
  410. }
  411. /**
  412. * Handles custom method calls, like findBy<field> for DB models,
  413. * and custom RPC calls for remote data sources.
  414. *
  415. * @param string $method Name of method to call.
  416. * @param array $params Parameters for the method.
  417. * @return mixed Whatever is returned by called method
  418. * @access protected
  419. */
  420. protected function call__($method, $params) {
  421. $result = $this->Behaviors->dispatchMethod($this, $method, $params);
  422. if ($result !== array('unhandled')) {
  423. return $result;
  424. }
  425. $db = ConnectionManager::getDataSource($this->useDbConfig);
  426. $return = $db->query($method, $params, $this);
  427. return $return;
  428. }
  429. /**
  430. * Bind model associations on the fly.
  431. *
  432. * If $reset is false, association will not be reset
  433. * to the originals defined in the model
  434. *
  435. * Example: Add a new hasOne binding to the Profile model not
  436. * defined in the model source code:
  437. * <code>
  438. * $this->User->bindModel( array('hasOne' => array('Profile')) );
  439. * </code>
  440. *
  441. * @param array $params Set of bindings (indexed by binding type)
  442. * @param boolean $reset Set to false to make the binding permanent
  443. * @return boolean Success
  444. * @access public
  445. * @link http://book.cakephp.org/view/86/Creating-and-Destroying-Associations-on-the-Fly
  446. */
  447. public function bindModel($params, $reset = true) {
  448. foreach ($params as $assoc => $model) {
  449. if ($reset === true) {
  450. $this->__backAssociation[$assoc] = $this->{$assoc};
  451. }
  452. foreach ($model as $key => $value) {
  453. $assocName = $key;
  454. if (is_numeric($key)) {
  455. $assocName = $value;
  456. $value = array();
  457. }
  458. $modelName = $assocName;
  459. $this->{$assoc}[$assocName] = $value;
  460. }
  461. }
  462. ModelAssociation::create($this);
  463. return true;
  464. }
  465. /**
  466. * Turn off associations on the fly.
  467. *
  468. * If $reset is false, association will not be reset
  469. * to the originals defined in the model
  470. *
  471. * Example: Turn off the associated Model Support request,
  472. * to temporarily lighten the User model:
  473. * <code>
  474. * $this->User->unbindModel( array('hasMany' => array('Supportrequest')) );
  475. * </code>
  476. *
  477. * @param array $params Set of bindings to unbind (indexed by binding type)
  478. * @param boolean $reset Set to false to make the unbinding permanent
  479. * @return boolean Success
  480. * @access public
  481. * @link http://book.cakephp.org/view/86/Creating-and-Destroying-Associations-on-the-Fly
  482. */
  483. public function unbindModel($params, $reset = true) {
  484. foreach ($params as $assoc => $models) {
  485. if ($reset === true) {
  486. $this->__backAssociation[$assoc] = $this->{$assoc};
  487. }
  488. foreach ($models as $model) {
  489. $this->__backAssociation = array_merge($this->__backAssociation, $this->{$assoc});
  490. unset ($this->__backAssociation[$model]);
  491. unset ($this->{$assoc}[$model]);
  492. }
  493. }
  494. return true;
  495. }
  496. /**
  497. * Create a set of associations.
  498. *
  499. * @return void
  500. * @access private
  501. */
  502. function __createLinks() {
  503. foreach ($this->__associations as $type) {
  504. if (!is_array($this->{$type})) {
  505. $this->{$type} = explode(',', $this->{$type});
  506. foreach ($this->{$type} as $i => $className) {
  507. $className = trim($className);
  508. unset ($this->{$type}[$i]);
  509. $this->{$type}[$className] = array();
  510. }
  511. }
  512. if (!empty($this->{$type})) {
  513. foreach ($this->{$type} as $assoc => $value) {
  514. $plugin = null;
  515. if (is_numeric($assoc)) {
  516. unset ($this->{$type}[$assoc]);
  517. $assoc = $value;
  518. $value = array();
  519. $this->{$type}[$assoc] = $value;
  520. if (strpos($assoc, '.') !== false) {
  521. $value = $this->{$type}[$assoc];
  522. unset($this->{$type}[$assoc]);
  523. list($plugin, $assoc) = pluginSplit($assoc, true);
  524. $this->{$type}[$assoc] = $value;
  525. }
  526. }
  527. $className = $assoc;
  528. if (!empty($value['className'])) {
  529. list($plugin, $className) = pluginSplit($value['className'], true);
  530. $this->{$type}[$assoc]['className'] = $className;
  531. }
  532. $this->__constructLinkedModel($assoc, $plugin . $className);
  533. }
  534. $this->__generateAssociation($type);
  535. }
  536. }
  537. }
  538. /**
  539. * Private helper method to create associated models of a given class.
  540. *
  541. * @param string $assoc Association name
  542. * @param string $className Class name
  543. * @deprecated $this->$className use $this->$assoc instead. $assoc is the 'key' in the associations array;
  544. * examples: var $hasMany = array('Assoc' => array('className' => 'ModelName'));
  545. * usage: $this->Assoc->modelMethods();
  546. *
  547. * var $hasMany = array('ModelName');
  548. * usage: $this->ModelName->modelMethods();
  549. * @return void
  550. * @access private
  551. */
  552. function __constructLinkedModel($assoc, $className = null) {
  553. if (empty($className)) {
  554. $className = $assoc;
  555. }
  556. if (!isset($this->{$assoc}) || $this->{$assoc}->name !== $className) {
  557. $model = array('class' => $className, 'alias' => $assoc);
  558. if (PHP5) {
  559. $this->{$assoc} = ClassRegistry::init($model);
  560. } else {
  561. $this->{$assoc} =& ClassRegistry::init($model);
  562. }
  563. if ($assoc) {
  564. $this->tableToModel[$this->{$assoc}->table] = $assoc;
  565. }
  566. }
  567. }
  568. /**
  569. * Build an array-based association from string.
  570. *
  571. * @param string $type 'belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany'
  572. * @return void
  573. * @access private
  574. */
  575. function __generateAssociation($type) {
  576. foreach ($this->{$type} as $assocKey => $assocData) {
  577. $class = $assocKey;
  578. $dynamicWith = false;
  579. foreach ($this->__associationKeys[$type] as $key) {
  580. if (!isset($this->{$type}[$assocKey][$key]) || $this->{$type}[$assocKey][$key] === null) {
  581. $data = '';
  582. switch ($key) {
  583. case 'fields':
  584. $data = '';
  585. break;
  586. case 'foreignKey':
  587. $data = (($type == 'belongsTo') ? Inflector::underscore($assocKey) : Inflector::singularize($this->table)) . '_id';
  588. break;
  589. case 'associationForeignKey':
  590. $data = Inflector::singularize($this->{$class}->table) . '_id';
  591. break;
  592. case 'with':
  593. $data = Inflector::camelize(Inflector::singularize($this->{$type}[$assocKey]['joinTable']));
  594. $dynamicWith = true;
  595. break;
  596. case 'joinTable':
  597. $tables = array($this->table, $this->{$class}->table);
  598. sort ($tables);
  599. $data = $tables[0] . '_' . $tables[1];
  600. break;
  601. case 'className':
  602. $data = $class;
  603. break;
  604. case 'unique':
  605. $data = true;
  606. break;
  607. }
  608. $this->{$type}[$assocKey][$key] = $data;
  609. }
  610. }
  611. if (!empty($this->{$type}[$assocKey]['with'])) {
  612. $joinClass = $this->{$type}[$assocKey]['with'];
  613. if (is_array($joinClass)) {
  614. $joinClass = key($joinClass);
  615. }
  616. $plugin = null;
  617. if (strpos($joinClass, '.') !== false) {
  618. list($plugin, $joinClass) = explode('.', $joinClass);
  619. $plugin .= '.';
  620. $this->{$type}[$assocKey]['with'] = $joinClass;
  621. }
  622. if (!ClassRegistry::isKeySet($joinClass) && $dynamicWith === true) {
  623. $this->{$joinClass} = new AppModel(array(
  624. 'name' => $joinClass,
  625. 'table' => $this->{$type}[$assocKey]['joinTable'],
  626. 'ds' => $this->useDbConfig
  627. ));
  628. } else {
  629. $this->__constructLinkedModel($joinClass, $plugin . $joinClass);
  630. $this->{$type}[$assocKey]['joinTable'] = $this->{$joinClass}->table;
  631. }
  632. if (count($this->{$joinClass}->schema()) <= 2 && $this->{$joinClass}->primaryKey !== false) {
  633. $this->{$joinClass}->primaryKey = $this->{$type}[$assocKey]['foreignKey'];
  634. }
  635. }
  636. }
  637. }
  638. /**
  639. * Sets a custom table for your controller class. Used by your controller to select a database table.
  640. *
  641. * @param string $tableName Name of the custom table
  642. * @return void
  643. * @access public
  644. */
  645. public function setSource($tableName) {
  646. $this->setDataSource($this->useDbConfig);
  647. $db = ConnectionManager::getDataSource($this->useDbConfig);
  648. $db->cacheSources = ($this->cacheSources && $db->cacheSources);
  649. if ($db->isInterfaceSupported('listSources')) {
  650. $sources = $db->listSources();
  651. if (is_array($sources) && !in_array(strtolower($this->tablePrefix . $tableName), array_map('strtolower', $sources))) {
  652. return $this->cakeError('missingTable', array(array(
  653. 'className' => $this->alias,
  654. 'table' => $this->tablePrefix . $tableName
  655. )));
  656. }
  657. $this->_schema = null;
  658. }
  659. $this->table = $this->useTable = $tableName;
  660. $this->tableToModel[$this->table] = $this->alias;
  661. $this->schema();
  662. }
  663. /**
  664. * This function does two things:
  665. *
  666. * 1. it scans the array $one for the primary key,
  667. * and if that's found, it sets the current id to the value of $one[id].
  668. * For all other keys than 'id' the keys and values of $one are copied to the 'data' property of this object.
  669. * 2. Returns an array with all of $one's keys and values.
  670. * (Alternative indata: two strings, which are mangled to
  671. * a one-item, two-dimensional array using $one for a key and $two as its value.)
  672. *
  673. * @param mixed $one Array or string of data
  674. * @param string $two Value string for the alternative indata method
  675. * @return array Data with all of $one's keys and values
  676. * @access public
  677. */
  678. public function set($one, $two = null) {
  679. if (!$one) {
  680. return;
  681. }
  682. if (is_object($one)) {
  683. $one = Set::reverse($one);
  684. }
  685. if (is_array($one)) {
  686. $data = $one;
  687. if (empty($one[$this->alias])) {
  688. if ($this->getAssociated(key($one)) === null) {
  689. $data = array($this->alias => $one);
  690. }
  691. }
  692. } else {
  693. $data = array($this->alias => array($one => $two));
  694. }
  695. foreach ($data as $modelName => $fieldSet) {
  696. if (is_array($fieldSet)) {
  697. foreach ($fieldSet as $fieldName => $fieldValue) {
  698. if (isset($this->validationErrors[$fieldName])) {
  699. unset ($this->validationErrors[$fieldName]);
  700. }
  701. if ($modelName === $this->alias) {
  702. if ($fieldName === $this->primaryKey) {
  703. $this->id = $fieldValue;
  704. }
  705. }
  706. if (is_array($fieldValue) || is_object($fieldValue)) {
  707. $fieldValue = $this->deconstruct($fieldName, $fieldValue);
  708. }
  709. $this->data[$modelName][$fieldName] = $fieldValue;
  710. }
  711. }
  712. }
  713. return $data;
  714. }
  715. /**
  716. * Deconstructs a complex data type (array or object) into a single field value.
  717. *
  718. * @param string $field The name of the field to be deconstructed
  719. * @param mixed $data An array or object to be deconstructed into a field
  720. * @return mixed The resulting data that should be assigned to a field
  721. * @access public
  722. */
  723. function deconstruct($field, $data) {
  724. if (!is_array($data)) {
  725. return $data;
  726. }
  727. $copy = $data;
  728. $type = $this->getColumnType($field);
  729. if (in_array($type, array('datetime', 'timestamp', 'date', 'time'))) {
  730. $useNewDate = (isset($data['year']) || isset($data['month']) ||
  731. isset($data['day']) || isset($data['hour']) || isset($data['minute']));
  732. $dateFields = array('Y' => 'year', 'm' => 'month', 'd' => 'day', 'H' => 'hour', 'i' => 'min', 's' => 'sec');
  733. $timeFields = array('H' => 'hour', 'i' => 'min', 's' => 'sec');
  734. $db = ConnectionManager::getDataSource($this->useDbConfig);
  735. $format = $db->columns[$type]['format'];
  736. $date = array();
  737. if (isset($data['hour']) && isset($data['meridian']) && $data['hour'] != 12 && 'pm' == $data['meridian']) {
  738. $data['hour'] = $data['hour'] + 12;
  739. }
  740. if (isset($data['hour']) && isset($data['meridian']) && $data['hour'] == 12 && 'am' == $data['meridian']) {
  741. $data['hour'] = '00';
  742. }
  743. if ($type == 'time') {
  744. foreach ($timeFields as $key => $val) {
  745. if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') {
  746. $data[$val] = '00';
  747. } elseif ($data[$val] === '') {
  748. $data[$val] = '';
  749. } else {
  750. $data[$val] = sprintf('%02d', $data[$val]);
  751. }
  752. if (!empty($data[$val])) {
  753. $date[$key] = $data[$val];
  754. } else {
  755. return null;
  756. }
  757. }
  758. }
  759. if ($type == 'datetime' || $type == 'timestamp' || $type == 'date') {
  760. foreach ($dateFields as $key => $val) {
  761. if ($val == 'hour' || $val == 'min' || $val == 'sec') {
  762. if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') {
  763. $data[$val] = '00';
  764. } else {
  765. $data[$val] = sprintf('%02d', $data[$val]);
  766. }
  767. }
  768. if (!isset($data[$val]) || isset($data[$val]) && (empty($data[$val]) || $data[$val][0] === '-')) {
  769. return null;
  770. }
  771. if (isset($data[$val]) && !empty($data[$val])) {
  772. $date[$key] = $data[$val];
  773. }
  774. }
  775. }
  776. $date = str_replace(array_keys($date), array_values($date), $format);
  777. if ($useNewDate && !empty($date)) {
  778. return $date;
  779. }
  780. }
  781. return $data;
  782. }
  783. /**
  784. * Returns an array of table metadata (column names and types) from the database.
  785. * $field => keys(type, null, default, key, length, extra)
  786. *
  787. * @param mixed $field Set to true to reload schema, or a string to return a specific field
  788. * @return array Array of table metadata
  789. * @access public
  790. */
  791. public function schema($field = false) {
  792. if (!is_array($this->_schema) || $field === true) {
  793. $db = ConnectionManager::getDataSource($this->useDbConfig);
  794. $db->cacheSources = ($this->cacheSources && $db->cacheSources);
  795. if ($db->isInterfaceSupported('describe') && $this->useTable !== false) {
  796. $this->_schema = $db->describe($this, $field);
  797. } elseif ($this->useTable === false) {
  798. $this->_schema = array();
  799. }
  800. }
  801. if (is_string($field)) {
  802. if (isset($this->_schema[$field])) {
  803. return $this->_schema[$field];
  804. } else {
  805. return null;
  806. }
  807. }
  808. return $this->_schema;
  809. }
  810. /**
  811. * Returns an associative array of field names and column types.
  812. *
  813. * @return array Field types indexed by field name
  814. * @access public
  815. */
  816. public function getColumnTypes() {
  817. $columns = $this->schema();
  818. if (empty($columns)) {
  819. trigger_error(__('(Model::getColumnTypes) Unable to build model field data. If you are using a model without a database table, try implementing schema()', true), E_USER_WARNING);
  820. }
  821. $cols = array();
  822. foreach ($columns as $field => $values) {
  823. $cols[$field] = $values['type'];
  824. }
  825. return $cols;
  826. }
  827. /**
  828. * Returns the column type of a column in the model.
  829. *
  830. * @param string $column The name of the model column
  831. * @return string Column type
  832. * @access public
  833. */
  834. public function getColumnType($column) {
  835. $db = ConnectionManager::getDataSource($this->useDbConfig);
  836. $cols = $this->schema();
  837. $model = null;
  838. $column = str_replace(array($db->startQuote, $db->endQuote), '', $column);
  839. if (strpos($column, '.')) {
  840. list($model, $column) = explode('.', $column);
  841. }
  842. if ($model != $this->alias && isset($this->{$model})) {
  843. return $this->{$model}->getColumnType($column);
  844. }
  845. if (isset($cols[$column]) && isset($cols[$column]['type'])) {
  846. return $cols[$column]['type'];
  847. }
  848. return null;
  849. }
  850. /**
  851. * Returns true if the supplied field exists in the model's database table.
  852. *
  853. * @param mixed $name Name of field to look for, or an array of names
  854. * @return mixed If $name is a string, returns a boolean indicating whether the field exists.
  855. * If $name is an array of field names, returns the first field that exists,
  856. * or false if none exist.
  857. * @access public
  858. */
  859. public function hasField($name) {
  860. if (is_array($name)) {
  861. foreach ($name as $n) {
  862. if ($this->hasField($n)) {
  863. return $n;
  864. }
  865. }
  866. return false;
  867. }
  868. if (empty($this->_schema)) {
  869. $this->schema();
  870. }
  871. if ($this->_schema != null) {
  872. return isset($this->_schema[$name]);
  873. }
  874. return false;
  875. }
  876. /**
  877. * Initializes the model for writing a new record, loading the default values
  878. * for those fields that are not defined in $data, and clearing previous validation errors.
  879. * Especially helpful for saving data in loops.
  880. *
  881. * @param mixed $data Optional data array to assign to the model after it is created. If null or false,
  882. * schema data defaults are not merged.
  883. * @param boolean $filterKey If true, overwrites any primary key input with an empty value
  884. * @return array The current Model::data; after merging $data and/or defaults from database
  885. * @access public
  886. * @link http://book.cakephp.org/view/75/Saving-Your-Data
  887. */
  888. public function create($data = array(), $filterKey = false) {
  889. $defaults = array();
  890. $this->id = false;
  891. $this->data = array();
  892. $this->__exists = null;
  893. $this->validationErrors = array();
  894. if ($data !== null && $data !== false) {
  895. foreach ($this->schema() as $field => $properties) {
  896. if ($this->primaryKey !== $field && isset($properties['default'])) {
  897. $defaults[$field] = $properties['default'];
  898. }
  899. }
  900. $this->set(Set::filter($defaults));
  901. $this->set($data);
  902. }
  903. if ($filterKey) {
  904. $this->set($this->primaryKey, false);
  905. }
  906. return $this->data;
  907. }
  908. /**
  909. * Returns a list of fields from the database, and sets the current model
  910. * data (Model::$data) with the record found.
  911. *
  912. * @param mixed $fields String of single fieldname, or an array of fieldnames.
  913. * @param mixed $id The ID of the record to read
  914. * @return array Array of database fields, or false if not found
  915. * @access public
  916. */
  917. public function read($fields = null, $id = null) {
  918. $this->validationErrors = array();
  919. if ($id != null) {
  920. $this->id = $id;
  921. }
  922. $id = $this->id;
  923. if (is_array($this->id)) {
  924. $id = $this->id[0];
  925. }
  926. if ($id !== null && $id !== false) {
  927. $this->data = $this->find('first', array(
  928. 'conditions' => array($this->alias . '.' . $this->primaryKey => $id),
  929. 'fields' => $fields
  930. ));
  931. return $this->data;
  932. } else {
  933. return false;
  934. }
  935. }
  936. /**
  937. * Returns the contents of a single field given the supplied conditions, in the
  938. * supplied order.
  939. *
  940. * @param string $name Name of field to get
  941. * @param array $conditions SQL conditions (defaults to NULL)
  942. * @param string $order SQL ORDER BY fragment
  943. * @return string field contents, or false if not found
  944. * @access public
  945. * @link http://book.cakephp.org/view/453/field
  946. */
  947. public function field($name, $conditions = null, $order = null) {
  948. if ($conditions === null && $this->id !== false) {
  949. $conditions = array($this->alias . '.' . $this->primaryKey => $this->id);
  950. }
  951. if ($this->recursive >= 1) {
  952. $recursive = -1;
  953. } else {
  954. $recursive = $this->recursive;
  955. }
  956. if ($data = $this->find($conditions, $name, $order, $recursive)) {
  957. if (strpos($name, '.') === false) {
  958. if (isset($data[$this->alias][$name])) {
  959. return $data[$this->alias][$name];
  960. }
  961. } else {
  962. $name = explode('.', $name);
  963. if (isset($data[$name[0]][$name[1]])) {
  964. return $data[$name[0]][$name[1]];
  965. }
  966. }
  967. if (!empty($data[0])) {
  968. $name = key($data[0]);
  969. return $data[0][$name];
  970. }
  971. } else {
  972. return false;
  973. }
  974. }
  975. /**
  976. * Saves the value of a single field to the database, based on the current
  977. * model ID.
  978. *
  979. * @param string $name Name of the table field
  980. * @param mixed $value Value of the field
  981. * @param array $validate See $options param in Model::save(). Does not respect 'fieldList' key if passed
  982. * @return boolean See Model::save()
  983. * @access public
  984. * @see Model::save()
  985. * @link http://book.cakephp.org/view/75/Saving-Your-Data
  986. */
  987. public function saveField($name, $value, $validate = false) {
  988. $id = $this->id;
  989. $this->create(false);
  990. if (is_array($validate)) {
  991. $options = array_merge(array('validate' => false, 'fieldList' => array($name)), $validate);
  992. } else {
  993. $options = array('validate' => $validate, 'fieldList' => array($name));
  994. }
  995. return $this->save(array($this->alias => array($this->primaryKey => $id, $name => $value)), $options);
  996. }
  997. /**
  998. * Saves model data (based on white-list, if supplied) to the database. By
  999. * default, validation occurs before save.
  1000. *
  1001. * @param array $data Data to save.
  1002. * @param mixed $validate Either a boolean, or an array.
  1003. * If a boolean, indicates whether or not to validate before saving.
  1004. * If an array, allows control of validate, callbacks, and fieldList
  1005. * @param array $fieldList List of fields to allow to be written
  1006. * @return mixed On success Model::$data if its not empty or true, false on failure
  1007. * @access public
  1008. * @link http://book.cakephp.org/view/75/Saving-Your-Data
  1009. */
  1010. public function save($data = null, $validate = true, $fieldList = array()) {
  1011. $defaults = array('validate' => true, 'fieldList' => array(), 'callbacks' => true);
  1012. $_whitelist = $this->whitelist;
  1013. $fields = array();
  1014. if (!is_array($validate)) {
  1015. $options = array_merge($defaults, compact('validate', 'fieldList', 'callbacks'));
  1016. } else {
  1017. $options = array_merge($defaults, $validate);
  1018. }
  1019. if (!empty($options['fieldList'])) {
  1020. $this->whitelist = $options['fieldList'];
  1021. } elseif ($options['fieldList'] === null) {
  1022. $this->whitelist = array();
  1023. }
  1024. $this->set($data);
  1025. if (empty($this->data) && !$this->hasField(array('created', 'updated', 'modified'))) {
  1026. return false;
  1027. }
  1028. foreach (array('created', 'updated', 'modified') as $field) {
  1029. $keyPresentAndEmpty = (
  1030. isset($this->data[$this->alias]) &&
  1031. array_key_exists($field, $this->data[$this->alias]) &&
  1032. $this->data[$this->alias][$field] === null
  1033. );
  1034. if ($keyPresentAndEmpty) {
  1035. unset($this->data[$this->alias][$field]);
  1036. }
  1037. }
  1038. $this->exists();
  1039. $dateFields = array('modified', 'updated');
  1040. if (!$this->__exists) {
  1041. $dateFields[] = 'created';
  1042. }
  1043. if (isset($this->data[$this->alias])) {
  1044. $fields = array_keys($this->data[$this->alias]);
  1045. }
  1046. if ($options['validate'] && !$this->validates($options)) {
  1047. $this->whitelist = $_whitelist;
  1048. return false;
  1049. }
  1050. $db = ConnectionManager::getDataSource($this->useDbConfig);
  1051. foreach ($dateFields as $updateCol) {
  1052. if ($this->hasField($updateCol) && !in_array($updateCol, $fields)) {
  1053. $default = array('formatter' => 'date');
  1054. $colType = array_merge($default, $db->columns[$this->getColumnType($updateCol)]);
  1055. if (!array_key_exists('format', $colType)) {
  1056. $time = strtotime('now');
  1057. } else {
  1058. $time = $colType['formatter']($colType['format']);
  1059. }
  1060. if (!empty($this->whitelist)) {
  1061. $this->whitelist[] = $updateCol;
  1062. }
  1063. $this->set($updateCol, $time);
  1064. }
  1065. }
  1066. if ($options['callbacks'] === true || $options['callbacks'] === 'before') {
  1067. $result = $this->Behaviors->trigger($this, 'beforeSave', array($options), array(
  1068. 'break' => true, 'breakOn' => false
  1069. ));
  1070. if (!$result || !$this->beforeSave($options)) {
  1071. $this->whitelist = $_whitelist;
  1072. return false;
  1073. }
  1074. }
  1075. $fields = $values = array();
  1076. if (isset($this->data[$this->alias][$this->primaryKey]) && empty($this->data[$this->alias][$this->primaryKey])) {
  1077. unset($this->data[$this->alias][$this->primaryKey]);
  1078. }
  1079. foreach ($this->data as $n => $v) {
  1080. if (isset($this->hasAndBelongsToMany[$n])) {
  1081. if (isset($v[$n])) {
  1082. $v = $v[$n];
  1083. }
  1084. $joined[$n] = $v;
  1085. } else {
  1086. if ($n === $this->alias) {
  1087. foreach (array('created', 'updated', 'modified') as $field) {
  1088. if (array_key_exists($field, $v) && empty($v[$field])) {
  1089. unset($v[$field]);
  1090. }
  1091. }
  1092. foreach ($v as $x => $y) {
  1093. if ($this->hasField($x) && (empty($this->whitelist) || in_array($x, $this->whitelist))) {
  1094. list($fields[], $values[]) = array($x, $y);
  1095. }
  1096. }
  1097. }
  1098. }
  1099. }
  1100. $count = count($fields);
  1101. if (!$this->__exists && $count > 0) {
  1102. $this->id = false;
  1103. }
  1104. $success = true;
  1105. $created = false;
  1106. if ($count > 0) {
  1107. $cache = $this->_prepareUpdateFields(array_combine($fields, $values));
  1108. if (!empty($this->id)) {
  1109. $success = (bool)$db->update($this, $fields, $values);
  1110. } else {
  1111. foreach ($this->_schema as $field => $properties) {
  1112. if ($this->primaryKey === $field) {
  1113. $fInfo = $this->_schema[$field];
  1114. $isUUID = ($fInfo['length'] === 36 &&
  1115. ($fInfo['type'] === 'string' || $fInfo['type'] === 'binary')
  1116. );
  1117. if (empty($this->data[$this->alias][$this->primaryKey]) && $isUUID) {
  1118. list($fields[], $values[]) = array($this->primaryKey, String::uuid());
  1119. }
  1120. break;
  1121. }
  1122. }
  1123. if (!$db->create($this, $fields, $values)) {
  1124. $success = $created = false;
  1125. } else {
  1126. $created = true;
  1127. }
  1128. }
  1129. if ($success && !empty($this->belongsTo)) {
  1130. $this->updateCounterCache($cache, $created);
  1131. }
  1132. }
  1133. if (!empty($joined) && $success === true) {
  1134. $this->__saveMulti($joined, $this->id);
  1135. }
  1136. if ($success && $count > 0) {
  1137. if (!empty($this->data)) {
  1138. $success = $this->data;
  1139. }
  1140. if ($options['callbacks'] === true || $options['callbacks'] === 'after') {
  1141. $this->Behaviors->trigger($this, 'afterSave', array($created, $options));
  1142. $this->afterSave($created);
  1143. }
  1144. if (!empty($this->data)) {
  1145. $success = Set::merge($success, $this->data);
  1146. }
  1147. $this->data = false;
  1148. $this->__exists = null;
  1149. $this->_clearCache();
  1150. $this->validationErrors = array();
  1151. }
  1152. $this->whitelist = $_whitelist;
  1153. return $success;
  1154. }
  1155. /**
  1156. * Saves model hasAndBelongsToMany data to the database.
  1157. *
  1158. * @param array $joined Data to save
  1159. * @param mixed $id ID of record in this model
  1160. * @access private
  1161. */
  1162. private function __saveMulti($joined, $id) {
  1163. $db = ConnectionManager::getDataSource($this->useDbConfig);
  1164. foreach ($joined as $assoc => $data) {
  1165. if (isset($this->hasAndBelongsToMany[$assoc])) {
  1166. list($join) = $this->joinModel($this->hasAndBelongsToMany[$assoc]['with']);
  1167. $isUUID = !empty($this->{$join}->primaryKey) && (
  1168. $this->{$join}->_schema[$this->{$join}->primaryKey]['length'] === 36 && (
  1169. $this->{$join}->_schema[$this->{$join}->primaryKey]['type'] === 'string' ||
  1170. $this->{$join}->_schema[$this->{$join}->primaryKey]['type'] === 'binary'
  1171. )
  1172. );
  1173. $newData = $newValues = array();
  1174. $primaryAdded = false;
  1175. $fields = array(
  1176. $db->name($this->hasAndBelongsToMany[$assoc]['foreignKey']),
  1177. $db->name($this->hasAndBelongsToMany[$assoc]['associationForeignKey'])
  1178. );
  1179. $idField = $db->name($this->{$join}->primaryKey);
  1180. if ($isUUID && !in_array($idField, $fields)) {
  1181. $fields[] = $idField;
  1182. $primaryAdded = true;
  1183. }
  1184. foreach ((array)$data as $row) {
  1185. if ((is_string($row) && (strlen($row) == 36 || strlen($row) == 16)) || is_numeric($row)) {
  1186. $values = array(
  1187. $db->value($id, $this->getColumnType($this->primaryKey)),
  1188. $db->value($row)
  1189. );
  1190. if ($isUUID && $primaryAdded) {
  1191. $values[] = $db->value(String::uuid());
  1192. }
  1193. $values = implode(',', $values);
  1194. $newValues[] = "({$values})";
  1195. unset($values);
  1196. } elseif (isset($row[$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
  1197. $newData[] = $row;
  1198. } elseif (isset($row[$join]) && isset($row[$join][$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
  1199. $newData[] = $row[$join];
  1200. }
  1201. }
  1202. if ($this->hasAndBelongsToMany[$assoc]['unique']) {
  1203. $conditions = array_merge(
  1204. array($join . '.' . $this->hasAndBelongsToMany[$assoc]['foreignKey'] => $id),
  1205. (array)$this->hasAndBelongsToMany[$assoc]['conditions']
  1206. );
  1207. $links = $this->{$join}->find('all', array(
  1208. 'conditions' => $conditions,
  1209. 'recursive' => empty($this->hasAndBelongsToMany[$assoc]['conditions']) ? -1 : 0,
  1210. 'fields' => $this->hasAndBelongsToMany[$assoc]['associationForeignKey']
  1211. ));
  1212. $associationForeignKey = "{$join}." . $this->hasAndBelongsToMany[$assoc]['associationForeignKey'];
  1213. $oldLinks = Set::extract($links, "{n}.{$associationForeignKey}");
  1214. if (!empty($oldLinks)) {
  1215. $conditions[$associationForeignKey] = $oldLinks;
  1216. $db->delete($this->{$join}, $conditions);
  1217. }
  1218. }
  1219. if (!empty($newData)) {
  1220. foreach ($newData as $data) {
  1221. $data[$this->hasAndBelongsToMany[$assoc]['foreignKey']] = $id;
  1222. $this->{$join}->create($data);
  1223. $this->{$join}->save();
  1224. }
  1225. }
  1226. if (!empty($newValues)) {
  1227. $fields = implode(',', $fields);
  1228. $db->insertMulti($this->{$join}, $fields, $newValues);
  1229. }
  1230. }
  1231. }
  1232. }
  1233. /**
  1234. * Updates the counter cache of belongsTo associations after a save or delete operation
  1235. *
  1236. * @param array $keys Optional foreign key data, defaults to the information $this->data
  1237. * @param boolean $created True if a new record was created, otherwise only associations with
  1238. * 'counterScope' defined get updated
  1239. * @return void
  1240. * @access public
  1241. */
  1242. public function updateCounterCache($keys = array(), $created = false) {
  1243. $keys = empty($keys) ? $this->data[$this->alias] : $keys;
  1244. $keys['old'] = isset($keys['old']) ? $keys['old'] : array();
  1245. foreach ($this->belongsTo as $parent => $assoc) {
  1246. $foreignKey = $assoc['foreignKey'];
  1247. $fkQuoted = $this->escapeField($assoc['foreignKey']);
  1248. if (!empty($assoc['counterCache'])) {
  1249. if ($assoc['counterCache'] === true) {
  1250. $assoc['counterCache'] = Inflector::underscore($this->alias) . '_count';
  1251. }
  1252. if (!$this->{$parent}->hasField($assoc['counterCache'])) {
  1253. continue;
  1254. }
  1255. if (!array_key_exists($foreignKey, $keys)) {
  1256. $keys[$foreignKey] = $this->field($foreignKey);
  1257. }
  1258. $recursive = (isset($assoc['counterScope']) ? 1 : -1);
  1259. $conditions = ($recursive == 1) ? (array)$assoc['counterScope'] : array();
  1260. if (isset($keys['old'][$foreignKey])) {
  1261. if ($keys['old'][$foreignKey] != $keys[$foreignKey]) {
  1262. $conditions[$fkQuoted] = $keys['old'][$foreignKey];
  1263. $count = intval($this->find('count', compact('conditions', 'recursive')));
  1264. $this->{$parent}->updateAll(
  1265. array($assoc['counterCache'] => $count),
  1266. array($this->{$parent}->escapeField() => $keys['old'][$foreignKey])
  1267. );
  1268. }
  1269. }
  1270. $conditions[$fkQuoted] = $keys[$foreignKey];
  1271. if ($recursive == 1) {
  1272. $conditions = array_merge($conditions, (array)$assoc['counterScope']);
  1273. }
  1274. $count = intval($this->find('count', compact('conditions', 'recursive')));
  1275. $this->{$parent}->updateAll(
  1276. array($assoc['counterCache'] => $count),
  1277. array($this->{$parent}->escapeField() => $keys[$foreignKey])
  1278. );
  1279. }
  1280. }
  1281. }
  1282. /**
  1283. * Helper method for Model::updateCounterCache(). Checks the fields to be updated for
  1284. *
  1285. * @param array $data The fields of the record that will be updated
  1286. * @return array Returns updated foreign key values, along with an 'old' key containing the old
  1287. * values, or empty if no foreign keys are updated.
  1288. * @access protected
  1289. */
  1290. protected function _prepareUpdateFields($data) {
  1291. $foreignKeys = array();
  1292. foreach ($this->belongsTo as $assoc => $info) {
  1293. if ($info['counterCache']) {
  1294. $foreignKeys[$assoc] = $info['foreignKey'];
  1295. }
  1296. }
  1297. $included = array_intersect($foreignKeys, array_keys($data));
  1298. if (empty($included) || empty($this->id)) {
  1299. return array();
  1300. }
  1301. $old = $this->find('first', array(
  1302. 'conditions' => array($this->primaryKey => $this->id),
  1303. 'fields' => array_values($included),
  1304. 'recursive' => -1
  1305. ));
  1306. return array_merge($data, array('old' => $old[$this->alias]));
  1307. }
  1308. /**
  1309. * Saves multiple individual records for a single model; Also works with a single record, as well as
  1310. * all its associated records.
  1311. *
  1312. * #### Options
  1313. *
  1314. * - validate: Set to false to disable validation, true to validate each record before
  1315. * saving, 'first' to validate *all* records before any are saved, or 'only' to only
  1316. * validate the records, but not save them.
  1317. * - atomic: If true (default), will attempt to save all records in a single transaction.
  1318. * Should be set to false if database/table does not support transactions.
  1319. * If false, we return an array similar to the $data array passed, but values are set to true/false
  1320. * depending on whether each record saved successfully.
  1321. * - fieldList: Equivalent to the $fieldList parameter in Model::save()
  1322. *
  1323. * @param array $data Record data to save. This can be either a numerically-indexed array (for saving multiple
  1324. * records of the same type), or an array indexed by association name.
  1325. * @param array $options Options to use when saving record data, See $options above.
  1326. * @return mixed True on success, or false on failure
  1327. * @access public
  1328. * @link http://book.cakephp.org/view/84/Saving-Related-Model-Data-hasOne-hasMany-belongsTo
  1329. * @link http://book.cakephp.org/view/75/Saving-Your-Data
  1330. */
  1331. public function saveAll($data = null, $options = array()) {
  1332. if (empty($data)) {
  1333. $data = $this->data;
  1334. }
  1335. $db = ConnectionManager::getDataSource($this->useDbConfig);
  1336. $options = array_merge(array('validate' => true, 'atomic' => true), $options);
  1337. $this->validationErrors = $validationErrors = array();
  1338. $validates = true;
  1339. $return = array();
  1340. if ($options['atomic'] && $options['validate'] !== 'only') {
  1341. $db->begin($this);
  1342. }
  1343. if (Set::numeric(array_keys($data))) {
  1344. while ($validates) {
  1345. foreach ($data as $key => $record) {
  1346. if (!$currentValidates = $this->__save($record, $options)) {
  1347. $validationErrors[$key] = $this->validationErrors;
  1348. }
  1349. if ($options['validate'] === 'only' || $options['validate'] === 'first') {
  1350. $validating = true;
  1351. if ($options['atomic']) {
  1352. $validates = $validates && $currentValidates;
  1353. } else {
  1354. $validates = $currentValidates;
  1355. }
  1356. } else {
  1357. $validating = false;
  1358. $validates = $currentValidates;
  1359. }
  1360. if (!$options['atomic']) {
  1361. $return[] = $validates;
  1362. } elseif (!$validates && !$validating) {
  1363. break;
  1364. }
  1365. }
  1366. $this->validationErrors = $validationErrors;
  1367. switch (true) {
  1368. case ($options['validate'] === 'only'):
  1369. return ($options['atomic'] ? $validates : $return);
  1370. break;
  1371. case ($options['validate'] === 'first'):
  1372. $options['validate'] = true;
  1373. continue;
  1374. break;
  1375. default:
  1376. if ($options['atomic']) {
  1377. if ($validates && ($db->commit($this) !== false)) {
  1378. return true;
  1379. }
  1380. $db->rollback($this);
  1381. return false;
  1382. }
  1383. return $return;
  1384. break;
  1385. }
  1386. }
  1387. return $return;
  1388. }
  1389. $associations = $this->getAssociated();
  1390. while ($validates) {
  1391. foreach ($data as $association => $values) {
  1392. if (isset($associations[$association])) {
  1393. switch ($associations[$association]) {
  1394. case 'belongsTo':
  1395. if ($this->{$association}->__save($values, $options)) {
  1396. $data[$this->alias][$this->belongsTo[$association]['foreignKey']] = $this->{$association}->id;
  1397. } else {
  1398. $validationErrors[$association] = $this->{$association}->validationErrors;
  1399. $validates = false;
  1400. }
  1401. if (!$options['atomic']) {
  1402. $return[$association][] = $validates;
  1403. }
  1404. break;
  1405. }
  1406. }
  1407. }
  1408. if (!$this->__save($data, $options)) {
  1409. $validationErrors[$this->alias] = $this->validationErrors;
  1410. $validates = false;
  1411. }
  1412. if (!$options['atomic']) {
  1413. $return[$this->alias] = $validates;
  1414. }
  1415. $validating = ($options['validate'] === 'only' || $options['validate'] === 'first');
  1416. foreach ($data as $association => $values) {
  1417. if (!$validates && !$validating) {
  1418. break;
  1419. }
  1420. if (isset($associations[$association])) {
  1421. $type = $associations[$association];
  1422. switch ($type) {
  1423. case 'hasOne':
  1424. $values[$this->{$type}[$association]['foreignKey']] = $this->id;
  1425. if (!$this->{$association}->__save($values, $options)) {
  1426. $validationErrors[$association] = $this->{$association}->validationErrors;
  1427. $validates = false;
  1428. }
  1429. if (!$options['atomic']) {
  1430. $return[$association][] = $validates;
  1431. }
  1432. break;
  1433. case 'hasMany':
  1434. foreach ($values as $i => $value) {
  1435. $values[$i][$this->{$type}[$association]['foreignKey']] = $this->id;
  1436. }
  1437. $_options = array_merge($options, array('atomic' => false));
  1438. if ($_options['validate'] === 'first') {
  1439. $_options['validate'] = 'only';
  1440. }
  1441. $_return = $this->{$association}->saveAll($values, $_options);
  1442. if ($_return === false || (is_array($_return) && in_array(false, $_return, true))) {
  1443. $validationErrors[$association] = $this->{$association}->validationErrors;
  1444. $validates = false;
  1445. }
  1446. if (is_array($_return)) {
  1447. foreach ($_return as $val) {
  1448. if (!isset($return[$association])) {
  1449. $return[$association] = array();
  1450. } elseif (!is_array($return[$association])) {
  1451. $return[$association] = array($return[$association]);
  1452. }
  1453. $return[$association][] = $val;
  1454. }
  1455. } else {
  1456. $return[$association] = $_return;
  1457. }
  1458. break;
  1459. }
  1460. }
  1461. }
  1462. $this->validationErrors = $validationErrors;
  1463. if (isset($validationErrors[$this->alias])) {
  1464. $this->validationErrors = $validationErrors[$this->alias];
  1465. }
  1466. switch (true) {
  1467. case ($options['validate'] === 'only'):
  1468. return ($options['atomic'] ? $validates : $return);
  1469. break;
  1470. case ($options['validate'] === 'first'):
  1471. $options['validate'] = true;
  1472. continue;
  1473. break;
  1474. default:
  1475. if ($options['atomic']) {
  1476. if ($validates) {
  1477. return ($db->commit($this) !== false);
  1478. } else {
  1479. $db->rollback($this);
  1480. }
  1481. }
  1482. return $return;
  1483. break;
  1484. }
  1485. }
  1486. }
  1487. /**
  1488. * Private helper method used by saveAll.
  1489. *
  1490. * @return boolean Success
  1491. * @access private
  1492. * @see Model::saveAll()
  1493. */
  1494. private function __save($data, $options) {
  1495. if ($options['validate'] === 'first' || $options['validate'] === 'only') {
  1496. if (!($this->create($data) && $this->validates($options))) {
  1497. return false;
  1498. }
  1499. } elseif (!($this->create(null) !== null && $this->save($data, $options))) {
  1500. return false;
  1501. }
  1502. return true;
  1503. }
  1504. /**
  1505. * Updates multiple model records based on a set of conditions.
  1506. *
  1507. * @param array $fields Set of fields and values, indexed by fields.
  1508. * Fields are treated as SQL snippets, to insert literal values manually escape your data.
  1509. * @param mixed $conditions Conditions to match, true for all records
  1510. * @return boolean True on success, false on failure
  1511. * @access public
  1512. * @link http://book.cakephp.org/view/75/Saving-Your-Data
  1513. */
  1514. public function updateAll($fields, $conditions = true) {
  1515. $db = ConnectionManager::getDataSource($this->useDbConfig);
  1516. return $db->update($this, $fields, null, $conditions);
  1517. }
  1518. /**
  1519. * @deprecated
  1520. * @link http://book.cakephp.org/view/691/remove
  1521. */
  1522. function remove($id = null, $cascade = true) {
  1523. trigger_error('Deprecated method, use Model::delete instead', E_USER_WARNING);
  1524. return $this->delete($id, $cascade);
  1525. }
  1526. /**
  1527. * Removes record for given ID. If no ID is given, the current ID is used. Returns true on success.
  1528. *
  1529. * @param mixed $id ID of record to delete
  1530. * @param boolean $cascade Set to true to delete records that depend on this record
  1531. * @return boolean True on success
  1532. * @access public
  1533. * @link http://book.cakephp.org/view/690/del
  1534. */
  1535. public function delete($id = null, $cascade = true) {
  1536. if (!empty($id)) {
  1537. $this->id = $id;
  1538. }
  1539. $id = $this->id;
  1540. if ($this->exists() && $this->beforeDelete($cascade)) {
  1541. $db = ConnectionManager::getDataSource($this->useDbConfig);
  1542. $filters = $this->Behaviors->trigger($this, 'beforeDelete', array($cascade), array(
  1543. 'break' => true, 'breakOn' => false
  1544. ));
  1545. if (!$filters) {
  1546. return false;
  1547. }
  1548. $this->_deleteDependent($id, $cascade);
  1549. $this->_deleteLinks($id);
  1550. $this->id = $id;
  1551. if (!empty($this->belongsTo)) {
  1552. $keys = $this->find('first', array('fields' => $this->__collectForeignKeys()));
  1553. }
  1554. if ($db->delete($this)) {
  1555. if (!empty($this->belongsTo)) {
  1556. $this->updateCounterCache($keys[$this->alias]);
  1557. }
  1558. $this->Behaviors->trigger($this, 'afterDelete');
  1559. $this->afterDelete();
  1560. $this->_clearCache();
  1561. $this->id = false;
  1562. $this->__exists = null;
  1563. return true;
  1564. }
  1565. }
  1566. return false;
  1567. }
  1568. /**
  1569. * Cascades model deletes through associated hasMany and hasOne child records.
  1570. *
  1571. * @param string $id ID of record that was deleted
  1572. * @param boolean $cascade Set to true to delete records that depend on this record
  1573. * @return void
  1574. * @access protected
  1575. */
  1576. protected function _deleteDependent($id, $cascade) {
  1577. if (!empty($this->__backAssociation)) {
  1578. $savedAssociatons = $this->__backAssociation;
  1579. $this->__backAssociation = array();
  1580. }
  1581. foreach (array_merge($this->hasMany, $this->hasOne) as $assoc => $data) {
  1582. if ($data['dependent'] === true && $cascade === true) {
  1583. $model = $this->{$assoc};
  1584. $conditions = array($model->escapeField($data['foreignKey']) => $id);
  1585. if ($data['conditions']) {
  1586. $conditions = array_merge($data['conditions'], $conditions);
  1587. }
  1588. $model->recursive = -1;
  1589. if (isset($data['exclusive']) && $data['exclusive']) {
  1590. $model->deleteAll($conditions);
  1591. } else {
  1592. $records = $model->find('all', array(
  1593. 'conditions' => $conditions, 'fields' => $model->primaryKey
  1594. ));
  1595. if (!empty($records)) {
  1596. foreach ($records as $record) {
  1597. $model->delete($record[$model->alias][$model->primaryKey]);
  1598. }
  1599. }
  1600. }
  1601. }
  1602. }
  1603. if (isset($savedAssociatons)) {
  1604. $this->__backAssociation = $savedAssociatons;
  1605. }
  1606. }
  1607. /**
  1608. * Cascades model deletes through HABTM join keys.
  1609. *
  1610. * @param string $id ID of record that was deleted
  1611. * @return void
  1612. * @access protected
  1613. */
  1614. protected function _deleteLinks($id) {
  1615. foreach ($this->hasAndBelongsToMany as $assoc => $data) {
  1616. $with = $data['with'];
  1617. $records = $this->{$data['with']}->find('all', array(
  1618. 'conditions' => array_merge(array(
  1619. $this->{$with}->escapeField($data['foreignKey']) => $id
  1620. )),
  1621. 'fields' => $this->{$with}->primaryKey,
  1622. 'recursive' => -1
  1623. ));
  1624. if (!empty($records)) {
  1625. foreach ($records as $record) {
  1626. $id = $record[$this->{$with}->alias][$this->{$with}->primaryKey];
  1627. $this->{$with}->delete($id);
  1628. }
  1629. }
  1630. }
  1631. }
  1632. /**
  1633. * Deletes multiple model records based on a set of conditions.
  1634. *
  1635. * @param mixed $conditions Conditions to match
  1636. * @param boolean $cascade Set to true to delete records that depend on this record
  1637. * @param boolean $callbacks Run callbacks (not being used)
  1638. * @return boolean True on success, false on failure
  1639. * @access public
  1640. * @link http://book.cakephp.org/view/692/deleteAll
  1641. */
  1642. public function deleteAll($conditions, $cascade = true, $callbacks = false) {
  1643. if (empty($conditions)) {
  1644. return false;
  1645. }
  1646. $db = ConnectionManager::getDataSource($this->useDbConfig);
  1647. if (!$cascade && !$callbacks) {
  1648. return $db->delete($this, $conditions);
  1649. } else {
  1650. $ids = Set::extract(
  1651. $this->find('all', array_merge(array(
  1652. 'fields' => "{$this->alias}.{$this->primaryKey}",
  1653. 'recursive' => 0), compact('conditions'))
  1654. ),
  1655. "{n}.{$this->alias}.{$this->primaryKey}"
  1656. );
  1657. if (empty($ids)) {
  1658. return true;
  1659. }
  1660. if ($callbacks) {
  1661. $_id = $this->id;
  1662. $result = true;
  1663. foreach ($ids as $id) {
  1664. $result = ($result && $this->delete($id, $cascade));
  1665. }
  1666. $this->id = $_id;
  1667. return $result;
  1668. } else {
  1669. foreach ($ids as $id) {
  1670. $this->_deleteLinks($id);
  1671. if ($cascade) {
  1672. $this->_deleteDependent($id, $cascade);
  1673. }
  1674. }
  1675. return $db->delete($this, array($this->alias . '.' . $this->primaryKey => $ids));
  1676. }
  1677. }
  1678. }
  1679. /**
  1680. * Collects foreign keys from associations.
  1681. *
  1682. * @return array
  1683. * @access private
  1684. */
  1685. private function __collectForeignKeys($type = 'belongsTo') {
  1686. $result = array();
  1687. foreach ($this->{$type} as $assoc => $data) {
  1688. if (isset($data['foreignKey']) && is_string($data['foreignKey'])) {
  1689. $result[$assoc] = $data['foreignKey'];
  1690. }
  1691. }
  1692. return $result;
  1693. }
  1694. /**
  1695. * Returns true if a record with the currently set ID exists.
  1696. *
  1697. * @param boolean $reset if true will force database query
  1698. * @return boolean True if such a record exists
  1699. * @access public
  1700. */
  1701. public function exists($reset = false) {
  1702. if (is_array($reset)) {
  1703. extract($reset, EXTR_OVERWRITE);
  1704. }
  1705. if ($this->getID() === false || $this->useTable === false) {
  1706. return false;
  1707. }
  1708. if (!empty($this->__exists) && $reset !== true) {
  1709. return $this->__exists;
  1710. }
  1711. $conditions = array($this->alias . '.' . $this->primaryKey => $this->getID());
  1712. $query = array('conditions' => $conditions, 'recursive' => -1, 'callbacks' => false);
  1713. if (is_array($reset)) {
  1714. $query = array_merge($query, $reset);
  1715. }
  1716. return $this->__exists = ($this->find('count', $query) > 0);
  1717. }
  1718. /**
  1719. * Returns true if a record that meets given conditions exists.
  1720. *
  1721. * @param array $conditions SQL conditions array
  1722. * @return boolean True if such a record exists
  1723. * @access public
  1724. */
  1725. public function hasAny($conditions = null) {
  1726. return ($this->find('count', array('conditions' => $conditions, 'recursive' => -1)) != false);
  1727. }
  1728. /**
  1729. * Returns a result set array.
  1730. *
  1731. * Also used to perform new-notation finds, where the first argument is type of find operation to perform
  1732. * (all / first / count / neighbors / list / threaded ),
  1733. * second parameter options for finding ( indexed array, including: 'conditions', 'limit',
  1734. * 'recursive', 'page', 'fields', 'offset', 'order')
  1735. *
  1736. * Eg:
  1737. * {{{
  1738. * find('all', array(
  1739. * 'conditions' => array('name' => 'Thomas Anderson'),
  1740. * 'fields' => array('name', 'email'),
  1741. * 'order' => 'field3 DESC',
  1742. * 'recursive' => 2,
  1743. * 'group' => 'type'
  1744. * ));
  1745. * }}}
  1746. *
  1747. * Specifying 'fields' for new-notation 'list':
  1748. *
  1749. * - If no fields are specified, then 'id' is used for key and 'model->displayField' is used for value.
  1750. * - If a single field is specified, 'id' is used for key and specified field is used for value.
  1751. * - If three fields are specified, they are used (in order) for key, value and group.
  1752. * - Otherwise, first and second fields are used for key and value.
  1753. *
  1754. * @param array $conditions SQL conditions array, or type of find operation (all / first / count /
  1755. * neighbors / list / threaded)
  1756. * @param mixed $fields Either a single string of a field name, or an array of field names, or
  1757. * options for matching
  1758. * @param string $order SQL ORDER BY conditions (e.g. "price DESC" or "name ASC")
  1759. * @param integer $recursive The number of levels deep to fetch associated records
  1760. * @return array Array of records
  1761. * @access public
  1762. * @link http://book.cakephp.org/view/449/find
  1763. */
  1764. public function find($conditions = null, $fields = array(), $order = null, $recursive = null) {
  1765. if (!is_string($conditions) || (is_string($conditions) && !array_key_exists($conditions, $this->_findMethods))) {
  1766. $type = 'first';
  1767. $query = array_merge(compact('conditions', 'fields', 'order', 'recursive'), array('limit' => 1));
  1768. } else {
  1769. list($type, $query) = array($conditions, $fields);
  1770. }
  1771. $this->findQueryType = $type;
  1772. $this->id = $this->getID();
  1773. $query = array_merge(
  1774. array(
  1775. 'conditions' => null, 'fields' => null, 'joins' => array(), 'limit' => null,
  1776. 'offset' => null, 'order' => null, 'page' => null, 'group' => null, 'callbacks' => true
  1777. ),
  1778. (array)$query
  1779. );
  1780. if ($type != 'all') {
  1781. if ($this->_findMethods[$type] === true) {
  1782. $query = $this->{'_find' . ucfirst($type)}('before', $query);
  1783. }
  1784. }
  1785. if (!is_numeric($query['page']) || intval($query['page']) < 1) {
  1786. $query['page'] = 1;
  1787. }
  1788. if ($query['page'] > 1 && !empty($query['limit'])) {
  1789. $query['offset'] = ($query['page'] - 1) * $query['limit'];
  1790. }
  1791. if ($query['order'] === null && $this->order !== null) {
  1792. $query['order'] = $this->order;
  1793. }
  1794. $query['order'] = array($query['order']);
  1795. if ($query['callbacks'] === true || $query['callbacks'] === 'before') {
  1796. $return = $this->Behaviors->trigger($this, 'beforeFind', array($query), array(
  1797. 'break' => true, 'breakOn' => false, 'modParams' => true
  1798. ));
  1799. $query = (is_array($return)) ? $return : $query;
  1800. if ($return === false) {
  1801. return null;
  1802. }
  1803. $return = $this->beforeFind($query);
  1804. $query = (is_array($return)) ? $return : $query;
  1805. if ($return === false) {
  1806. return null;
  1807. }
  1808. }
  1809. if (!$db = ConnectionManager::getDataSource($this->useDbConfig)) {
  1810. return false;
  1811. }
  1812. $results = $db->read($this, $query);
  1813. $this->resetAssociations();
  1814. if ($query['callbacks'] === true || $query['callbacks'] === 'after') {
  1815. $results = $this->__filterResults($results);
  1816. }
  1817. $this->findQueryType = null;
  1818. if ($type === 'all') {
  1819. return $results;
  1820. } else {
  1821. if ($this->_findMethods[$type] === true) {
  1822. return $this->{'_find' . ucfirst($type)}('after', $query, $results);
  1823. }
  1824. }
  1825. }
  1826. /**
  1827. * Handles the before/after filter logic for find('first') operations. Only called by Model::find().
  1828. *
  1829. * @param string $state Either "before" or "after"
  1830. * @param array $query
  1831. * @param array $data
  1832. * @return array
  1833. * @access protected
  1834. * @see Model::find()
  1835. */
  1836. protected function _findFirst($state, $query, $results = array()) {
  1837. if ($state == 'before') {
  1838. $query['limit'] = 1;
  1839. if (empty($query['conditions']) && !empty($this->id)) {
  1840. $query['conditions'] = array($this->escapeField() => $this->id);
  1841. }
  1842. return $query;
  1843. } elseif ($state == 'after') {
  1844. if (empty($results[0])) {
  1845. return false;
  1846. }
  1847. return $results[0];
  1848. }
  1849. }
  1850. /**
  1851. * Handles the before/after filter logic for find('count') operations. Only called by Model::find().
  1852. *
  1853. * @param string $state Either "before" or "after"
  1854. * @param array $query
  1855. * @param array $data
  1856. * @return int The number of records found, or false
  1857. * @access protected
  1858. * @see Model::find()
  1859. */
  1860. protected function _findCount($state, $query, $results = array()) {
  1861. if ($state == 'before') {
  1862. $db = ConnectionManager::getDataSource($this->useDbConfig);
  1863. if (empty($query['fields'])) {
  1864. $query['fields'] = $db->calculate($this, 'count');
  1865. } elseif (is_string($query['fields']) && !preg_match('/count/i', $query['fields'])) {
  1866. $query['fields'] = $db->calculate($this, 'count', array(
  1867. $db->expression($query['fields']), 'count'
  1868. ));
  1869. }
  1870. $query['order'] = false;
  1871. return $query;
  1872. } elseif ($state == 'after') {
  1873. if (isset($results[0][0]['count'])) {
  1874. return intval($results[0][0]['count']);
  1875. } elseif (isset($results[0][$this->alias]['count'])) {
  1876. return intval($results[0][$this->alias]['count']);
  1877. }
  1878. return false;
  1879. }
  1880. }
  1881. /**
  1882. * Handles the before/after filter logic for find('list') operations. Only called by Model::find().
  1883. *
  1884. * @param string $state Either "before" or "after"
  1885. * @param array $query
  1886. * @param array $data
  1887. * @return array Key/value pairs of primary keys/display field values of all records found
  1888. * @access protected
  1889. * @see Model::find()
  1890. */
  1891. protected function _findList($state, $query, $results = array()) {
  1892. if ($state == 'before') {
  1893. if (empty($query['fields'])) {
  1894. $query['fields'] = array("{$this->alias}.{$this->primaryKey}", "{$this->alias}.{$this->displayField}");
  1895. $list = array("{n}.{$this->alias}.{$this->primaryKey}", "{n}.{$this->alias}.{$this->displayField}", null);
  1896. } else {
  1897. if (!is_array($query['fields'])) {
  1898. $query['fields'] = String::tokenize($query['fields']);
  1899. }
  1900. if (count($query['fields']) == 1) {
  1901. if (strpos($query['fields'][0], '.') === false) {
  1902. $query['fields'][0] = $this->alias . '.' . $query['fields'][0];
  1903. }
  1904. $list = array("{n}.{$this->alias}.{$this->primaryKey}", '{n}.' . $query['fields'][0], null);
  1905. $query['fields'] = array("{$this->alias}.{$this->primaryKey}", $query['fields'][0]);
  1906. } elseif (count($query['fields']) == 3) {
  1907. for ($i = 0; $i < 3; $i++) {
  1908. if (strpos($query['fields'][$i], '.') === false) {
  1909. $query['fields'][$i] = $this->alias . '.' . $query['fields'][$i];
  1910. }
  1911. }
  1912. $list = array('{n}.' . $query['fields'][0], '{n}.' . $query['fields'][1], '{n}.' . $query['fields'][2]);
  1913. } else {
  1914. for ($i = 0; $i < 2; $i++) {
  1915. if (strpos($query['fields'][$i], '.') === false) {
  1916. $query['fields'][$i] = $this->alias . '.' . $query['fields'][$i];
  1917. }
  1918. }
  1919. $list = array('{n}.' . $query['fields'][0], '{n}.' . $query['fields'][1], null);
  1920. }
  1921. }
  1922. if (!isset($query['recursive']) || $query['recursive'] === null) {
  1923. $query['recursive'] = -1;
  1924. }
  1925. list($query['list']['keyPath'], $query['list']['valuePath'], $query['list']['groupPath']) = $list;
  1926. return $query;
  1927. } elseif ($state == 'after') {
  1928. if (empty($results)) {
  1929. return array();
  1930. }
  1931. $lst = $query['list'];
  1932. return Set::combine($results, $lst['keyPath'], $lst['valuePath'], $lst['groupPath']);
  1933. }
  1934. }
  1935. /**
  1936. * Detects the previous field's value, then uses logic to find the 'wrapping'
  1937. * rows and return them.
  1938. *
  1939. * @param string $state Either "before" or "after"
  1940. * @param mixed $query
  1941. * @param array $results
  1942. * @return array
  1943. * @access protected
  1944. */
  1945. protected function _findNeighbors($state, $query, $results = array()) {
  1946. if ($state == 'before') {
  1947. $query = array_merge(array('recursive' => 0), $query);
  1948. extract($query);
  1949. $conditions = (array)$conditions;
  1950. if (isset($field) && isset($value)) {
  1951. if (strpos($field, '.') === false) {
  1952. $field = $this->alias . '.' . $field;
  1953. }
  1954. } else {
  1955. $field = $this->alias . '.' . $this->primaryKey;
  1956. $value = $this->id;
  1957. }
  1958. $query['conditions'] = array_merge($conditions, array($field . ' <' => $value));
  1959. $query['order'] = $field . ' DESC';
  1960. $query['limit'] = 1;
  1961. $query['field'] = $field;
  1962. $query['value'] = $value;
  1963. return $query;
  1964. } elseif ($state == 'after') {
  1965. extract($query);
  1966. unset($query['conditions'][$field . ' <']);
  1967. $return = array();
  1968. if (isset($results[0])) {
  1969. $prevVal = Set::extract('/' . str_replace('.', '/', $field), $results[0]);
  1970. $query['conditions'][$field . ' >='] = $prevVal[0];
  1971. $query['conditions'][$field . ' !='] = $value;
  1972. $query['limit'] = 2;
  1973. } else {
  1974. $return['prev'] = null;
  1975. $query['conditions'][$field . ' >'] = $value;
  1976. $query['limit'] = 1;
  1977. }
  1978. $query['order'] = $field . ' ASC';
  1979. $return2 = $this->find('all', $query);
  1980. if (!array_key_exists('prev', $return)) {
  1981. $return['prev'] = $return2[0];
  1982. }
  1983. if (count($return2) == 2) {
  1984. $return['next'] = $return2[1];
  1985. } elseif (count($return2) == 1 && !$return['prev']) {
  1986. $return['next'] = $return2[0];
  1987. } else {
  1988. $return['next'] = null;
  1989. }
  1990. return $return;
  1991. }
  1992. }
  1993. /**
  1994. * In the event of ambiguous results returned (multiple top level results, with different parent_ids)
  1995. * top level results with different parent_ids to the first result will be dropped
  1996. *
  1997. * @param mixed $state
  1998. * @param mixed $query
  1999. * @param array $results
  2000. * @return array Threaded results
  2001. * @access protected
  2002. */
  2003. protected function _findThreaded($state, $query, $results = array()) {
  2004. if ($state == 'before') {
  2005. return $query;
  2006. } elseif ($state == 'after') {
  2007. $return = $idMap = array();
  2008. $ids = Set::extract($results, '{n}.' . $this->alias . '.' . $this->primaryKey);
  2009. foreach ($results as $result) {
  2010. $result['children'] = array();
  2011. $id = $result[$this->alias][$this->primaryKey];
  2012. $parentId = $result[$this->alias]['parent_id'];
  2013. if (isset($idMap[$id]['children'])) {
  2014. $idMap[$id] = array_merge($result, (array)$idMap[$id]);
  2015. } else {
  2016. $idMap[$id] = array_merge($result, array('children' => array()));
  2017. }
  2018. if (!$parentId || !in_array($parentId, $ids)) {
  2019. $return[] =& $idMap[$id];
  2020. } else {
  2021. $idMap[$parentId]['children'][] =& $idMap[$id];
  2022. }
  2023. }
  2024. if (count($return) > 1) {
  2025. $ids = array_unique(Set::extract('/' . $this->alias . '/parent_id', $return));
  2026. if (count($ids) > 1) {
  2027. $root = $return[0][$this->alias]['parent_id'];
  2028. foreach ($return as $key => $value) {
  2029. if ($value[$this->alias]['parent_id'] != $root) {
  2030. unset($return[$key]);
  2031. }
  2032. }
  2033. }
  2034. }
  2035. return $return;
  2036. }
  2037. }
  2038. /**
  2039. * Passes query results through model and behavior afterFilter() methods.
  2040. *
  2041. * @param array Results to filter
  2042. * @param boolean $primary If this is the primary model results (results from model where the find operation was performed)
  2043. * @return array Set of filtered results
  2044. * @access private
  2045. */
  2046. private function __filterResults($results, $primary = true) {
  2047. $return = $this->Behaviors->trigger($this, 'afterFind', array($results, $primary), array('modParams' => true));
  2048. if ($return !== true) {
  2049. $results = $return;
  2050. }
  2051. return $this->afterFind($results, $primary);
  2052. }
  2053. /**
  2054. * Called only when bindTo<ModelName>() is used.
  2055. * This resets the association arrays for the model back
  2056. * to those originally defined in the model.
  2057. *
  2058. * @return boolean Success
  2059. * @access public
  2060. */
  2061. public function resetAssociations() {
  2062. if (!empty($this->__backAssociation)) {
  2063. foreach ($this->__associations as $type) {
  2064. if (isset($this->__backAssociation[$type])) {
  2065. $this->{$type} = $this->__backAssociation[$type];
  2066. }
  2067. }
  2068. $this->__backAssociation = array();
  2069. }
  2070. foreach ($this->__associations as $type) {
  2071. foreach ($this->{$type} as $key => $name) {
  2072. if (!empty($this->{$key}->__backAssociation)) {
  2073. $this->{$key}->resetAssociations();
  2074. }
  2075. }
  2076. }
  2077. $this->__backAssociation = array();
  2078. return true;
  2079. }
  2080. /**
  2081. * Returns false if any fields passed match any (by default, all if $or = false) of their matching values.
  2082. *
  2083. * @param array $fields Field/value pairs to search (if no values specified, they are pulled from $this->data)
  2084. * @param boolean $or If false, all fields specified must match in order for a false return value
  2085. * @return boolean False if any records matching any fields are found
  2086. * @access public
  2087. */
  2088. public function isUnique($fields, $or = true) {
  2089. if (!is_array($fields)) {
  2090. $fields = func_get_args();
  2091. if (is_bool($fields[count($fields) - 1])) {
  2092. $or = $fields[count($fields) - 1];
  2093. unset($fields[count($fields) - 1]);
  2094. }
  2095. }
  2096. foreach ($fields as $field => $value) {
  2097. if (is_numeric($field)) {
  2098. unset($fields[$field]);
  2099. $field = $value;
  2100. if (isset($this->data[$this->alias][$field])) {
  2101. $value = $this->data[$this->alias][$field];
  2102. } else {
  2103. $value = null;
  2104. }
  2105. }
  2106. if (strpos($field, '.') === false) {
  2107. unset($fields[$field]);
  2108. $fields[$this->alias . '.' . $field] = $value;
  2109. }
  2110. }
  2111. if ($or) {
  2112. $fields = array('or' => $fields);
  2113. }
  2114. if (!empty($this->id)) {
  2115. $fields[$this->alias . '.' . $this->primaryKey . ' !='] = $this->id;
  2116. }
  2117. return ($this->find('count', array('conditions' => $fields, 'recursive' => -1)) == 0);
  2118. }
  2119. /**
  2120. * Returns a resultset for a given SQL statement. Custom SQL queries should be performed with this method.
  2121. *
  2122. * @param string $sql SQL statement
  2123. * @return array Resultset
  2124. * @access public
  2125. * @link http://book.cakephp.org/view/456/query
  2126. */
  2127. public function query() {
  2128. $params = func_get_args();
  2129. $db = ConnectionManager::getDataSource($this->useDbConfig);
  2130. return call_user_func_array(array(&$db, 'query'), $params);
  2131. }
  2132. /**
  2133. * Returns true if all fields pass validation.
  2134. *
  2135. * Will validate the currently set data. Use Model::set() or Model::create() to set the active data.
  2136. *
  2137. * @param string $options An optional array of custom options to be made available in the beforeValidate callback
  2138. * @return boolean True if there are no errors
  2139. * @access public
  2140. * @link http://book.cakephp.org/view/410/Validating-Data-from-the-Controller
  2141. */
  2142. public function validates($options = array()) {
  2143. $errors = $this->invalidFields($options);
  2144. if (is_array($errors)) {
  2145. return count($errors) === 0;
  2146. }
  2147. return $errors;
  2148. }
  2149. /**
  2150. * Returns an array of fields that have failed validation.
  2151. *
  2152. * @param string $options An optional array of custom options to be made available in the beforeValidate callback
  2153. * @return array Array of invalid fields
  2154. * @see Model::validates()
  2155. * @access public
  2156. * @link http://book.cakephp.org/view/410/Validating-Data-from-the-Controller
  2157. */
  2158. public function invalidFields($options = array()) {
  2159. if (
  2160. !$this->Behaviors->trigger(
  2161. $this,
  2162. 'beforeValidate',
  2163. array($options),
  2164. array('break' => true, 'breakOn' => false)
  2165. ) ||
  2166. $this->beforeValidate($options) === false
  2167. ) {
  2168. return false;
  2169. }
  2170. if (!isset($this->validate) || empty($this->validate)) {
  2171. return $this->validationErrors;
  2172. }
  2173. $data = $this->data;
  2174. $methods = array_map('strtolower', get_class_methods($this));
  2175. $behaviorMethods = array_keys($this->Behaviors->methods());
  2176. if (isset($data[$this->alias])) {
  2177. $data = $data[$this->alias];
  2178. } elseif (!is_array($data)) {
  2179. $data = array();
  2180. }
  2181. $this->exists();
  2182. $_validate = $this->validate;
  2183. $whitelist = $this->whitelist;
  2184. if (array_key_exists('fieldList', $options)) {
  2185. $whitelist = $options['fieldList'];
  2186. }
  2187. if (!empty($whitelist)) {
  2188. $validate = array();
  2189. foreach ((array)$whitelist as $f) {
  2190. if (!empty($this->validate[$f])) {
  2191. $validate[$f] = $this->validate[$f];
  2192. }
  2193. }
  2194. $this->validate = $validate;
  2195. }
  2196. foreach ($this->validate as $fieldName => $ruleSet) {
  2197. if (!is_array($ruleSet) || (is_array($ruleSet) && isset($ruleSet['rule']))) {
  2198. $ruleSet = array($ruleSet);
  2199. }
  2200. $default = array(
  2201. 'allowEmpty' => null,
  2202. 'required' => null,
  2203. 'rule' => 'blank',
  2204. 'last' => false,
  2205. 'on' => null
  2206. );
  2207. foreach ($ruleSet as $index => $validator) {
  2208. if (!is_array($validator)) {
  2209. $validator = array('rule' => $validator);
  2210. }
  2211. $validator = array_merge($default, $validator);
  2212. if (isset($validator['message'])) {
  2213. $message = $validator['message'];
  2214. } else {
  2215. $message = __('This field cannot be left blank', true);
  2216. }
  2217. if (
  2218. empty($validator['on']) || ($validator['on'] == 'create' &&
  2219. !$this->__exists) || ($validator['on'] == 'update' && $this->__exists
  2220. )) {
  2221. $required = (
  2222. (!isset($data[$fieldName]) && $validator['required'] === true) ||
  2223. (
  2224. isset($data[$fieldName]) && (empty($data[$fieldName]) &&
  2225. !is_numeric($data[$fieldName])) && $validator['allowEmpty'] === false
  2226. )
  2227. );
  2228. if ($required) {
  2229. $this->invalidate($fieldName, $message);
  2230. if ($validator['last']) {
  2231. break;
  2232. }
  2233. } elseif (array_key_exists($fieldName, $data)) {
  2234. if (empty($data[$fieldName]) && $data[$fieldName] != '0' && $validator['allowEmpty'] === true) {
  2235. break;
  2236. }
  2237. if (is_array($validator['rule'])) {
  2238. $rule = $validator['rule'][0];
  2239. unset($validator['rule'][0]);
  2240. $ruleParams = array_merge(array($data[$fieldName]), array_values($validator['rule']));
  2241. } else {
  2242. $rule = $validator['rule'];
  2243. $ruleParams = array($data[$fieldName]);
  2244. }
  2245. $valid = true;
  2246. if (in_array(strtolower($rule), $methods)) {
  2247. $ruleParams[] = $validator;
  2248. $ruleParams[0] = array($fieldName => $ruleParams[0]);
  2249. $valid = $this->dispatchMethod($rule, $ruleParams);
  2250. } elseif (in_array($rule, $behaviorMethods) || in_array(strtolower($rule), $behaviorMethods)) {
  2251. $ruleParams[] = $validator;
  2252. $ruleParams[0] = array($fieldName => $ruleParams[0]);
  2253. $valid = $this->Behaviors->dispatchMethod($this, $rule, $ruleParams);
  2254. } elseif (method_exists('Validation', $rule)) {
  2255. $valid = Validation::dispatchMethod($rule, $ruleParams);
  2256. } elseif (!is_array($validator['rule'])) {
  2257. $valid = preg_match($rule, $data[$fieldName]);
  2258. } elseif (Configure::read('debug') > 0) {
  2259. $error = sprintf(
  2260. __('Could not find validation handler %s for %s', true),
  2261. $rule,
  2262. $fieldName
  2263. );
  2264. trigger_error($error, E_USER_WARNING);
  2265. }
  2266. if (!$valid || (is_string($valid) && strlen($valid) > 0)) {
  2267. if (is_string($valid) && strlen($valid) > 0) {
  2268. $validator['message'] = $valid;
  2269. } elseif (!isset($validator['message'])) {
  2270. if (is_string($index)) {
  2271. $validator['message'] = $index;
  2272. } elseif (is_numeric($index) && count($ruleSet) > 1) {
  2273. $validator['message'] = $index + 1;
  2274. } else {
  2275. $validator['message'] = $message;
  2276. }
  2277. }
  2278. $this->invalidate($fieldName, $validator['message']);
  2279. if ($validator['last']) {
  2280. break;
  2281. }
  2282. }
  2283. }
  2284. }
  2285. }
  2286. }
  2287. $this->validate = $_validate;
  2288. return $this->validationErrors;
  2289. }
  2290. /**
  2291. * Marks a field as invalid, optionally setting the name of validation
  2292. * rule (in case of multiple validation for field) that was broken.
  2293. *
  2294. * @param string $field The name of the field to invalidate
  2295. * @param mixed $value Name of validation rule that was not failed, or validation message to
  2296. * be returned. If no validation key is provided, defaults to true.
  2297. * @access public
  2298. */
  2299. public function invalidate($field, $value = true) {
  2300. if (!is_array($this->validationErrors)) {
  2301. $this->validationErrors = array();
  2302. }
  2303. $this->validationErrors[$field] = $value;
  2304. }
  2305. /**
  2306. * Returns true if given field name is a foreign key in this model.
  2307. *
  2308. * @param string $field Returns true if the input string ends in "_id"
  2309. * @return boolean True if the field is a foreign key listed in the belongsTo array.
  2310. * @access public
  2311. */
  2312. public function isForeignKey($field) {
  2313. $foreignKeys = array();
  2314. if (!empty($this->belongsTo)) {
  2315. foreach ($this->belongsTo as $assoc => $data) {
  2316. $foreignKeys[] = $data['foreignKey'];
  2317. }
  2318. }
  2319. return in_array($field, $foreignKeys);
  2320. }
  2321. /**
  2322. * Escapes the field name and prepends the model name. Escaping is done according to the current database driver's rules.
  2323. *
  2324. * @param string $field Field to escape (e.g: id)
  2325. * @param string $alias Alias for the model (e.g: Post)
  2326. * @return string The name of the escaped field for this Model (i.e. id becomes `Post`.`id`).
  2327. * @access public
  2328. */
  2329. public function escapeField($field = null, $alias = null) {
  2330. if (empty($alias)) {
  2331. $alias = $this->alias;
  2332. }
  2333. if (empty($field)) {
  2334. $field = $this->primaryKey;
  2335. }
  2336. $db = ConnectionManager::getDataSource($this->useDbConfig);
  2337. if (strpos($field, $db->name($alias)) === 0) {
  2338. return $field;
  2339. }
  2340. return $db->name($alias . '.' . $field);
  2341. }
  2342. /**
  2343. * Returns the current record's ID
  2344. *
  2345. * @param integer $list Index on which the composed ID is located
  2346. * @return mixed The ID of the current record, false if no ID
  2347. * @access public
  2348. */
  2349. public function getID($list = 0) {
  2350. if (empty($this->id) || (is_array($this->id) && isset($this->id[0]) && empty($this->id[0]))) {
  2351. return false;
  2352. }
  2353. if (!is_array($this->id)) {
  2354. return $this->id;
  2355. }
  2356. if (empty($this->id)) {
  2357. return false;
  2358. }
  2359. if (isset($this->id[$list]) && !empty($this->id[$list])) {
  2360. return $this->id[$list];
  2361. } elseif (isset($this->id[$list])) {
  2362. return false;
  2363. }
  2364. foreach ($this->id as $id) {
  2365. return $id;
  2366. }
  2367. return false;
  2368. }
  2369. /**
  2370. * Returns the ID of the last record this model inserted.
  2371. *
  2372. * @return mixed Last inserted ID
  2373. * @access public
  2374. */
  2375. public function getLastInsertID() {
  2376. return $this->getInsertID();
  2377. }
  2378. /**
  2379. * Returns the ID of the last record this model inserted.
  2380. *
  2381. * @return mixed Last inserted ID
  2382. * @access public
  2383. */
  2384. public function getInsertID() {
  2385. return $this->__insertID;
  2386. }
  2387. /**
  2388. * Sets the ID of the last record this model inserted
  2389. *
  2390. * @param mixed Last inserted ID
  2391. * @access public
  2392. */
  2393. public function setInsertID($id) {
  2394. $this->__insertID = $id;
  2395. }
  2396. /**
  2397. * Returns the number of rows returned from the last query.
  2398. *
  2399. * @return int Number of rows
  2400. * @access public
  2401. */
  2402. public function getNumRows() {
  2403. $db = ConnectionManager::getDataSource($this->useDbConfig);
  2404. return $db->lastNumRows();
  2405. }
  2406. /**
  2407. * Returns the number of rows affected by the last query.
  2408. *
  2409. * @return int Number of rows
  2410. * @access public
  2411. */
  2412. public function getAffectedRows() {
  2413. $db = ConnectionManager::getDataSource($this->useDbConfig);
  2414. return $db->lastAffected();
  2415. }
  2416. /**
  2417. * Sets the DataSource to which this model is bound.
  2418. *
  2419. * @param string $dataSource The name of the DataSource, as defined in app/config/database.php
  2420. * @return boolean True on success
  2421. * @access public
  2422. */
  2423. public function setDataSource($dataSource = null) {
  2424. $oldConfig = $this->useDbConfig;
  2425. if ($dataSource != null) {
  2426. $this->useDbConfig = $dataSource;
  2427. }
  2428. $db = ConnectionManager::getDataSource($this->useDbConfig);
  2429. if (!empty($oldConfig) && isset($db->config['prefix'])) {
  2430. $oldDb = ConnectionManager::getDataSource($oldConfig);
  2431. if (!isset($this->tablePrefix) || (!isset($oldDb->config['prefix']) || $this->tablePrefix == $oldDb->config['prefix'])) {
  2432. $this->tablePrefix = $db->config['prefix'];
  2433. }
  2434. } elseif (isset($db->config['prefix'])) {
  2435. $this->tablePrefix = $db->config['prefix'];
  2436. }
  2437. if (empty($db) || !is_object($db)) {
  2438. return $this->cakeError('missingConnection', array(array('className' => $this->alias)));
  2439. }
  2440. }
  2441. /**
  2442. * Gets the DataSource to which this model is bound.
  2443. * Not safe for use with some versions of PHP4, because this class is overloaded.
  2444. *
  2445. * @return object A DataSource object
  2446. * @access public
  2447. */
  2448. public function &getDataSource() {
  2449. $db = ConnectionManager::getDataSource($this->useDbConfig);
  2450. return $db;
  2451. }
  2452. /**
  2453. * Gets all the models with which this model is associated.
  2454. *
  2455. * @param string $type Only result associations of this type
  2456. * @return array Associations
  2457. * @access public
  2458. */
  2459. public function getAssociated($type = null) {
  2460. if ($type == null) {
  2461. $associated = array();
  2462. foreach ($this->__associations as $assoc) {
  2463. if (!empty($this->{$assoc})) {
  2464. $models = array_keys($this->{$assoc});
  2465. foreach ($models as $m) {
  2466. $associated[$m] = $assoc;
  2467. }
  2468. }
  2469. }
  2470. return $associated;
  2471. } elseif (in_array($type, $this->__associations)) {
  2472. if (empty($this->{$type})) {
  2473. return array();
  2474. }
  2475. return array_keys($this->{$type});
  2476. } else {
  2477. $assoc = array_merge(
  2478. $this->hasOne,
  2479. $this->hasMany,
  2480. $this->belongsTo,
  2481. $this->hasAndBelongsToMany
  2482. );
  2483. if (array_key_exists($type, $assoc)) {
  2484. foreach ($this->__associations as $a) {
  2485. if (isset($this->{$a}[$type])) {
  2486. $assoc[$type]['association'] = $a;
  2487. break;
  2488. }
  2489. }
  2490. return $assoc[$type];
  2491. }
  2492. return null;
  2493. }
  2494. }
  2495. /**
  2496. * Gets the name and fields to be used by a join model. This allows specifying join fields
  2497. * in the association definition.
  2498. *
  2499. * @param object $model The model to be joined
  2500. * @param mixed $with The 'with' key of the model association
  2501. * @param array $keys Any join keys which must be merged with the keys queried
  2502. * @return array
  2503. * @access public
  2504. */
  2505. public function joinModel($assoc, $keys = array()) {
  2506. if (is_string($assoc)) {
  2507. return array($assoc, array_keys($this->{$assoc}->schema()));
  2508. } elseif (is_array($assoc)) {
  2509. $with = key($assoc);
  2510. return array($with, array_unique(array_merge($assoc[$with], $keys)));
  2511. }
  2512. trigger_error(
  2513. sprintf(__('Invalid join model settings in %s', true), $model->alias),
  2514. E_USER_WARNING
  2515. );
  2516. }
  2517. /**
  2518. * Called before each find operation. Return false if you want to halt the find
  2519. * call, otherwise return the (modified) query data.
  2520. *
  2521. * @param array $queryData Data used to execute this query, i.e. conditions, order, etc.
  2522. * @return mixed true if the operation should continue, false if it should abort; or, modified
  2523. * $queryData to continue with new $queryData
  2524. * @access public
  2525. * @link http://book.cakephp.org/view/680/beforeFind
  2526. */
  2527. public function beforeFind($queryData) {
  2528. return true;
  2529. }
  2530. /**
  2531. * Called after each find operation. Can be used to modify any results returned by find().
  2532. * Return value should be the (modified) results.
  2533. *
  2534. * @param mixed $results The results of the find operation
  2535. * @param boolean $primary Whether this model is being queried directly (vs. being queried as an association)
  2536. * @return mixed Result of the find operation
  2537. * @access public
  2538. * @link http://book.cakephp.org/view/681/afterFind
  2539. */
  2540. public function afterFind($results, $primary = false) {
  2541. return $results;
  2542. }
  2543. /**
  2544. * Called before each save operation, after validation. Return a non-true result
  2545. * to halt the save.
  2546. *
  2547. * @return boolean True if the operation should continue, false if it should abort
  2548. * @access public
  2549. * @link http://book.cakephp.org/view/683/beforeSave
  2550. */
  2551. public function beforeSave($options = array()) {
  2552. return true;
  2553. }
  2554. /**
  2555. * Called after each successful save operation.
  2556. *
  2557. * @param boolean $created True if this save created a new record
  2558. * @access public
  2559. * @link http://book.cakephp.org/view/684/afterSave
  2560. */
  2561. public function afterSave($created) {
  2562. }
  2563. /**
  2564. * Called before every deletion operation.
  2565. *
  2566. * @param boolean $cascade If true records that depend on this record will also be deleted
  2567. * @return boolean True if the operation should continue, false if it should abort
  2568. * @access public
  2569. * @link http://book.cakephp.org/view/685/beforeDelete
  2570. */
  2571. public function beforeDelete($cascade = true) {
  2572. return true;
  2573. }
  2574. /**
  2575. * Called after every deletion operation.
  2576. *
  2577. * @access public
  2578. * @link http://book.cakephp.org/view/686/afterDelete
  2579. */
  2580. public function afterDelete() {
  2581. }
  2582. /**
  2583. * Called during validation operations, before validation. Please note that custom
  2584. * validation rules can be defined in $validate.
  2585. *
  2586. * @return boolean True if validate operation should continue, false to abort
  2587. * @param $options array Options passed from model::save(), see $options of model::save().
  2588. * @access public
  2589. * @link http://book.cakephp.org/view/682/beforeValidate
  2590. */
  2591. public function beforeValidate($options = array()) {
  2592. return true;
  2593. }
  2594. /**
  2595. * Called when a DataSource-level error occurs.
  2596. *
  2597. * @access public
  2598. * @link http://book.cakephp.org/view/687/onError
  2599. */
  2600. public function onError() {
  2601. }
  2602. /**
  2603. * Private method. Clears cache for this model.
  2604. *
  2605. * @param string $type If null this deletes cached views if Cache.check is true
  2606. * Will be used to allow deleting query cache also
  2607. * @return boolean true on delete
  2608. * @access protected
  2609. * @todo
  2610. */
  2611. protected function _clearCache($type = null) {
  2612. if ($type === null) {
  2613. if (Configure::read('Cache.check') === true) {
  2614. $assoc[] = strtolower(Inflector::pluralize($this->alias));
  2615. $assoc[] = strtolower(Inflector::underscore(Inflector::pluralize($this->alias)));
  2616. foreach ($this->__associations as $key => $association) {
  2617. foreach ($this->$association as $key => $className) {
  2618. $check = strtolower(Inflector::pluralize($className['className']));
  2619. if (!in_array($check, $assoc)) {
  2620. $assoc[] = strtolower(Inflector::pluralize($className['className']));
  2621. $assoc[] = strtolower(Inflector::underscore(Inflector::pluralize($className['className'])));
  2622. }
  2623. }
  2624. }
  2625. clearCache($assoc);
  2626. return true;
  2627. }
  2628. } else {
  2629. //Will use for query cache deleting
  2630. }
  2631. }
  2632. /**
  2633. * Called when serializing a model.
  2634. *
  2635. * @return array Set of object variable names this model has
  2636. * @access protected
  2637. */
  2638. private function __sleep() {
  2639. $return = array_keys(get_object_vars($this));
  2640. return $return;
  2641. }
  2642. /**
  2643. * Called when de-serializing a model.
  2644. *
  2645. * @access protected
  2646. * @todo
  2647. */
  2648. private function __wakeup() {
  2649. }
  2650. }
  2651. final class ModelAssociation {
  2652. /**
  2653. * Default list of association keys.
  2654. *
  2655. * @var array
  2656. * @access private
  2657. */
  2658. private static $__associationKeys = array(
  2659. 'belongsTo' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'counterCache'),
  2660. 'hasOne' => array('className', 'foreignKey','conditions', 'fields','order', 'dependent'),
  2661. 'hasMany' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'dependent', 'exclusive', 'finderQuery', 'counterQuery'),
  2662. 'hasAndBelongsToMany' => array('className', 'joinTable', 'with', 'foreignKey', 'associationForeignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'unique', 'finderQuery', 'deleteQuery', 'insertQuery'));
  2663. /**
  2664. * Holds provided/generated association key names and other data for all associations.
  2665. *
  2666. * @var array
  2667. * @access private
  2668. */
  2669. private static $__associations = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
  2670. /**
  2671. * Create a set of associations.
  2672. *
  2673. * @return void
  2674. * @access private
  2675. */
  2676. public static function create(Model &$model) {
  2677. foreach (self::$__associations as $type) {
  2678. if (!is_array($model->{$type})) {
  2679. $model->{$type} = explode(',', $model->{$type});
  2680. foreach ($model->{$type} as $i => $className) {
  2681. $className = trim($className);
  2682. unset ($model->{$type}[$i]);
  2683. $model->{$type}[$className] = array();
  2684. }
  2685. }
  2686. if (!empty($model->{$type})) {
  2687. foreach ($model->{$type} as $assoc => $value) {
  2688. $plugin = null;
  2689. if (is_numeric($assoc)) {
  2690. unset ($model->{$type}[$assoc]);
  2691. $assoc = $value;
  2692. $value = array();
  2693. $model->{$type}[$assoc] = $value;
  2694. if (strpos($assoc, '.') !== false) {
  2695. $value = $model->{$type}[$assoc];
  2696. unset($model->{$type}[$assoc]);
  2697. list($plugin, $assoc) = explode('.', $assoc);
  2698. $model->{$type}[$assoc] = $value;
  2699. $plugin = $plugin . '.';
  2700. }
  2701. }
  2702. $className = $assoc;
  2703. if (isset($value['className']) && !empty($value['className'])) {
  2704. $className = $value['className'];
  2705. if (strpos($className, '.') !== false) {
  2706. list($plugin, $className) = explode('.', $className);
  2707. $plugin = $plugin . '.';
  2708. $model->{$type}[$assoc]['className'] = $className;
  2709. }
  2710. }
  2711. self::construct($model, $assoc, $plugin . $className);
  2712. }
  2713. self::generate($model, $type);
  2714. }
  2715. }
  2716. }
  2717. /**
  2718. * Private helper method to create associated models of a given class.
  2719. *
  2720. * @param string $assoc Association name
  2721. * @param string $className Class name
  2722. * @deprecated $this->$className use $this->$assoc instead. $assoc is the 'key' in the associations array;
  2723. * examples: var $hasMany = array('Assoc' => array('className' => 'ModelName'));
  2724. * usage: $this->Assoc->modelMethods();
  2725. *
  2726. * public $hasMany = array('ModelName');
  2727. * usage: $this->ModelName->modelMethods();
  2728. * @return void
  2729. * @access private
  2730. */
  2731. public static function construct(Model &$model, $assoc, $className = null) {
  2732. if (empty($className)) {
  2733. $className = $assoc;
  2734. }
  2735. if (!isset($model->{$assoc}) || $model->{$assoc}->name !== $className) {
  2736. $init = array('class' => $className, 'alias' => $assoc);
  2737. $model->{$assoc} = ClassRegistry::init($init);
  2738. if ($assoc) {
  2739. $model->tableToModel[$model->{$assoc}->table] = $assoc;
  2740. }
  2741. }
  2742. }
  2743. /**
  2744. * Build an array-based association from string.
  2745. *
  2746. * @param string $type 'belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany'
  2747. * @return void
  2748. * @access private
  2749. */
  2750. public static function generate(Model &$model, $type) {
  2751. foreach ($model->{$type} as $assocKey => $assocData) {
  2752. $class = $assocKey;
  2753. $dynamicWith = false;
  2754. foreach (self::$__associationKeys[$type] as $key) {
  2755. if (!isset($model->{$type}[$assocKey][$key]) || $model->{$type}[$assocKey][$key] === null) {
  2756. $data = '';
  2757. switch ($key) {
  2758. case 'fields':
  2759. $data = '';
  2760. break;
  2761. case 'foreignKey':
  2762. $data = (($type == 'belongsTo') ? Inflector::underscore($assocKey) : Inflector::singularize($model->table)) . '_id';
  2763. break;
  2764. case 'associationForeignKey':
  2765. $data = Inflector::singularize($model->{$class}->table) . '_id';
  2766. break;
  2767. case 'with':
  2768. $data = Inflector::camelize(Inflector::singularize($model->{$type}[$assocKey]['joinTable']));
  2769. $dynamicWith = true;
  2770. break;
  2771. case 'joinTable':
  2772. $tables = array($model->table, $model->{$class}->table);
  2773. sort ($tables);
  2774. $data = $tables[0] . '_' . $tables[1];
  2775. break;
  2776. case 'className':
  2777. $data = $class;
  2778. break;
  2779. case 'unique':
  2780. $data = true;
  2781. break;
  2782. }
  2783. $model->{$type}[$assocKey][$key] = $data;
  2784. }
  2785. }
  2786. if (!empty($model->{$type}[$assocKey]['with'])) {
  2787. $joinClass = $model->{$type}[$assocKey]['with'];
  2788. if (is_array($joinClass)) {
  2789. $joinClass = key($joinClass);
  2790. }
  2791. $plugin = null;
  2792. if (strpos($joinClass, '.') !== false) {
  2793. list($plugin, $joinClass) = explode('.', $joinClass);
  2794. $plugin = $plugin . '.';
  2795. $model->{$type}[$assocKey]['with'] = $joinClass;
  2796. }
  2797. if (!ClassRegistry::isKeySet($joinClass) && $dynamicWith === true) {
  2798. $model->{$joinClass} = new AppModel(array(
  2799. 'name' => $joinClass,
  2800. 'table' => $model->{$type}[$assocKey]['joinTable'],
  2801. 'ds' => $model->useDbConfig
  2802. ));
  2803. } else {
  2804. self::construct($model, $joinClass, $plugin . $joinClass);
  2805. $model->{$type}[$assocKey]['joinTable'] = $model->{$joinClass}->table;
  2806. }
  2807. if (count($model->{$joinClass}->schema()) <= 2 && $model->{$joinClass}->primaryKey !== false) {
  2808. $model->{$joinClass}->primaryKey = $model->{$type}[$assocKey]['foreignKey'];
  2809. }
  2810. }
  2811. }
  2812. }
  2813. }
  2814. ?>