PageRenderTime 52ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/cake/libs/model/model.php

http://github.com/Datawalke/Coordino
PHP | 3093 lines | 1822 code | 278 blank | 993 comment | 540 complexity | d0f2e3801bd069b5210355eb5fa4a4d9 MD5 | raw file

Large files files are truncated, but you can 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-2012, 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-2012, 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. $this->setDataSource($this->useDbConfig);
  681. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  682. $db->cacheSources = ($this->cacheSources && $db->cacheSources);
  683. if ($db->isInterfaceSupported('listSources')) {
  684. $sources = $db->listSources();
  685. if (is_array($sources) && !in_array(strtolower($this->tablePrefix . $tableName), array_map('strtolower', $sources))) {
  686. return $this->cakeError('missingTable', array(array(
  687. 'className' => $this->alias,
  688. 'table' => $this->tablePrefix . $tableName,
  689. 'code' => 500
  690. )));
  691. }
  692. $this->_schema = null;
  693. }
  694. $this->table = $this->useTable = $tableName;
  695. $this->tableToModel[$this->table] = $this->alias;
  696. $this->schema();
  697. }
  698. /**
  699. * This function does two things:
  700. *
  701. * 1. it scans the array $one for the primary key,
  702. * and if that's found, it sets the current id to the value of $one[id].
  703. * For all other keys than 'id' the keys and values of $one are copied to the 'data' property of this object.
  704. * 2. Returns an array with all of $one's keys and values.
  705. * (Alternative indata: two strings, which are mangled to
  706. * a one-item, two-dimensional array using $one for a key and $two as its value.)
  707. *
  708. * @param mixed $one Array or string of data
  709. * @param string $two Value string for the alternative indata method
  710. * @return array Data with all of $one's keys and values
  711. * @access public
  712. * @link http://book.cakephp.org/view/1031/Saving-Your-Data
  713. */
  714. function set($one, $two = null) {
  715. if (!$one) {
  716. return;
  717. }
  718. if (is_object($one)) {
  719. $one = Set::reverse($one);
  720. }
  721. if (is_array($one)) {
  722. $data = $one;
  723. if (empty($one[$this->alias])) {
  724. if ($this->getAssociated(key($one)) === null) {
  725. $data = array($this->alias => $one);
  726. }
  727. }
  728. } else {
  729. $data = array($this->alias => array($one => $two));
  730. }
  731. foreach ($data as $modelName => $fieldSet) {
  732. if (is_array($fieldSet)) {
  733. foreach ($fieldSet as $fieldName => $fieldValue) {
  734. if (isset($this->validationErrors[$fieldName])) {
  735. unset ($this->validationErrors[$fieldName]);
  736. }
  737. if ($modelName === $this->alias) {
  738. if ($fieldName === $this->primaryKey) {
  739. $this->id = $fieldValue;
  740. }
  741. }
  742. if (is_array($fieldValue) || is_object($fieldValue)) {
  743. $fieldValue = $this->deconstruct($fieldName, $fieldValue);
  744. }
  745. $this->data[$modelName][$fieldName] = $fieldValue;
  746. }
  747. }
  748. }
  749. return $data;
  750. }
  751. /**
  752. * Deconstructs a complex data type (array or object) into a single field value.
  753. *
  754. * @param string $field The name of the field to be deconstructed
  755. * @param mixed $data An array or object to be deconstructed into a field
  756. * @return mixed The resulting data that should be assigned to a field
  757. * @access public
  758. */
  759. function deconstruct($field, $data) {
  760. if (!is_array($data)) {
  761. return $data;
  762. }
  763. $copy = $data;
  764. $type = $this->getColumnType($field);
  765. if (in_array($type, array('datetime', 'timestamp', 'date', 'time'))) {
  766. $useNewDate = (isset($data['year']) || isset($data['month']) ||
  767. isset($data['day']) || isset($data['hour']) || isset($data['minute']));
  768. $dateFields = array('Y' => 'year', 'm' => 'month', 'd' => 'day', 'H' => 'hour', 'i' => 'min', 's' => 'sec');
  769. $timeFields = array('H' => 'hour', 'i' => 'min', 's' => 'sec');
  770. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  771. $format = $db->columns[$type]['format'];
  772. $date = array();
  773. if (isset($data['hour']) && isset($data['meridian']) && $data['hour'] != 12 && 'pm' == $data['meridian']) {
  774. $data['hour'] = $data['hour'] + 12;
  775. }
  776. if (isset($data['hour']) && isset($data['meridian']) && $data['hour'] == 12 && 'am' == $data['meridian']) {
  777. $data['hour'] = '00';
  778. }
  779. if ($type == 'time') {
  780. foreach ($timeFields as $key => $val) {
  781. if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') {
  782. $data[$val] = '00';
  783. } elseif ($data[$val] === '') {
  784. $data[$val] = '';
  785. } else {
  786. $data[$val] = sprintf('%02d', $data[$val]);
  787. }
  788. if (!empty($data[$val])) {
  789. $date[$key] = $data[$val];
  790. } else {
  791. return null;
  792. }
  793. }
  794. }
  795. if ($type == 'datetime' || $type == 'timestamp' || $type == 'date') {
  796. foreach ($dateFields as $key => $val) {
  797. if ($val == 'hour' || $val == 'min' || $val == 'sec') {
  798. if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') {
  799. $data[$val] = '00';
  800. } else {
  801. $data[$val] = sprintf('%02d', $data[$val]);
  802. }
  803. }
  804. if (!isset($data[$val]) || isset($data[$val]) && (empty($data[$val]) || $data[$val][0] === '-')) {
  805. return null;
  806. }
  807. if (isset($data[$val]) && !empty($data[$val])) {
  808. $date[$key] = $data[$val];
  809. }
  810. }
  811. }
  812. $date = str_replace(array_keys($date), array_values($date), $format);
  813. if ($useNewDate && !empty($date)) {
  814. return $date;
  815. }
  816. }
  817. return $data;
  818. }
  819. /**
  820. * Returns an array of table metadata (column names and types) from the database.
  821. * $field => keys(type, null, default, key, length, extra)
  822. *
  823. * @param mixed $field Set to true to reload schema, or a string to return a specific field
  824. * @return array Array of table metadata
  825. * @access public
  826. */
  827. function schema($field = false) {
  828. if (!is_array($this->_schema) || $field === true) {
  829. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  830. $db->cacheSources = ($this->cacheSources && $db->cacheSources);
  831. if ($db->isInterfaceSupported('describe') && $this->useTable !== false) {
  832. $this->_schema = $db->describe($this, $field);
  833. } elseif ($this->useTable === false) {
  834. $this->_schema = array();
  835. }
  836. }
  837. if (is_string($field)) {
  838. if (isset($this->_schema[$field])) {
  839. return $this->_schema[$field];
  840. } else {
  841. return null;
  842. }
  843. }
  844. return $this->_schema;
  845. }
  846. /**
  847. * Returns an associative array of field names and column types.
  848. *
  849. * @return array Field types indexed by field name
  850. * @access public
  851. */
  852. function getColumnTypes() {
  853. $columns = $this->schema();
  854. if (empty($columns)) {
  855. 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);
  856. }
  857. $cols = array();
  858. foreach ($columns as $field => $values) {
  859. $cols[$field] = $values['type'];
  860. }
  861. return $cols;
  862. }
  863. /**
  864. * Returns the column type of a column in the model.
  865. *
  866. * @param string $column The name of the model column
  867. * @return string Column type
  868. * @access public
  869. */
  870. function getColumnType($column) {
  871. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  872. $cols = $this->schema();
  873. $model = null;
  874. $column = str_replace(array($db->startQuote, $db->endQuote), '', $column);
  875. if (strpos($column, '.')) {
  876. list($model, $column) = explode('.', $column);
  877. }
  878. if ($model != $this->alias && isset($this->{$model})) {
  879. return $this->{$model}->getColumnType($column);
  880. }
  881. if (isset($cols[$column]) && isset($cols[$column]['type'])) {
  882. return $cols[$column]['type'];
  883. }
  884. return null;
  885. }
  886. /**
  887. * Returns true if the supplied field exists in the model's database table.
  888. *
  889. * @param mixed $name Name of field to look for, or an array of names
  890. * @param boolean $checkVirtual checks if the field is declared as virtual
  891. * @return mixed If $name is a string, returns a boolean indicating whether the field exists.
  892. * If $name is an array of field names, returns the first field that exists,
  893. * or false if none exist.
  894. * @access public
  895. */
  896. function hasField($name, $checkVirtual = false) {
  897. if (is_array($name)) {
  898. foreach ($name as $n) {
  899. if ($this->hasField($n, $checkVirtual)) {
  900. return $n;
  901. }
  902. }
  903. return false;
  904. }
  905. if ($checkVirtual && !empty($this->virtualFields)) {
  906. if ($this->isVirtualField($name)) {
  907. return true;
  908. }
  909. }
  910. if (empty($this->_schema)) {
  911. $this->schema();
  912. }
  913. if ($this->_schema != null) {
  914. return isset($this->_schema[$name]);
  915. }
  916. return false;
  917. }
  918. /**
  919. * Returns true if the supplied field is a model Virtual Field
  920. *
  921. * @param mixed $name Name of field to look for
  922. * @return boolean indicating whether the field exists as a model virtual field.
  923. * @access public
  924. */
  925. function isVirtualField($field) {
  926. if (empty($this->virtualFields) || !is_string($field)) {
  927. return false;
  928. }
  929. if (isset($this->virtualFields[$field])) {
  930. return true;
  931. }
  932. if (strpos($field, '.') !== false) {
  933. list($model, $field) = explode('.', $field);
  934. if ($model == $this->alias && isset($this->virtualFields[$field])) {
  935. return true;
  936. }
  937. }
  938. return false;
  939. }
  940. /**
  941. * Returns the expression for a model virtual field
  942. *
  943. * @param mixed $name Name of field to look for
  944. * @return mixed If $field is string expression bound to virtual field $field
  945. * If $field is null, returns an array of all model virtual fields
  946. * or false if none $field exist.
  947. * @access public
  948. */
  949. function getVirtualField($field = null) {
  950. if ($field == null) {
  951. return empty($this->virtualFields) ? false : $this->virtualFields;
  952. }
  953. if ($this->isVirtualField($field)) {
  954. if (strpos($field, '.') !== false) {
  955. list($model, $field) = explode('.', $field);
  956. }
  957. return $this->virtualFields[$field];
  958. }
  959. return false;
  960. }
  961. /**
  962. * Initializes the model for writing a new record, loading the default values
  963. * for those fields that are not defined in $data, and clearing previous validation errors.
  964. * Especially helpful for saving data in loops.
  965. *
  966. * @param mixed $data Optional data array to assign to the model after it is created. If null or false,
  967. * schema data defaults are not merged.
  968. * @param boolean $filterKey If true, overwrites any primary key input with an empty value
  969. * @return array The current Model::data; after merging $data and/or defaults from database
  970. * @access public
  971. * @link http://book.cakephp.org/view/1031/Saving-Your-Data
  972. */
  973. function create($data = array(), $filterKey = false) {
  974. $defaults = array();
  975. $this->id = false;
  976. $this->data = array();
  977. $this->validationErrors = array();
  978. if ($data !== null && $data !== false) {
  979. foreach ($this->schema() as $field => $properties) {
  980. if ($this->primaryKey !== $field && isset($properties['default']) && $properties['default'] !== '') {
  981. $defaults[$field] = $properties['default'];
  982. }
  983. }
  984. $this->set($defaults);
  985. $this->set($data);
  986. }
  987. if ($filterKey) {
  988. $this->set($this->primaryKey, false);
  989. }
  990. return $this->data;
  991. }
  992. /**
  993. * Returns a list of fields from the database, and sets the current model
  994. * data (Model::$data) with the record found.
  995. *
  996. * @param mixed $fields String of single fieldname, or an array of fieldnames.
  997. * @param mixed $id The ID of the record to read
  998. * @return array Array of database fields, or false if not found
  999. * @access public
  1000. * @link http://book.cakephp.org/view/1017/Retrieving-Your-Data#read-1029
  1001. */
  1002. function read($fields = null, $id = null) {
  1003. $this->validationErrors = array();
  1004. if ($id != null) {
  1005. $this->id = $id;
  1006. }
  1007. $id = $this->id;
  1008. if (is_array($this->id)) {
  1009. $id = $this->id[0];
  1010. }
  1011. if ($id !== null && $id !== false) {
  1012. $this->data = $this->find('first', array(
  1013. 'conditions' => array($this->alias . '.' . $this->primaryKey => $id),
  1014. 'fields' => $fields
  1015. ));
  1016. return $this->data;
  1017. } else {
  1018. return false;
  1019. }
  1020. }
  1021. /**
  1022. * Returns the contents of a single field given the supplied conditions, in the
  1023. * supplied order.
  1024. *
  1025. * @param string $name Name of field to get
  1026. * @param array $conditions SQL conditions (defaults to NULL)
  1027. * @param string $order SQL ORDER BY fragment
  1028. * @return string field contents, or false if not found
  1029. * @access public
  1030. * @link http://book.cakephp.org/view/1017/Retrieving-Your-Data#field-1028
  1031. */
  1032. function field($name, $conditions = null, $order = null) {
  1033. if ($conditions === null && $this->id !== false) {
  1034. $conditions = array($this->alias . '.' . $this->primaryKey => $this->id);
  1035. }
  1036. if ($this->recursive >= 1) {
  1037. $recursive = -1;
  1038. } else {
  1039. $recursive = $this->recursive;
  1040. }
  1041. $fields = $name;
  1042. if ($data = $this->find('first', compact('conditions', 'fields', 'order', 'recursive'))) {
  1043. if (strpos($name, '.') === false) {
  1044. if (isset($data[$this->alias][$name])) {
  1045. return $data[$this->alias][$name];
  1046. }
  1047. } else {
  1048. $name = explode('.', $name);
  1049. if (isset($data[$name[0]][$name[1]])) {
  1050. return $data[$name[0]][$name[1]];
  1051. }
  1052. }
  1053. if (isset($data[0]) && count($data[0]) > 0) {
  1054. return array_shift($data[0]);
  1055. }
  1056. } else {
  1057. return false;
  1058. }
  1059. }
  1060. /**
  1061. * Saves the value of a single field to the database, based on the current
  1062. * model ID.
  1063. *
  1064. * @param string $name Name of the table field
  1065. * @param mixed $value Value of the field
  1066. * @param array $validate See $options param in Model::save(). Does not respect 'fieldList' key if passed
  1067. * @return boolean See Model::save()
  1068. * @access public
  1069. * @see Model::save()
  1070. * @link http://book.cakephp.org/view/1031/Saving-Your-Data
  1071. */
  1072. function saveField($name, $value, $validate = false) {
  1073. $id = $this->id;
  1074. $this->create(false);
  1075. if (is_array($validate)) {
  1076. $options = array_merge(array('validate' => false, 'fieldList' => array($name)), $validate);
  1077. } else {
  1078. $options = array('validate' => $validate, 'fieldList' => array($name));
  1079. }
  1080. return $this->save(array($this->alias => array($this->primaryKey => $id, $name => $value)), $options);
  1081. }
  1082. /**
  1083. * Saves model data (based on white-list, if supplied) to the database. By
  1084. * default, validation occurs before save.
  1085. *
  1086. * @param array $data Data to save.
  1087. * @param mixed $validate Either a boolean, or an array.
  1088. * If a boolean, indicates whether or not to validate before saving.
  1089. * If an array, allows control of validate, callbacks, and fieldList
  1090. * @param array $fieldList List of fields to allow to be written
  1091. * @return mixed On success Model::$data if its not empty or true, false on failure
  1092. * @access public
  1093. * @link http://book.cakephp.org/view/1031/Saving-Your-Data
  1094. */
  1095. function save($data = null, $validate = true, $fieldList = array()) {
  1096. $defaults = array('validate' => true, 'fieldList' => array(), 'callbacks' => true);
  1097. $_whitelist = $this->whitelist;
  1098. $fields = array();
  1099. if (!is_array($validate)) {
  1100. $options = array_merge($defaults, compact('validate', 'fieldList', 'callbacks'));
  1101. } else {
  1102. $options = array_merge($defaults, $validate);
  1103. }
  1104. if (!empty($options['fieldList'])) {
  1105. $this->whitelist = $options['fieldList'];
  1106. } elseif ($options['fieldList'] === null) {
  1107. $this->whitelist = array();
  1108. }
  1109. $this->set($data);
  1110. if (empty($this->data) && !$this->hasField(array('created', 'updated', 'modified'))) {
  1111. return false;
  1112. }
  1113. foreach (array('created', 'updated', 'modified') as $field) {
  1114. $keyPresentAndEmpty = (
  1115. isset($this->data[$this->alias]) &&
  1116. array_key_exists($field, $this->data[$this->alias]) &&
  1117. $this->data[$this->alias][$field] === null
  1118. );
  1119. if ($keyPresentAndEmpty) {
  1120. unset($this->data[$this->alias][$field]);
  1121. }
  1122. }
  1123. $exists = $this->exists();
  1124. $dateFields = array('modified', 'updated');
  1125. if (!$exists) {
  1126. $dateFields[] = 'created';
  1127. }
  1128. if (isset($this->data[$this->alias])) {
  1129. $fields = array_keys($this->data[$this->alias]);
  1130. }
  1131. if ($options['validate'] && !$this->validates($options)) {
  1132. $this->whitelist = $_whitelist;
  1133. return false;
  1134. }
  1135. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  1136. foreach ($dateFields as $updateCol) {
  1137. if ($this->hasField($updateCol) && !in_array($updateCol, $fields)) {
  1138. $default = array('formatter' => 'date');
  1139. $colType = array_merge($default, $db->columns[$this->getColumnType($updateCol)]);
  1140. if (!array_key_exists('format', $colType)) {
  1141. $time = strtotime('now');
  1142. } else {
  1143. $time = $colType['formatter']($colType['format']);
  1144. }
  1145. if (!empty($this->whitelist)) {
  1146. $this->whitelist[] = $updateCol;
  1147. }
  1148. $this->set($updateCol, $time);
  1149. }
  1150. }
  1151. if ($options['callbacks'] === true || $options['callbacks'] === 'before') {
  1152. $result = $this->Behaviors->trigger($this, 'beforeSave', array($options), array(
  1153. 'break' => true, 'breakOn' => false
  1154. ));
  1155. if (!$result || !$this->beforeSave($options)) {
  1156. $this->whitelist = $_whitelist;
  1157. return false;
  1158. }
  1159. }
  1160. if (empty($this->data[$this->alias][$this->primaryKey])) {
  1161. unset($this->data[$this->alias][$this->primaryKey]);
  1162. }
  1163. $fields = $values = array();
  1164. foreach ($this->data as $n => $v) {
  1165. if (isset($this->hasAndBelongsToMany[$n])) {
  1166. if (isset($v[$n])) {
  1167. $v = $v[$n];
  1168. }
  1169. $joined[$n] = $v;
  1170. } else {
  1171. if ($n === $this->alias) {
  1172. foreach (array('created', 'updated', 'modified') as $field) {
  1173. if (array_key_exists($field, $v) && empty($v[$field])) {
  1174. unset($v[$field]);
  1175. }
  1176. }
  1177. foreach ($v as $x => $y) {
  1178. if ($this->hasField($x) && (empty($this->whitelist) || in_array($x, $this->whitelist))) {
  1179. list($fields[], $values[]) = array($x, $y);
  1180. }
  1181. }
  1182. }
  1183. }
  1184. }
  1185. $count = count($fields);
  1186. if (!$exists && $count > 0) {
  1187. $this->id = false;
  1188. }
  1189. $success = true;
  1190. $created = false;
  1191. if ($count > 0) {
  1192. $cache = $this->_prepareUpdateFields(array_combine($fields, $values));
  1193. if (!empty($this->id)) {
  1194. $success = (bool)$db->update($this, $fields, $values);
  1195. } else {
  1196. $fInfo = $this->_schema[$this->primaryKey];
  1197. $isUUID = ($fInfo['length'] == 36 &&
  1198. ($fInfo['type'] === 'string' || $fInfo['type'] === 'binary')
  1199. );
  1200. if (empty($this->data[$this->alias][$this->primaryKey]) && $isUUID) {
  1201. if (array_key_exists($this->primaryKey, $this->data[$this->alias])) {
  1202. $j = array_search($this->primaryKey, $fields);
  1203. $values[$j] = String::uuid();
  1204. } else {
  1205. list($fields[], $values[]) = array($this->primaryKey, String::uuid());
  1206. }
  1207. }
  1208. if (!$db->create($this, $fields, $values)) {
  1209. $success = $created = false;
  1210. } else {
  1211. $created = true;
  1212. }
  1213. }
  1214. if ($success && !empty($this->belongsTo)) {
  1215. $this->updateCounterCache($cache, $created);
  1216. }
  1217. }
  1218. if (!empty($joined) && $success === true) {
  1219. $this->__saveMulti($joined, $this->id, $db);
  1220. }
  1221. if ($success && $count > 0) {
  1222. if (!empty($this->data)) {
  1223. $success = $this->data;
  1224. }
  1225. if ($options['callbacks'] === true || $options['callbacks'] === 'after') {
  1226. $this->Behaviors->trigger($this, 'afterSave', array($created, $options));
  1227. $this->afterSave($created);
  1228. }
  1229. if (!empty($this->data)) {
  1230. $success = Set::merge($success, $this->data);
  1231. }
  1232. $this->data = false;
  1233. $this->_clearCache();
  1234. $this->validationErrors = array();
  1235. }
  1236. $this->whitelist = $_whitelist;
  1237. return $success;
  1238. }
  1239. /**
  1240. * Saves model hasAndBelongsToMany data to the database.
  1241. *
  1242. * @param array $joined Data to save
  1243. * @param mixed $id ID of record in this model
  1244. * @access private
  1245. */
  1246. function __saveMulti($joined, $id, &$db) {
  1247. foreach ($joined as $assoc => $data) {
  1248. if (isset($this->hasAndBelongsToMany[$assoc])) {
  1249. list($join) = $this->joinModel($this->hasAndBelongsToMany[$assoc]['with']);
  1250. $isUUID = !empty($this->{$join}->primaryKey) && (
  1251. $this->{$join}->_schema[$this->{$join}->primaryKey]['length'] == 36 && (
  1252. $this->{$join}->_schema[$this->{$join}->primaryKey]['type'] === 'string' ||
  1253. $this->{$join}->_schema[$this->{$join}->primaryKey]['type'] === 'binary'
  1254. )
  1255. );
  1256. $newData = $newValues = array();
  1257. $primaryAdded = false;
  1258. $fields = array(
  1259. $db->name($this->hasAndBelongsToMany[$assoc]['foreignKey']),
  1260. $db->name($this->hasAndBelongsToMany[$assoc]['associationForeignKey'])
  1261. );
  1262. $idField = $db->name($this->{$join}->primaryKey);
  1263. if ($isUUID && !in_array($idField, $fields)) {
  1264. $fields[] = $idField;
  1265. $primaryAdded = true;
  1266. }
  1267. foreach ((array)$data as $row) {
  1268. if ((is_string($row) && (strlen($row) == 36 || strlen($row) == 16)) || is_numeric($row)) {
  1269. $values = array(
  1270. $db->value($id, $this->getColumnType($this->primaryKey)),
  1271. $db->value($row)
  1272. );
  1273. if ($isUUID && $primaryAdded) {
  1274. $values[] = $db->value(String::uuid());
  1275. }
  1276. $values = implode(',', $values);
  1277. $newValues[] = "({$values})";
  1278. unset($values);
  1279. } elseif (isset($row[$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
  1280. $newData[] = $row;
  1281. } elseif (isset($row[$join]) && isset($row[$join][$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
  1282. $newData[] = $row[$join];
  1283. }
  1284. }
  1285. if ($this->hasAndBelongsToMany[$assoc]['unique']) {
  1286. $conditions = array(
  1287. $join . '.' . $this->hasAndBelongsToMany[$assoc]['foreignKey'] => $id
  1288. );
  1289. if (!empty($this->hasAndBelongsToMany[$assoc]['conditions'])) {
  1290. $conditions = array_merge($conditions, (array)$this->hasAndBelongsToMany[$assoc]['conditions']);
  1291. }
  1292. $links = $this->{$join}->find('all', array(
  1293. 'conditions' => $conditions,
  1294. 'recursive' => empty($this->hasAndBelongsToMany[$assoc]['conditions']) ? -1 : 0,
  1295. 'fields' => $this->hasAndBelongsToMany[$assoc]['associationForeignKey']
  1296. ));
  1297. $associationForeignKey = "{$join}." . $this->hasAndBelongsToMany[$assoc]['associationForeignKey'];
  1298. $oldLinks = Set::extract($links, "{n}.{$associationForeignKey}");
  1299. if (!empty($oldLinks)) {
  1300. $conditions[$associationForeignKey] = $oldLinks;
  1301. $db->delete($this->{$join}, $conditions);
  1302. }
  1303. }
  1304. if (!empty($newData)) {
  1305. foreach ($newData as $data) {
  1306. $data[$this->hasAndBelongsToMany[$assoc]['foreignKey']] = $id;
  1307. $this->{$join}->create($data);
  1308. $this->{$join}->save();
  1309. }
  1310. }
  1311. if (!empty($newValues)) {
  1312. $fields = implode(',', $fields);
  1313. $db->insertMulti($this->{$join}, $fields, $newValues);
  1314. }
  1315. }
  1316. }
  1317. }
  1318. /**
  1319. * Updates the counter cache of belongsTo associations after a save or delete operation
  1320. *
  1321. * @param array $keys Optional foreign key data, defaults to the information $this->data
  1322. * @param boolean $created True if a new record was created, otherwise only associations with
  1323. * 'counterScope' defined get updated
  1324. * @return void
  1325. * @access public
  1326. */
  1327. function updateCounterCache($keys = array(), $created = false) {
  1328. $keys = empty($keys) ? $this->data[$this->alias] : $keys;
  1329. $keys['old'] = isset($keys['old']) ? $keys['old'] : array();
  1330. foreach ($this->belongsTo as $parent => $assoc) {
  1331. $foreignKey = $assoc['foreignKey'];
  1332. $fkQuoted = $this->escapeField($assoc['foreignKey']);
  1333. if (!empty($assoc['counterCache'])) {
  1334. if ($assoc['counterCache'] === true) {
  1335. $assoc['counterCache'] = Inflector::underscore($this->alias) . '_count';
  1336. }
  1337. if (!$this->{$parent}->hasField($assoc['counterCache'])) {
  1338. continue;
  1339. }
  1340. if (!array_key_exists($foreignKey, $keys)) {
  1341. $keys[$foreignKey] = $this->field($foreignKey);
  1342. }
  1343. $recursive = (isset($assoc['counterScope']) ? 1 : -1);
  1344. $conditions = ($recursive == 1) ? (array)$assoc['counterScope'] : array();
  1345. if (isset($keys['old'][$foreignKey])) {
  1346. if ($keys['old'][$foreignKey] != $keys[$foreignKey]) {
  1347. $conditions[$fkQuoted] = $keys['old'][$foreignKey];
  1348. $count = intval($this->find('count', compact('conditions', 'recursive')));
  1349. $this->{$parent}->updateAll(
  1350. array($assoc['counterCache'] => $count),
  1351. array($this->{$parent}->escapeField() => $keys['old'][$foreignKey])
  1352. );
  1353. }
  1354. }
  1355. $conditions[$fkQuoted] = $keys[$foreignKey];
  1356. if ($recursive == 1) {
  1357. $conditions = array_merge($conditions, (array)$assoc['counterScope']);
  1358. }
  1359. $count = intval($this->find('count', compact('conditions', 'recursive')));
  1360. $this->{$parent}->updateAll(
  1361. array($assoc['counterCache'] => $count),
  1362. array($this->{$parent}->escapeField() => $keys[$foreignKey])
  1363. );
  1364. }
  1365. }
  1366. }
  1367. /**
  1368. * Helper method for Model::updateCounterCache(). Checks the fields to be updated for
  1369. *
  1370. * @param array $data The fields of the record that will be updated
  1371. * @return array Returns updated foreign key values, along with an 'old' key containing the old
  1372. * values, or empty if no foreign keys are updated.
  1373. * @access protected
  1374. */
  1375. function _prepareUpdateFields($data) {
  1376. $foreignKeys = array();
  1377. foreach ($this->belongsTo as $assoc => $info) {
  1378. if ($info['counterCache']) {
  1379. $foreignKeys[$assoc] = $info['foreignKey'];
  1380. }
  1381. }
  1382. $included = array_intersect($foreignKeys, array_keys($data));
  1383. if (empty($included) || empty($this->id)) {
  1384. return array();
  1385. }
  1386. $old = $this->find('first', array(
  1387. 'conditions' => array($this->primaryKey => $this->id),
  1388. 'fields' => array_values($included),
  1389. 'recursive' => -1
  1390. ));
  1391. return array_merge($data, array('old' => $old[$this->alias]));
  1392. }
  1393. /**
  1394. * Saves multiple individual records for a single model; Also works with a single record, as well as
  1395. * all its associated records.
  1396. *
  1397. * #### Options
  1398. *
  1399. * - validate: Set to false to disable validation, true to validate each record before saving,
  1400. * 'first' to validate *all* records before any are saved (default),
  1401. * or 'only' to only validate the records, but not save them.
  1402. * - atomic: If true (default), will attempt to save all records in a single transaction.
  1403. * Should be set to false if database/table does not support transactions.
  1404. * - fieldList: Equivalent to the $fieldList parameter in Model::save()
  1405. *
  1406. * @param array $data Record data to save. This can be either a numerically-indexed array (for saving multiple
  1407. * records of the same type), or an array indexed by association name.
  1408. * @param array $options Options to use when saving record data, See $options above.
  1409. * @return mixed If atomic: True on success, or false on failure.
  1410. * Otherwise: array similar to the $data array passed, but values are set to true/false
  1411. * depending on whether each record saved successfully.
  1412. * @access public
  1413. * @link http://book.cakephp.org/view/1032/Saving-Related-Model-Data-hasOne-hasMany-belongsTo
  1414. * @link http://book.cakephp.org/view/1031/Saving-Your-Data
  1415. */
  1416. function saveAll($data = null, $options = array()) {
  1417. if (empty($data)) {
  1418. $data = $this->data;
  1419. }
  1420. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  1421. $options = array_merge(array('validate' => 'first', 'atomic' => true), $options);
  1422. $this->validationErrors = $validationErrors = array();
  1423. $validates = true;
  1424. $return = array();
  1425. if (empty($data) && $options['validate'] !== false) {
  1426. $result = $this->save($data, $options);
  1427. return !empty($result);
  1428. }
  1429. if ($options['atomic'] && $options['validate'] !== 'only') {
  1430. $transactionBegun = $db->begin($this);
  1431. }
  1432. if (Set::numeric(array_keys($data))) {
  1433. while ($validates) {
  1434. $return = array();
  1435. foreach ($data as $key => $record) {
  1436. if (!$currentValidates = $this->__save($record, $options)) {
  1437. $validationErrors[$key] = $this->validationErrors;
  1438. }
  1439. if ($options['validate'] === 'only' || $options['validate'] === 'first') {
  1440. $validating = true;
  1441. if ($options['atomic']) {
  1442. $validates = $validates && $currentValidates;
  1443. } else {
  1444. $validates = $currentValidates;
  1445. }
  1446. } else {
  1447. $validating = false;
  1448. $validates = $currentValidates;
  1449. }
  1450. if (!$options['atomic']) {
  1451. $return[] = $validates;
  1452. } elseif (!$validates && !$validating) {
  1453. break;
  1454. }
  1455. }
  1456. $this->validationErrors = $validationErrors;
  1457. switch (true) {
  1458. case ($options['validate'] === 'only'):
  1459. return ($options['atomic'] ? $validates : $return);
  1460. break;
  1461. case ($options['validate'] === 'first'):
  1462. $options['validate'] = true;
  1463. break;
  1464. default:
  1465. if ($options['atomic']) {
  1466. if ($validates) {
  1467. if ($transactionBegun) {
  1468. return $db->commit($this) !== false;
  1469. } else {
  1470. return true;
  1471. }
  1472. }
  1473. $db->rollback($this);
  1474. return false;
  1475. }
  1476. return $return;
  1477. break;
  1478. }
  1479. }
  1480. if ($options['atomic'] && !$validates) {
  1481. $db->rollback($this);
  1482. return false;
  1483. }
  1484. return $return;
  1485. }
  1486. $associations = $this->getAssociated();
  1487. while ($validates) {
  1488. foreach ($data as $association => $values) {
  1489. if (isset($associations[$association])) {
  1490. switch ($associations[$association]) {
  1491. case 'belongsTo':
  1492. if ($this->{$association}->__save($values, $options)) {
  1493. $data[$this->alias][$this->belongsTo[$association]['foreignKey']] = $this->{$association}->id;
  1494. } else {
  1495. $validationErrors[$association] = $this->{$association}->validationErrors;
  1496. $validates = false;
  1497. }
  1498. if (!$options['atomic']) {
  1499. $return[$association][] = $validates;
  1500. }
  1501. break;
  1502. }
  1503. }
  1504. }
  1505. if (!$this->__save($data, $options)) {
  1506. $validationErrors[$this->alias] = $this->validationErrors;
  1507. $validates = false;
  1508. }
  1509. if (!$options['atomic']) {
  1510. $return[$this->alias] = $validates;
  1511. }
  1512. $validating = ($options['validate'] === 'only' || $options['validate'] === 'first');
  1513. foreach ($data as $association => $values) {
  1514. if (!$validates && !$validating) {
  1515. break;
  1516. }
  1517. if (isset($associations[$association])) {
  1518. $type = $associations[$association];
  1519. switch ($type) {
  1520. case 'hasOne':
  1521. if (!$validating) {
  1522. $values[$this->{$type}[$association]['foreignKey']] = $this->id;
  1523. }
  1524. if (!$this->{$association}->__save($values, $options)) {
  1525. $validationErrors[$association] = $this->{$association}->validationErrors;
  1526. $validates = false;
  1527. }
  1528. if (!$options['atomic']) {
  1529. $return[$association][] = $validates;
  1530. }
  1531. break;
  1532. case 'hasMany':

Large files files are truncated, but you can click here to view the full file