PageRenderTime 79ms CodeModel.GetById 31ms RepoModel.GetById 1ms app.codeStats 0ms

/cake/libs/model/model.php

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