PageRenderTime 61ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/cake/libs/model/model.php

https://github.com/msadouni/cakephp2x
PHP | 3107 lines | 1862 code | 293 blank | 952 comment | 517 complexity | 57ec65b152476aabc33723ecfbee02e0 MD5 | raw file

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

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