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

/cake/libs/model/model.php

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

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