PageRenderTime 75ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/cake/libs/model/model.php

https://github.com/MrRio/wildflower
PHP | 2856 lines | 1733 code | 166 blank | 957 comment | 495 complexity | 134806387b0e280d7c9ef7eb37c641bd MD5 | raw file
Possible License(s): LGPL-2.1

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

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

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