/code/ryzom/tools/server/www/webtt/cake/libs/model/model.php

https://bitbucket.org/mattraykowski/ryzomcore_demoshard · PHP · 3072 lines · 1808 code · 273 blank · 991 comment · 530 complexity · 07673b977d51b8f9a7d1cb247a0e818d MD5 · raw file

Large files are truncated click here to view the full 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-2010, 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-2010, 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/1000/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/1057/Model-Attributes#useDbConfig-1058
  50. */
  51. var $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/1057/Model-Attributes#useTable-1059
  58. */
  59. var $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/1057/Model-Attributes#displayField-1062
  66. */
  67. var $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. var $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/1057/Model-Attributes#data-1065
  82. */
  83. var $data = array();
  84. /**
  85. * Table name for this Model.
  86. *
  87. * @var string
  88. * @access public
  89. */
  90. var $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/1057/Model-Attributes#primaryKey-1061
  97. */
  98. var $primaryKey = null;
  99. /**
  100. * Field-by-field table metadata.
  101. *
  102. * @var array
  103. * @access protected
  104. * @link http://book.cakephp.org/view/1057/Model-Attributes#_schema-1066
  105. */
  106. var $_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/1057/Model-Attributes#validate-1067
  114. * @link http://book.cakephp.org/view/1143/Data-Validation
  115. */
  116. var $validate = array();
  117. /**
  118. * List of validation errors.
  119. *
  120. * @var array
  121. * @access public
  122. * @link http://book.cakephp.org/view/1182/Validating-Data-from-the-Controller
  123. */
  124. var $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/1057/Model-Attributes#tablePrefix-1060
  131. */
  132. var $tablePrefix = null;
  133. /**
  134. * Name of the model.
  135. *
  136. * @var string
  137. * @access public
  138. * @link http://book.cakephp.org/view/1057/Model-Attributes#name-1068
  139. */
  140. var $name = null;
  141. /**
  142. * Alias name for model.
  143. *
  144. * @var string
  145. * @access public
  146. */
  147. var $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. var $tableToModel = array();
  155. /**
  156. * Whether or not to log transactions for this model.
  157. *
  158. * @var boolean
  159. * @access public
  160. */
  161. var $logTransactions = false;
  162. /**
  163. * Whether or not to cache queries for this model. This enables in-memory
  164. * caching only, the results are not stored beyond the current request.
  165. *
  166. * @var boolean
  167. * @access public
  168. * @link http://book.cakephp.org/view/1057/Model-Attributes#cacheQueries-1069
  169. */
  170. var $cacheQueries = false;
  171. /**
  172. * Detailed list of belongsTo associations.
  173. *
  174. * @var array
  175. * @access public
  176. * @link http://book.cakephp.org/view/1042/belongsTo
  177. */
  178. var $belongsTo = array();
  179. /**
  180. * Detailed list of hasOne associations.
  181. *
  182. * @var array
  183. * @access public
  184. * @link http://book.cakephp.org/view/1041/hasOne
  185. */
  186. var $hasOne = array();
  187. /**
  188. * Detailed list of hasMany associations.
  189. *
  190. * @var array
  191. * @access public
  192. * @link http://book.cakephp.org/view/1043/hasMany
  193. */
  194. var $hasMany = array();
  195. /**
  196. * Detailed list of hasAndBelongsToMany associations.
  197. *
  198. * @var array
  199. * @access public
  200. * @link http://book.cakephp.org/view/1044/hasAndBelongsToMany-HABTM
  201. */
  202. var $hasAndBelongsToMany = array();
  203. /**
  204. * List of behaviors to load when the model object is initialized. Settings can be
  205. * passed to behaviors by using the behavior name as index. Eg:
  206. *
  207. * var $actsAs = array('Translate', 'MyBehavior' => array('setting1' => 'value1'))
  208. *
  209. * @var array
  210. * @access public
  211. * @link http://book.cakephp.org/view/1072/Using-Behaviors
  212. */
  213. var $actsAs = null;
  214. /**
  215. * Holds the Behavior objects currently bound to this model.
  216. *
  217. * @var BehaviorCollection
  218. * @access public
  219. */
  220. var $Behaviors = null;
  221. /**
  222. * Whitelist of fields allowed to be saved.
  223. *
  224. * @var array
  225. * @access public
  226. */
  227. var $whitelist = array();
  228. /**
  229. * Whether or not to cache sources for this model.
  230. *
  231. * @var boolean
  232. * @access public
  233. */
  234. var $cacheSources = true;
  235. /**
  236. * Type of find query currently executing.
  237. *
  238. * @var string
  239. * @access public
  240. */
  241. var $findQueryType = null;
  242. /**
  243. * Number of associations to recurse through during find calls. Fetches only
  244. * the first level by default.
  245. *
  246. * @var integer
  247. * @access public
  248. * @link http://book.cakephp.org/view/1057/Model-Attributes#recursive-1063
  249. */
  250. var $recursive = 1;
  251. /**
  252. * The column name(s) and direction(s) to order find results by default.
  253. *
  254. * var $order = "Post.created DESC";
  255. * var $order = array("Post.view_count DESC", "Post.rating DESC");
  256. *
  257. * @var string
  258. * @access public
  259. * @link http://book.cakephp.org/view/1057/Model-Attributes#order-1064
  260. */
  261. var $order = null;
  262. /**
  263. * Array of virtual fields this model has. Virtual fields are aliased
  264. * SQL expressions. Fields added to this property will be read as other fields in a model
  265. * but will not be saveable.
  266. *
  267. * `var $virtualFields = array('two' => '1 + 1');`
  268. *
  269. * Is a simplistic example of how to set virtualFields
  270. *
  271. * @var array
  272. * @access public
  273. */
  274. var $virtualFields = array();
  275. /**
  276. * Default list of association keys.
  277. *
  278. * @var array
  279. * @access private
  280. */
  281. var $__associationKeys = array(
  282. 'belongsTo' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'counterCache'),
  283. 'hasOne' => array('className', 'foreignKey','conditions', 'fields','order', 'dependent'),
  284. 'hasMany' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'dependent', 'exclusive', 'finderQuery', 'counterQuery'),
  285. 'hasAndBelongsToMany' => array('className', 'joinTable', 'with', 'foreignKey', 'associationForeignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'unique', 'finderQuery', 'deleteQuery', 'insertQuery')
  286. );
  287. /**
  288. * Holds provided/generated association key names and other data for all associations.
  289. *
  290. * @var array
  291. * @access private
  292. */
  293. var $__associations = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
  294. /**
  295. * Holds model associations temporarily to allow for dynamic (un)binding.
  296. *
  297. * @var array
  298. * @access private
  299. */
  300. var $__backAssociation = array();
  301. /**
  302. * The ID of the model record that was last inserted.
  303. *
  304. * @var integer
  305. * @access private
  306. */
  307. var $__insertID = null;
  308. /**
  309. * The number of records returned by the last query.
  310. *
  311. * @var integer
  312. * @access private
  313. */
  314. var $__numRows = null;
  315. /**
  316. * The number of records affected by the last query.
  317. *
  318. * @var integer
  319. * @access private
  320. */
  321. var $__affectedRows = null;
  322. /**
  323. * List of valid finder method options, supplied as the first parameter to find().
  324. *
  325. * @var array
  326. * @access protected
  327. */
  328. var $_findMethods = array(
  329. 'all' => true, 'first' => true, 'count' => true,
  330. 'neighbors' => true, 'list' => true, 'threaded' => true
  331. );
  332. /**
  333. * Constructor. Binds the model's database table to the object.
  334. *
  335. * If `$id` is an array it can be used to pass several options into the model.
  336. *
  337. * - id - The id to start the model on.
  338. * - table - The table to use for this model.
  339. * - ds - The connection name this model is connected to.
  340. * - name - The name of the model eg. Post.
  341. * - alias - The alias of the model, this is used for registering the instance in the `ClassRegistry`.
  342. * eg. `ParentThread`
  343. *
  344. * ### Overriding Model's __construct method.
  345. *
  346. * When overriding Model::__construct() be careful to include and pass in all 3 of the
  347. * arguments to `parent::__construct($id, $table, $ds);`
  348. *
  349. * ### Dynamically creating models
  350. *
  351. * You can dynamically create model instances using the $id array syntax.
  352. *
  353. * {{{
  354. * $Post = new Model(array('table' => 'posts', 'name' => 'Post', 'ds' => 'connection2'));
  355. * }}}
  356. *
  357. * Would create a model attached to the posts table on connection2. Dynamic model creation is useful
  358. * when you want a model object that contains no associations or attached behaviors.
  359. *
  360. * @param mixed $id Set this ID for this model on startup, can also be an array of options, see above.
  361. * @param string $table Name of database table to use.
  362. * @param string $ds DataSource connection name.
  363. */
  364. function __construct($id = false, $table = null, $ds = null) {
  365. parent::__construct();
  366. if (is_array($id)) {
  367. extract(array_merge(
  368. array(
  369. 'id' => $this->id, 'table' => $this->useTable, 'ds' => $this->useDbConfig,
  370. 'name' => $this->name, 'alias' => $this->alias
  371. ),
  372. $id
  373. ));
  374. }
  375. if ($this->name === null) {
  376. $this->name = (isset($name) ? $name : get_class($this));
  377. }
  378. if ($this->alias === null) {
  379. $this->alias = (isset($alias) ? $alias : $this->name);
  380. }
  381. if ($this->primaryKey === null) {
  382. $this->primaryKey = 'id';
  383. }
  384. ClassRegistry::addObject($this->alias, $this);
  385. $this->id = $id;
  386. unset($id);
  387. if ($table === false) {
  388. $this->useTable = false;
  389. } elseif ($table) {
  390. $this->useTable = $table;
  391. }
  392. if ($ds !== null) {
  393. $this->useDbConfig = $ds;
  394. }
  395. if (is_subclass_of($this, 'AppModel')) {
  396. $appVars = get_class_vars('AppModel');
  397. $merge = array('_findMethods');
  398. if ($this->actsAs !== null || $this->actsAs !== false) {
  399. $merge[] = 'actsAs';
  400. }
  401. $parentClass = get_parent_class($this);
  402. if (strtolower($parentClass) !== 'appmodel') {
  403. $parentVars = get_class_vars($parentClass);
  404. foreach ($merge as $var) {
  405. if (isset($parentVars[$var]) && !empty($parentVars[$var])) {
  406. $appVars[$var] = Set::merge($appVars[$var], $parentVars[$var]);
  407. }
  408. }
  409. }
  410. foreach ($merge as $var) {
  411. if (isset($appVars[$var]) && !empty($appVars[$var]) && is_array($this->{$var})) {
  412. $this->{$var} = Set::merge($appVars[$var], $this->{$var});
  413. }
  414. }
  415. }
  416. $this->Behaviors = new BehaviorCollection();
  417. if ($this->useTable !== false) {
  418. $this->setDataSource($ds);
  419. if ($this->useTable === null) {
  420. $this->useTable = Inflector::tableize($this->name);
  421. }
  422. $this->setSource($this->useTable);
  423. if ($this->displayField == null) {
  424. $this->displayField = $this->hasField(array('title', 'name', $this->primaryKey));
  425. }
  426. } elseif ($this->table === false) {
  427. $this->table = Inflector::tableize($this->name);
  428. }
  429. $this->__createLinks();
  430. $this->Behaviors->init($this->alias, $this->actsAs);
  431. }
  432. /**
  433. * Handles custom method calls, like findBy<field> for DB models,
  434. * and custom RPC calls for remote data sources.
  435. *
  436. * @param string $method Name of method to call.
  437. * @param array $params Parameters for the method.
  438. * @return mixed Whatever is returned by called method
  439. * @access protected
  440. */
  441. function call__($method, $params) {
  442. $result = $this->Behaviors->dispatchMethod($this, $method, $params);
  443. if ($result !== array('unhandled')) {
  444. return $result;
  445. }
  446. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  447. $return = $db->query($method, $params, $this);
  448. if (!PHP5) {
  449. $this->resetAssociations();
  450. }
  451. return $return;
  452. }
  453. /**
  454. * Bind model associations on the fly.
  455. *
  456. * If `$reset` is false, association will not be reset
  457. * to the originals defined in the model
  458. *
  459. * Example: Add a new hasOne binding to the Profile model not
  460. * defined in the model source code:
  461. *
  462. * `$this->User->bindModel( array('hasOne' => array('Profile')) );`
  463. *
  464. * Bindings that are not made permanent will be reset by the next Model::find() call on this
  465. * model.
  466. *
  467. * @param array $params Set of bindings (indexed by binding type)
  468. * @param boolean $reset Set to false to make the binding permanent
  469. * @return boolean Success
  470. * @access public
  471. * @link http://book.cakephp.org/view/1045/Creating-and-Destroying-Associations-on-the-Fly
  472. */
  473. function bindModel($params, $reset = true) {
  474. foreach ($params as $assoc => $model) {
  475. if ($reset === true && !isset($this->__backAssociation[$assoc])) {
  476. $this->__backAssociation[$assoc] = $this->{$assoc};
  477. }
  478. foreach ($model as $key => $value) {
  479. $assocName = $key;
  480. if (is_numeric($key)) {
  481. $assocName = $value;
  482. $value = array();
  483. }
  484. $modelName = $assocName;
  485. $this->{$assoc}[$assocName] = $value;
  486. if ($reset === false && isset($this->__backAssociation[$assoc])) {
  487. $this->__backAssociation[$assoc][$assocName] = $value;
  488. }
  489. }
  490. }
  491. $this->__createLinks();
  492. return true;
  493. }
  494. /**
  495. * Turn off associations on the fly.
  496. *
  497. * If $reset is false, association will not be reset
  498. * to the originals defined in the model
  499. *
  500. * Example: Turn off the associated Model Support request,
  501. * to temporarily lighten the User model:
  502. *
  503. * `$this->User->unbindModel( array('hasMany' => array('Supportrequest')) );`
  504. *
  505. * unbound models that are not made permanent will reset with the next call to Model::find()
  506. *
  507. * @param array $params Set of bindings to unbind (indexed by binding type)
  508. * @param boolean $reset Set to false to make the unbinding permanent
  509. * @return boolean Success
  510. * @access public
  511. * @link http://book.cakephp.org/view/1045/Creating-and-Destroying-Associations-on-the-Fly
  512. */
  513. function unbindModel($params, $reset = true) {
  514. foreach ($params as $assoc => $models) {
  515. if ($reset === true && !isset($this->__backAssociation[$assoc])) {
  516. $this->__backAssociation[$assoc] = $this->{$assoc};
  517. }
  518. foreach ($models as $model) {
  519. if ($reset === false && isset($this->__backAssociation[$assoc][$model])) {
  520. unset($this->__backAssociation[$assoc][$model]);
  521. }
  522. unset($this->{$assoc}[$model]);
  523. }
  524. }
  525. return true;
  526. }
  527. /**
  528. * Create a set of associations.
  529. *
  530. * @return void
  531. * @access private
  532. */
  533. function __createLinks() {
  534. foreach ($this->__associations as $type) {
  535. if (!is_array($this->{$type})) {
  536. $this->{$type} = explode(',', $this->{$type});
  537. foreach ($this->{$type} as $i => $className) {
  538. $className = trim($className);
  539. unset ($this->{$type}[$i]);
  540. $this->{$type}[$className] = array();
  541. }
  542. }
  543. if (!empty($this->{$type})) {
  544. foreach ($this->{$type} as $assoc => $value) {
  545. $plugin = null;
  546. if (is_numeric($assoc)) {
  547. unset ($this->{$type}[$assoc]);
  548. $assoc = $value;
  549. $value = array();
  550. $this->{$type}[$assoc] = $value;
  551. if (strpos($assoc, '.') !== false) {
  552. $value = $this->{$type}[$assoc];
  553. unset($this->{$type}[$assoc]);
  554. list($plugin, $assoc) = pluginSplit($assoc, true);
  555. $this->{$type}[$assoc] = $value;
  556. }
  557. }
  558. $className = $assoc;
  559. if (!empty($value['className'])) {
  560. list($plugin, $className) = pluginSplit($value['className'], true);
  561. $this->{$type}[$assoc]['className'] = $className;
  562. }
  563. $this->__constructLinkedModel($assoc, $plugin . $className);
  564. }
  565. $this->__generateAssociation($type);
  566. }
  567. }
  568. }
  569. /**
  570. * Private helper method to create associated models of a given class.
  571. *
  572. * @param string $assoc Association name
  573. * @param string $className Class name
  574. * @deprecated $this->$className use $this->$assoc instead. $assoc is the 'key' in the associations array;
  575. * examples: var $hasMany = array('Assoc' => array('className' => 'ModelName'));
  576. * usage: $this->Assoc->modelMethods();
  577. *
  578. * var $hasMany = array('ModelName');
  579. * usage: $this->ModelName->modelMethods();
  580. * @return void
  581. * @access private
  582. */
  583. function __constructLinkedModel($assoc, $className = null) {
  584. if (empty($className)) {
  585. $className = $assoc;
  586. }
  587. if (!isset($this->{$assoc}) || $this->{$assoc}->name !== $className) {
  588. $model = array('class' => $className, 'alias' => $assoc);
  589. if (PHP5) {
  590. $this->{$assoc} = ClassRegistry::init($model);
  591. } else {
  592. $this->{$assoc} =& ClassRegistry::init($model);
  593. }
  594. if (strpos($className, '.') !== false) {
  595. ClassRegistry::addObject($className, $this->{$assoc});
  596. }
  597. if ($assoc) {
  598. $this->tableToModel[$this->{$assoc}->table] = $assoc;
  599. }
  600. }
  601. }
  602. /**
  603. * Build an array-based association from string.
  604. *
  605. * @param string $type 'belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany'
  606. * @return void
  607. * @access private
  608. */
  609. function __generateAssociation($type) {
  610. foreach ($this->{$type} as $assocKey => $assocData) {
  611. $class = $assocKey;
  612. $dynamicWith = false;
  613. foreach ($this->__associationKeys[$type] as $key) {
  614. if (!isset($this->{$type}[$assocKey][$key]) || $this->{$type}[$assocKey][$key] === null) {
  615. $data = '';
  616. switch ($key) {
  617. case 'fields':
  618. $data = '';
  619. break;
  620. case 'foreignKey':
  621. $data = (($type == 'belongsTo') ? Inflector::underscore($assocKey) : Inflector::singularize($this->table)) . '_id';
  622. break;
  623. case 'associationForeignKey':
  624. $data = Inflector::singularize($this->{$class}->table) . '_id';
  625. break;
  626. case 'with':
  627. $data = Inflector::camelize(Inflector::singularize($this->{$type}[$assocKey]['joinTable']));
  628. $dynamicWith = true;
  629. break;
  630. case 'joinTable':
  631. $tables = array($this->table, $this->{$class}->table);
  632. sort ($tables);
  633. $data = $tables[0] . '_' . $tables[1];
  634. break;
  635. case 'className':
  636. $data = $class;
  637. break;
  638. case 'unique':
  639. $data = true;
  640. break;
  641. }
  642. $this->{$type}[$assocKey][$key] = $data;
  643. }
  644. }
  645. if (!empty($this->{$type}[$assocKey]['with'])) {
  646. $joinClass = $this->{$type}[$assocKey]['with'];
  647. if (is_array($joinClass)) {
  648. $joinClass = key($joinClass);
  649. }
  650. $plugin = null;
  651. if (strpos($joinClass, '.') !== false) {
  652. list($plugin, $joinClass) = explode('.', $joinClass);
  653. $plugin .= '.';
  654. $this->{$type}[$assocKey]['with'] = $joinClass;
  655. }
  656. if (!ClassRegistry::isKeySet($joinClass) && $dynamicWith === true) {
  657. $this->{$joinClass} = new AppModel(array(
  658. 'name' => $joinClass,
  659. 'table' => $this->{$type}[$assocKey]['joinTable'],
  660. 'ds' => $this->useDbConfig
  661. ));
  662. } else {
  663. $this->__constructLinkedModel($joinClass, $plugin . $joinClass);
  664. $this->{$type}[$assocKey]['joinTable'] = $this->{$joinClass}->table;
  665. }
  666. if (count($this->{$joinClass}->schema()) <= 2 && $this->{$joinClass}->primaryKey !== false) {
  667. $this->{$joinClass}->primaryKey = $this->{$type}[$assocKey]['foreignKey'];
  668. }
  669. }
  670. }
  671. }
  672. /**
  673. * Sets a custom table for your controller class. Used by your controller to select a database table.
  674. *
  675. * @param string $tableName Name of the custom table
  676. * @return void
  677. * @access public
  678. */
  679. function setSource($tableName) {
  680. // debug_print_backtrace();
  681. $this->setDataSource($this->useDbConfig);
  682. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  683. $db->cacheSources = ($this->cacheSources && $db->cacheSources);
  684. if ($db->isInterfaceSupported('listSources')) {
  685. $sources = $db->listSources();
  686. if (is_array($sources) && !in_array(strtolower($this->tablePrefix . $tableName), array_map('strtolower', $sources))) {
  687. return $this->cakeError('missingTable', array(array(
  688. 'className' => $this->alias,
  689. 'table' => $this->tablePrefix . $tableName,
  690. 'code' => 500
  691. )));
  692. }
  693. $this->_schema = null;
  694. }
  695. $this->table = $this->useTable = $tableName;
  696. $this->tableToModel[$this->table] = $this->alias;
  697. $this->schema();
  698. }
  699. /**
  700. * This function does two things:
  701. *
  702. * 1. it scans the array $one for the primary key,
  703. * and if that's found, it sets the current id to the value of $one[id].
  704. * For all other keys than 'id' the keys and values of $one are copied to the 'data' property of this object.
  705. * 2. Returns an array with all of $one's keys and values.
  706. * (Alternative indata: two strings, which are mangled to
  707. * a one-item, two-dimensional array using $one for a key and $two as its value.)
  708. *
  709. * @param mixed $one Array or string of data
  710. * @param string $two Value string for the alternative indata method
  711. * @return array Data with all of $one's keys and values
  712. * @access public
  713. * @link http://book.cakephp.org/view/1031/Saving-Your-Data
  714. */
  715. function set($one, $two = null) {
  716. if (!$one) {
  717. return;
  718. }
  719. if (is_object($one)) {
  720. $one = Set::reverse($one);
  721. }
  722. if (is_array($one)) {
  723. $data = $one;
  724. if (empty($one[$this->alias])) {
  725. if ($this->getAssociated(key($one)) === null) {
  726. $data = array($this->alias => $one);
  727. }
  728. }
  729. } else {
  730. $data = array($this->alias => array($one => $two));
  731. }
  732. foreach ($data as $modelName => $fieldSet) {
  733. if (is_array($fieldSet)) {
  734. foreach ($fieldSet as $fieldName => $fieldValue) {
  735. if (isset($this->validationErrors[$fieldName])) {
  736. unset ($this->validationErrors[$fieldName]);
  737. }
  738. if ($modelName === $this->alias) {
  739. if ($fieldName === $this->primaryKey) {
  740. $this->id = $fieldValue;
  741. }
  742. }
  743. if (is_array($fieldValue) || is_object($fieldValue)) {
  744. $fieldValue = $this->deconstruct($fieldName, $fieldValue);
  745. }
  746. $this->data[$modelName][$fieldName] = $fieldValue;
  747. }
  748. }
  749. }
  750. return $data;
  751. }
  752. /**
  753. * Deconstructs a complex data type (array or object) into a single field value.
  754. *
  755. * @param string $field The name of the field to be deconstructed
  756. * @param mixed $data An array or object to be deconstructed into a field
  757. * @return mixed The resulting data that should be assigned to a field
  758. * @access public
  759. */
  760. function deconstruct($field, $data) {
  761. if (!is_array($data)) {
  762. return $data;
  763. }
  764. $copy = $data;
  765. $type = $this->getColumnType($field);
  766. if (in_array($type, array('datetime', 'timestamp', 'date', 'time'))) {
  767. $useNewDate = (isset($data['year']) || isset($data['month']) ||
  768. isset($data['day']) || isset($data['hour']) || isset($data['minute']));
  769. $dateFields = array('Y' => 'year', 'm' => 'month', 'd' => 'day', 'H' => 'hour', 'i' => 'min', 's' => 'sec');
  770. $timeFields = array('H' => 'hour', 'i' => 'min', 's' => 'sec');
  771. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  772. $format = $db->columns[$type]['format'];
  773. $date = array();
  774. if (isset($data['hour']) && isset($data['meridian']) && $data['hour'] != 12 && 'pm' == $data['meridian']) {
  775. $data['hour'] = $data['hour'] + 12;
  776. }
  777. if (isset($data['hour']) && isset($data['meridian']) && $data['hour'] == 12 && 'am' == $data['meridian']) {
  778. $data['hour'] = '00';
  779. }
  780. if ($type == 'time') {
  781. foreach ($timeFields as $key => $val) {
  782. if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') {
  783. $data[$val] = '00';
  784. } elseif ($data[$val] === '') {
  785. $data[$val] = '';
  786. } else {
  787. $data[$val] = sprintf('%02d', $data[$val]);
  788. }
  789. if (!empty($data[$val])) {
  790. $date[$key] = $data[$val];
  791. } else {
  792. return null;
  793. }
  794. }
  795. }
  796. if ($type == 'datetime' || $type == 'timestamp' || $type == 'date') {
  797. foreach ($dateFields as $key => $val) {
  798. if ($val == 'hour' || $val == 'min' || $val == 'sec') {
  799. if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') {
  800. $data[$val] = '00';
  801. } else {
  802. $data[$val] = sprintf('%02d', $data[$val]);
  803. }
  804. }
  805. if (!isset($data[$val]) || isset($data[$val]) && (empty($data[$val]) || $data[$val][0] === '-')) {
  806. return null;
  807. }
  808. if (isset($data[$val]) && !empty($data[$val])) {
  809. $date[$key] = $data[$val];
  810. }
  811. }
  812. }
  813. $date = str_replace(array_keys($date), array_values($date), $format);
  814. if ($useNewDate && !empty($date)) {
  815. return $date;
  816. }
  817. }
  818. return $data;
  819. }
  820. /**
  821. * Returns an array of table metadata (column names and types) from the database.
  822. * $field => keys(type, null, default, key, length, extra)
  823. *
  824. * @param mixed $field Set to true to reload schema, or a string to return a specific field
  825. * @return array Array of table metadata
  826. * @access public
  827. */
  828. function schema($field = false) {
  829. if (!is_array($this->_schema) || $field === true) {
  830. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  831. $db->cacheSources = ($this->cacheSources && $db->cacheSources);
  832. if ($db->isInterfaceSupported('describe') && $this->useTable !== false) {
  833. $this->_schema = $db->describe($this, $field);
  834. } elseif ($this->useTable === false) {
  835. $this->_schema = array();
  836. }
  837. }
  838. if (is_string($field)) {
  839. if (isset($this->_schema[$field])) {
  840. return $this->_schema[$field];
  841. } else {
  842. return null;
  843. }
  844. }
  845. return $this->_schema;
  846. }
  847. /**
  848. * Returns an associative array of field names and column types.
  849. *
  850. * @return array Field types indexed by field name
  851. * @access public
  852. */
  853. function getColumnTypes() {
  854. $columns = $this->schema();
  855. if (empty($columns)) {
  856. 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);
  857. }
  858. $cols = array();
  859. foreach ($columns as $field => $values) {
  860. $cols[$field] = $values['type'];
  861. }
  862. return $cols;
  863. }
  864. /**
  865. * Returns the column type of a column in the model.
  866. *
  867. * @param string $column The name of the model column
  868. * @return string Column type
  869. * @access public
  870. */
  871. function getColumnType($column) {
  872. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  873. $cols = $this->schema();
  874. $model = null;
  875. $column = str_replace(array($db->startQuote, $db->endQuote), '', $column);
  876. if (strpos($column, '.')) {
  877. list($model, $column) = explode('.', $column);
  878. }
  879. if ($model != $this->alias && isset($this->{$model})) {
  880. return $this->{$model}->getColumnType($column);
  881. }
  882. if (isset($cols[$column]) && isset($cols[$column]['type'])) {
  883. return $cols[$column]['type'];
  884. }
  885. return null;
  886. }
  887. /**
  888. * Returns true if the supplied field exists in the model's database table.
  889. *
  890. * @param mixed $name Name of field to look for, or an array of names
  891. * @param boolean $checkVirtual checks if the field is declared as virtual
  892. * @return mixed If $name is a string, returns a boolean indicating whether the field exists.
  893. * If $name is an array of field names, returns the first field that exists,
  894. * or false if none exist.
  895. * @access public
  896. */
  897. function hasField($name, $checkVirtual = false) {
  898. if (is_array($name)) {
  899. foreach ($name as $n) {
  900. if ($this->hasField($n, $checkVirtual)) {
  901. return $n;
  902. }
  903. }
  904. return false;
  905. }
  906. if ($checkVirtual && !empty($this->virtualFields)) {
  907. if ($this->isVirtualField($name)) {
  908. return true;
  909. }
  910. }
  911. if (empty($this->_schema)) {
  912. $this->schema();
  913. }
  914. if ($this->_schema != null) {
  915. return isset($this->_schema[$name]);
  916. }
  917. return false;
  918. }
  919. /**
  920. * Returns true if the supplied field is a model Virtual Field
  921. *
  922. * @param mixed $name Name of field to look for
  923. * @return boolean indicating whether the field exists as a model virtual field.
  924. * @access public
  925. */
  926. function isVirtualField($field) {
  927. if (empty($this->virtualFields) || !is_string($field)) {
  928. return false;
  929. }
  930. if (isset($this->virtualFields[$field])) {
  931. return true;
  932. }
  933. if (strpos($field, '.') !== false) {
  934. list($model, $field) = explode('.', $field);
  935. if (isset($this->virtualFields[$field])) {
  936. return true;
  937. }
  938. }
  939. return false;
  940. }
  941. /**
  942. * Returns the expression for a model virtual field
  943. *
  944. * @param mixed $name Name of field to look for
  945. * @return mixed If $field is string expression bound to virtual field $field
  946. * If $field is null, returns an array of all model virtual fields
  947. * or false if none $field exist.
  948. * @access public
  949. */
  950. function getVirtualField($field = null) {
  951. if ($field == null) {
  952. return empty($this->virtualFields) ? false : $this->virtualFields;
  953. }
  954. if ($this->isVirtualField($field)) {
  955. if (strpos($field, '.') !== false) {
  956. list($model, $field) = explode('.', $field);
  957. }
  958. return $this->virtualFields[$field];
  959. }
  960. return false;
  961. }
  962. /**
  963. * Initializes the model for writing a new record, loading the default values
  964. * for those fields that are not defined in $data, and clearing previous validation errors.
  965. * Especially helpful for saving data in loops.
  966. *
  967. * @param mixed $data Optional data array to assign to the model after it is created. If null or false,
  968. * schema data defaults are not merged.
  969. * @param boolean $filterKey If true, overwrites any primary key input with an empty value
  970. * @return array The current Model::data; after merging $data and/or defaults from database
  971. * @access public
  972. * @link http://book.cakephp.org/view/1031/Saving-Your-Data
  973. */
  974. function create($data = array(), $filterKey = false) {
  975. $defaults = array();
  976. $this->id = false;
  977. $this->data = array();
  978. $this->validationErrors = array();
  979. if ($data !== null && $data !== false) {
  980. foreach ($this->schema() as $field => $properties) {
  981. if ($this->primaryKey !== $field && isset($properties['default']) && $properties['default'] !== '') {
  982. $defaults[$field] = $properties['default'];
  983. }
  984. }
  985. $this->set($defaults);
  986. $this->set($data);
  987. }
  988. if ($filterKey) {
  989. $this->set($this->primaryKey, false);
  990. }
  991. return $this->data;
  992. }
  993. /**
  994. * Returns a list of fields from the database, and sets the current model
  995. * data (Model::$data) with the record found.
  996. *
  997. * @param mixed $fields String of single fieldname, or an array of fieldnames.
  998. * @param mixed $id The ID of the record to read
  999. * @return array Array of database fields, or false if not found
  1000. * @access public
  1001. * @link http://book.cakephp.org/view/1017/Retrieving-Your-Data#read-1029
  1002. */
  1003. function read($fields = null, $id = null) {
  1004. $this->validationErrors = array();
  1005. if ($id != null) {
  1006. $this->id = $id;
  1007. }
  1008. $id = $this->id;
  1009. if (is_array($this->id)) {
  1010. $id = $this->id[0];
  1011. }
  1012. if ($id !== null && $id !== false) {
  1013. $this->data = $this->find('first', array(
  1014. 'conditions' => array($this->alias . '.' . $this->primaryKey => $id),
  1015. 'fields' => $fields
  1016. ));
  1017. return $this->data;
  1018. } else {
  1019. return false;
  1020. }
  1021. }
  1022. /**
  1023. * Returns the contents of a single field given the supplied conditions, in the
  1024. * supplied order.
  1025. *
  1026. * @param string $name Name of field to get
  1027. * @param array $conditions SQL conditions (defaults to NULL)
  1028. * @param string $order SQL ORDER BY fragment
  1029. * @return string field contents, or false if not found
  1030. * @access public
  1031. * @link http://book.cakephp.org/view/1017/Retrieving-Your-Data#field-1028
  1032. */
  1033. function field($name, $conditions = null, $order = null) {
  1034. if ($conditions === null && $this->id !== false) {
  1035. $conditions = array($this->alias . '.' . $this->primaryKey => $this->id);
  1036. }
  1037. if ($this->recursive >= 1) {
  1038. $recursive = -1;
  1039. } else {
  1040. $recursive = $this->recursive;
  1041. }
  1042. $fields = $name;
  1043. if ($data = $this->find('first', compact('conditions', 'fields', 'order', 'recursive'))) {
  1044. if (strpos($name, '.') === false) {
  1045. if (isset($data[$this->alias][$name])) {
  1046. return $data[$this->alias][$name];
  1047. }
  1048. } else {
  1049. $name = explode('.', $name);
  1050. if (isset($data[$name[0]][$name[1]])) {
  1051. return $data[$name[0]][$name[1]];
  1052. }
  1053. }
  1054. if (isset($data[0]) && count($data[0]) > 0) {
  1055. return array_shift($data[0]);
  1056. }
  1057. } else {
  1058. return false;
  1059. }
  1060. }
  1061. /**
  1062. * Saves the value of a single field to the database, based on the current
  1063. * model ID.
  1064. *
  1065. * @param string $name Name of the table field
  1066. * @param mixed $value Value of the field
  1067. * @param array $validate See $options param in Model::save(). Does not respect 'fieldList' key if passed
  1068. * @return boolean See Model::save()
  1069. * @access public
  1070. * @see Model::save()
  1071. * @link http://book.cakephp.org/view/1031/Saving-Your-Data
  1072. */
  1073. function saveField($name, $value, $validate = false) {
  1074. $id = $this->id;
  1075. $this->create(false);
  1076. if (is_array($validate)) {
  1077. $options = array_merge(array('validate' => false, 'fieldList' => array($name)), $validate);
  1078. } else {
  1079. $options = array('validate' => $validate, 'fieldList' => array($name));
  1080. }
  1081. return $this->save(array($this->alias => array($this->primaryKey => $id, $name => $value)), $options);
  1082. }
  1083. /**
  1084. * Saves model data (based on white-list, if supplied) to the database. By
  1085. * default, validation occurs before save.
  1086. *
  1087. * @param array $data Data to save.
  1088. * @param mixed $validate Either a boolean, or an array.
  1089. * If a boolean, indicates whether or not to validate before saving.
  1090. * If an array, allows control of validate, callbacks, and fieldList
  1091. * @param array $fieldList List of fields to allow to be written
  1092. * @return mixed On success Model::$data if its not empty or true, false on failure
  1093. * @access public
  1094. * @link http://book.cakephp.org/view/1031/Saving-Your-Data
  1095. */
  1096. function save($data = null, $validate = true, $fieldList = array()) {
  1097. $defaults = array('validate' => true, 'fieldList' => array(), 'callbacks' => true);
  1098. $_whitelist = $this->whitelist;
  1099. $fields = array();
  1100. if (!is_array($validate)) {
  1101. $options = array_merge($defaults, compact('validate', 'fieldList', 'callbacks'));
  1102. } else {
  1103. $options = array_merge($defaults, $validate);
  1104. }
  1105. if (!empty($options['fieldList'])) {
  1106. $this->whitelist = $options['fieldList'];
  1107. } elseif ($options['fieldList'] === null) {
  1108. $this->whitelist = array();
  1109. }
  1110. $this->set($data);
  1111. if (empty($this->data) && !$this->hasField(array('created', 'updated', 'modified'))) {
  1112. return false;
  1113. }
  1114. foreach (array('created', 'updated', 'modified') as $field) {
  1115. $keyPresentAndEmpty = (
  1116. isset($this->data[$this->alias]) &&
  1117. array_key_exists($field, $this->data[$this->alias]) &&
  1118. $this->data[$this->alias][$field] === null
  1119. );
  1120. if ($keyPresentAndEmpty) {
  1121. unset($this->data[$this->alias][$field]);
  1122. }
  1123. }
  1124. $exists = $this->exists();
  1125. $dateFields = array('modified', 'updated');
  1126. if (!$exists) {
  1127. $dateFields[] = 'created';
  1128. }
  1129. if (isset($this->data[$this->alias])) {
  1130. $fields = array_keys($this->data[$this->alias]);
  1131. }
  1132. if ($options['validate'] && !$this->validates($options)) {
  1133. $this->whitelist = $_whitelist;
  1134. return false;
  1135. }
  1136. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  1137. foreach ($dateFields as $updateCol) {
  1138. if ($this->hasField($updateCol) && !in_array($updateCol, $fields)) {
  1139. $default = array('formatter' => 'date');
  1140. $colType = array_merge($default, $db->columns[$this->getColumnType($updateCol)]);
  1141. if (!array_key_exists('format', $colType)) {
  1142. $time = strtotime('now');
  1143. } else {
  1144. $time = $colType['formatter']($colType['format']);
  1145. }
  1146. if (!empty($this->whitelist)) {
  1147. $this->whitelist[] = $updateCol;
  1148. }
  1149. $this->set($updateCol, $time);
  1150. }
  1151. }
  1152. if ($options['callbacks'] === true || $options['callbacks'] === 'before') {
  1153. $result = $this->Behaviors->trigger($this, 'beforeSave', array($options), array(
  1154. 'break' => true, 'breakOn' => false
  1155. ));
  1156. if (!$result || !$this->beforeSave($options)) {
  1157. $this->whitelist = $_whitelist;
  1158. return false;
  1159. }
  1160. }
  1161. if (empty($this->data[$this->alias][$this->primaryKey])) {
  1162. unset($this->data[$this->alias][$this->primaryKey]);
  1163. }
  1164. $fields = $values = array();
  1165. foreach ($this->data as $n => $v) {
  1166. if (isset($this->hasAndBelongsToMany[$n])) {
  1167. if (isset($v[$n])) {
  1168. $v = $v[$n];
  1169. }
  1170. $joined[$n] = $v;
  1171. } else {
  1172. if ($n === $this->alias) {
  1173. foreach (array('created', 'updated', 'modified') as $field) {
  1174. if (array_key_exists($field, $v) && empty($v[$field])) {
  1175. unset($v[$field]);
  1176. }
  1177. }
  1178. foreach ($v as $x => $y) {
  1179. if ($this->hasField($x) && (empty($this->whitelist) || in_array($x, $this->whitelist))) {
  1180. list($fields[], $values[]) = array($x, $y);
  1181. }
  1182. }
  1183. }
  1184. }
  1185. }
  1186. $count = count($fields);
  1187. if (!$exists && $count > 0) {
  1188. $this->id = false;
  1189. }
  1190. $success = true;
  1191. $created = false;
  1192. if ($count > 0) {
  1193. $cache = $this->_prepareUpdateFields(array_combine($fields, $values));
  1194. if (!empty($this->id)) {
  1195. $success = (bool)$db->update($this, $fields, $values);
  1196. } else {
  1197. $fInfo = $this->_schema[$this->primaryKey];
  1198. $isUUID = ($fInfo['length'] == 36 &&
  1199. ($fInfo['type'] === 'string' || $fInfo['type'] === 'binary')
  1200. );
  1201. if (empty($this->data[$this->alias][$this->primaryKey]) && $isUUID) {
  1202. if (array_key_exists($this->primaryKey, $this->data[$this->alias])) {
  1203. $j = array_search($this->primaryKey, $fields);
  1204. $values[$j] = String::uuid();
  1205. } else {
  1206. list($fields[], $values[]) = array($this->primaryKey, String::uuid());
  1207. }
  1208. }
  1209. if (!$db->create($this, $fields, $values)) {
  1210. $success = $created = false;
  1211. } else {
  1212. $created = true;
  1213. }
  1214. }
  1215. if ($success && !empty($this->belongsTo)) {
  1216. $this->updateCounterCache($cache, $created);
  1217. }
  1218. }
  1219. if (!empty($joined) && $success === true) {
  1220. $this->__saveMulti($joined, $this->id, $db);
  1221. }
  1222. if ($success && $count > 0) {
  1223. if (!empty($this->data)) {
  1224. $success = $this->data;
  1225. }
  1226. if ($options['callbacks'] === true || $options['callbacks'] === 'after') {
  1227. $this->Behaviors->trigger($this, 'afterSave', array($created, $options));
  1228. $this->afterSave($created);
  1229. }
  1230. if (!empty($this->data)) {
  1231. $success = Set::merge($success, $this->data);
  1232. }
  1233. $this->data = false;
  1234. $this->_clearCache();
  1235. $this->validationErrors = array();
  1236. }
  1237. $this->whitelist = $_whitelist;
  1238. return $success;
  1239. }
  1240. /**
  1241. * Saves model hasAndBelongsToMany data to the database.
  1242. *
  1243. * @param array $joined Data to save
  1244. * @param mixed $id ID of record in this model
  1245. * @access private
  1246. */
  1247. function __saveMulti($joined, $id, &$db) {
  1248. foreach ($joined as $assoc => $data) {
  1249. if (isset($this->hasAndBelongsToMany[$assoc])) {
  1250. list($join) = $this->joinModel($this->hasAndBelongsToMany[$assoc]['with']);
  1251. $isUUID = !empty($this->{$join}->primaryKey) && (
  1252. $this->{$join}->_schema[$this->{$join}->primaryKey]['length'] == 36 && (
  1253. $this->{$join}->_schema[$this->{$join}->primaryKey]['type'] === 'string' ||
  1254. $this->{$join}->_schema[$this->{$join}->primaryKey]['type'] === 'binary'
  1255. )
  1256. );
  1257. $newData = $newValues = array();
  1258. $primaryAdded = false;
  1259. $fields = array(
  1260. $db->name($this->hasAndBelongsToMany[$assoc]['foreignKey']),
  1261. $db->name($this->hasAndBelongsToMany[$assoc]['associationForeignKey'])
  1262. );
  1263. $idField = $db->name($this->{$join}->primaryKey);
  1264. if ($isUUID && !in_array($idField, $fields)) {
  1265. $fields[] = $idField;
  1266. $primaryAdded = true;
  1267. }
  1268. foreach ((array)$data as $row) {
  1269. if ((is_string($row) && (strlen($row) == 36 || strlen($row) == 16)) || is_numeric($row)) {
  1270. $values = array(
  1271. $db->value($id, $this->getColumnType($this->primaryKey)),
  1272. $db->value($row)
  1273. );
  1274. if ($isUUID && $primaryAdded) {
  1275. $values[] = $db->value(String::uuid());
  1276. }
  1277. $values = implode(',', $values);
  1278. $newValues[] = "({$values})";
  1279. unset($values);
  1280. } elseif (isset($row[$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
  1281. $newData[] = $row;
  1282. } elseif (isset($row[$join]) && isset($row[$join][$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
  1283. $newData[] = $row[$join];
  1284. }
  1285. }
  1286. if ($this->hasAndBelongsToMany[$assoc]['unique']) {
  1287. $conditions = array(
  1288. $join . '.' . $this->hasAndBelongsToMany[$assoc]['foreignKey'] => $id
  1289. );
  1290. if (!empty($this->hasAndBelongsToMany[$assoc]['conditions'])) {
  1291. $conditions = array_merge($conditions, (array)$this->hasAndBelongsToMany[$assoc]['conditions']);
  1292. }
  1293. $links = $this->{$join}->find('all', array(
  1294. 'conditions' => $conditions,
  1295. 'recursive' => empty($this->hasAndBelongsToMany[$assoc]['conditions']) ? -1 : 0,
  1296. 'fields' => $this->hasAndBelongsToMany[$assoc]['associationForeignKey']
  1297. ));
  1298. $associationForeignKey = "{$join}." . $this->hasAndBelongsToMany[$assoc]['associationForeignKey'];
  1299. $oldLinks = Set::extract($links, "{n}.{$associationForeignKey}");
  1300. if (!empty($oldLinks)) {
  1301. $conditions[$associationForeignKey] = $oldLinks;
  1302. $db->delete($this->{$join}, $conditions);
  1303. }
  1304. }
  1305. if (!empty($newData)) {
  1306. foreach ($newData as $data) {
  1307. $data[$this->hasAndBelongsToMany[$assoc]['foreignKey']] = $id;
  1308. $this->{$join}->create($data);
  1309. $this->{$join}->save();
  1310. }
  1311. }
  1312. if (!empty($newValues)) {
  1313. $fields = implode(',', $fields);
  1314. $db->insertMulti($this->{$join}, $fields, $newValues);
  1315. }
  1316. }
  1317. }
  1318. }
  1319. /**
  1320. * Updates the counter cache of belongsTo associations after a save or delete operation
  1321. *
  1322. * @param array $keys Optional foreign key data, defaults to the information $this->data
  1323. * @param boolean $created True if a new record was created, otherwise only associations with
  1324. * 'counterScope' defined get updated
  1325. * @return void
  1326. * @access public
  1327. */
  1328. function updateCounterCache($keys = array(), $created = false) {
  1329. $keys = empty($keys) ? $this->data[$this->alias] : $keys;
  1330. $keys['old'] = isset($keys['old']) ? $keys['old'] : array();
  1331. foreach ($this->belongsTo as $parent => $assoc) {
  1332. $foreignKey = $assoc['foreignKey'];
  1333. $fkQuoted = $this->escapeField($assoc['foreignKey']);
  1334. if (!empty($assoc['counterCache'])) {
  1335. if ($assoc['counterCache'] === true) {
  1336. $assoc['counterCache'] = Inflector::underscore($this->alias) . '_count';
  1337. }
  1338. if (!$this->{$parent}->hasField($assoc['counterCache'])) {
  1339. continue;
  1340. }
  1341. if (!array_key_exists($foreignKey, $keys)) {
  1342. $keys[$foreignKey] = $this->field($foreignKey);
  1343. }
  1344. $recursive = (isset($assoc['counterScope']) ? 1 : -1);
  1345. $conditions = ($recursive == 1) ? (array)$assoc['counterScope'] : array();
  1346. if (isset($keys['old'][$foreignKey])) {
  1347. if ($keys['old'][$foreignKey] != $keys[$foreignKey]) {
  1348. $conditions[$fkQuoted] = $keys['old'][$foreignKey];
  1349. $count = intval($this->find('count', compact('conditions', 'recursive')));
  1350. $this->{$parent}->updateAll(
  1351. array($assoc['counterCache'] => $count),
  1352. array($this->{$parent}->escapeField() => $keys['old'][$foreignKey])
  1353. );
  1354. }
  1355. }
  1356. $conditions[$fkQuoted] = $keys[$foreignKey];
  1357. if ($recursive == 1) {
  1358. $conditions = array_merge($conditions, (array)$assoc['counterScope']);
  1359. }
  1360. $count = intval($this->find('count', compact('conditions', 'recursive')));
  1361. $this->{$parent}->updateAll(
  1362. array($assoc['counterCache'] => $count),
  1363. array($this->{$parent}->escapeField() => $keys[$foreignKey])
  1364. );
  1365. }
  1366. }
  1367. }
  1368. /**
  1369. * Helper method for Model::updateCounterCache(). Checks the fields to be updated for
  1370. *
  1371. * @param array $data The fields of the record that will be updated
  1372. * @return array Returns updated foreign key values, along with an 'old' key containing the old
  1373. * values, or empty if no foreign keys are updated.
  1374. * @access protected
  1375. */
  1376. function _prepareUpdateFields($data) {
  1377. $foreignKeys = array();
  1378. foreach ($this->belongsTo as $assoc => $info) {
  1379. if ($info['counterCache']) {
  1380. $foreignKeys[$assoc] = $info['foreignKey'];
  1381. }
  1382. }
  1383. $included = array_intersect($foreignKeys, array_keys($data));
  1384. if (empty($included) || empty($this->id)) {
  1385. return array();
  1386. }
  1387. $old = $this->find('first', array(
  1388. 'conditions' => array($this->primaryKey => $this->id),
  1389. 'fields' => array_values($included),
  1390. 'recursive' => -1
  1391. ));
  1392. return array_merge($data, array('old' => $old[$this->alias]));
  1393. }
  1394. /**
  1395. * Saves multiple individual records for a single model; Also works with a single record, as well as
  1396. * all its associated records.
  1397. *
  1398. * #### Options
  1399. *
  1400. * - validate: Set to false to disable validation, true to validate each record before saving,
  1401. * 'first' to validate *all* records before any are saved (default),
  1402. * or 'only' to only validate the records, but not save them.
  1403. * - atomic: If true (default), will attempt to save all records in a single transaction.
  1404. * Should be set to false if database/table does not support transactions.
  1405. * - fieldList: Equivalent to the $fieldList parameter in Model::save()
  1406. *
  1407. * @param array $data Record data to save. This can be either a numerically-indexed array (for saving multiple
  1408. * records of the same type), or an array indexed by association name.
  1409. * @param array $options Options to use when saving record data, See $options above.
  1410. * @return mixed If atomic: True on success, or false on failure.
  1411. * Otherwise: array similar to the $data array passed, but values are set to true/false
  1412. * depending on whether each record saved successfully.
  1413. * @access public
  1414. * @link http://book.cakephp.org/view/1032/Saving-Related-Model-Data-hasOne-hasMany-belongsTo
  1415. * @link http://book.cakephp.org/view/1031/Saving-Your-Data
  1416. */
  1417. function saveAll($data = null, $options = array()) {
  1418. if (empty($data)) {
  1419. $data = $this->data;
  1420. }
  1421. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  1422. $options = array_merge(array('validate' => 'first', 'atomic' => true), $options);
  1423. $this->validationErrors = $validationErrors = array();
  1424. $validates = true;
  1425. $return = array();
  1426. if (empty($data) && $options['validate'] !== false) {
  1427. $result = $this->save($data, $options);
  1428. return !empty($result);
  1429. }
  1430. if ($options['atomic'] && $options['validate'] !== 'only') {
  1431. $transactionBegun = $db->begin($this);
  1432. }
  1433. if (Set::numeric(array_keys($data))) {
  1434. while ($validates) {
  1435. $return = array();
  1436. foreach ($data as $key => $record) {
  1437. if (!$currentValidates = $this->__save($record, $options)) {
  1438. $validationErrors[$key] = $this->validationErrors;
  1439. }
  1440. if ($options['validate'] === 'only' || $options['validate'] === 'first') {
  1441. $validating = true;
  1442. if ($options['atomic']) {
  1443. $validates = $validates && $currentValidates;
  1444. } else {
  1445. $validates = $currentValidates;
  1446. }
  1447. } else {
  1448. $validating = false;
  1449. $validates = $currentValidates;
  1450. }
  1451. if (!$options['atomic']) {
  1452. $return[] = $validates;
  1453. } elseif (!$validates && !$validating) {
  1454. break;
  1455. }
  1456. }
  1457. $this->validationErrors = $validationErrors;
  1458. switch (true) {
  1459. case ($options['validate'] === 'only'):
  1460. return ($options['atomic'] ? $validates : $return);
  1461. break;
  1462. case ($options['validate'] === 'first'):
  1463. $options['validate'] = true;
  1464. break;
  1465. default:
  1466. if ($options['atomic']) {
  1467. if ($validates) {
  1468. if ($transactionBegun) {
  1469. return $db->commit($this) !== false;
  1470. } else {
  1471. return true;
  1472. }
  1473. }
  1474. $db->rollback($this);
  1475. return false;
  1476. }
  1477. return $return;
  1478. break;
  1479. }
  1480. }
  1481. if ($options['atomic'] && !$validates) {
  1482. $db->rollback($this);
  1483. return false;
  1484. }
  1485. return $return;
  1486. }
  1487. $associations = $this->getAssociated();
  1488. while ($validates) {
  1489. foreach ($data as $association => $values) {
  1490. if (isset($associations[$association])) {
  1491. switch ($associations[$association]) {
  1492. case 'belongsTo':
  1493. if ($this->{$association}->__save($values, $options)) {
  1494. $data[$this->alias][$this->belongsTo[$association]['foreignKey']] = $this->{$association}->id;
  1495. } else {
  1496. $validationErrors[$association] = $this->{$association}->validationErrors;
  1497. $validates = false;
  1498. }
  1499. if (!$options['atomic']) {
  1500. $return[$association][] = $validates;
  1501. }
  1502. break;
  1503. }
  1504. }
  1505. }
  1506. if (!$this->__save($data, $options)) {
  1507. $validationErrors[$this->alias] = $this->validationErrors;
  1508. $validates = false;
  1509. }
  1510. if (!$options['atomic']) {
  1511. $return[$this->alias] = $validates;
  1512. }
  1513. $validating = ($options['validate'] === 'only' || $options['validate'] === 'first');
  1514. foreach ($data as $association => $values) {
  1515. if (!$validates && !$validating) {
  1516. break;
  1517. }
  1518. if (isset($associations[$association])) {
  1519. $type = $associations[$association];
  1520. switch ($type) {
  1521. case 'hasOne':
  1522. $values[$this->{$type}[$association]['foreignKey']] = $this->id;
  1523. if (!$this->{$association}->__save($values, $options)) {
  1524. $validationErrors[$association] = $this->{$association}->validationErrors;
  1525. $validates = false;
  1526. }
  1527. if (!$options['atomic']) {
  1528. $return[$association][] = $validates;
  1529. }
  1530. break;
  1531. case 'hasMany':
  1532. foreach ($values as $i => $value