PageRenderTime 71ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/cake/libs/model/model.php

http://github.com/Datawalke/Coordino
PHP | 3093 lines | 1822 code | 278 blank | 993 comment | 540 complexity | d0f2e3801bd069b5210355eb5fa4a4d9 MD5 | raw file
  1. <?php
  2. /**
  3. * Object-relational mapper.
  4. *
  5. * DBO-backed object data model, for mapping database tables to Cake objects.
  6. *
  7. * PHP versions 5
  8. *
  9. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  10. * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. *
  12. * Licensed under The MIT License
  13. * Redistributions of files must retain the above copyright notice.
  14. *
  15. * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
  16. * @link http://cakephp.org CakePHP(tm) Project
  17. * @package cake
  18. * @subpackage cake.cake.libs.model
  19. * @since CakePHP(tm) v 0.10.0.0
  20. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  21. */
  22. /**
  23. * Included libs
  24. */
  25. App::import('Core', array('ClassRegistry', 'Validation', 'Set', 'String'));
  26. App::import('Model', 'ModelBehavior', false);
  27. App::import('Model', 'ConnectionManager', false);
  28. if (!class_exists('Overloadable')) {
  29. require LIBS . 'overloadable.php';
  30. }
  31. /**
  32. * Object-relational mapper.
  33. *
  34. * DBO-backed object data model.
  35. * Automatically selects a database table name based on a pluralized lowercase object class name
  36. * (i.e. class 'User' => table 'users'; class 'Man' => table 'men')
  37. * The table is required to have at least 'id auto_increment' primary key.
  38. *
  39. * @package cake
  40. * @subpackage cake.cake.libs.model
  41. * @link http://book.cakephp.org/view/1000/Models
  42. */
  43. class Model extends Overloadable {
  44. /**
  45. * The name of the DataSource connection that this Model uses
  46. *
  47. * @var string
  48. * @access public
  49. * @link http://book.cakephp.org/view/1057/Model-Attributes#useDbConfig-1058
  50. */
  51. var $useDbConfig = 'default';
  52. /**
  53. * Custom database table name, or null/false if no table association is desired.
  54. *
  55. * @var string
  56. * @access public
  57. * @link http://book.cakephp.org/view/1057/Model-Attributes#useTable-1059
  58. */
  59. var $useTable = null;
  60. /**
  61. * Custom display field name. Display fields are used by Scaffold, in SELECT boxes' OPTION elements.
  62. *
  63. * @var string
  64. * @access public
  65. * @link http://book.cakephp.org/view/1057/Model-Attributes#displayField-1062
  66. */
  67. var $displayField = null;
  68. /**
  69. * Value of the primary key ID of the record that this model is currently pointing to.
  70. * Automatically set after database insertions.
  71. *
  72. * @var mixed
  73. * @access public
  74. */
  75. var $id = false;
  76. /**
  77. * Container for the data that this model gets from persistent storage (usually, a database).
  78. *
  79. * @var array
  80. * @access public
  81. * @link http://book.cakephp.org/view/1057/Model-Attributes#data-1065
  82. */
  83. var $data = array();
  84. /**
  85. * Table name for this Model.
  86. *
  87. * @var string
  88. * @access public
  89. */
  90. var $table = false;
  91. /**
  92. * The name of the primary key field for this model.
  93. *
  94. * @var string
  95. * @access public
  96. * @link http://book.cakephp.org/view/1057/Model-Attributes#primaryKey-1061
  97. */
  98. var $primaryKey = null;
  99. /**
  100. * Field-by-field table metadata.
  101. *
  102. * @var array
  103. * @access protected
  104. * @link http://book.cakephp.org/view/1057/Model-Attributes#_schema-1066
  105. */
  106. var $_schema = null;
  107. /**
  108. * List of validation rules. Append entries for validation as ('field_name' => '/^perl_compat_regexp$/')
  109. * that have to match with preg_match(). Use these rules with Model::validate()
  110. *
  111. * @var array
  112. * @access public
  113. * @link http://book.cakephp.org/view/1057/Model-Attributes#validate-1067
  114. * @link http://book.cakephp.org/view/1143/Data-Validation
  115. */
  116. var $validate = array();
  117. /**
  118. * List of validation errors.
  119. *
  120. * @var array
  121. * @access public
  122. * @link http://book.cakephp.org/view/1182/Validating-Data-from-the-Controller
  123. */
  124. var $validationErrors = array();
  125. /**
  126. * Database table prefix for tables in model.
  127. *
  128. * @var string
  129. * @access public
  130. * @link http://book.cakephp.org/view/1057/Model-Attributes#tablePrefix-1060
  131. */
  132. var $tablePrefix = null;
  133. /**
  134. * Name of the model.
  135. *
  136. * @var string
  137. * @access public
  138. * @link http://book.cakephp.org/view/1057/Model-Attributes#name-1068
  139. */
  140. var $name = null;
  141. /**
  142. * Alias name for model.
  143. *
  144. * @var string
  145. * @access public
  146. */
  147. var $alias = null;
  148. /**
  149. * List of table names included in the model description. Used for associations.
  150. *
  151. * @var array
  152. * @access public
  153. */
  154. var $tableToModel = array();
  155. /**
  156. * Whether or not to log transactions for this model.
  157. *
  158. * @var boolean
  159. * @access public
  160. */
  161. var $logTransactions = false;
  162. /**
  163. * Whether or not to cache queries for this model. This enables in-memory
  164. * caching only, the results are not stored beyond the current request.
  165. *
  166. * @var boolean
  167. * @access public
  168. * @link http://book.cakephp.org/view/1057/Model-Attributes#cacheQueries-1069
  169. */
  170. var $cacheQueries = false;
  171. /**
  172. * Detailed list of belongsTo associations.
  173. *
  174. * @var array
  175. * @access public
  176. * @link http://book.cakephp.org/view/1042/belongsTo
  177. */
  178. var $belongsTo = array();
  179. /**
  180. * Detailed list of hasOne associations.
  181. *
  182. * @var array
  183. * @access public
  184. * @link http://book.cakephp.org/view/1041/hasOne
  185. */
  186. var $hasOne = array();
  187. /**
  188. * Detailed list of hasMany associations.
  189. *
  190. * @var array
  191. * @access public
  192. * @link http://book.cakephp.org/view/1043/hasMany
  193. */
  194. var $hasMany = array();
  195. /**
  196. * Detailed list of hasAndBelongsToMany associations.
  197. *
  198. * @var array
  199. * @access public
  200. * @link http://book.cakephp.org/view/1044/hasAndBelongsToMany-HABTM
  201. */
  202. var $hasAndBelongsToMany = array();
  203. /**
  204. * List of behaviors to load when the model object is initialized. Settings can be
  205. * passed to behaviors by using the behavior name as index. Eg:
  206. *
  207. * var $actsAs = array('Translate', 'MyBehavior' => array('setting1' => 'value1'))
  208. *
  209. * @var array
  210. * @access public
  211. * @link http://book.cakephp.org/view/1072/Using-Behaviors
  212. */
  213. var $actsAs = null;
  214. /**
  215. * Holds the Behavior objects currently bound to this model.
  216. *
  217. * @var BehaviorCollection
  218. * @access public
  219. */
  220. var $Behaviors = null;
  221. /**
  222. * Whitelist of fields allowed to be saved.
  223. *
  224. * @var array
  225. * @access public
  226. */
  227. var $whitelist = array();
  228. /**
  229. * Whether or not to cache sources for this model.
  230. *
  231. * @var boolean
  232. * @access public
  233. */
  234. var $cacheSources = true;
  235. /**
  236. * Type of find query currently executing.
  237. *
  238. * @var string
  239. * @access public
  240. */
  241. var $findQueryType = null;
  242. /**
  243. * Number of associations to recurse through during find calls. Fetches only
  244. * the first level by default.
  245. *
  246. * @var integer
  247. * @access public
  248. * @link http://book.cakephp.org/view/1057/Model-Attributes#recursive-1063
  249. */
  250. var $recursive = 1;
  251. /**
  252. * The column name(s) and direction(s) to order find results by default.
  253. *
  254. * var $order = "Post.created DESC";
  255. * var $order = array("Post.view_count DESC", "Post.rating DESC");
  256. *
  257. * @var string
  258. * @access public
  259. * @link http://book.cakephp.org/view/1057/Model-Attributes#order-1064
  260. */
  261. var $order = null;
  262. /**
  263. * Array of virtual fields this model has. Virtual fields are aliased
  264. * SQL expressions. Fields added to this property will be read as other fields in a model
  265. * but will not be saveable.
  266. *
  267. * `var $virtualFields = array('two' => '1 + 1');`
  268. *
  269. * Is a simplistic example of how to set virtualFields
  270. *
  271. * @var array
  272. * @access public
  273. */
  274. var $virtualFields = array();
  275. /**
  276. * Default list of association keys.
  277. *
  278. * @var array
  279. * @access private
  280. */
  281. var $__associationKeys = array(
  282. 'belongsTo' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'counterCache'),
  283. 'hasOne' => array('className', 'foreignKey','conditions', 'fields','order', 'dependent'),
  284. 'hasMany' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'dependent', 'exclusive', 'finderQuery', 'counterQuery'),
  285. 'hasAndBelongsToMany' => array('className', 'joinTable', 'with', 'foreignKey', 'associationForeignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'unique', 'finderQuery', 'deleteQuery', 'insertQuery')
  286. );
  287. /**
  288. * Holds provided/generated association key names and other data for all associations.
  289. *
  290. * @var array
  291. * @access private
  292. */
  293. var $__associations = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
  294. /**
  295. * Holds model associations temporarily to allow for dynamic (un)binding.
  296. *
  297. * @var array
  298. * @access private
  299. */
  300. var $__backAssociation = array();
  301. /**
  302. * The ID of the model record that was last inserted.
  303. *
  304. * @var integer
  305. * @access private
  306. */
  307. var $__insertID = null;
  308. /**
  309. * The number of records returned by the last query.
  310. *
  311. * @var integer
  312. * @access private
  313. */
  314. var $__numRows = null;
  315. /**
  316. * The number of records affected by the last query.
  317. *
  318. * @var integer
  319. * @access private
  320. */
  321. var $__affectedRows = null;
  322. /**
  323. * List of valid finder method options, supplied as the first parameter to find().
  324. *
  325. * @var array
  326. * @access protected
  327. */
  328. var $_findMethods = array(
  329. 'all' => true, 'first' => true, 'count' => true,
  330. 'neighbors' => true, 'list' => true, 'threaded' => true
  331. );
  332. /**
  333. * Constructor. Binds the model's database table to the object.
  334. *
  335. * If `$id` is an array it can be used to pass several options into the model.
  336. *
  337. * - id - The id to start the model on.
  338. * - table - The table to use for this model.
  339. * - ds - The connection name this model is connected to.
  340. * - name - The name of the model eg. Post.
  341. * - alias - The alias of the model, this is used for registering the instance in the `ClassRegistry`.
  342. * eg. `ParentThread`
  343. *
  344. * ### Overriding Model's __construct method.
  345. *
  346. * When overriding Model::__construct() be careful to include and pass in all 3 of the
  347. * arguments to `parent::__construct($id, $table, $ds);`
  348. *
  349. * ### Dynamically creating models
  350. *
  351. * You can dynamically create model instances using the $id array syntax.
  352. *
  353. * {{{
  354. * $Post = new Model(array('table' => 'posts', 'name' => 'Post', 'ds' => 'connection2'));
  355. * }}}
  356. *
  357. * Would create a model attached to the posts table on connection2. Dynamic model creation is useful
  358. * when you want a model object that contains no associations or attached behaviors.
  359. *
  360. * @param mixed $id Set this ID for this model on startup, can also be an array of options, see above.
  361. * @param string $table Name of database table to use.
  362. * @param string $ds DataSource connection name.
  363. */
  364. function __construct($id = false, $table = null, $ds = null) {
  365. parent::__construct();
  366. if (is_array($id)) {
  367. extract(array_merge(
  368. array(
  369. 'id' => $this->id, 'table' => $this->useTable, 'ds' => $this->useDbConfig,
  370. 'name' => $this->name, 'alias' => $this->alias
  371. ),
  372. $id
  373. ));
  374. }
  375. if ($this->name === null) {
  376. $this->name = (isset($name) ? $name : get_class($this));
  377. }
  378. if ($this->alias === null) {
  379. $this->alias = (isset($alias) ? $alias : $this->name);
  380. }
  381. if ($this->primaryKey === null) {
  382. $this->primaryKey = 'id';
  383. }
  384. ClassRegistry::addObject($this->alias, $this);
  385. $this->id = $id;
  386. unset($id);
  387. if ($table === false) {
  388. $this->useTable = false;
  389. } elseif ($table) {
  390. $this->useTable = $table;
  391. }
  392. if ($ds !== null) {
  393. $this->useDbConfig = $ds;
  394. }
  395. if (is_subclass_of($this, 'AppModel')) {
  396. $appVars = get_class_vars('AppModel');
  397. $merge = array('_findMethods');
  398. if ($this->actsAs !== null || $this->actsAs !== false) {
  399. $merge[] = 'actsAs';
  400. }
  401. $parentClass = get_parent_class($this);
  402. if (strtolower($parentClass) !== 'appmodel') {
  403. $parentVars = get_class_vars($parentClass);
  404. foreach ($merge as $var) {
  405. if (isset($parentVars[$var]) && !empty($parentVars[$var])) {
  406. $appVars[$var] = Set::merge($appVars[$var], $parentVars[$var]);
  407. }
  408. }
  409. }
  410. foreach ($merge as $var) {
  411. if (isset($appVars[$var]) && !empty($appVars[$var]) && is_array($this->{$var})) {
  412. $this->{$var} = Set::merge($appVars[$var], $this->{$var});
  413. }
  414. }
  415. }
  416. $this->Behaviors = new BehaviorCollection();
  417. if ($this->useTable !== false) {
  418. $this->setDataSource($ds);
  419. if ($this->useTable === null) {
  420. $this->useTable = Inflector::tableize($this->name);
  421. }
  422. $this->setSource($this->useTable);
  423. if ($this->displayField == null) {
  424. $this->displayField = $this->hasField(array('title', 'name', $this->primaryKey));
  425. }
  426. } elseif ($this->table === false) {
  427. $this->table = Inflector::tableize($this->name);
  428. }
  429. $this->__createLinks();
  430. $this->Behaviors->init($this->alias, $this->actsAs);
  431. }
  432. /**
  433. * Handles custom method calls, like findBy<field> for DB models,
  434. * and custom RPC calls for remote data sources.
  435. *
  436. * @param string $method Name of method to call.
  437. * @param array $params Parameters for the method.
  438. * @return mixed Whatever is returned by called method
  439. * @access protected
  440. */
  441. function call__($method, $params) {
  442. $result = $this->Behaviors->dispatchMethod($this, $method, $params);
  443. if ($result !== array('unhandled')) {
  444. return $result;
  445. }
  446. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  447. $return = $db->query($method, $params, $this);
  448. if (!PHP5) {
  449. $this->resetAssociations();
  450. }
  451. return $return;
  452. }
  453. /**
  454. * Bind model associations on the fly.
  455. *
  456. * If `$reset` is false, association will not be reset
  457. * to the originals defined in the model
  458. *
  459. * Example: Add a new hasOne binding to the Profile model not
  460. * defined in the model source code:
  461. *
  462. * `$this->User->bindModel( array('hasOne' => array('Profile')) );`
  463. *
  464. * Bindings that are not made permanent will be reset by the next Model::find() call on this
  465. * model.
  466. *
  467. * @param array $params Set of bindings (indexed by binding type)
  468. * @param boolean $reset Set to false to make the binding permanent
  469. * @return boolean Success
  470. * @access public
  471. * @link http://book.cakephp.org/view/1045/Creating-and-Destroying-Associations-on-the-Fly
  472. */
  473. function bindModel($params, $reset = true) {
  474. foreach ($params as $assoc => $model) {
  475. if ($reset === true && !isset($this->__backAssociation[$assoc])) {
  476. $this->__backAssociation[$assoc] = $this->{$assoc};
  477. }
  478. foreach ($model as $key => $value) {
  479. $assocName = $key;
  480. if (is_numeric($key)) {
  481. $assocName = $value;
  482. $value = array();
  483. }
  484. $modelName = $assocName;
  485. $this->{$assoc}[$assocName] = $value;
  486. if ($reset === false && isset($this->__backAssociation[$assoc])) {
  487. $this->__backAssociation[$assoc][$assocName] = $value;
  488. }
  489. }
  490. }
  491. $this->__createLinks();
  492. return true;
  493. }
  494. /**
  495. * Turn off associations on the fly.
  496. *
  497. * If $reset is false, association will not be reset
  498. * to the originals defined in the model
  499. *
  500. * Example: Turn off the associated Model Support request,
  501. * to temporarily lighten the User model:
  502. *
  503. * `$this->User->unbindModel( array('hasMany' => array('Supportrequest')) );`
  504. *
  505. * unbound models that are not made permanent will reset with the next call to Model::find()
  506. *
  507. * @param array $params Set of bindings to unbind (indexed by binding type)
  508. * @param boolean $reset Set to false to make the unbinding permanent
  509. * @return boolean Success
  510. * @access public
  511. * @link http://book.cakephp.org/view/1045/Creating-and-Destroying-Associations-on-the-Fly
  512. */
  513. function unbindModel($params, $reset = true) {
  514. foreach ($params as $assoc => $models) {
  515. if ($reset === true && !isset($this->__backAssociation[$assoc])) {
  516. $this->__backAssociation[$assoc] = $this->{$assoc};
  517. }
  518. foreach ($models as $model) {
  519. if ($reset === false && isset($this->__backAssociation[$assoc][$model])) {
  520. unset($this->__backAssociation[$assoc][$model]);
  521. }
  522. unset($this->{$assoc}[$model]);
  523. }
  524. }
  525. return true;
  526. }
  527. /**
  528. * Create a set of associations.
  529. *
  530. * @return void
  531. * @access private
  532. */
  533. function __createLinks() {
  534. foreach ($this->__associations as $type) {
  535. if (!is_array($this->{$type})) {
  536. $this->{$type} = explode(',', $this->{$type});
  537. foreach ($this->{$type} as $i => $className) {
  538. $className = trim($className);
  539. unset ($this->{$type}[$i]);
  540. $this->{$type}[$className] = array();
  541. }
  542. }
  543. if (!empty($this->{$type})) {
  544. foreach ($this->{$type} as $assoc => $value) {
  545. $plugin = null;
  546. if (is_numeric($assoc)) {
  547. unset ($this->{$type}[$assoc]);
  548. $assoc = $value;
  549. $value = array();
  550. $this->{$type}[$assoc] = $value;
  551. if (strpos($assoc, '.') !== false) {
  552. $value = $this->{$type}[$assoc];
  553. unset($this->{$type}[$assoc]);
  554. list($plugin, $assoc) = pluginSplit($assoc, true);
  555. $this->{$type}[$assoc] = $value;
  556. }
  557. }
  558. $className = $assoc;
  559. if (!empty($value['className'])) {
  560. list($plugin, $className) = pluginSplit($value['className'], true);
  561. $this->{$type}[$assoc]['className'] = $className;
  562. }
  563. $this->__constructLinkedModel($assoc, $plugin . $className);
  564. }
  565. $this->__generateAssociation($type);
  566. }
  567. }
  568. }
  569. /**
  570. * Private helper method to create associated models of a given class.
  571. *
  572. * @param string $assoc Association name
  573. * @param string $className Class name
  574. * @deprecated $this->$className use $this->$assoc instead. $assoc is the 'key' in the associations array;
  575. * examples: var $hasMany = array('Assoc' => array('className' => 'ModelName'));
  576. * usage: $this->Assoc->modelMethods();
  577. *
  578. * var $hasMany = array('ModelName');
  579. * usage: $this->ModelName->modelMethods();
  580. * @return void
  581. * @access private
  582. */
  583. function __constructLinkedModel($assoc, $className = null) {
  584. if (empty($className)) {
  585. $className = $assoc;
  586. }
  587. if (!isset($this->{$assoc}) || $this->{$assoc}->name !== $className) {
  588. $model = array('class' => $className, 'alias' => $assoc);
  589. if (PHP5) {
  590. $this->{$assoc} = ClassRegistry::init($model);
  591. } else {
  592. $this->{$assoc} =& ClassRegistry::init($model);
  593. }
  594. if (strpos($className, '.') !== false) {
  595. ClassRegistry::addObject($className, $this->{$assoc});
  596. }
  597. if ($assoc) {
  598. $this->tableToModel[$this->{$assoc}->table] = $assoc;
  599. }
  600. }
  601. }
  602. /**
  603. * Build an array-based association from string.
  604. *
  605. * @param string $type 'belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany'
  606. * @return void
  607. * @access private
  608. */
  609. function __generateAssociation($type) {
  610. foreach ($this->{$type} as $assocKey => $assocData) {
  611. $class = $assocKey;
  612. $dynamicWith = false;
  613. foreach ($this->__associationKeys[$type] as $key) {
  614. if (!isset($this->{$type}[$assocKey][$key]) || $this->{$type}[$assocKey][$key] === null) {
  615. $data = '';
  616. switch ($key) {
  617. case 'fields':
  618. $data = '';
  619. break;
  620. case 'foreignKey':
  621. $data = (($type == 'belongsTo') ? Inflector::underscore($assocKey) : Inflector::singularize($this->table)) . '_id';
  622. break;
  623. case 'associationForeignKey':
  624. $data = Inflector::singularize($this->{$class}->table) . '_id';
  625. break;
  626. case 'with':
  627. $data = Inflector::camelize(Inflector::singularize($this->{$type}[$assocKey]['joinTable']));
  628. $dynamicWith = true;
  629. break;
  630. case 'joinTable':
  631. $tables = array($this->table, $this->{$class}->table);
  632. sort ($tables);
  633. $data = $tables[0] . '_' . $tables[1];
  634. break;
  635. case 'className':
  636. $data = $class;
  637. break;
  638. case 'unique':
  639. $data = true;
  640. break;
  641. }
  642. $this->{$type}[$assocKey][$key] = $data;
  643. }
  644. }
  645. if (!empty($this->{$type}[$assocKey]['with'])) {
  646. $joinClass = $this->{$type}[$assocKey]['with'];
  647. if (is_array($joinClass)) {
  648. $joinClass = key($joinClass);
  649. }
  650. $plugin = null;
  651. if (strpos($joinClass, '.') !== false) {
  652. list($plugin, $joinClass) = explode('.', $joinClass);
  653. $plugin .= '.';
  654. $this->{$type}[$assocKey]['with'] = $joinClass;
  655. }
  656. if (!ClassRegistry::isKeySet($joinClass) && $dynamicWith === true) {
  657. $this->{$joinClass} = new AppModel(array(
  658. 'name' => $joinClass,
  659. 'table' => $this->{$type}[$assocKey]['joinTable'],
  660. 'ds' => $this->useDbConfig
  661. ));
  662. } else {
  663. $this->__constructLinkedModel($joinClass, $plugin . $joinClass);
  664. $this->{$type}[$assocKey]['joinTable'] = $this->{$joinClass}->table;
  665. }
  666. if (count($this->{$joinClass}->schema()) <= 2 && $this->{$joinClass}->primaryKey !== false) {
  667. $this->{$joinClass}->primaryKey = $this->{$type}[$assocKey]['foreignKey'];
  668. }
  669. }
  670. }
  671. }
  672. /**
  673. * Sets a custom table for your controller class. Used by your controller to select a database table.
  674. *
  675. * @param string $tableName Name of the custom table
  676. * @return void
  677. * @access public
  678. */
  679. function setSource($tableName) {
  680. $this->setDataSource($this->useDbConfig);
  681. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  682. $db->cacheSources = ($this->cacheSources && $db->cacheSources);
  683. if ($db->isInterfaceSupported('listSources')) {
  684. $sources = $db->listSources();
  685. if (is_array($sources) && !in_array(strtolower($this->tablePrefix . $tableName), array_map('strtolower', $sources))) {
  686. return $this->cakeError('missingTable', array(array(
  687. 'className' => $this->alias,
  688. 'table' => $this->tablePrefix . $tableName,
  689. 'code' => 500
  690. )));
  691. }
  692. $this->_schema = null;
  693. }
  694. $this->table = $this->useTable = $tableName;
  695. $this->tableToModel[$this->table] = $this->alias;
  696. $this->schema();
  697. }
  698. /**
  699. * This function does two things:
  700. *
  701. * 1. it scans the array $one for the primary key,
  702. * and if that's found, it sets the current id to the value of $one[id].
  703. * For all other keys than 'id' the keys and values of $one are copied to the 'data' property of this object.
  704. * 2. Returns an array with all of $one's keys and values.
  705. * (Alternative indata: two strings, which are mangled to
  706. * a one-item, two-dimensional array using $one for a key and $two as its value.)
  707. *
  708. * @param mixed $one Array or string of data
  709. * @param string $two Value string for the alternative indata method
  710. * @return array Data with all of $one's keys and values
  711. * @access public
  712. * @link http://book.cakephp.org/view/1031/Saving-Your-Data
  713. */
  714. function set($one, $two = null) {
  715. if (!$one) {
  716. return;
  717. }
  718. if (is_object($one)) {
  719. $one = Set::reverse($one);
  720. }
  721. if (is_array($one)) {
  722. $data = $one;
  723. if (empty($one[$this->alias])) {
  724. if ($this->getAssociated(key($one)) === null) {
  725. $data = array($this->alias => $one);
  726. }
  727. }
  728. } else {
  729. $data = array($this->alias => array($one => $two));
  730. }
  731. foreach ($data as $modelName => $fieldSet) {
  732. if (is_array($fieldSet)) {
  733. foreach ($fieldSet as $fieldName => $fieldValue) {
  734. if (isset($this->validationErrors[$fieldName])) {
  735. unset ($this->validationErrors[$fieldName]);
  736. }
  737. if ($modelName === $this->alias) {
  738. if ($fieldName === $this->primaryKey) {
  739. $this->id = $fieldValue;
  740. }
  741. }
  742. if (is_array($fieldValue) || is_object($fieldValue)) {
  743. $fieldValue = $this->deconstruct($fieldName, $fieldValue);
  744. }
  745. $this->data[$modelName][$fieldName] = $fieldValue;
  746. }
  747. }
  748. }
  749. return $data;
  750. }
  751. /**
  752. * Deconstructs a complex data type (array or object) into a single field value.
  753. *
  754. * @param string $field The name of the field to be deconstructed
  755. * @param mixed $data An array or object to be deconstructed into a field
  756. * @return mixed The resulting data that should be assigned to a field
  757. * @access public
  758. */
  759. function deconstruct($field, $data) {
  760. if (!is_array($data)) {
  761. return $data;
  762. }
  763. $copy = $data;
  764. $type = $this->getColumnType($field);
  765. if (in_array($type, array('datetime', 'timestamp', 'date', 'time'))) {
  766. $useNewDate = (isset($data['year']) || isset($data['month']) ||
  767. isset($data['day']) || isset($data['hour']) || isset($data['minute']));
  768. $dateFields = array('Y' => 'year', 'm' => 'month', 'd' => 'day', 'H' => 'hour', 'i' => 'min', 's' => 'sec');
  769. $timeFields = array('H' => 'hour', 'i' => 'min', 's' => 'sec');
  770. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  771. $format = $db->columns[$type]['format'];
  772. $date = array();
  773. if (isset($data['hour']) && isset($data['meridian']) && $data['hour'] != 12 && 'pm' == $data['meridian']) {
  774. $data['hour'] = $data['hour'] + 12;
  775. }
  776. if (isset($data['hour']) && isset($data['meridian']) && $data['hour'] == 12 && 'am' == $data['meridian']) {
  777. $data['hour'] = '00';
  778. }
  779. if ($type == 'time') {
  780. foreach ($timeFields as $key => $val) {
  781. if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') {
  782. $data[$val] = '00';
  783. } elseif ($data[$val] === '') {
  784. $data[$val] = '';
  785. } else {
  786. $data[$val] = sprintf('%02d', $data[$val]);
  787. }
  788. if (!empty($data[$val])) {
  789. $date[$key] = $data[$val];
  790. } else {
  791. return null;
  792. }
  793. }
  794. }
  795. if ($type == 'datetime' || $type == 'timestamp' || $type == 'date') {
  796. foreach ($dateFields as $key => $val) {
  797. if ($val == 'hour' || $val == 'min' || $val == 'sec') {
  798. if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') {
  799. $data[$val] = '00';
  800. } else {
  801. $data[$val] = sprintf('%02d', $data[$val]);
  802. }
  803. }
  804. if (!isset($data[$val]) || isset($data[$val]) && (empty($data[$val]) || $data[$val][0] === '-')) {
  805. return null;
  806. }
  807. if (isset($data[$val]) && !empty($data[$val])) {
  808. $date[$key] = $data[$val];
  809. }
  810. }
  811. }
  812. $date = str_replace(array_keys($date), array_values($date), $format);
  813. if ($useNewDate && !empty($date)) {
  814. return $date;
  815. }
  816. }
  817. return $data;
  818. }
  819. /**
  820. * Returns an array of table metadata (column names and types) from the database.
  821. * $field => keys(type, null, default, key, length, extra)
  822. *
  823. * @param mixed $field Set to true to reload schema, or a string to return a specific field
  824. * @return array Array of table metadata
  825. * @access public
  826. */
  827. function schema($field = false) {
  828. if (!is_array($this->_schema) || $field === true) {
  829. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  830. $db->cacheSources = ($this->cacheSources && $db->cacheSources);
  831. if ($db->isInterfaceSupported('describe') && $this->useTable !== false) {
  832. $this->_schema = $db->describe($this, $field);
  833. } elseif ($this->useTable === false) {
  834. $this->_schema = array();
  835. }
  836. }
  837. if (is_string($field)) {
  838. if (isset($this->_schema[$field])) {
  839. return $this->_schema[$field];
  840. } else {
  841. return null;
  842. }
  843. }
  844. return $this->_schema;
  845. }
  846. /**
  847. * Returns an associative array of field names and column types.
  848. *
  849. * @return array Field types indexed by field name
  850. * @access public
  851. */
  852. function getColumnTypes() {
  853. $columns = $this->schema();
  854. if (empty($columns)) {
  855. trigger_error(__('(Model::getColumnTypes) Unable to build model field data. If you are using a model without a database table, try implementing schema()', true), E_USER_WARNING);
  856. }
  857. $cols = array();
  858. foreach ($columns as $field => $values) {
  859. $cols[$field] = $values['type'];
  860. }
  861. return $cols;
  862. }
  863. /**
  864. * Returns the column type of a column in the model.
  865. *
  866. * @param string $column The name of the model column
  867. * @return string Column type
  868. * @access public
  869. */
  870. function getColumnType($column) {
  871. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  872. $cols = $this->schema();
  873. $model = null;
  874. $column = str_replace(array($db->startQuote, $db->endQuote), '', $column);
  875. if (strpos($column, '.')) {
  876. list($model, $column) = explode('.', $column);
  877. }
  878. if ($model != $this->alias && isset($this->{$model})) {
  879. return $this->{$model}->getColumnType($column);
  880. }
  881. if (isset($cols[$column]) && isset($cols[$column]['type'])) {
  882. return $cols[$column]['type'];
  883. }
  884. return null;
  885. }
  886. /**
  887. * Returns true if the supplied field exists in the model's database table.
  888. *
  889. * @param mixed $name Name of field to look for, or an array of names
  890. * @param boolean $checkVirtual checks if the field is declared as virtual
  891. * @return mixed If $name is a string, returns a boolean indicating whether the field exists.
  892. * If $name is an array of field names, returns the first field that exists,
  893. * or false if none exist.
  894. * @access public
  895. */
  896. function hasField($name, $checkVirtual = false) {
  897. if (is_array($name)) {
  898. foreach ($name as $n) {
  899. if ($this->hasField($n, $checkVirtual)) {
  900. return $n;
  901. }
  902. }
  903. return false;
  904. }
  905. if ($checkVirtual && !empty($this->virtualFields)) {
  906. if ($this->isVirtualField($name)) {
  907. return true;
  908. }
  909. }
  910. if (empty($this->_schema)) {
  911. $this->schema();
  912. }
  913. if ($this->_schema != null) {
  914. return isset($this->_schema[$name]);
  915. }
  916. return false;
  917. }
  918. /**
  919. * Returns true if the supplied field is a model Virtual Field
  920. *
  921. * @param mixed $name Name of field to look for
  922. * @return boolean indicating whether the field exists as a model virtual field.
  923. * @access public
  924. */
  925. function isVirtualField($field) {
  926. if (empty($this->virtualFields) || !is_string($field)) {
  927. return false;
  928. }
  929. if (isset($this->virtualFields[$field])) {
  930. return true;
  931. }
  932. if (strpos($field, '.') !== false) {
  933. list($model, $field) = explode('.', $field);
  934. if ($model == $this->alias && isset($this->virtualFields[$field])) {
  935. return true;
  936. }
  937. }
  938. return false;
  939. }
  940. /**
  941. * Returns the expression for a model virtual field
  942. *
  943. * @param mixed $name Name of field to look for
  944. * @return mixed If $field is string expression bound to virtual field $field
  945. * If $field is null, returns an array of all model virtual fields
  946. * or false if none $field exist.
  947. * @access public
  948. */
  949. function getVirtualField($field = null) {
  950. if ($field == null) {
  951. return empty($this->virtualFields) ? false : $this->virtualFields;
  952. }
  953. if ($this->isVirtualField($field)) {
  954. if (strpos($field, '.') !== false) {
  955. list($model, $field) = explode('.', $field);
  956. }
  957. return $this->virtualFields[$field];
  958. }
  959. return false;
  960. }
  961. /**
  962. * Initializes the model for writing a new record, loading the default values
  963. * for those fields that are not defined in $data, and clearing previous validation errors.
  964. * Especially helpful for saving data in loops.
  965. *
  966. * @param mixed $data Optional data array to assign to the model after it is created. If null or false,
  967. * schema data defaults are not merged.
  968. * @param boolean $filterKey If true, overwrites any primary key input with an empty value
  969. * @return array The current Model::data; after merging $data and/or defaults from database
  970. * @access public
  971. * @link http://book.cakephp.org/view/1031/Saving-Your-Data
  972. */
  973. function create($data = array(), $filterKey = false) {
  974. $defaults = array();
  975. $this->id = false;
  976. $this->data = array();
  977. $this->validationErrors = array();
  978. if ($data !== null && $data !== false) {
  979. foreach ($this->schema() as $field => $properties) {
  980. if ($this->primaryKey !== $field && isset($properties['default']) && $properties['default'] !== '') {
  981. $defaults[$field] = $properties['default'];
  982. }
  983. }
  984. $this->set($defaults);
  985. $this->set($data);
  986. }
  987. if ($filterKey) {
  988. $this->set($this->primaryKey, false);
  989. }
  990. return $this->data;
  991. }
  992. /**
  993. * Returns a list of fields from the database, and sets the current model
  994. * data (Model::$data) with the record found.
  995. *
  996. * @param mixed $fields String of single fieldname, or an array of fieldnames.
  997. * @param mixed $id The ID of the record to read
  998. * @return array Array of database fields, or false if not found
  999. * @access public
  1000. * @link http://book.cakephp.org/view/1017/Retrieving-Your-Data#read-1029
  1001. */
  1002. function read($fields = null, $id = null) {
  1003. $this->validationErrors = array();
  1004. if ($id != null) {
  1005. $this->id = $id;
  1006. }
  1007. $id = $this->id;
  1008. if (is_array($this->id)) {
  1009. $id = $this->id[0];
  1010. }
  1011. if ($id !== null && $id !== false) {
  1012. $this->data = $this->find('first', array(
  1013. 'conditions' => array($this->alias . '.' . $this->primaryKey => $id),
  1014. 'fields' => $fields
  1015. ));
  1016. return $this->data;
  1017. } else {
  1018. return false;
  1019. }
  1020. }
  1021. /**
  1022. * Returns the contents of a single field given the supplied conditions, in the
  1023. * supplied order.
  1024. *
  1025. * @param string $name Name of field to get
  1026. * @param array $conditions SQL conditions (defaults to NULL)
  1027. * @param string $order SQL ORDER BY fragment
  1028. * @return string field contents, or false if not found
  1029. * @access public
  1030. * @link http://book.cakephp.org/view/1017/Retrieving-Your-Data#field-1028
  1031. */
  1032. function field($name, $conditions = null, $order = null) {
  1033. if ($conditions === null && $this->id !== false) {
  1034. $conditions = array($this->alias . '.' . $this->primaryKey => $this->id);
  1035. }
  1036. if ($this->recursive >= 1) {
  1037. $recursive = -1;
  1038. } else {
  1039. $recursive = $this->recursive;
  1040. }
  1041. $fields = $name;
  1042. if ($data = $this->find('first', compact('conditions', 'fields', 'order', 'recursive'))) {
  1043. if (strpos($name, '.') === false) {
  1044. if (isset($data[$this->alias][$name])) {
  1045. return $data[$this->alias][$name];
  1046. }
  1047. } else {
  1048. $name = explode('.', $name);
  1049. if (isset($data[$name[0]][$name[1]])) {
  1050. return $data[$name[0]][$name[1]];
  1051. }
  1052. }
  1053. if (isset($data[0]) && count($data[0]) > 0) {
  1054. return array_shift($data[0]);
  1055. }
  1056. } else {
  1057. return false;
  1058. }
  1059. }
  1060. /**
  1061. * Saves the value of a single field to the database, based on the current
  1062. * model ID.
  1063. *
  1064. * @param string $name Name of the table field
  1065. * @param mixed $value Value of the field
  1066. * @param array $validate See $options param in Model::save(). Does not respect 'fieldList' key if passed
  1067. * @return boolean See Model::save()
  1068. * @access public
  1069. * @see Model::save()
  1070. * @link http://book.cakephp.org/view/1031/Saving-Your-Data
  1071. */
  1072. function saveField($name, $value, $validate = false) {
  1073. $id = $this->id;
  1074. $this->create(false);
  1075. if (is_array($validate)) {
  1076. $options = array_merge(array('validate' => false, 'fieldList' => array($name)), $validate);
  1077. } else {
  1078. $options = array('validate' => $validate, 'fieldList' => array($name));
  1079. }
  1080. return $this->save(array($this->alias => array($this->primaryKey => $id, $name => $value)), $options);
  1081. }
  1082. /**
  1083. * Saves model data (based on white-list, if supplied) to the database. By
  1084. * default, validation occurs before save.
  1085. *
  1086. * @param array $data Data to save.
  1087. * @param mixed $validate Either a boolean, or an array.
  1088. * If a boolean, indicates whether or not to validate before saving.
  1089. * If an array, allows control of validate, callbacks, and fieldList
  1090. * @param array $fieldList List of fields to allow to be written
  1091. * @return mixed On success Model::$data if its not empty or true, false on failure
  1092. * @access public
  1093. * @link http://book.cakephp.org/view/1031/Saving-Your-Data
  1094. */
  1095. function save($data = null, $validate = true, $fieldList = array()) {
  1096. $defaults = array('validate' => true, 'fieldList' => array(), 'callbacks' => true);
  1097. $_whitelist = $this->whitelist;
  1098. $fields = array();
  1099. if (!is_array($validate)) {
  1100. $options = array_merge($defaults, compact('validate', 'fieldList', 'callbacks'));
  1101. } else {
  1102. $options = array_merge($defaults, $validate);
  1103. }
  1104. if (!empty($options['fieldList'])) {
  1105. $this->whitelist = $options['fieldList'];
  1106. } elseif ($options['fieldList'] === null) {
  1107. $this->whitelist = array();
  1108. }
  1109. $this->set($data);
  1110. if (empty($this->data) && !$this->hasField(array('created', 'updated', 'modified'))) {
  1111. return false;
  1112. }
  1113. foreach (array('created', 'updated', 'modified') as $field) {
  1114. $keyPresentAndEmpty = (
  1115. isset($this->data[$this->alias]) &&
  1116. array_key_exists($field, $this->data[$this->alias]) &&
  1117. $this->data[$this->alias][$field] === null
  1118. );
  1119. if ($keyPresentAndEmpty) {
  1120. unset($this->data[$this->alias][$field]);
  1121. }
  1122. }
  1123. $exists = $this->exists();
  1124. $dateFields = array('modified', 'updated');
  1125. if (!$exists) {
  1126. $dateFields[] = 'created';
  1127. }
  1128. if (isset($this->data[$this->alias])) {
  1129. $fields = array_keys($this->data[$this->alias]);
  1130. }
  1131. if ($options['validate'] && !$this->validates($options)) {
  1132. $this->whitelist = $_whitelist;
  1133. return false;
  1134. }
  1135. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  1136. foreach ($dateFields as $updateCol) {
  1137. if ($this->hasField($updateCol) && !in_array($updateCol, $fields)) {
  1138. $default = array('formatter' => 'date');
  1139. $colType = array_merge($default, $db->columns[$this->getColumnType($updateCol)]);
  1140. if (!array_key_exists('format', $colType)) {
  1141. $time = strtotime('now');
  1142. } else {
  1143. $time = $colType['formatter']($colType['format']);
  1144. }
  1145. if (!empty($this->whitelist)) {
  1146. $this->whitelist[] = $updateCol;
  1147. }
  1148. $this->set($updateCol, $time);
  1149. }
  1150. }
  1151. if ($options['callbacks'] === true || $options['callbacks'] === 'before') {
  1152. $result = $this->Behaviors->trigger($this, 'beforeSave', array($options), array(
  1153. 'break' => true, 'breakOn' => false
  1154. ));
  1155. if (!$result || !$this->beforeSave($options)) {
  1156. $this->whitelist = $_whitelist;
  1157. return false;
  1158. }
  1159. }
  1160. if (empty($this->data[$this->alias][$this->primaryKey])) {
  1161. unset($this->data[$this->alias][$this->primaryKey]);
  1162. }
  1163. $fields = $values = array();
  1164. foreach ($this->data as $n => $v) {
  1165. if (isset($this->hasAndBelongsToMany[$n])) {
  1166. if (isset($v[$n])) {
  1167. $v = $v[$n];
  1168. }
  1169. $joined[$n] = $v;
  1170. } else {
  1171. if ($n === $this->alias) {
  1172. foreach (array('created', 'updated', 'modified') as $field) {
  1173. if (array_key_exists($field, $v) && empty($v[$field])) {
  1174. unset($v[$field]);
  1175. }
  1176. }
  1177. foreach ($v as $x => $y) {
  1178. if ($this->hasField($x) && (empty($this->whitelist) || in_array($x, $this->whitelist))) {
  1179. list($fields[], $values[]) = array($x, $y);
  1180. }
  1181. }
  1182. }
  1183. }
  1184. }
  1185. $count = count($fields);
  1186. if (!$exists && $count > 0) {
  1187. $this->id = false;
  1188. }
  1189. $success = true;
  1190. $created = false;
  1191. if ($count > 0) {
  1192. $cache = $this->_prepareUpdateFields(array_combine($fields, $values));
  1193. if (!empty($this->id)) {
  1194. $success = (bool)$db->update($this, $fields, $values);
  1195. } else {
  1196. $fInfo = $this->_schema[$this->primaryKey];
  1197. $isUUID = ($fInfo['length'] == 36 &&
  1198. ($fInfo['type'] === 'string' || $fInfo['type'] === 'binary')
  1199. );
  1200. if (empty($this->data[$this->alias][$this->primaryKey]) && $isUUID) {
  1201. if (array_key_exists($this->primaryKey, $this->data[$this->alias])) {
  1202. $j = array_search($this->primaryKey, $fields);
  1203. $values[$j] = String::uuid();
  1204. } else {
  1205. list($fields[], $values[]) = array($this->primaryKey, String::uuid());
  1206. }
  1207. }
  1208. if (!$db->create($this, $fields, $values)) {
  1209. $success = $created = false;
  1210. } else {
  1211. $created = true;
  1212. }
  1213. }
  1214. if ($success && !empty($this->belongsTo)) {
  1215. $this->updateCounterCache($cache, $created);
  1216. }
  1217. }
  1218. if (!empty($joined) && $success === true) {
  1219. $this->__saveMulti($joined, $this->id, $db);
  1220. }
  1221. if ($success && $count > 0) {
  1222. if (!empty($this->data)) {
  1223. $success = $this->data;
  1224. }
  1225. if ($options['callbacks'] === true || $options['callbacks'] === 'after') {
  1226. $this->Behaviors->trigger($this, 'afterSave', array($created, $options));
  1227. $this->afterSave($created);
  1228. }
  1229. if (!empty($this->data)) {
  1230. $success = Set::merge($success, $this->data);
  1231. }
  1232. $this->data = false;
  1233. $this->_clearCache();
  1234. $this->validationErrors = array();
  1235. }
  1236. $this->whitelist = $_whitelist;
  1237. return $success;
  1238. }
  1239. /**
  1240. * Saves model hasAndBelongsToMany data to the database.
  1241. *
  1242. * @param array $joined Data to save
  1243. * @param mixed $id ID of record in this model
  1244. * @access private
  1245. */
  1246. function __saveMulti($joined, $id, &$db) {
  1247. foreach ($joined as $assoc => $data) {
  1248. if (isset($this->hasAndBelongsToMany[$assoc])) {
  1249. list($join) = $this->joinModel($this->hasAndBelongsToMany[$assoc]['with']);
  1250. $isUUID = !empty($this->{$join}->primaryKey) && (
  1251. $this->{$join}->_schema[$this->{$join}->primaryKey]['length'] == 36 && (
  1252. $this->{$join}->_schema[$this->{$join}->primaryKey]['type'] === 'string' ||
  1253. $this->{$join}->_schema[$this->{$join}->primaryKey]['type'] === 'binary'
  1254. )
  1255. );
  1256. $newData = $newValues = array();
  1257. $primaryAdded = false;
  1258. $fields = array(
  1259. $db->name($this->hasAndBelongsToMany[$assoc]['foreignKey']),
  1260. $db->name($this->hasAndBelongsToMany[$assoc]['associationForeignKey'])
  1261. );
  1262. $idField = $db->name($this->{$join}->primaryKey);
  1263. if ($isUUID && !in_array($idField, $fields)) {
  1264. $fields[] = $idField;
  1265. $primaryAdded = true;
  1266. }
  1267. foreach ((array)$data as $row) {
  1268. if ((is_string($row) && (strlen($row) == 36 || strlen($row) == 16)) || is_numeric($row)) {
  1269. $values = array(
  1270. $db->value($id, $this->getColumnType($this->primaryKey)),
  1271. $db->value($row)
  1272. );
  1273. if ($isUUID && $primaryAdded) {
  1274. $values[] = $db->value(String::uuid());
  1275. }
  1276. $values = implode(',', $values);
  1277. $newValues[] = "({$values})";
  1278. unset($values);
  1279. } elseif (isset($row[$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
  1280. $newData[] = $row;
  1281. } elseif (isset($row[$join]) && isset($row[$join][$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
  1282. $newData[] = $row[$join];
  1283. }
  1284. }
  1285. if ($this->hasAndBelongsToMany[$assoc]['unique']) {
  1286. $conditions = array(
  1287. $join . '.' . $this->hasAndBelongsToMany[$assoc]['foreignKey'] => $id
  1288. );
  1289. if (!empty($this->hasAndBelongsToMany[$assoc]['conditions'])) {
  1290. $conditions = array_merge($conditions, (array)$this->hasAndBelongsToMany[$assoc]['conditions']);
  1291. }
  1292. $links = $this->{$join}->find('all', array(
  1293. 'conditions' => $conditions,
  1294. 'recursive' => empty($this->hasAndBelongsToMany[$assoc]['conditions']) ? -1 : 0,
  1295. 'fields' => $this->hasAndBelongsToMany[$assoc]['associationForeignKey']
  1296. ));
  1297. $associationForeignKey = "{$join}." . $this->hasAndBelongsToMany[$assoc]['associationForeignKey'];
  1298. $oldLinks = Set::extract($links, "{n}.{$associationForeignKey}");
  1299. if (!empty($oldLinks)) {
  1300. $conditions[$associationForeignKey] = $oldLinks;
  1301. $db->delete($this->{$join}, $conditions);
  1302. }
  1303. }
  1304. if (!empty($newData)) {
  1305. foreach ($newData as $data) {
  1306. $data[$this->hasAndBelongsToMany[$assoc]['foreignKey']] = $id;
  1307. $this->{$join}->create($data);
  1308. $this->{$join}->save();
  1309. }
  1310. }
  1311. if (!empty($newValues)) {
  1312. $fields = implode(',', $fields);
  1313. $db->insertMulti($this->{$join}, $fields, $newValues);
  1314. }
  1315. }
  1316. }
  1317. }
  1318. /**
  1319. * Updates the counter cache of belongsTo associations after a save or delete operation
  1320. *
  1321. * @param array $keys Optional foreign key data, defaults to the information $this->data
  1322. * @param boolean $created True if a new record was created, otherwise only associations with
  1323. * 'counterScope' defined get updated
  1324. * @return void
  1325. * @access public
  1326. */
  1327. function updateCounterCache($keys = array(), $created = false) {
  1328. $keys = empty($keys) ? $this->data[$this->alias] : $keys;
  1329. $keys['old'] = isset($keys['old']) ? $keys['old'] : array();
  1330. foreach ($this->belongsTo as $parent => $assoc) {
  1331. $foreignKey = $assoc['foreignKey'];
  1332. $fkQuoted = $this->escapeField($assoc['foreignKey']);
  1333. if (!empty($assoc['counterCache'])) {
  1334. if ($assoc['counterCache'] === true) {
  1335. $assoc['counterCache'] = Inflector::underscore($this->alias) . '_count';
  1336. }
  1337. if (!$this->{$parent}->hasField($assoc['counterCache'])) {
  1338. continue;
  1339. }
  1340. if (!array_key_exists($foreignKey, $keys)) {
  1341. $keys[$foreignKey] = $this->field($foreignKey);
  1342. }
  1343. $recursive = (isset($assoc['counterScope']) ? 1 : -1);
  1344. $conditions = ($recursive == 1) ? (array)$assoc['counterScope'] : array();
  1345. if (isset($keys['old'][$foreignKey])) {
  1346. if ($keys['old'][$foreignKey] != $keys[$foreignKey]) {
  1347. $conditions[$fkQuoted] = $keys['old'][$foreignKey];
  1348. $count = intval($this->find('count', compact('conditions', 'recursive')));
  1349. $this->{$parent}->updateAll(
  1350. array($assoc['counterCache'] => $count),
  1351. array($this->{$parent}->escapeField() => $keys['old'][$foreignKey])
  1352. );
  1353. }
  1354. }
  1355. $conditions[$fkQuoted] = $keys[$foreignKey];
  1356. if ($recursive == 1) {
  1357. $conditions = array_merge($conditions, (array)$assoc['counterScope']);
  1358. }
  1359. $count = intval($this->find('count', compact('conditions', 'recursive')));
  1360. $this->{$parent}->updateAll(
  1361. array($assoc['counterCache'] => $count),
  1362. array($this->{$parent}->escapeField() => $keys[$foreignKey])
  1363. );
  1364. }
  1365. }
  1366. }
  1367. /**
  1368. * Helper method for Model::updateCounterCache(). Checks the fields to be updated for
  1369. *
  1370. * @param array $data The fields of the record that will be updated
  1371. * @return array Returns updated foreign key values, along with an 'old' key containing the old
  1372. * values, or empty if no foreign keys are updated.
  1373. * @access protected
  1374. */
  1375. function _prepareUpdateFields($data) {
  1376. $foreignKeys = array();
  1377. foreach ($this->belongsTo as $assoc => $info) {
  1378. if ($info['counterCache']) {
  1379. $foreignKeys[$assoc] = $info['foreignKey'];
  1380. }
  1381. }
  1382. $included = array_intersect($foreignKeys, array_keys($data));
  1383. if (empty($included) || empty($this->id)) {
  1384. return array();
  1385. }
  1386. $old = $this->find('first', array(
  1387. 'conditions' => array($this->primaryKey => $this->id),
  1388. 'fields' => array_values($included),
  1389. 'recursive' => -1
  1390. ));
  1391. return array_merge($data, array('old' => $old[$this->alias]));
  1392. }
  1393. /**
  1394. * Saves multiple individual records for a single model; Also works with a single record, as well as
  1395. * all its associated records.
  1396. *
  1397. * #### Options
  1398. *
  1399. * - validate: Set to false to disable validation, true to validate each record before saving,
  1400. * 'first' to validate *all* records before any are saved (default),
  1401. * or 'only' to only validate the records, but not save them.
  1402. * - atomic: If true (default), will attempt to save all records in a single transaction.
  1403. * Should be set to false if database/table does not support transactions.
  1404. * - fieldList: Equivalent to the $fieldList parameter in Model::save()
  1405. *
  1406. * @param array $data Record data to save. This can be either a numerically-indexed array (for saving multiple
  1407. * records of the same type), or an array indexed by association name.
  1408. * @param array $options Options to use when saving record data, See $options above.
  1409. * @return mixed If atomic: True on success, or false on failure.
  1410. * Otherwise: array similar to the $data array passed, but values are set to true/false
  1411. * depending on whether each record saved successfully.
  1412. * @access public
  1413. * @link http://book.cakephp.org/view/1032/Saving-Related-Model-Data-hasOne-hasMany-belongsTo
  1414. * @link http://book.cakephp.org/view/1031/Saving-Your-Data
  1415. */
  1416. function saveAll($data = null, $options = array()) {
  1417. if (empty($data)) {
  1418. $data = $this->data;
  1419. }
  1420. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  1421. $options = array_merge(array('validate' => 'first', 'atomic' => true), $options);
  1422. $this->validationErrors = $validationErrors = array();
  1423. $validates = true;
  1424. $return = array();
  1425. if (empty($data) && $options['validate'] !== false) {
  1426. $result = $this->save($data, $options);
  1427. return !empty($result);
  1428. }
  1429. if ($options['atomic'] && $options['validate'] !== 'only') {
  1430. $transactionBegun = $db->begin($this);
  1431. }
  1432. if (Set::numeric(array_keys($data))) {
  1433. while ($validates) {
  1434. $return = array();
  1435. foreach ($data as $key => $record) {
  1436. if (!$currentValidates = $this->__save($record, $options)) {
  1437. $validationErrors[$key] = $this->validationErrors;
  1438. }
  1439. if ($options['validate'] === 'only' || $options['validate'] === 'first') {
  1440. $validating = true;
  1441. if ($options['atomic']) {
  1442. $validates = $validates && $currentValidates;
  1443. } else {
  1444. $validates = $currentValidates;
  1445. }
  1446. } else {
  1447. $validating = false;
  1448. $validates = $currentValidates;
  1449. }
  1450. if (!$options['atomic']) {
  1451. $return[] = $validates;
  1452. } elseif (!$validates && !$validating) {
  1453. break;
  1454. }
  1455. }
  1456. $this->validationErrors = $validationErrors;
  1457. switch (true) {
  1458. case ($options['validate'] === 'only'):
  1459. return ($options['atomic'] ? $validates : $return);
  1460. break;
  1461. case ($options['validate'] === 'first'):
  1462. $options['validate'] = true;
  1463. break;
  1464. default:
  1465. if ($options['atomic']) {
  1466. if ($validates) {
  1467. if ($transactionBegun) {
  1468. return $db->commit($this) !== false;
  1469. } else {
  1470. return true;
  1471. }
  1472. }
  1473. $db->rollback($this);
  1474. return false;
  1475. }
  1476. return $return;
  1477. break;
  1478. }
  1479. }
  1480. if ($options['atomic'] && !$validates) {
  1481. $db->rollback($this);
  1482. return false;
  1483. }
  1484. return $return;
  1485. }
  1486. $associations = $this->getAssociated();
  1487. while ($validates) {
  1488. foreach ($data as $association => $values) {
  1489. if (isset($associations[$association])) {
  1490. switch ($associations[$association]) {
  1491. case 'belongsTo':
  1492. if ($this->{$association}->__save($values, $options)) {
  1493. $data[$this->alias][$this->belongsTo[$association]['foreignKey']] = $this->{$association}->id;
  1494. } else {
  1495. $validationErrors[$association] = $this->{$association}->validationErrors;
  1496. $validates = false;
  1497. }
  1498. if (!$options['atomic']) {
  1499. $return[$association][] = $validates;
  1500. }
  1501. break;
  1502. }
  1503. }
  1504. }
  1505. if (!$this->__save($data, $options)) {
  1506. $validationErrors[$this->alias] = $this->validationErrors;
  1507. $validates = false;
  1508. }
  1509. if (!$options['atomic']) {
  1510. $return[$this->alias] = $validates;
  1511. }
  1512. $validating = ($options['validate'] === 'only' || $options['validate'] === 'first');
  1513. foreach ($data as $association => $values) {
  1514. if (!$validates && !$validating) {
  1515. break;
  1516. }
  1517. if (isset($associations[$association])) {
  1518. $type = $associations[$association];
  1519. switch ($type) {
  1520. case 'hasOne':
  1521. if (!$validating) {
  1522. $values[$this->{$type}[$association]['foreignKey']] = $this->id;
  1523. }
  1524. if (!$this->{$association}->__save($values, $options)) {
  1525. $validationErrors[$association] = $this->{$association}->validationErrors;
  1526. $validates = false;
  1527. }
  1528. if (!$options['atomic']) {
  1529. $return[$association][] = $validates;
  1530. }
  1531. break;
  1532. case 'hasMany':
  1533. if (!$validating) {
  1534. foreach ($values as $i => $value) {
  1535. $values[$i][$this->{$type}[$association]['foreignKey']] = $this->id;
  1536. }
  1537. }
  1538. $_options = array_merge($options, array('atomic' => false));
  1539. if ($_options['validate'] === 'first') {
  1540. $_options['validate'] = 'only';
  1541. }
  1542. $_return = $this->{$association}->saveAll($values, $_options);
  1543. if ($_return === false || (is_array($_return) && in_array(false, $_return, true))) {
  1544. $validationErrors[$association] = $this->{$association}->validationErrors;
  1545. $validates = false;
  1546. }
  1547. if (is_array($_return)) {
  1548. foreach ($_return as $val) {
  1549. if (!isset($return[$association])) {
  1550. $return[$association] = array();
  1551. } elseif (!is_array($return[$association])) {
  1552. $return[$association] = array($return[$association]);
  1553. }
  1554. $return[$association][] = $val;
  1555. }
  1556. } else {
  1557. $return[$association] = $_return;
  1558. }
  1559. break;
  1560. }
  1561. }
  1562. }
  1563. $this->validationErrors = $validationErrors;
  1564. if (isset($validationErrors[$this->alias])) {
  1565. $this->validationErrors = $validationErrors[$this->alias];
  1566. }
  1567. switch (true) {
  1568. case ($options['validate'] === 'only'):
  1569. return ($options['atomic'] ? $validates : $return);
  1570. break;
  1571. case ($options['validate'] === 'first'):
  1572. $options['validate'] = true;
  1573. $return = array();
  1574. break;
  1575. default:
  1576. if ($options['atomic']) {
  1577. if ($validates) {
  1578. if ($transactionBegun) {
  1579. return $db->commit($this) !== false;
  1580. } else {
  1581. return true;
  1582. }
  1583. } else {
  1584. $db->rollback($this);
  1585. }
  1586. }
  1587. return $return;
  1588. break;
  1589. }
  1590. if ($options['atomic'] && !$validates) {
  1591. $db->rollback($this);
  1592. return false;
  1593. }
  1594. }
  1595. }
  1596. /**
  1597. * Private helper method used by saveAll.
  1598. *
  1599. * @return boolean Success
  1600. * @access private
  1601. * @see Model::saveAll()
  1602. */
  1603. function __save($data, $options) {
  1604. if ($options['validate'] === 'first' || $options['validate'] === 'only') {
  1605. if (!($this->create($data) && $this->validates($options))) {
  1606. return false;
  1607. }
  1608. } elseif (!($this->create(null) !== null && $this->save($data, $options))) {
  1609. return false;
  1610. }
  1611. return true;
  1612. }
  1613. /**
  1614. * Updates multiple model records based on a set of conditions.
  1615. *
  1616. * @param array $fields Set of fields and values, indexed by fields.
  1617. * Fields are treated as SQL snippets, to insert literal values manually escape your data.
  1618. * @param mixed $conditions Conditions to match, true for all records
  1619. * @return boolean True on success, false on failure
  1620. * @access public
  1621. * @link http://book.cakephp.org/view/1031/Saving-Your-Data
  1622. */
  1623. function updateAll($fields, $conditions = true) {
  1624. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  1625. return $db->update($this, $fields, null, $conditions);
  1626. }
  1627. /**
  1628. * Removes record for given ID. If no ID is given, the current ID is used. Returns true on success.
  1629. *
  1630. * @param mixed $id ID of record to delete
  1631. * @param boolean $cascade Set to true to delete records that depend on this record
  1632. * @return boolean True on success
  1633. * @access public
  1634. * @link http://book.cakephp.org/view/1036/delete
  1635. */
  1636. function delete($id = null, $cascade = true) {
  1637. if (!empty($id)) {
  1638. $this->id = $id;
  1639. }
  1640. $id = $this->id;
  1641. if ($this->beforeDelete($cascade)) {
  1642. $filters = $this->Behaviors->trigger($this, 'beforeDelete', array($cascade), array(
  1643. 'break' => true, 'breakOn' => false
  1644. ));
  1645. if (!$filters || !$this->exists()) {
  1646. return false;
  1647. }
  1648. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  1649. $this->_deleteDependent($id, $cascade);
  1650. $this->_deleteLinks($id);
  1651. $this->id = $id;
  1652. if (!empty($this->belongsTo)) {
  1653. $keys = $this->find('first', array(
  1654. 'fields' => $this->__collectForeignKeys(),
  1655. 'conditions' => array($this->alias . '.' . $this->primaryKey => $id)
  1656. ));
  1657. }
  1658. if ($db->delete($this, array($this->alias . '.' . $this->primaryKey => $id))) {
  1659. if (!empty($this->belongsTo)) {
  1660. $this->updateCounterCache($keys[$this->alias]);
  1661. }
  1662. $this->Behaviors->trigger($this, 'afterDelete');
  1663. $this->afterDelete();
  1664. $this->_clearCache();
  1665. $this->id = false;
  1666. return true;
  1667. }
  1668. }
  1669. return false;
  1670. }
  1671. /**
  1672. * Cascades model deletes through associated hasMany and hasOne child records.
  1673. *
  1674. * @param string $id ID of record that was deleted
  1675. * @param boolean $cascade Set to true to delete records that depend on this record
  1676. * @return void
  1677. * @access protected
  1678. */
  1679. function _deleteDependent($id, $cascade) {
  1680. if (!empty($this->__backAssociation)) {
  1681. $savedAssociatons = $this->__backAssociation;
  1682. $this->__backAssociation = array();
  1683. }
  1684. if ($cascade === true) {
  1685. foreach (array_merge($this->hasMany, $this->hasOne) as $assoc => $data) {
  1686. if ($data['dependent'] === true) {
  1687. $model =& $this->{$assoc};
  1688. if ($data['foreignKey'] === false && $data['conditions'] && in_array($this->name, $model->getAssociated('belongsTo'))) {
  1689. $model->recursive = 0;
  1690. $conditions = array($this->escapeField(null, $this->name) => $id);
  1691. } else {
  1692. $model->recursive = -1;
  1693. $conditions = array($model->escapeField($data['foreignKey']) => $id);
  1694. if ($data['conditions']) {
  1695. $conditions = array_merge((array)$data['conditions'], $conditions);
  1696. }
  1697. }
  1698. if (isset($data['exclusive']) && $data['exclusive']) {
  1699. $model->deleteAll($conditions);
  1700. } else {
  1701. $records = $model->find('all', array(
  1702. 'conditions' => $conditions, 'fields' => $model->primaryKey
  1703. ));
  1704. if (!empty($records)) {
  1705. foreach ($records as $record) {
  1706. $model->delete($record[$model->alias][$model->primaryKey]);
  1707. }
  1708. }
  1709. }
  1710. }
  1711. }
  1712. }
  1713. if (isset($savedAssociatons)) {
  1714. $this->__backAssociation = $savedAssociatons;
  1715. }
  1716. }
  1717. /**
  1718. * Cascades model deletes through HABTM join keys.
  1719. *
  1720. * @param string $id ID of record that was deleted
  1721. * @return void
  1722. * @access protected
  1723. */
  1724. function _deleteLinks($id) {
  1725. foreach ($this->hasAndBelongsToMany as $assoc => $data) {
  1726. $joinModel = $data['with'];
  1727. $records = $this->{$joinModel}->find('all', array(
  1728. 'conditions' => array_merge(array($this->{$joinModel}->escapeField($data['foreignKey']) => $id)),
  1729. 'fields' => $this->{$joinModel}->primaryKey,
  1730. 'recursive' => -1
  1731. ));
  1732. if (!empty($records)) {
  1733. foreach ($records as $record) {
  1734. $this->{$joinModel}->delete($record[$this->{$joinModel}->alias][$this->{$joinModel}->primaryKey]);
  1735. }
  1736. }
  1737. }
  1738. }
  1739. /**
  1740. * Deletes multiple model records based on a set of conditions.
  1741. *
  1742. * @param mixed $conditions Conditions to match
  1743. * @param boolean $cascade Set to true to delete records that depend on this record
  1744. * @param boolean $callbacks Run callbacks
  1745. * @return boolean True on success, false on failure
  1746. * @access public
  1747. * @link http://book.cakephp.org/view/1038/deleteAll
  1748. */
  1749. function deleteAll($conditions, $cascade = true, $callbacks = false) {
  1750. if (empty($conditions)) {
  1751. return false;
  1752. }
  1753. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  1754. if (!$cascade && !$callbacks) {
  1755. return $db->delete($this, $conditions);
  1756. } else {
  1757. $ids = $this->find('all', array_merge(array(
  1758. 'fields' => "{$this->alias}.{$this->primaryKey}",
  1759. 'recursive' => 0), compact('conditions'))
  1760. );
  1761. if ($ids === false) {
  1762. return false;
  1763. }
  1764. $ids = Set::extract($ids, "{n}.{$this->alias}.{$this->primaryKey}");
  1765. if (empty($ids)) {
  1766. return true;
  1767. }
  1768. if ($callbacks) {
  1769. $_id = $this->id;
  1770. $result = true;
  1771. foreach ($ids as $id) {
  1772. $result = ($result && $this->delete($id, $cascade));
  1773. }
  1774. $this->id = $_id;
  1775. return $result;
  1776. } else {
  1777. foreach ($ids as $id) {
  1778. $this->_deleteLinks($id);
  1779. if ($cascade) {
  1780. $this->_deleteDependent($id, $cascade);
  1781. }
  1782. }
  1783. return $db->delete($this, array($this->alias . '.' . $this->primaryKey => $ids));
  1784. }
  1785. }
  1786. }
  1787. /**
  1788. * Collects foreign keys from associations.
  1789. *
  1790. * @return array
  1791. * @access private
  1792. */
  1793. function __collectForeignKeys($type = 'belongsTo') {
  1794. $result = array();
  1795. foreach ($this->{$type} as $assoc => $data) {
  1796. if (isset($data['foreignKey']) && is_string($data['foreignKey'])) {
  1797. $result[$assoc] = $data['foreignKey'];
  1798. }
  1799. }
  1800. return $result;
  1801. }
  1802. /**
  1803. * Returns true if a record with the currently set ID exists.
  1804. *
  1805. * Internally calls Model::getID() to obtain the current record ID to verify,
  1806. * and then performs a Model::find('count') on the currently configured datasource
  1807. * to ascertain the existence of the record in persistent storage.
  1808. *
  1809. * @return boolean True if such a record exists
  1810. * @access public
  1811. */
  1812. function exists() {
  1813. if ($this->getID() === false) {
  1814. return false;
  1815. }
  1816. $conditions = array($this->alias . '.' . $this->primaryKey => $this->getID());
  1817. $query = array('conditions' => $conditions, 'recursive' => -1, 'callbacks' => false);
  1818. return ($this->find('count', $query) > 0);
  1819. }
  1820. /**
  1821. * Returns true if a record that meets given conditions exists.
  1822. *
  1823. * @param array $conditions SQL conditions array
  1824. * @return boolean True if such a record exists
  1825. * @access public
  1826. */
  1827. function hasAny($conditions = null) {
  1828. return ($this->find('count', array('conditions' => $conditions, 'recursive' => -1)) != false);
  1829. }
  1830. /**
  1831. * Queries the datasource and returns a result set array.
  1832. *
  1833. * Also used to perform new-notation finds, where the first argument is type of find operation to perform
  1834. * (all / first / count / neighbors / list / threaded ),
  1835. * second parameter options for finding ( indexed array, including: 'conditions', 'limit',
  1836. * 'recursive', 'page', 'fields', 'offset', 'order')
  1837. *
  1838. * Eg:
  1839. * {{{
  1840. * find('all', array(
  1841. * 'conditions' => array('name' => 'Thomas Anderson'),
  1842. * 'fields' => array('name', 'email'),
  1843. * 'order' => 'field3 DESC',
  1844. * 'recursive' => 2,
  1845. * 'group' => 'type'
  1846. * ));
  1847. * }}}
  1848. *
  1849. * In addition to the standard query keys above, you can provide Datasource, and behavior specific
  1850. * keys. For example, when using a SQL based datasource you can use the joins key to specify additional
  1851. * joins that should be part of the query.
  1852. *
  1853. * {{{
  1854. * find('all', array(
  1855. * 'conditions' => array('name' => 'Thomas Anderson'),
  1856. * 'joins' => array(
  1857. * array(
  1858. * 'alias' => 'Thought',
  1859. * 'table' => 'thoughts',
  1860. * 'type' => 'LEFT',
  1861. * 'conditions' => '`Thought`.`person_id` = `Person`.`id`'
  1862. * )
  1863. * )
  1864. * ));
  1865. * }}}
  1866. *
  1867. * Behaviors and find types can also define custom finder keys which are passed into find().
  1868. *
  1869. * Specifying 'fields' for new-notation 'list':
  1870. *
  1871. * - If no fields are specified, then 'id' is used for key and 'model->displayField' is used for value.
  1872. * - If a single field is specified, 'id' is used for key and specified field is used for value.
  1873. * - If three fields are specified, they are used (in order) for key, value and group.
  1874. * - Otherwise, first and second fields are used for key and value.
  1875. *
  1876. * Note: find(list) + database views have issues with MySQL 5.0. Try upgrading to MySQL 5.1 if you
  1877. * have issues with database views.
  1878. *
  1879. * @param array $conditions SQL conditions array, or type of find operation (all / first / count /
  1880. * neighbors / list / threaded)
  1881. * @param mixed $fields Either a single string of a field name, or an array of field names, or
  1882. * options for matching
  1883. * @param string $order SQL ORDER BY conditions (e.g. "price DESC" or "name ASC")
  1884. * @param integer $recursive The number of levels deep to fetch associated records
  1885. * @return array Array of records
  1886. * @access public
  1887. * @link http://book.cakephp.org/view/1018/find
  1888. */
  1889. function find($conditions = null, $fields = array(), $order = null, $recursive = null) {
  1890. if (!is_string($conditions) || (is_string($conditions) && !array_key_exists($conditions, $this->_findMethods))) {
  1891. $type = 'first';
  1892. $query = array_merge(compact('conditions', 'fields', 'order', 'recursive'), array('limit' => 1));
  1893. } else {
  1894. list($type, $query) = array($conditions, $fields);
  1895. }
  1896. $this->findQueryType = $type;
  1897. $this->id = $this->getID();
  1898. $query = array_merge(
  1899. array(
  1900. 'conditions' => null, 'fields' => null, 'joins' => array(), 'limit' => null,
  1901. 'offset' => null, 'order' => null, 'page' => null, 'group' => null, 'callbacks' => true
  1902. ),
  1903. (array)$query
  1904. );
  1905. if ($type != 'all') {
  1906. if ($this->_findMethods[$type] === true) {
  1907. $query = $this->{'_find' . ucfirst($type)}('before', $query);
  1908. }
  1909. }
  1910. if (!is_numeric($query['page']) || intval($query['page']) < 1) {
  1911. $query['page'] = 1;
  1912. }
  1913. if ($query['page'] > 1 && !empty($query['limit'])) {
  1914. $query['offset'] = ($query['page'] - 1) * $query['limit'];
  1915. }
  1916. if ($query['order'] === null && $this->order !== null) {
  1917. $query['order'] = $this->order;
  1918. }
  1919. $query['order'] = array($query['order']);
  1920. if ($query['callbacks'] === true || $query['callbacks'] === 'before') {
  1921. $return = $this->Behaviors->trigger($this, 'beforeFind', array($query), array(
  1922. 'break' => true, 'breakOn' => false, 'modParams' => true
  1923. ));
  1924. $query = (is_array($return)) ? $return : $query;
  1925. if ($return === false) {
  1926. return null;
  1927. }
  1928. $return = $this->beforeFind($query);
  1929. $query = (is_array($return)) ? $return : $query;
  1930. if ($return === false) {
  1931. return null;
  1932. }
  1933. }
  1934. if (!$db =& ConnectionManager::getDataSource($this->useDbConfig)) {
  1935. return false;
  1936. }
  1937. $results = $db->read($this, $query);
  1938. $this->resetAssociations();
  1939. if ($query['callbacks'] === true || $query['callbacks'] === 'after') {
  1940. $results = $this->__filterResults($results);
  1941. }
  1942. $this->findQueryType = null;
  1943. if ($type === 'all') {
  1944. return $results;
  1945. } else {
  1946. if ($this->_findMethods[$type] === true) {
  1947. return $this->{'_find' . ucfirst($type)}('after', $query, $results);
  1948. }
  1949. }
  1950. }
  1951. /**
  1952. * Handles the before/after filter logic for find('first') operations. Only called by Model::find().
  1953. *
  1954. * @param string $state Either "before" or "after"
  1955. * @param array $query
  1956. * @param array $data
  1957. * @return array
  1958. * @access protected
  1959. * @see Model::find()
  1960. */
  1961. function _findFirst($state, $query, $results = array()) {
  1962. if ($state == 'before') {
  1963. $query['limit'] = 1;
  1964. return $query;
  1965. } elseif ($state == 'after') {
  1966. if (empty($results[0])) {
  1967. return false;
  1968. }
  1969. return $results[0];
  1970. }
  1971. }
  1972. /**
  1973. * Handles the before/after filter logic for find('count') operations. Only called by Model::find().
  1974. *
  1975. * @param string $state Either "before" or "after"
  1976. * @param array $query
  1977. * @param array $data
  1978. * @return int The number of records found, or false
  1979. * @access protected
  1980. * @see Model::find()
  1981. */
  1982. function _findCount($state, $query, $results = array()) {
  1983. if ($state == 'before') {
  1984. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  1985. if (empty($query['fields'])) {
  1986. $query['fields'] = $db->calculate($this, 'count');
  1987. } elseif (is_string($query['fields']) && !preg_match('/count/i', $query['fields'])) {
  1988. $query['fields'] = $db->calculate($this, 'count', array(
  1989. $db->expression($query['fields']), 'count'
  1990. ));
  1991. }
  1992. $query['order'] = false;
  1993. return $query;
  1994. } elseif ($state == 'after') {
  1995. if (isset($results[0][0]['count'])) {
  1996. return intval($results[0][0]['count']);
  1997. } elseif (isset($results[0][$this->alias]['count'])) {
  1998. return intval($results[0][$this->alias]['count']);
  1999. }
  2000. return false;
  2001. }
  2002. }
  2003. /**
  2004. * Handles the before/after filter logic for find('list') operations. Only called by Model::find().
  2005. *
  2006. * @param string $state Either "before" or "after"
  2007. * @param array $query
  2008. * @param array $data
  2009. * @return array Key/value pairs of primary keys/display field values of all records found
  2010. * @access protected
  2011. * @see Model::find()
  2012. */
  2013. function _findList($state, $query, $results = array()) {
  2014. if ($state == 'before') {
  2015. if (empty($query['fields'])) {
  2016. $query['fields'] = array("{$this->alias}.{$this->primaryKey}", "{$this->alias}.{$this->displayField}");
  2017. $list = array("{n}.{$this->alias}.{$this->primaryKey}", "{n}.{$this->alias}.{$this->displayField}", null);
  2018. } else {
  2019. if (!is_array($query['fields'])) {
  2020. $query['fields'] = String::tokenize($query['fields']);
  2021. }
  2022. if (count($query['fields']) == 1) {
  2023. if (strpos($query['fields'][0], '.') === false) {
  2024. $query['fields'][0] = $this->alias . '.' . $query['fields'][0];
  2025. }
  2026. $list = array("{n}.{$this->alias}.{$this->primaryKey}", '{n}.' . $query['fields'][0], null);
  2027. $query['fields'] = array("{$this->alias}.{$this->primaryKey}", $query['fields'][0]);
  2028. } elseif (count($query['fields']) == 3) {
  2029. for ($i = 0; $i < 3; $i++) {
  2030. if (strpos($query['fields'][$i], '.') === false) {
  2031. $query['fields'][$i] = $this->alias . '.' . $query['fields'][$i];
  2032. }
  2033. }
  2034. $list = array('{n}.' . $query['fields'][0], '{n}.' . $query['fields'][1], '{n}.' . $query['fields'][2]);
  2035. } else {
  2036. for ($i = 0; $i < 2; $i++) {
  2037. if (strpos($query['fields'][$i], '.') === false) {
  2038. $query['fields'][$i] = $this->alias . '.' . $query['fields'][$i];
  2039. }
  2040. }
  2041. $list = array('{n}.' . $query['fields'][0], '{n}.' . $query['fields'][1], null);
  2042. }
  2043. }
  2044. if (!isset($query['recursive']) || $query['recursive'] === null) {
  2045. $query['recursive'] = -1;
  2046. }
  2047. list($query['list']['keyPath'], $query['list']['valuePath'], $query['list']['groupPath']) = $list;
  2048. return $query;
  2049. } elseif ($state == 'after') {
  2050. if (empty($results)) {
  2051. return array();
  2052. }
  2053. $lst = $query['list'];
  2054. return Set::combine($results, $lst['keyPath'], $lst['valuePath'], $lst['groupPath']);
  2055. }
  2056. }
  2057. /**
  2058. * Detects the previous field's value, then uses logic to find the 'wrapping'
  2059. * rows and return them.
  2060. *
  2061. * @param string $state Either "before" or "after"
  2062. * @param mixed $query
  2063. * @param array $results
  2064. * @return array
  2065. * @access protected
  2066. */
  2067. function _findNeighbors($state, $query, $results = array()) {
  2068. if ($state == 'before') {
  2069. $query = array_merge(array('recursive' => 0), $query);
  2070. extract($query);
  2071. $conditions = (array)$conditions;
  2072. if (isset($field) && isset($value)) {
  2073. if (strpos($field, '.') === false) {
  2074. $field = $this->alias . '.' . $field;
  2075. }
  2076. } else {
  2077. $field = $this->alias . '.' . $this->primaryKey;
  2078. $value = $this->id;
  2079. }
  2080. $query['conditions'] = array_merge($conditions, array($field . ' <' => $value));
  2081. $query['order'] = $field . ' DESC';
  2082. $query['limit'] = 1;
  2083. $query['field'] = $field;
  2084. $query['value'] = $value;
  2085. return $query;
  2086. } elseif ($state == 'after') {
  2087. extract($query);
  2088. unset($query['conditions'][$field . ' <']);
  2089. $return = array();
  2090. if (isset($results[0])) {
  2091. $prevVal = Set::extract('/' . str_replace('.', '/', $field), $results[0]);
  2092. $query['conditions'][$field . ' >='] = $prevVal[0];
  2093. $query['conditions'][$field . ' !='] = $value;
  2094. $query['limit'] = 2;
  2095. } else {
  2096. $return['prev'] = null;
  2097. $query['conditions'][$field . ' >'] = $value;
  2098. $query['limit'] = 1;
  2099. }
  2100. $query['order'] = $field . ' ASC';
  2101. $return2 = $this->find('all', $query);
  2102. if (!array_key_exists('prev', $return)) {
  2103. $return['prev'] = $return2[0];
  2104. }
  2105. if (count($return2) == 2) {
  2106. $return['next'] = $return2[1];
  2107. } elseif (count($return2) == 1 && !$return['prev']) {
  2108. $return['next'] = $return2[0];
  2109. } else {
  2110. $return['next'] = null;
  2111. }
  2112. return $return;
  2113. }
  2114. }
  2115. /**
  2116. * In the event of ambiguous results returned (multiple top level results, with different parent_ids)
  2117. * top level results with different parent_ids to the first result will be dropped
  2118. *
  2119. * @param mixed $state
  2120. * @param mixed $query
  2121. * @param array $results
  2122. * @return array Threaded results
  2123. * @access protected
  2124. */
  2125. function _findThreaded($state, $query, $results = array()) {
  2126. if ($state == 'before') {
  2127. return $query;
  2128. } elseif ($state == 'after') {
  2129. $return = $idMap = array();
  2130. $ids = Set::extract($results, '{n}.' . $this->alias . '.' . $this->primaryKey);
  2131. foreach ($results as $result) {
  2132. $result['children'] = array();
  2133. $id = $result[$this->alias][$this->primaryKey];
  2134. $parentId = $result[$this->alias]['parent_id'];
  2135. if (isset($idMap[$id]['children'])) {
  2136. $idMap[$id] = array_merge($result, (array)$idMap[$id]);
  2137. } else {
  2138. $idMap[$id] = array_merge($result, array('children' => array()));
  2139. }
  2140. if (!$parentId || !in_array($parentId, $ids)) {
  2141. $return[] =& $idMap[$id];
  2142. } else {
  2143. $idMap[$parentId]['children'][] =& $idMap[$id];
  2144. }
  2145. }
  2146. if (count($return) > 1) {
  2147. $ids = array_unique(Set::extract('/' . $this->alias . '/parent_id', $return));
  2148. if (count($ids) > 1) {
  2149. $root = $return[0][$this->alias]['parent_id'];
  2150. foreach ($return as $key => $value) {
  2151. if ($value[$this->alias]['parent_id'] != $root) {
  2152. unset($return[$key]);
  2153. }
  2154. }
  2155. }
  2156. }
  2157. return $return;
  2158. }
  2159. }
  2160. /**
  2161. * Passes query results through model and behavior afterFilter() methods.
  2162. *
  2163. * @param array Results to filter
  2164. * @param boolean $primary If this is the primary model results (results from model where the find operation was performed)
  2165. * @return array Set of filtered results
  2166. * @access private
  2167. */
  2168. function __filterResults($results, $primary = true) {
  2169. $return = $this->Behaviors->trigger($this, 'afterFind', array($results, $primary), array('modParams' => true));
  2170. if ($return !== true) {
  2171. $results = $return;
  2172. }
  2173. return $this->afterFind($results, $primary);
  2174. }
  2175. /**
  2176. * This resets the association arrays for the model back
  2177. * to those originally defined in the model. Normally called at the end
  2178. * of each call to Model::find()
  2179. *
  2180. * @return boolean Success
  2181. * @access public
  2182. */
  2183. function resetAssociations() {
  2184. if (!empty($this->__backAssociation)) {
  2185. foreach ($this->__associations as $type) {
  2186. if (isset($this->__backAssociation[$type])) {
  2187. $this->{$type} = $this->__backAssociation[$type];
  2188. }
  2189. }
  2190. $this->__backAssociation = array();
  2191. }
  2192. foreach ($this->__associations as $type) {
  2193. foreach ($this->{$type} as $key => $name) {
  2194. if (!empty($this->{$key}->__backAssociation)) {
  2195. $this->{$key}->resetAssociations();
  2196. }
  2197. }
  2198. }
  2199. $this->__backAssociation = array();
  2200. return true;
  2201. }
  2202. /**
  2203. * Returns false if any fields passed match any (by default, all if $or = false) of their matching values.
  2204. *
  2205. * @param array $fields Field/value pairs to search (if no values specified, they are pulled from $this->data)
  2206. * @param boolean $or If false, all fields specified must match in order for a false return value
  2207. * @return boolean False if any records matching any fields are found
  2208. * @access public
  2209. */
  2210. function isUnique($fields, $or = true) {
  2211. if (!is_array($fields)) {
  2212. $fields = func_get_args();
  2213. if (is_bool($fields[count($fields) - 1])) {
  2214. $or = $fields[count($fields) - 1];
  2215. unset($fields[count($fields) - 1]);
  2216. }
  2217. }
  2218. foreach ($fields as $field => $value) {
  2219. if (is_numeric($field)) {
  2220. unset($fields[$field]);
  2221. $field = $value;
  2222. if (isset($this->data[$this->alias][$field])) {
  2223. $value = $this->data[$this->alias][$field];
  2224. } else {
  2225. $value = null;
  2226. }
  2227. }
  2228. if (strpos($field, '.') === false) {
  2229. unset($fields[$field]);
  2230. $fields[$this->alias . '.' . $field] = $value;
  2231. }
  2232. }
  2233. if ($or) {
  2234. $fields = array('or' => $fields);
  2235. }
  2236. if (!empty($this->id)) {
  2237. $fields[$this->alias . '.' . $this->primaryKey . ' !='] = $this->id;
  2238. }
  2239. return ($this->find('count', array('conditions' => $fields, 'recursive' => -1)) == 0);
  2240. }
  2241. /**
  2242. * Returns a resultset for a given SQL statement. Custom SQL queries should be performed with this method.
  2243. *
  2244. * @param string $sql SQL statement
  2245. * @return array Resultset
  2246. * @access public
  2247. * @link http://book.cakephp.org/view/1027/query
  2248. */
  2249. function query() {
  2250. $params = func_get_args();
  2251. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  2252. return call_user_func_array(array(&$db, 'query'), $params);
  2253. }
  2254. /**
  2255. * Returns true if all fields pass validation. Will validate hasAndBelongsToMany associations
  2256. * that use the 'with' key as well. Since __saveMulti is incapable of exiting a save operation.
  2257. *
  2258. * Will validate the currently set data. Use Model::set() or Model::create() to set the active data.
  2259. *
  2260. * @param string $options An optional array of custom options to be made available in the beforeValidate callback
  2261. * @return boolean True if there are no errors
  2262. * @access public
  2263. * @link http://book.cakephp.org/view/1182/Validating-Data-from-the-Controller
  2264. */
  2265. function validates($options = array()) {
  2266. $errors = $this->invalidFields($options);
  2267. if (empty($errors) && $errors !== false) {
  2268. $errors = $this->__validateWithModels($options);
  2269. }
  2270. if (is_array($errors)) {
  2271. return count($errors) === 0;
  2272. }
  2273. return $errors;
  2274. }
  2275. /**
  2276. * Returns an array of fields that have failed validation. On the current model.
  2277. *
  2278. * @param string $options An optional array of custom options to be made available in the beforeValidate callback
  2279. * @return array Array of invalid fields
  2280. * @see Model::validates()
  2281. * @access public
  2282. * @link http://book.cakephp.org/view/1182/Validating-Data-from-the-Controller
  2283. */
  2284. function invalidFields($options = array()) {
  2285. if (
  2286. !$this->Behaviors->trigger(
  2287. $this,
  2288. 'beforeValidate',
  2289. array($options),
  2290. array('break' => true, 'breakOn' => false)
  2291. ) ||
  2292. $this->beforeValidate($options) === false
  2293. ) {
  2294. return false;
  2295. }
  2296. if (!isset($this->validate) || empty($this->validate)) {
  2297. return $this->validationErrors;
  2298. }
  2299. $data = $this->data;
  2300. $methods = array_map('strtolower', get_class_methods($this));
  2301. $behaviorMethods = array_keys($this->Behaviors->methods());
  2302. if (isset($data[$this->alias])) {
  2303. $data = $data[$this->alias];
  2304. } elseif (!is_array($data)) {
  2305. $data = array();
  2306. }
  2307. $Validation =& Validation::getInstance();
  2308. $exists = null;
  2309. $_validate = $this->validate;
  2310. $whitelist = $this->whitelist;
  2311. if (!empty($options['fieldList'])) {
  2312. $whitelist = $options['fieldList'];
  2313. }
  2314. if (!empty($whitelist)) {
  2315. $validate = array();
  2316. foreach ((array)$whitelist as $f) {
  2317. if (!empty($this->validate[$f])) {
  2318. $validate[$f] = $this->validate[$f];
  2319. }
  2320. }
  2321. $this->validate = $validate;
  2322. }
  2323. foreach ($this->validate as $fieldName => $ruleSet) {
  2324. if (!is_array($ruleSet) || (is_array($ruleSet) && isset($ruleSet['rule']))) {
  2325. $ruleSet = array($ruleSet);
  2326. }
  2327. $default = array(
  2328. 'allowEmpty' => null,
  2329. 'required' => null,
  2330. 'rule' => 'blank',
  2331. 'last' => false,
  2332. 'on' => null
  2333. );
  2334. foreach ($ruleSet as $index => $validator) {
  2335. if (!is_array($validator)) {
  2336. $validator = array('rule' => $validator);
  2337. }
  2338. $validator = array_merge($default, $validator);
  2339. if (isset($validator['message'])) {
  2340. $message = $validator['message'];
  2341. } else {
  2342. $message = __('This field cannot be left blank', true);
  2343. }
  2344. if (!empty($validator['on'])) {
  2345. if ($exists === null) {
  2346. $exists = $this->exists();
  2347. }
  2348. if (($validator['on'] == 'create' && $exists) || ($validator['on'] == 'update' && !$exists)) {
  2349. continue;
  2350. }
  2351. }
  2352. $required = (
  2353. (!isset($data[$fieldName]) && $validator['required'] === true) ||
  2354. (
  2355. isset($data[$fieldName]) && (empty($data[$fieldName]) &&
  2356. !is_numeric($data[$fieldName])) && $validator['allowEmpty'] === false
  2357. )
  2358. );
  2359. if ($required) {
  2360. $this->invalidate($fieldName, $message);
  2361. if ($validator['last']) {
  2362. break;
  2363. }
  2364. } elseif (array_key_exists($fieldName, $data)) {
  2365. if (empty($data[$fieldName]) && $data[$fieldName] != '0' && $validator['allowEmpty'] === true) {
  2366. break;
  2367. }
  2368. if (is_array($validator['rule'])) {
  2369. $rule = $validator['rule'][0];
  2370. unset($validator['rule'][0]);
  2371. $ruleParams = array_merge(array($data[$fieldName]), array_values($validator['rule']));
  2372. } else {
  2373. $rule = $validator['rule'];
  2374. $ruleParams = array($data[$fieldName]);
  2375. }
  2376. $valid = true;
  2377. if (in_array(strtolower($rule), $methods)) {
  2378. $ruleParams[] = $validator;
  2379. $ruleParams[0] = array($fieldName => $ruleParams[0]);
  2380. $valid = $this->dispatchMethod($rule, $ruleParams);
  2381. } elseif (in_array($rule, $behaviorMethods) || in_array(strtolower($rule), $behaviorMethods)) {
  2382. $ruleParams[] = $validator;
  2383. $ruleParams[0] = array($fieldName => $ruleParams[0]);
  2384. $valid = $this->Behaviors->dispatchMethod($this, $rule, $ruleParams);
  2385. } elseif (method_exists($Validation, $rule)) {
  2386. $valid = $Validation->dispatchMethod($rule, $ruleParams);
  2387. } elseif (!is_array($validator['rule'])) {
  2388. $valid = preg_match($rule, $data[$fieldName]);
  2389. } elseif (Configure::read('debug') > 0) {
  2390. trigger_error(sprintf(__('Could not find validation handler %s for %s', true), $rule, $fieldName), E_USER_WARNING);
  2391. }
  2392. if (!$valid || (is_string($valid) && strlen($valid) > 0)) {
  2393. if (is_string($valid) && strlen($valid) > 0) {
  2394. $validator['message'] = $valid;
  2395. } elseif (!isset($validator['message'])) {
  2396. if (is_string($index)) {
  2397. $validator['message'] = $index;
  2398. } elseif (is_numeric($index) && count($ruleSet) > 1) {
  2399. $validator['message'] = $index + 1;
  2400. } else {
  2401. $validator['message'] = $message;
  2402. }
  2403. }
  2404. $this->invalidate($fieldName, $validator['message']);
  2405. if ($validator['last']) {
  2406. break;
  2407. }
  2408. }
  2409. }
  2410. }
  2411. }
  2412. $this->validate = $_validate;
  2413. return $this->validationErrors;
  2414. }
  2415. /**
  2416. * Runs validation for hasAndBelongsToMany associations that have 'with' keys
  2417. * set. And data in the set() data set.
  2418. *
  2419. * @param array $options Array of options to use on Valdation of with models
  2420. * @return boolean Failure of validation on with models.
  2421. * @access private
  2422. * @see Model::validates()
  2423. */
  2424. function __validateWithModels($options) {
  2425. $valid = true;
  2426. foreach ($this->hasAndBelongsToMany as $assoc => $association) {
  2427. if (empty($association['with']) || !isset($this->data[$assoc])) {
  2428. continue;
  2429. }
  2430. list($join) = $this->joinModel($this->hasAndBelongsToMany[$assoc]['with']);
  2431. $data = $this->data[$assoc];
  2432. $newData = array();
  2433. foreach ((array)$data as $row) {
  2434. if (isset($row[$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
  2435. $newData[] = $row;
  2436. } elseif (isset($row[$join]) && isset($row[$join][$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
  2437. $newData[] = $row[$join];
  2438. }
  2439. }
  2440. if (empty($newData)) {
  2441. continue;
  2442. }
  2443. foreach ($newData as $data) {
  2444. $data[$this->hasAndBelongsToMany[$assoc]['foreignKey']] = $this->id;
  2445. $this->{$join}->create($data);
  2446. $valid = ($valid && $this->{$join}->validates($options));
  2447. }
  2448. }
  2449. return $valid;
  2450. }
  2451. /**
  2452. * Marks a field as invalid, optionally setting the name of validation
  2453. * rule (in case of multiple validation for field) that was broken.
  2454. *
  2455. * @param string $field The name of the field to invalidate
  2456. * @param mixed $value Name of validation rule that was not failed, or validation message to
  2457. * be returned. If no validation key is provided, defaults to true.
  2458. * @access public
  2459. */
  2460. function invalidate($field, $value = true) {
  2461. if (!is_array($this->validationErrors)) {
  2462. $this->validationErrors = array();
  2463. }
  2464. $this->validationErrors[$field] = $value;
  2465. }
  2466. /**
  2467. * Returns true if given field name is a foreign key in this model.
  2468. *
  2469. * @param string $field Returns true if the input string ends in "_id"
  2470. * @return boolean True if the field is a foreign key listed in the belongsTo array.
  2471. * @access public
  2472. */
  2473. function isForeignKey($field) {
  2474. $foreignKeys = array();
  2475. if (!empty($this->belongsTo)) {
  2476. foreach ($this->belongsTo as $assoc => $data) {
  2477. $foreignKeys[] = $data['foreignKey'];
  2478. }
  2479. }
  2480. return in_array($field, $foreignKeys);
  2481. }
  2482. /**
  2483. * Escapes the field name and prepends the model name. Escaping is done according to the
  2484. * current database driver's rules.
  2485. *
  2486. * @param string $field Field to escape (e.g: id)
  2487. * @param string $alias Alias for the model (e.g: Post)
  2488. * @return string The name of the escaped field for this Model (i.e. id becomes `Post`.`id`).
  2489. * @access public
  2490. */
  2491. function escapeField($field = null, $alias = null) {
  2492. if (empty($alias)) {
  2493. $alias = $this->alias;
  2494. }
  2495. if (empty($field)) {
  2496. $field = $this->primaryKey;
  2497. }
  2498. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  2499. if (strpos($field, $db->name($alias) . '.') === 0) {
  2500. return $field;
  2501. }
  2502. return $db->name($alias . '.' . $field);
  2503. }
  2504. /**
  2505. * Returns the current record's ID
  2506. *
  2507. * @param integer $list Index on which the composed ID is located
  2508. * @return mixed The ID of the current record, false if no ID
  2509. * @access public
  2510. */
  2511. function getID($list = 0) {
  2512. if (empty($this->id) || (is_array($this->id) && isset($this->id[0]) && empty($this->id[0]))) {
  2513. return false;
  2514. }
  2515. if (!is_array($this->id)) {
  2516. return $this->id;
  2517. }
  2518. if (empty($this->id)) {
  2519. return false;
  2520. }
  2521. if (isset($this->id[$list]) && !empty($this->id[$list])) {
  2522. return $this->id[$list];
  2523. } elseif (isset($this->id[$list])) {
  2524. return false;
  2525. }
  2526. foreach ($this->id as $id) {
  2527. return $id;
  2528. }
  2529. return false;
  2530. }
  2531. /**
  2532. * Returns the ID of the last record this model inserted.
  2533. *
  2534. * @return mixed Last inserted ID
  2535. * @access public
  2536. */
  2537. function getLastInsertID() {
  2538. return $this->getInsertID();
  2539. }
  2540. /**
  2541. * Returns the ID of the last record this model inserted.
  2542. *
  2543. * @return mixed Last inserted ID
  2544. * @access public
  2545. */
  2546. function getInsertID() {
  2547. return $this->__insertID;
  2548. }
  2549. /**
  2550. * Sets the ID of the last record this model inserted
  2551. *
  2552. * @param mixed Last inserted ID
  2553. * @access public
  2554. */
  2555. function setInsertID($id) {
  2556. $this->__insertID = $id;
  2557. }
  2558. /**
  2559. * Returns the number of rows returned from the last query.
  2560. *
  2561. * @return int Number of rows
  2562. * @access public
  2563. */
  2564. function getNumRows() {
  2565. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  2566. return $db->lastNumRows();
  2567. }
  2568. /**
  2569. * Returns the number of rows affected by the last query.
  2570. *
  2571. * @return int Number of rows
  2572. * @access public
  2573. */
  2574. function getAffectedRows() {
  2575. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  2576. return $db->lastAffected();
  2577. }
  2578. /**
  2579. * Sets the DataSource to which this model is bound.
  2580. *
  2581. * @param string $dataSource The name of the DataSource, as defined in app/config/database.php
  2582. * @return boolean True on success
  2583. * @access public
  2584. */
  2585. function setDataSource($dataSource = null) {
  2586. $oldConfig = $this->useDbConfig;
  2587. if ($dataSource != null) {
  2588. $this->useDbConfig = $dataSource;
  2589. }
  2590. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  2591. if (!empty($oldConfig) && isset($db->config['prefix'])) {
  2592. $oldDb =& ConnectionManager::getDataSource($oldConfig);
  2593. if (!isset($this->tablePrefix) || (!isset($oldDb->config['prefix']) || $this->tablePrefix == $oldDb->config['prefix'])) {
  2594. $this->tablePrefix = $db->config['prefix'];
  2595. }
  2596. } elseif (isset($db->config['prefix'])) {
  2597. $this->tablePrefix = $db->config['prefix'];
  2598. }
  2599. if (empty($db) || !is_object($db)) {
  2600. return $this->cakeError('missingConnection', array(array('code' => 500, 'className' => $this->alias)));
  2601. }
  2602. }
  2603. /**
  2604. * Gets the DataSource to which this model is bound.
  2605. * Not safe for use with some versions of PHP4, because this class is overloaded.
  2606. *
  2607. * @return object A DataSource object
  2608. * @access public
  2609. */
  2610. function &getDataSource() {
  2611. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  2612. return $db;
  2613. }
  2614. /**
  2615. * Gets all the models with which this model is associated.
  2616. *
  2617. * @param string $type Only result associations of this type
  2618. * @return array Associations
  2619. * @access public
  2620. */
  2621. function getAssociated($type = null) {
  2622. if ($type == null) {
  2623. $associated = array();
  2624. foreach ($this->__associations as $assoc) {
  2625. if (!empty($this->{$assoc})) {
  2626. $models = array_keys($this->{$assoc});
  2627. foreach ($models as $m) {
  2628. $associated[$m] = $assoc;
  2629. }
  2630. }
  2631. }
  2632. return $associated;
  2633. } elseif (in_array($type, $this->__associations)) {
  2634. if (empty($this->{$type})) {
  2635. return array();
  2636. }
  2637. return array_keys($this->{$type});
  2638. } else {
  2639. $assoc = array_merge(
  2640. $this->hasOne,
  2641. $this->hasMany,
  2642. $this->belongsTo,
  2643. $this->hasAndBelongsToMany
  2644. );
  2645. if (array_key_exists($type, $assoc)) {
  2646. foreach ($this->__associations as $a) {
  2647. if (isset($this->{$a}[$type])) {
  2648. $assoc[$type]['association'] = $a;
  2649. break;
  2650. }
  2651. }
  2652. return $assoc[$type];
  2653. }
  2654. return null;
  2655. }
  2656. }
  2657. /**
  2658. * Gets the name and fields to be used by a join model. This allows specifying join fields
  2659. * in the association definition.
  2660. *
  2661. * @param object $model The model to be joined
  2662. * @param mixed $with The 'with' key of the model association
  2663. * @param array $keys Any join keys which must be merged with the keys queried
  2664. * @return array
  2665. * @access public
  2666. */
  2667. function joinModel($assoc, $keys = array()) {
  2668. if (is_string($assoc)) {
  2669. return array($assoc, array_keys($this->{$assoc}->schema()));
  2670. } elseif (is_array($assoc)) {
  2671. $with = key($assoc);
  2672. return array($with, array_unique(array_merge($assoc[$with], $keys)));
  2673. }
  2674. trigger_error(
  2675. sprintf(__('Invalid join model settings in %s', true), $model->alias),
  2676. E_USER_WARNING
  2677. );
  2678. }
  2679. /**
  2680. * Called before each find operation. Return false if you want to halt the find
  2681. * call, otherwise return the (modified) query data.
  2682. *
  2683. * @param array $queryData Data used to execute this query, i.e. conditions, order, etc.
  2684. * @return mixed true if the operation should continue, false if it should abort; or, modified
  2685. * $queryData to continue with new $queryData
  2686. * @access public
  2687. * @link http://book.cakephp.org/view/1048/Callback-Methods#beforeFind-1049
  2688. */
  2689. function beforeFind($queryData) {
  2690. return true;
  2691. }
  2692. /**
  2693. * Called after each find operation. Can be used to modify any results returned by find().
  2694. * Return value should be the (modified) results.
  2695. *
  2696. * @param mixed $results The results of the find operation
  2697. * @param boolean $primary Whether this model is being queried directly (vs. being queried as an association)
  2698. * @return mixed Result of the find operation
  2699. * @access public
  2700. * @link http://book.cakephp.org/view/1048/Callback-Methods#afterFind-1050
  2701. */
  2702. function afterFind($results, $primary = false) {
  2703. return $results;
  2704. }
  2705. /**
  2706. * Called before each save operation, after validation. Return a non-true result
  2707. * to halt the save.
  2708. *
  2709. * @return boolean True if the operation should continue, false if it should abort
  2710. * @access public
  2711. * @link http://book.cakephp.org/view/1048/Callback-Methods#beforeSave-1052
  2712. */
  2713. function beforeSave($options = array()) {
  2714. return true;
  2715. }
  2716. /**
  2717. * Called after each successful save operation.
  2718. *
  2719. * @param boolean $created True if this save created a new record
  2720. * @access public
  2721. * @link http://book.cakephp.org/view/1048/Callback-Methods#afterSave-1053
  2722. */
  2723. function afterSave($created) {
  2724. }
  2725. /**
  2726. * Called before every deletion operation.
  2727. *
  2728. * @param boolean $cascade If true records that depend on this record will also be deleted
  2729. * @return boolean True if the operation should continue, false if it should abort
  2730. * @access public
  2731. * @link http://book.cakephp.org/view/1048/Callback-Methods#beforeDelete-1054
  2732. */
  2733. function beforeDelete($cascade = true) {
  2734. return true;
  2735. }
  2736. /**
  2737. * Called after every deletion operation.
  2738. *
  2739. * @access public
  2740. * @link http://book.cakephp.org/view/1048/Callback-Methods#afterDelete-1055
  2741. */
  2742. function afterDelete() {
  2743. }
  2744. /**
  2745. * Called during validation operations, before validation. Please note that custom
  2746. * validation rules can be defined in $validate.
  2747. *
  2748. * @return boolean True if validate operation should continue, false to abort
  2749. * @param $options array Options passed from model::save(), see $options of model::save().
  2750. * @access public
  2751. * @link http://book.cakephp.org/view/1048/Callback-Methods#beforeValidate-1051
  2752. */
  2753. function beforeValidate($options = array()) {
  2754. return true;
  2755. }
  2756. /**
  2757. * Called when a DataSource-level error occurs.
  2758. *
  2759. * @access public
  2760. * @link http://book.cakephp.org/view/1048/Callback-Methods#onError-1056
  2761. */
  2762. function onError() {
  2763. }
  2764. /**
  2765. * Private method. Clears cache for this model.
  2766. *
  2767. * @param string $type If null this deletes cached views if Cache.check is true
  2768. * Will be used to allow deleting query cache also
  2769. * @return boolean true on delete
  2770. * @access protected
  2771. * @todo
  2772. */
  2773. function _clearCache($type = null) {
  2774. if ($type === null) {
  2775. if (Configure::read('Cache.check') === true) {
  2776. $assoc[] = strtolower(Inflector::pluralize($this->alias));
  2777. $assoc[] = strtolower(Inflector::underscore(Inflector::pluralize($this->alias)));
  2778. foreach ($this->__associations as $key => $association) {
  2779. foreach ($this->$association as $key => $className) {
  2780. $check = strtolower(Inflector::pluralize($className['className']));
  2781. if (!in_array($check, $assoc)) {
  2782. $assoc[] = strtolower(Inflector::pluralize($className['className']));
  2783. $assoc[] = strtolower(Inflector::underscore(Inflector::pluralize($className['className'])));
  2784. }
  2785. }
  2786. }
  2787. clearCache($assoc);
  2788. return true;
  2789. }
  2790. } else {
  2791. //Will use for query cache deleting
  2792. }
  2793. }
  2794. /**
  2795. * Called when serializing a model.
  2796. *
  2797. * @return array Set of object variable names this model has
  2798. * @access private
  2799. */
  2800. function __sleep() {
  2801. $return = array_keys(get_object_vars($this));
  2802. return $return;
  2803. }
  2804. /**
  2805. * Called when de-serializing a model.
  2806. *
  2807. * @access private
  2808. * @todo
  2809. */
  2810. function __wakeup() {
  2811. }
  2812. }
  2813. if (!defined('CAKEPHP_UNIT_TEST_EXECUTION')) {
  2814. Overloadable::overload('Model');
  2815. }