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

/code/ryzom/tools/server/www/webtt/cake/libs/model/model.php

https://bitbucket.org/mattraykowski/ryzomcore_demoshard
PHP | 3072 lines | 1808 code | 273 blank | 991 comment | 530 complexity | 07673b977d51b8f9a7d1cb247a0e818d MD5 | raw file
Possible License(s): AGPL-3.0, GPL-3.0, LGPL-2.1
  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-2010, 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-2010, 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. // debug_print_backtrace();
  681. $this->setDataSource($this->useDbConfig);
  682. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  683. $db->cacheSources = ($this->cacheSources && $db->cacheSources);
  684. if ($db->isInterfaceSupported('listSources')) {
  685. $sources = $db->listSources();
  686. if (is_array($sources) && !in_array(strtolower($this->tablePrefix . $tableName), array_map('strtolower', $sources))) {
  687. return $this->cakeError('missingTable', array(array(
  688. 'className' => $this->alias,
  689. 'table' => $this->tablePrefix . $tableName,
  690. 'code' => 500
  691. )));
  692. }
  693. $this->_schema = null;
  694. }
  695. $this->table = $this->useTable = $tableName;
  696. $this->tableToModel[$this->table] = $this->alias;
  697. $this->schema();
  698. }
  699. /**
  700. * This function does two things:
  701. *
  702. * 1. it scans the array $one for the primary key,
  703. * and if that's found, it sets the current id to the value of $one[id].
  704. * For all other keys than 'id' the keys and values of $one are copied to the 'data' property of this object.
  705. * 2. Returns an array with all of $one's keys and values.
  706. * (Alternative indata: two strings, which are mangled to
  707. * a one-item, two-dimensional array using $one for a key and $two as its value.)
  708. *
  709. * @param mixed $one Array or string of data
  710. * @param string $two Value string for the alternative indata method
  711. * @return array Data with all of $one's keys and values
  712. * @access public
  713. * @link http://book.cakephp.org/view/1031/Saving-Your-Data
  714. */
  715. function set($one, $two = null) {
  716. if (!$one) {
  717. return;
  718. }
  719. if (is_object($one)) {
  720. $one = Set::reverse($one);
  721. }
  722. if (is_array($one)) {
  723. $data = $one;
  724. if (empty($one[$this->alias])) {
  725. if ($this->getAssociated(key($one)) === null) {
  726. $data = array($this->alias => $one);
  727. }
  728. }
  729. } else {
  730. $data = array($this->alias => array($one => $two));
  731. }
  732. foreach ($data as $modelName => $fieldSet) {
  733. if (is_array($fieldSet)) {
  734. foreach ($fieldSet as $fieldName => $fieldValue) {
  735. if (isset($this->validationErrors[$fieldName])) {
  736. unset ($this->validationErrors[$fieldName]);
  737. }
  738. if ($modelName === $this->alias) {
  739. if ($fieldName === $this->primaryKey) {
  740. $this->id = $fieldValue;
  741. }
  742. }
  743. if (is_array($fieldValue) || is_object($fieldValue)) {
  744. $fieldValue = $this->deconstruct($fieldName, $fieldValue);
  745. }
  746. $this->data[$modelName][$fieldName] = $fieldValue;
  747. }
  748. }
  749. }
  750. return $data;
  751. }
  752. /**
  753. * Deconstructs a complex data type (array or object) into a single field value.
  754. *
  755. * @param string $field The name of the field to be deconstructed
  756. * @param mixed $data An array or object to be deconstructed into a field
  757. * @return mixed The resulting data that should be assigned to a field
  758. * @access public
  759. */
  760. function deconstruct($field, $data) {
  761. if (!is_array($data)) {
  762. return $data;
  763. }
  764. $copy = $data;
  765. $type = $this->getColumnType($field);
  766. if (in_array($type, array('datetime', 'timestamp', 'date', 'time'))) {
  767. $useNewDate = (isset($data['year']) || isset($data['month']) ||
  768. isset($data['day']) || isset($data['hour']) || isset($data['minute']));
  769. $dateFields = array('Y' => 'year', 'm' => 'month', 'd' => 'day', 'H' => 'hour', 'i' => 'min', 's' => 'sec');
  770. $timeFields = array('H' => 'hour', 'i' => 'min', 's' => 'sec');
  771. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  772. $format = $db->columns[$type]['format'];
  773. $date = array();
  774. if (isset($data['hour']) && isset($data['meridian']) && $data['hour'] != 12 && 'pm' == $data['meridian']) {
  775. $data['hour'] = $data['hour'] + 12;
  776. }
  777. if (isset($data['hour']) && isset($data['meridian']) && $data['hour'] == 12 && 'am' == $data['meridian']) {
  778. $data['hour'] = '00';
  779. }
  780. if ($type == 'time') {
  781. foreach ($timeFields as $key => $val) {
  782. if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') {
  783. $data[$val] = '00';
  784. } elseif ($data[$val] === '') {
  785. $data[$val] = '';
  786. } else {
  787. $data[$val] = sprintf('%02d', $data[$val]);
  788. }
  789. if (!empty($data[$val])) {
  790. $date[$key] = $data[$val];
  791. } else {
  792. return null;
  793. }
  794. }
  795. }
  796. if ($type == 'datetime' || $type == 'timestamp' || $type == 'date') {
  797. foreach ($dateFields as $key => $val) {
  798. if ($val == 'hour' || $val == 'min' || $val == 'sec') {
  799. if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') {
  800. $data[$val] = '00';
  801. } else {
  802. $data[$val] = sprintf('%02d', $data[$val]);
  803. }
  804. }
  805. if (!isset($data[$val]) || isset($data[$val]) && (empty($data[$val]) || $data[$val][0] === '-')) {
  806. return null;
  807. }
  808. if (isset($data[$val]) && !empty($data[$val])) {
  809. $date[$key] = $data[$val];
  810. }
  811. }
  812. }
  813. $date = str_replace(array_keys($date), array_values($date), $format);
  814. if ($useNewDate && !empty($date)) {
  815. return $date;
  816. }
  817. }
  818. return $data;
  819. }
  820. /**
  821. * Returns an array of table metadata (column names and types) from the database.
  822. * $field => keys(type, null, default, key, length, extra)
  823. *
  824. * @param mixed $field Set to true to reload schema, or a string to return a specific field
  825. * @return array Array of table metadata
  826. * @access public
  827. */
  828. function schema($field = false) {
  829. if (!is_array($this->_schema) || $field === true) {
  830. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  831. $db->cacheSources = ($this->cacheSources && $db->cacheSources);
  832. if ($db->isInterfaceSupported('describe') && $this->useTable !== false) {
  833. $this->_schema = $db->describe($this, $field);
  834. } elseif ($this->useTable === false) {
  835. $this->_schema = array();
  836. }
  837. }
  838. if (is_string($field)) {
  839. if (isset($this->_schema[$field])) {
  840. return $this->_schema[$field];
  841. } else {
  842. return null;
  843. }
  844. }
  845. return $this->_schema;
  846. }
  847. /**
  848. * Returns an associative array of field names and column types.
  849. *
  850. * @return array Field types indexed by field name
  851. * @access public
  852. */
  853. function getColumnTypes() {
  854. $columns = $this->schema();
  855. if (empty($columns)) {
  856. 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);
  857. }
  858. $cols = array();
  859. foreach ($columns as $field => $values) {
  860. $cols[$field] = $values['type'];
  861. }
  862. return $cols;
  863. }
  864. /**
  865. * Returns the column type of a column in the model.
  866. *
  867. * @param string $column The name of the model column
  868. * @return string Column type
  869. * @access public
  870. */
  871. function getColumnType($column) {
  872. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  873. $cols = $this->schema();
  874. $model = null;
  875. $column = str_replace(array($db->startQuote, $db->endQuote), '', $column);
  876. if (strpos($column, '.')) {
  877. list($model, $column) = explode('.', $column);
  878. }
  879. if ($model != $this->alias && isset($this->{$model})) {
  880. return $this->{$model}->getColumnType($column);
  881. }
  882. if (isset($cols[$column]) && isset($cols[$column]['type'])) {
  883. return $cols[$column]['type'];
  884. }
  885. return null;
  886. }
  887. /**
  888. * Returns true if the supplied field exists in the model's database table.
  889. *
  890. * @param mixed $name Name of field to look for, or an array of names
  891. * @param boolean $checkVirtual checks if the field is declared as virtual
  892. * @return mixed If $name is a string, returns a boolean indicating whether the field exists.
  893. * If $name is an array of field names, returns the first field that exists,
  894. * or false if none exist.
  895. * @access public
  896. */
  897. function hasField($name, $checkVirtual = false) {
  898. if (is_array($name)) {
  899. foreach ($name as $n) {
  900. if ($this->hasField($n, $checkVirtual)) {
  901. return $n;
  902. }
  903. }
  904. return false;
  905. }
  906. if ($checkVirtual && !empty($this->virtualFields)) {
  907. if ($this->isVirtualField($name)) {
  908. return true;
  909. }
  910. }
  911. if (empty($this->_schema)) {
  912. $this->schema();
  913. }
  914. if ($this->_schema != null) {
  915. return isset($this->_schema[$name]);
  916. }
  917. return false;
  918. }
  919. /**
  920. * Returns true if the supplied field is a model Virtual Field
  921. *
  922. * @param mixed $name Name of field to look for
  923. * @return boolean indicating whether the field exists as a model virtual field.
  924. * @access public
  925. */
  926. function isVirtualField($field) {
  927. if (empty($this->virtualFields) || !is_string($field)) {
  928. return false;
  929. }
  930. if (isset($this->virtualFields[$field])) {
  931. return true;
  932. }
  933. if (strpos($field, '.') !== false) {
  934. list($model, $field) = explode('.', $field);
  935. if (isset($this->virtualFields[$field])) {
  936. return true;
  937. }
  938. }
  939. return false;
  940. }
  941. /**
  942. * Returns the expression for a model virtual field
  943. *
  944. * @param mixed $name Name of field to look for
  945. * @return mixed If $field is string expression bound to virtual field $field
  946. * If $field is null, returns an array of all model virtual fields
  947. * or false if none $field exist.
  948. * @access public
  949. */
  950. function getVirtualField($field = null) {
  951. if ($field == null) {
  952. return empty($this->virtualFields) ? false : $this->virtualFields;
  953. }
  954. if ($this->isVirtualField($field)) {
  955. if (strpos($field, '.') !== false) {
  956. list($model, $field) = explode('.', $field);
  957. }
  958. return $this->virtualFields[$field];
  959. }
  960. return false;
  961. }
  962. /**
  963. * Initializes the model for writing a new record, loading the default values
  964. * for those fields that are not defined in $data, and clearing previous validation errors.
  965. * Especially helpful for saving data in loops.
  966. *
  967. * @param mixed $data Optional data array to assign to the model after it is created. If null or false,
  968. * schema data defaults are not merged.
  969. * @param boolean $filterKey If true, overwrites any primary key input with an empty value
  970. * @return array The current Model::data; after merging $data and/or defaults from database
  971. * @access public
  972. * @link http://book.cakephp.org/view/1031/Saving-Your-Data
  973. */
  974. function create($data = array(), $filterKey = false) {
  975. $defaults = array();
  976. $this->id = false;
  977. $this->data = array();
  978. $this->validationErrors = array();
  979. if ($data !== null && $data !== false) {
  980. foreach ($this->schema() as $field => $properties) {
  981. if ($this->primaryKey !== $field && isset($properties['default']) && $properties['default'] !== '') {
  982. $defaults[$field] = $properties['default'];
  983. }
  984. }
  985. $this->set($defaults);
  986. $this->set($data);
  987. }
  988. if ($filterKey) {
  989. $this->set($this->primaryKey, false);
  990. }
  991. return $this->data;
  992. }
  993. /**
  994. * Returns a list of fields from the database, and sets the current model
  995. * data (Model::$data) with the record found.
  996. *
  997. * @param mixed $fields String of single fieldname, or an array of fieldnames.
  998. * @param mixed $id The ID of the record to read
  999. * @return array Array of database fields, or false if not found
  1000. * @access public
  1001. * @link http://book.cakephp.org/view/1017/Retrieving-Your-Data#read-1029
  1002. */
  1003. function read($fields = null, $id = null) {
  1004. $this->validationErrors = array();
  1005. if ($id != null) {
  1006. $this->id = $id;
  1007. }
  1008. $id = $this->id;
  1009. if (is_array($this->id)) {
  1010. $id = $this->id[0];
  1011. }
  1012. if ($id !== null && $id !== false) {
  1013. $this->data = $this->find('first', array(
  1014. 'conditions' => array($this->alias . '.' . $this->primaryKey => $id),
  1015. 'fields' => $fields
  1016. ));
  1017. return $this->data;
  1018. } else {
  1019. return false;
  1020. }
  1021. }
  1022. /**
  1023. * Returns the contents of a single field given the supplied conditions, in the
  1024. * supplied order.
  1025. *
  1026. * @param string $name Name of field to get
  1027. * @param array $conditions SQL conditions (defaults to NULL)
  1028. * @param string $order SQL ORDER BY fragment
  1029. * @return string field contents, or false if not found
  1030. * @access public
  1031. * @link http://book.cakephp.org/view/1017/Retrieving-Your-Data#field-1028
  1032. */
  1033. function field($name, $conditions = null, $order = null) {
  1034. if ($conditions === null && $this->id !== false) {
  1035. $conditions = array($this->alias . '.' . $this->primaryKey => $this->id);
  1036. }
  1037. if ($this->recursive >= 1) {
  1038. $recursive = -1;
  1039. } else {
  1040. $recursive = $this->recursive;
  1041. }
  1042. $fields = $name;
  1043. if ($data = $this->find('first', compact('conditions', 'fields', 'order', 'recursive'))) {
  1044. if (strpos($name, '.') === false) {
  1045. if (isset($data[$this->alias][$name])) {
  1046. return $data[$this->alias][$name];
  1047. }
  1048. } else {
  1049. $name = explode('.', $name);
  1050. if (isset($data[$name[0]][$name[1]])) {
  1051. return $data[$name[0]][$name[1]];
  1052. }
  1053. }
  1054. if (isset($data[0]) && count($data[0]) > 0) {
  1055. return array_shift($data[0]);
  1056. }
  1057. } else {
  1058. return false;
  1059. }
  1060. }
  1061. /**
  1062. * Saves the value of a single field to the database, based on the current
  1063. * model ID.
  1064. *
  1065. * @param string $name Name of the table field
  1066. * @param mixed $value Value of the field
  1067. * @param array $validate See $options param in Model::save(). Does not respect 'fieldList' key if passed
  1068. * @return boolean See Model::save()
  1069. * @access public
  1070. * @see Model::save()
  1071. * @link http://book.cakephp.org/view/1031/Saving-Your-Data
  1072. */
  1073. function saveField($name, $value, $validate = false) {
  1074. $id = $this->id;
  1075. $this->create(false);
  1076. if (is_array($validate)) {
  1077. $options = array_merge(array('validate' => false, 'fieldList' => array($name)), $validate);
  1078. } else {
  1079. $options = array('validate' => $validate, 'fieldList' => array($name));
  1080. }
  1081. return $this->save(array($this->alias => array($this->primaryKey => $id, $name => $value)), $options);
  1082. }
  1083. /**
  1084. * Saves model data (based on white-list, if supplied) to the database. By
  1085. * default, validation occurs before save.
  1086. *
  1087. * @param array $data Data to save.
  1088. * @param mixed $validate Either a boolean, or an array.
  1089. * If a boolean, indicates whether or not to validate before saving.
  1090. * If an array, allows control of validate, callbacks, and fieldList
  1091. * @param array $fieldList List of fields to allow to be written
  1092. * @return mixed On success Model::$data if its not empty or true, false on failure
  1093. * @access public
  1094. * @link http://book.cakephp.org/view/1031/Saving-Your-Data
  1095. */
  1096. function save($data = null, $validate = true, $fieldList = array()) {
  1097. $defaults = array('validate' => true, 'fieldList' => array(), 'callbacks' => true);
  1098. $_whitelist = $this->whitelist;
  1099. $fields = array();
  1100. if (!is_array($validate)) {
  1101. $options = array_merge($defaults, compact('validate', 'fieldList', 'callbacks'));
  1102. } else {
  1103. $options = array_merge($defaults, $validate);
  1104. }
  1105. if (!empty($options['fieldList'])) {
  1106. $this->whitelist = $options['fieldList'];
  1107. } elseif ($options['fieldList'] === null) {
  1108. $this->whitelist = array();
  1109. }
  1110. $this->set($data);
  1111. if (empty($this->data) && !$this->hasField(array('created', 'updated', 'modified'))) {
  1112. return false;
  1113. }
  1114. foreach (array('created', 'updated', 'modified') as $field) {
  1115. $keyPresentAndEmpty = (
  1116. isset($this->data[$this->alias]) &&
  1117. array_key_exists($field, $this->data[$this->alias]) &&
  1118. $this->data[$this->alias][$field] === null
  1119. );
  1120. if ($keyPresentAndEmpty) {
  1121. unset($this->data[$this->alias][$field]);
  1122. }
  1123. }
  1124. $exists = $this->exists();
  1125. $dateFields = array('modified', 'updated');
  1126. if (!$exists) {
  1127. $dateFields[] = 'created';
  1128. }
  1129. if (isset($this->data[$this->alias])) {
  1130. $fields = array_keys($this->data[$this->alias]);
  1131. }
  1132. if ($options['validate'] && !$this->validates($options)) {
  1133. $this->whitelist = $_whitelist;
  1134. return false;
  1135. }
  1136. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  1137. foreach ($dateFields as $updateCol) {
  1138. if ($this->hasField($updateCol) && !in_array($updateCol, $fields)) {
  1139. $default = array('formatter' => 'date');
  1140. $colType = array_merge($default, $db->columns[$this->getColumnType($updateCol)]);
  1141. if (!array_key_exists('format', $colType)) {
  1142. $time = strtotime('now');
  1143. } else {
  1144. $time = $colType['formatter']($colType['format']);
  1145. }
  1146. if (!empty($this->whitelist)) {
  1147. $this->whitelist[] = $updateCol;
  1148. }
  1149. $this->set($updateCol, $time);
  1150. }
  1151. }
  1152. if ($options['callbacks'] === true || $options['callbacks'] === 'before') {
  1153. $result = $this->Behaviors->trigger($this, 'beforeSave', array($options), array(
  1154. 'break' => true, 'breakOn' => false
  1155. ));
  1156. if (!$result || !$this->beforeSave($options)) {
  1157. $this->whitelist = $_whitelist;
  1158. return false;
  1159. }
  1160. }
  1161. if (empty($this->data[$this->alias][$this->primaryKey])) {
  1162. unset($this->data[$this->alias][$this->primaryKey]);
  1163. }
  1164. $fields = $values = array();
  1165. foreach ($this->data as $n => $v) {
  1166. if (isset($this->hasAndBelongsToMany[$n])) {
  1167. if (isset($v[$n])) {
  1168. $v = $v[$n];
  1169. }
  1170. $joined[$n] = $v;
  1171. } else {
  1172. if ($n === $this->alias) {
  1173. foreach (array('created', 'updated', 'modified') as $field) {
  1174. if (array_key_exists($field, $v) && empty($v[$field])) {
  1175. unset($v[$field]);
  1176. }
  1177. }
  1178. foreach ($v as $x => $y) {
  1179. if ($this->hasField($x) && (empty($this->whitelist) || in_array($x, $this->whitelist))) {
  1180. list($fields[], $values[]) = array($x, $y);
  1181. }
  1182. }
  1183. }
  1184. }
  1185. }
  1186. $count = count($fields);
  1187. if (!$exists && $count > 0) {
  1188. $this->id = false;
  1189. }
  1190. $success = true;
  1191. $created = false;
  1192. if ($count > 0) {
  1193. $cache = $this->_prepareUpdateFields(array_combine($fields, $values));
  1194. if (!empty($this->id)) {
  1195. $success = (bool)$db->update($this, $fields, $values);
  1196. } else {
  1197. $fInfo = $this->_schema[$this->primaryKey];
  1198. $isUUID = ($fInfo['length'] == 36 &&
  1199. ($fInfo['type'] === 'string' || $fInfo['type'] === 'binary')
  1200. );
  1201. if (empty($this->data[$this->alias][$this->primaryKey]) && $isUUID) {
  1202. if (array_key_exists($this->primaryKey, $this->data[$this->alias])) {
  1203. $j = array_search($this->primaryKey, $fields);
  1204. $values[$j] = String::uuid();
  1205. } else {
  1206. list($fields[], $values[]) = array($this->primaryKey, String::uuid());
  1207. }
  1208. }
  1209. if (!$db->create($this, $fields, $values)) {
  1210. $success = $created = false;
  1211. } else {
  1212. $created = true;
  1213. }
  1214. }
  1215. if ($success && !empty($this->belongsTo)) {
  1216. $this->updateCounterCache($cache, $created);
  1217. }
  1218. }
  1219. if (!empty($joined) && $success === true) {
  1220. $this->__saveMulti($joined, $this->id, $db);
  1221. }
  1222. if ($success && $count > 0) {
  1223. if (!empty($this->data)) {
  1224. $success = $this->data;
  1225. }
  1226. if ($options['callbacks'] === true || $options['callbacks'] === 'after') {
  1227. $this->Behaviors->trigger($this, 'afterSave', array($created, $options));
  1228. $this->afterSave($created);
  1229. }
  1230. if (!empty($this->data)) {
  1231. $success = Set::merge($success, $this->data);
  1232. }
  1233. $this->data = false;
  1234. $this->_clearCache();
  1235. $this->validationErrors = array();
  1236. }
  1237. $this->whitelist = $_whitelist;
  1238. return $success;
  1239. }
  1240. /**
  1241. * Saves model hasAndBelongsToMany data to the database.
  1242. *
  1243. * @param array $joined Data to save
  1244. * @param mixed $id ID of record in this model
  1245. * @access private
  1246. */
  1247. function __saveMulti($joined, $id, &$db) {
  1248. foreach ($joined as $assoc => $data) {
  1249. if (isset($this->hasAndBelongsToMany[$assoc])) {
  1250. list($join) = $this->joinModel($this->hasAndBelongsToMany[$assoc]['with']);
  1251. $isUUID = !empty($this->{$join}->primaryKey) && (
  1252. $this->{$join}->_schema[$this->{$join}->primaryKey]['length'] == 36 && (
  1253. $this->{$join}->_schema[$this->{$join}->primaryKey]['type'] === 'string' ||
  1254. $this->{$join}->_schema[$this->{$join}->primaryKey]['type'] === 'binary'
  1255. )
  1256. );
  1257. $newData = $newValues = array();
  1258. $primaryAdded = false;
  1259. $fields = array(
  1260. $db->name($this->hasAndBelongsToMany[$assoc]['foreignKey']),
  1261. $db->name($this->hasAndBelongsToMany[$assoc]['associationForeignKey'])
  1262. );
  1263. $idField = $db->name($this->{$join}->primaryKey);
  1264. if ($isUUID && !in_array($idField, $fields)) {
  1265. $fields[] = $idField;
  1266. $primaryAdded = true;
  1267. }
  1268. foreach ((array)$data as $row) {
  1269. if ((is_string($row) && (strlen($row) == 36 || strlen($row) == 16)) || is_numeric($row)) {
  1270. $values = array(
  1271. $db->value($id, $this->getColumnType($this->primaryKey)),
  1272. $db->value($row)
  1273. );
  1274. if ($isUUID && $primaryAdded) {
  1275. $values[] = $db->value(String::uuid());
  1276. }
  1277. $values = implode(',', $values);
  1278. $newValues[] = "({$values})";
  1279. unset($values);
  1280. } elseif (isset($row[$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
  1281. $newData[] = $row;
  1282. } elseif (isset($row[$join]) && isset($row[$join][$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
  1283. $newData[] = $row[$join];
  1284. }
  1285. }
  1286. if ($this->hasAndBelongsToMany[$assoc]['unique']) {
  1287. $conditions = array(
  1288. $join . '.' . $this->hasAndBelongsToMany[$assoc]['foreignKey'] => $id
  1289. );
  1290. if (!empty($this->hasAndBelongsToMany[$assoc]['conditions'])) {
  1291. $conditions = array_merge($conditions, (array)$this->hasAndBelongsToMany[$assoc]['conditions']);
  1292. }
  1293. $links = $this->{$join}->find('all', array(
  1294. 'conditions' => $conditions,
  1295. 'recursive' => empty($this->hasAndBelongsToMany[$assoc]['conditions']) ? -1 : 0,
  1296. 'fields' => $this->hasAndBelongsToMany[$assoc]['associationForeignKey']
  1297. ));
  1298. $associationForeignKey = "{$join}." . $this->hasAndBelongsToMany[$assoc]['associationForeignKey'];
  1299. $oldLinks = Set::extract($links, "{n}.{$associationForeignKey}");
  1300. if (!empty($oldLinks)) {
  1301. $conditions[$associationForeignKey] = $oldLinks;
  1302. $db->delete($this->{$join}, $conditions);
  1303. }
  1304. }
  1305. if (!empty($newData)) {
  1306. foreach ($newData as $data) {
  1307. $data[$this->hasAndBelongsToMany[$assoc]['foreignKey']] = $id;
  1308. $this->{$join}->create($data);
  1309. $this->{$join}->save();
  1310. }
  1311. }
  1312. if (!empty($newValues)) {
  1313. $fields = implode(',', $fields);
  1314. $db->insertMulti($this->{$join}, $fields, $newValues);
  1315. }
  1316. }
  1317. }
  1318. }
  1319. /**
  1320. * Updates the counter cache of belongsTo associations after a save or delete operation
  1321. *
  1322. * @param array $keys Optional foreign key data, defaults to the information $this->data
  1323. * @param boolean $created True if a new record was created, otherwise only associations with
  1324. * 'counterScope' defined get updated
  1325. * @return void
  1326. * @access public
  1327. */
  1328. function updateCounterCache($keys = array(), $created = false) {
  1329. $keys = empty($keys) ? $this->data[$this->alias] : $keys;
  1330. $keys['old'] = isset($keys['old']) ? $keys['old'] : array();
  1331. foreach ($this->belongsTo as $parent => $assoc) {
  1332. $foreignKey = $assoc['foreignKey'];
  1333. $fkQuoted = $this->escapeField($assoc['foreignKey']);
  1334. if (!empty($assoc['counterCache'])) {
  1335. if ($assoc['counterCache'] === true) {
  1336. $assoc['counterCache'] = Inflector::underscore($this->alias) . '_count';
  1337. }
  1338. if (!$this->{$parent}->hasField($assoc['counterCache'])) {
  1339. continue;
  1340. }
  1341. if (!array_key_exists($foreignKey, $keys)) {
  1342. $keys[$foreignKey] = $this->field($foreignKey);
  1343. }
  1344. $recursive = (isset($assoc['counterScope']) ? 1 : -1);
  1345. $conditions = ($recursive == 1) ? (array)$assoc['counterScope'] : array();
  1346. if (isset($keys['old'][$foreignKey])) {
  1347. if ($keys['old'][$foreignKey] != $keys[$foreignKey]) {
  1348. $conditions[$fkQuoted] = $keys['old'][$foreignKey];
  1349. $count = intval($this->find('count', compact('conditions', 'recursive')));
  1350. $this->{$parent}->updateAll(
  1351. array($assoc['counterCache'] => $count),
  1352. array($this->{$parent}->escapeField() => $keys['old'][$foreignKey])
  1353. );
  1354. }
  1355. }
  1356. $conditions[$fkQuoted] = $keys[$foreignKey];
  1357. if ($recursive == 1) {
  1358. $conditions = array_merge($conditions, (array)$assoc['counterScope']);
  1359. }
  1360. $count = intval($this->find('count', compact('conditions', 'recursive')));
  1361. $this->{$parent}->updateAll(
  1362. array($assoc['counterCache'] => $count),
  1363. array($this->{$parent}->escapeField() => $keys[$foreignKey])
  1364. );
  1365. }
  1366. }
  1367. }
  1368. /**
  1369. * Helper method for Model::updateCounterCache(). Checks the fields to be updated for
  1370. *
  1371. * @param array $data The fields of the record that will be updated
  1372. * @return array Returns updated foreign key values, along with an 'old' key containing the old
  1373. * values, or empty if no foreign keys are updated.
  1374. * @access protected
  1375. */
  1376. function _prepareUpdateFields($data) {
  1377. $foreignKeys = array();
  1378. foreach ($this->belongsTo as $assoc => $info) {
  1379. if ($info['counterCache']) {
  1380. $foreignKeys[$assoc] = $info['foreignKey'];
  1381. }
  1382. }
  1383. $included = array_intersect($foreignKeys, array_keys($data));
  1384. if (empty($included) || empty($this->id)) {
  1385. return array();
  1386. }
  1387. $old = $this->find('first', array(
  1388. 'conditions' => array($this->primaryKey => $this->id),
  1389. 'fields' => array_values($included),
  1390. 'recursive' => -1
  1391. ));
  1392. return array_merge($data, array('old' => $old[$this->alias]));
  1393. }
  1394. /**
  1395. * Saves multiple individual records for a single model; Also works with a single record, as well as
  1396. * all its associated records.
  1397. *
  1398. * #### Options
  1399. *
  1400. * - validate: Set to false to disable validation, true to validate each record before saving,
  1401. * 'first' to validate *all* records before any are saved (default),
  1402. * or 'only' to only validate the records, but not save them.
  1403. * - atomic: If true (default), will attempt to save all records in a single transaction.
  1404. * Should be set to false if database/table does not support transactions.
  1405. * - fieldList: Equivalent to the $fieldList parameter in Model::save()
  1406. *
  1407. * @param array $data Record data to save. This can be either a numerically-indexed array (for saving multiple
  1408. * records of the same type), or an array indexed by association name.
  1409. * @param array $options Options to use when saving record data, See $options above.
  1410. * @return mixed If atomic: True on success, or false on failure.
  1411. * Otherwise: array similar to the $data array passed, but values are set to true/false
  1412. * depending on whether each record saved successfully.
  1413. * @access public
  1414. * @link http://book.cakephp.org/view/1032/Saving-Related-Model-Data-hasOne-hasMany-belongsTo
  1415. * @link http://book.cakephp.org/view/1031/Saving-Your-Data
  1416. */
  1417. function saveAll($data = null, $options = array()) {
  1418. if (empty($data)) {
  1419. $data = $this->data;
  1420. }
  1421. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  1422. $options = array_merge(array('validate' => 'first', 'atomic' => true), $options);
  1423. $this->validationErrors = $validationErrors = array();
  1424. $validates = true;
  1425. $return = array();
  1426. if (empty($data) && $options['validate'] !== false) {
  1427. $result = $this->save($data, $options);
  1428. return !empty($result);
  1429. }
  1430. if ($options['atomic'] && $options['validate'] !== 'only') {
  1431. $transactionBegun = $db->begin($this);
  1432. }
  1433. if (Set::numeric(array_keys($data))) {
  1434. while ($validates) {
  1435. $return = array();
  1436. foreach ($data as $key => $record) {
  1437. if (!$currentValidates = $this->__save($record, $options)) {
  1438. $validationErrors[$key] = $this->validationErrors;
  1439. }
  1440. if ($options['validate'] === 'only' || $options['validate'] === 'first') {
  1441. $validating = true;
  1442. if ($options['atomic']) {
  1443. $validates = $validates && $currentValidates;
  1444. } else {
  1445. $validates = $currentValidates;
  1446. }
  1447. } else {
  1448. $validating = false;
  1449. $validates = $currentValidates;
  1450. }
  1451. if (!$options['atomic']) {
  1452. $return[] = $validates;
  1453. } elseif (!$validates && !$validating) {
  1454. break;
  1455. }
  1456. }
  1457. $this->validationErrors = $validationErrors;
  1458. switch (true) {
  1459. case ($options['validate'] === 'only'):
  1460. return ($options['atomic'] ? $validates : $return);
  1461. break;
  1462. case ($options['validate'] === 'first'):
  1463. $options['validate'] = true;
  1464. break;
  1465. default:
  1466. if ($options['atomic']) {
  1467. if ($validates) {
  1468. if ($transactionBegun) {
  1469. return $db->commit($this) !== false;
  1470. } else {
  1471. return true;
  1472. }
  1473. }
  1474. $db->rollback($this);
  1475. return false;
  1476. }
  1477. return $return;
  1478. break;
  1479. }
  1480. }
  1481. if ($options['atomic'] && !$validates) {
  1482. $db->rollback($this);
  1483. return false;
  1484. }
  1485. return $return;
  1486. }
  1487. $associations = $this->getAssociated();
  1488. while ($validates) {
  1489. foreach ($data as $association => $values) {
  1490. if (isset($associations[$association])) {
  1491. switch ($associations[$association]) {
  1492. case 'belongsTo':
  1493. if ($this->{$association}->__save($values, $options)) {
  1494. $data[$this->alias][$this->belongsTo[$association]['foreignKey']] = $this->{$association}->id;
  1495. } else {
  1496. $validationErrors[$association] = $this->{$association}->validationErrors;
  1497. $validates = false;
  1498. }
  1499. if (!$options['atomic']) {
  1500. $return[$association][] = $validates;
  1501. }
  1502. break;
  1503. }
  1504. }
  1505. }
  1506. if (!$this->__save($data, $options)) {
  1507. $validationErrors[$this->alias] = $this->validationErrors;
  1508. $validates = false;
  1509. }
  1510. if (!$options['atomic']) {
  1511. $return[$this->alias] = $validates;
  1512. }
  1513. $validating = ($options['validate'] === 'only' || $options['validate'] === 'first');
  1514. foreach ($data as $association => $values) {
  1515. if (!$validates && !$validating) {
  1516. break;
  1517. }
  1518. if (isset($associations[$association])) {
  1519. $type = $associations[$association];
  1520. switch ($type) {
  1521. case 'hasOne':
  1522. $values[$this->{$type}[$association]['foreignKey']] = $this->id;
  1523. if (!$this->{$association}->__save($values, $options)) {
  1524. $validationErrors[$association] = $this->{$association}->validationErrors;
  1525. $validates = false;
  1526. }
  1527. if (!$options['atomic']) {
  1528. $return[$association][] = $validates;
  1529. }
  1530. break;
  1531. case 'hasMany':
  1532. foreach ($values as $i => $value) {
  1533. $values[$i][$this->{$type}[$association]['foreignKey']] = $this->id;
  1534. }
  1535. $_options = array_merge($options, array('atomic' => false));
  1536. if ($_options['validate'] === 'first') {
  1537. $_options['validate'] = 'only';
  1538. }
  1539. $_return = $this->{$association}->saveAll($values, $_options);
  1540. if ($_return === false || (is_array($_return) && in_array(false, $_return, true))) {
  1541. $validationErrors[$association] = $this->{$association}->validationErrors;
  1542. $validates = false;
  1543. }
  1544. if (is_array($_return)) {
  1545. foreach ($_return as $val) {
  1546. if (!isset($return[$association])) {
  1547. $return[$association] = array();
  1548. } elseif (!is_array($return[$association])) {
  1549. $return[$association] = array($return[$association]);
  1550. }
  1551. $return[$association][] = $val;
  1552. }
  1553. } else {
  1554. $return[$association] = $_return;
  1555. }
  1556. break;
  1557. }
  1558. }
  1559. }
  1560. $this->validationErrors = $validationErrors;
  1561. if (isset($validationErrors[$this->alias])) {
  1562. $this->validationErrors = $validationErrors[$this->alias];
  1563. }
  1564. switch (true) {
  1565. case ($options['validate'] === 'only'):
  1566. return ($options['atomic'] ? $validates : $return);
  1567. break;
  1568. case ($options['validate'] === 'first'):
  1569. $options['validate'] = true;
  1570. $return = array();
  1571. break;
  1572. default:
  1573. if ($options['atomic']) {
  1574. if ($validates) {
  1575. if ($transactionBegun) {
  1576. return $db->commit($this) !== false;
  1577. } else {
  1578. return true;
  1579. }
  1580. } else {
  1581. $db->rollback($this);
  1582. }
  1583. }
  1584. return $return;
  1585. break;
  1586. }
  1587. if ($options['atomic'] && !$validates) {
  1588. $db->rollback($this);
  1589. return false;
  1590. }
  1591. }
  1592. }
  1593. /**
  1594. * Private helper method used by saveAll.
  1595. *
  1596. * @return boolean Success
  1597. * @access private
  1598. * @see Model::saveAll()
  1599. */
  1600. function __save($data, $options) {
  1601. if ($options['validate'] === 'first' || $options['validate'] === 'only') {
  1602. if (!($this->create($data) && $this->validates($options))) {
  1603. return false;
  1604. }
  1605. } elseif (!($this->create(null) !== null && $this->save($data, $options))) {
  1606. return false;
  1607. }
  1608. return true;
  1609. }
  1610. /**
  1611. * Updates multiple model records based on a set of conditions.
  1612. *
  1613. * @param array $fields Set of fields and values, indexed by fields.
  1614. * Fields are treated as SQL snippets, to insert literal values manually escape your data.
  1615. * @param mixed $conditions Conditions to match, true for all records
  1616. * @return boolean True on success, false on failure
  1617. * @access public
  1618. * @link http://book.cakephp.org/view/1031/Saving-Your-Data
  1619. */
  1620. function updateAll($fields, $conditions = true) {
  1621. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  1622. return $db->update($this, $fields, null, $conditions);
  1623. }
  1624. /**
  1625. * Removes record for given ID. If no ID is given, the current ID is used. Returns true on success.
  1626. *
  1627. * @param mixed $id ID of record to delete
  1628. * @param boolean $cascade Set to true to delete records that depend on this record
  1629. * @return boolean True on success
  1630. * @access public
  1631. * @link http://book.cakephp.org/view/1036/delete
  1632. */
  1633. function delete($id = null, $cascade = true) {
  1634. if (!empty($id)) {
  1635. $this->id = $id;
  1636. }
  1637. $id = $this->id;
  1638. if ($this->beforeDelete($cascade)) {
  1639. $filters = $this->Behaviors->trigger($this, 'beforeDelete', array($cascade), array(
  1640. 'break' => true, 'breakOn' => false
  1641. ));
  1642. if (!$filters || !$this->exists()) {
  1643. return false;
  1644. }
  1645. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  1646. $this->_deleteDependent($id, $cascade);
  1647. $this->_deleteLinks($id);
  1648. $this->id = $id;
  1649. if (!empty($this->belongsTo)) {
  1650. $keys = $this->find('first', array(
  1651. 'fields' => $this->__collectForeignKeys(),
  1652. 'conditions' => array($this->alias . '.' . $this->primaryKey => $id)
  1653. ));
  1654. }
  1655. if ($db->delete($this, array($this->alias . '.' . $this->primaryKey => $id))) {
  1656. if (!empty($this->belongsTo)) {
  1657. $this->updateCounterCache($keys[$this->alias]);
  1658. }
  1659. $this->Behaviors->trigger($this, 'afterDelete');
  1660. $this->afterDelete();
  1661. $this->_clearCache();
  1662. $this->id = false;
  1663. return true;
  1664. }
  1665. }
  1666. return false;
  1667. }
  1668. /**
  1669. * Cascades model deletes through associated hasMany and hasOne child records.
  1670. *
  1671. * @param string $id ID of record that was deleted
  1672. * @param boolean $cascade Set to true to delete records that depend on this record
  1673. * @return void
  1674. * @access protected
  1675. */
  1676. function _deleteDependent($id, $cascade) {
  1677. if (!empty($this->__backAssociation)) {
  1678. $savedAssociatons = $this->__backAssociation;
  1679. $this->__backAssociation = array();
  1680. }
  1681. foreach (array_merge($this->hasMany, $this->hasOne) as $assoc => $data) {
  1682. if ($data['dependent'] === true && $cascade === true) {
  1683. $model =& $this->{$assoc};
  1684. $conditions = array($model->escapeField($data['foreignKey']) => $id);
  1685. if ($data['conditions']) {
  1686. $conditions = array_merge((array)$data['conditions'], $conditions);
  1687. }
  1688. $model->recursive = -1;
  1689. if (isset($data['exclusive']) && $data['exclusive']) {
  1690. $model->deleteAll($conditions);
  1691. } else {
  1692. $records = $model->find('all', array(
  1693. 'conditions' => $conditions, 'fields' => $model->primaryKey
  1694. ));
  1695. if (!empty($records)) {
  1696. foreach ($records as $record) {
  1697. $model->delete($record[$model->alias][$model->primaryKey]);
  1698. }
  1699. }
  1700. }
  1701. }
  1702. }
  1703. if (isset($savedAssociatons)) {
  1704. $this->__backAssociation = $savedAssociatons;
  1705. }
  1706. }
  1707. /**
  1708. * Cascades model deletes through HABTM join keys.
  1709. *
  1710. * @param string $id ID of record that was deleted
  1711. * @return void
  1712. * @access protected
  1713. */
  1714. function _deleteLinks($id) {
  1715. foreach ($this->hasAndBelongsToMany as $assoc => $data) {
  1716. $joinModel = $data['with'];
  1717. $records = $this->{$joinModel}->find('all', array(
  1718. 'conditions' => array_merge(array($this->{$joinModel}->escapeField($data['foreignKey']) => $id)),
  1719. 'fields' => $this->{$joinModel}->primaryKey,
  1720. 'recursive' => -1
  1721. ));
  1722. if (!empty($records)) {
  1723. foreach ($records as $record) {
  1724. $this->{$joinModel}->delete($record[$this->{$joinModel}->alias][$this->{$joinModel}->primaryKey]);
  1725. }
  1726. }
  1727. }
  1728. }
  1729. /**
  1730. * Deletes multiple model records based on a set of conditions.
  1731. *
  1732. * @param mixed $conditions Conditions to match
  1733. * @param boolean $cascade Set to true to delete records that depend on this record
  1734. * @param boolean $callbacks Run callbacks
  1735. * @return boolean True on success, false on failure
  1736. * @access public
  1737. * @link http://book.cakephp.org/view/1038/deleteAll
  1738. */
  1739. function deleteAll($conditions, $cascade = true, $callbacks = false) {
  1740. if (empty($conditions)) {
  1741. return false;
  1742. }
  1743. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  1744. if (!$cascade && !$callbacks) {
  1745. return $db->delete($this, $conditions);
  1746. } else {
  1747. $ids = $this->find('all', array_merge(array(
  1748. 'fields' => "{$this->alias}.{$this->primaryKey}",
  1749. 'recursive' => 0), compact('conditions'))
  1750. );
  1751. if ($ids === false) {
  1752. return false;
  1753. }
  1754. $ids = Set::extract($ids, "{n}.{$this->alias}.{$this->primaryKey}");
  1755. if (empty($ids)) {
  1756. return true;
  1757. }
  1758. if ($callbacks) {
  1759. $_id = $this->id;
  1760. $result = true;
  1761. foreach ($ids as $id) {
  1762. $result = ($result && $this->delete($id, $cascade));
  1763. }
  1764. $this->id = $_id;
  1765. return $result;
  1766. } else {
  1767. foreach ($ids as $id) {
  1768. $this->_deleteLinks($id);
  1769. if ($cascade) {
  1770. $this->_deleteDependent($id, $cascade);
  1771. }
  1772. }
  1773. return $db->delete($this, array($this->alias . '.' . $this->primaryKey => $ids));
  1774. }
  1775. }
  1776. }
  1777. /**
  1778. * Collects foreign keys from associations.
  1779. *
  1780. * @return array
  1781. * @access private
  1782. */
  1783. function __collectForeignKeys($type = 'belongsTo') {
  1784. $result = array();
  1785. foreach ($this->{$type} as $assoc => $data) {
  1786. if (isset($data['foreignKey']) && is_string($data['foreignKey'])) {
  1787. $result[$assoc] = $data['foreignKey'];
  1788. }
  1789. }
  1790. return $result;
  1791. }
  1792. /**
  1793. * Returns true if a record with the currently set ID exists.
  1794. *
  1795. * Internally calls Model::getID() to obtain the current record ID to verify,
  1796. * and then performs a Model::find('count') on the currently configured datasource
  1797. * to ascertain the existence of the record in persistent storage.
  1798. *
  1799. * @return boolean True if such a record exists
  1800. * @access public
  1801. */
  1802. function exists() {
  1803. if ($this->getID() === false) {
  1804. return false;
  1805. }
  1806. $conditions = array($this->alias . '.' . $this->primaryKey => $this->getID());
  1807. $query = array('conditions' => $conditions, 'recursive' => -1, 'callbacks' => false);
  1808. return ($this->find('count', $query) > 0);
  1809. }
  1810. /**
  1811. * Returns true if a record that meets given conditions exists.
  1812. *
  1813. * @param array $conditions SQL conditions array
  1814. * @return boolean True if such a record exists
  1815. * @access public
  1816. */
  1817. function hasAny($conditions = null) {
  1818. return ($this->find('count', array('conditions' => $conditions, 'recursive' => -1)) != false);
  1819. }
  1820. /**
  1821. * Queries the datasource and returns a result set array.
  1822. *
  1823. * Also used to perform new-notation finds, where the first argument is type of find operation to perform
  1824. * (all / first / count / neighbors / list / threaded ),
  1825. * second parameter options for finding ( indexed array, including: 'conditions', 'limit',
  1826. * 'recursive', 'page', 'fields', 'offset', 'order')
  1827. *
  1828. * Eg:
  1829. * {{{
  1830. * find('all', array(
  1831. * 'conditions' => array('name' => 'Thomas Anderson'),
  1832. * 'fields' => array('name', 'email'),
  1833. * 'order' => 'field3 DESC',
  1834. * 'recursive' => 2,
  1835. * 'group' => 'type'
  1836. * ));
  1837. * }}}
  1838. *
  1839. * In addition to the standard query keys above, you can provide Datasource, and behavior specific
  1840. * keys. For example, when using a SQL based datasource you can use the joins key to specify additional
  1841. * joins that should be part of the query.
  1842. *
  1843. * {{{
  1844. * find('all', array(
  1845. * 'conditions' => array('name' => 'Thomas Anderson'),
  1846. * 'joins' => array(
  1847. * array(
  1848. * 'alias' => 'Thought',
  1849. * 'table' => 'thoughts',
  1850. * 'type' => 'LEFT',
  1851. * 'conditions' => '`Thought`.`person_id` = `Person`.`id`'
  1852. * )
  1853. * )
  1854. * ));
  1855. * }}}
  1856. *
  1857. * Behaviors and find types can also define custom finder keys which are passed into find().
  1858. *
  1859. * Specifying 'fields' for new-notation 'list':
  1860. *
  1861. * - If no fields are specified, then 'id' is used for key and 'model->displayField' is used for value.
  1862. * - If a single field is specified, 'id' is used for key and specified field is used for value.
  1863. * - If three fields are specified, they are used (in order) for key, value and group.
  1864. * - Otherwise, first and second fields are used for key and value.
  1865. *
  1866. * @param array $conditions SQL conditions array, or type of find operation (all / first / count /
  1867. * neighbors / list / threaded)
  1868. * @param mixed $fields Either a single string of a field name, or an array of field names, or
  1869. * options for matching
  1870. * @param string $order SQL ORDER BY conditions (e.g. "price DESC" or "name ASC")
  1871. * @param integer $recursive The number of levels deep to fetch associated records
  1872. * @return array Array of records
  1873. * @access public
  1874. * @link http://book.cakephp.org/view/1018/find
  1875. */
  1876. function find($conditions = null, $fields = array(), $order = null, $recursive = null) {
  1877. if (!is_string($conditions) || (is_string($conditions) && !array_key_exists($conditions, $this->_findMethods))) {
  1878. $type = 'first';
  1879. $query = array_merge(compact('conditions', 'fields', 'order', 'recursive'), array('limit' => 1));
  1880. } else {
  1881. list($type, $query) = array($conditions, $fields);
  1882. }
  1883. $this->findQueryType = $type;
  1884. $this->id = $this->getID();
  1885. $query = array_merge(
  1886. array(
  1887. 'conditions' => null, 'fields' => null, 'joins' => array(), 'limit' => null,
  1888. 'offset' => null, 'order' => null, 'page' => null, 'group' => null, 'callbacks' => true
  1889. ),
  1890. (array)$query
  1891. );
  1892. if ($type != 'all') {
  1893. if ($this->_findMethods[$type] === true) {
  1894. $query = $this->{'_find' . ucfirst($type)}('before', $query);
  1895. }
  1896. }
  1897. if (!is_numeric($query['page']) || intval($query['page']) < 1) {
  1898. $query['page'] = 1;
  1899. }
  1900. if ($query['page'] > 1 && !empty($query['limit'])) {
  1901. $query['offset'] = ($query['page'] - 1) * $query['limit'];
  1902. }
  1903. if ($query['order'] === null && $this->order !== null) {
  1904. $query['order'] = $this->order;
  1905. }
  1906. $query['order'] = array($query['order']);
  1907. if ($query['callbacks'] === true || $query['callbacks'] === 'before') {
  1908. $return = $this->Behaviors->trigger($this, 'beforeFind', array($query), array(
  1909. 'break' => true, 'breakOn' => false, 'modParams' => true
  1910. ));
  1911. $query = (is_array($return)) ? $return : $query;
  1912. if ($return === false) {
  1913. return null;
  1914. }
  1915. $return = $this->beforeFind($query);
  1916. $query = (is_array($return)) ? $return : $query;
  1917. if ($return === false) {
  1918. return null;
  1919. }
  1920. }
  1921. if (!$db =& ConnectionManager::getDataSource($this->useDbConfig)) {
  1922. return false;
  1923. }
  1924. $results = $db->read($this, $query);
  1925. $this->resetAssociations();
  1926. if ($query['callbacks'] === true || $query['callbacks'] === 'after') {
  1927. $results = $this->__filterResults($results);
  1928. }
  1929. $this->findQueryType = null;
  1930. if ($type === 'all') {
  1931. return $results;
  1932. } else {
  1933. if ($this->_findMethods[$type] === true) {
  1934. return $this->{'_find' . ucfirst($type)}('after', $query, $results);
  1935. }
  1936. }
  1937. }
  1938. /**
  1939. * Handles the before/after filter logic for find('first') operations. Only called by Model::find().
  1940. *
  1941. * @param string $state Either "before" or "after"
  1942. * @param array $query
  1943. * @param array $data
  1944. * @return array
  1945. * @access protected
  1946. * @see Model::find()
  1947. */
  1948. function _findFirst($state, $query, $results = array()) {
  1949. if ($state == 'before') {
  1950. $query['limit'] = 1;
  1951. return $query;
  1952. } elseif ($state == 'after') {
  1953. if (empty($results[0])) {
  1954. return false;
  1955. }
  1956. return $results[0];
  1957. }
  1958. }
  1959. /**
  1960. * Handles the before/after filter logic for find('count') operations. Only called by Model::find().
  1961. *
  1962. * @param string $state Either "before" or "after"
  1963. * @param array $query
  1964. * @param array $data
  1965. * @return int The number of records found, or false
  1966. * @access protected
  1967. * @see Model::find()
  1968. */
  1969. function _findCount($state, $query, $results = array()) {
  1970. if ($state == 'before') {
  1971. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  1972. if (empty($query['fields'])) {
  1973. $query['fields'] = $db->calculate($this, 'count');
  1974. } elseif (is_string($query['fields']) && !preg_match('/count/i', $query['fields'])) {
  1975. $query['fields'] = $db->calculate($this, 'count', array(
  1976. $db->expression($query['fields']), 'count'
  1977. ));
  1978. }
  1979. $query['order'] = false;
  1980. return $query;
  1981. } elseif ($state == 'after') {
  1982. if (isset($results[0][0]['count'])) {
  1983. return intval($results[0][0]['count']);
  1984. } elseif (isset($results[0][$this->alias]['count'])) {
  1985. return intval($results[0][$this->alias]['count']);
  1986. }
  1987. return false;
  1988. }
  1989. }
  1990. /**
  1991. * Handles the before/after filter logic for find('list') operations. Only called by Model::find().
  1992. *
  1993. * @param string $state Either "before" or "after"
  1994. * @param array $query
  1995. * @param array $data
  1996. * @return array Key/value pairs of primary keys/display field values of all records found
  1997. * @access protected
  1998. * @see Model::find()
  1999. */
  2000. function _findList($state, $query, $results = array()) {
  2001. if ($state == 'before') {
  2002. if (empty($query['fields'])) {
  2003. $query['fields'] = array("{$this->alias}.{$this->primaryKey}", "{$this->alias}.{$this->displayField}");
  2004. $list = array("{n}.{$this->alias}.{$this->primaryKey}", "{n}.{$this->alias}.{$this->displayField}", null);
  2005. } else {
  2006. if (!is_array($query['fields'])) {
  2007. $query['fields'] = String::tokenize($query['fields']);
  2008. }
  2009. if (count($query['fields']) == 1) {
  2010. if (strpos($query['fields'][0], '.') === false) {
  2011. $query['fields'][0] = $this->alias . '.' . $query['fields'][0];
  2012. }
  2013. $list = array("{n}.{$this->alias}.{$this->primaryKey}", '{n}.' . $query['fields'][0], null);
  2014. $query['fields'] = array("{$this->alias}.{$this->primaryKey}", $query['fields'][0]);
  2015. } elseif (count($query['fields']) == 3) {
  2016. for ($i = 0; $i < 3; $i++) {
  2017. if (strpos($query['fields'][$i], '.') === false) {
  2018. $query['fields'][$i] = $this->alias . '.' . $query['fields'][$i];
  2019. }
  2020. }
  2021. $list = array('{n}.' . $query['fields'][0], '{n}.' . $query['fields'][1], '{n}.' . $query['fields'][2]);
  2022. } else {
  2023. for ($i = 0; $i < 2; $i++) {
  2024. if (strpos($query['fields'][$i], '.') === false) {
  2025. $query['fields'][$i] = $this->alias . '.' . $query['fields'][$i];
  2026. }
  2027. }
  2028. $list = array('{n}.' . $query['fields'][0], '{n}.' . $query['fields'][1], null);
  2029. }
  2030. }
  2031. if (!isset($query['recursive']) || $query['recursive'] === null) {
  2032. $query['recursive'] = -1;
  2033. }
  2034. list($query['list']['keyPath'], $query['list']['valuePath'], $query['list']['groupPath']) = $list;
  2035. return $query;
  2036. } elseif ($state == 'after') {
  2037. if (empty($results)) {
  2038. return array();
  2039. }
  2040. $lst = $query['list'];
  2041. return Set::combine($results, $lst['keyPath'], $lst['valuePath'], $lst['groupPath']);
  2042. }
  2043. }
  2044. /**
  2045. * Detects the previous field's value, then uses logic to find the 'wrapping'
  2046. * rows and return them.
  2047. *
  2048. * @param string $state Either "before" or "after"
  2049. * @param mixed $query
  2050. * @param array $results
  2051. * @return array
  2052. * @access protected
  2053. */
  2054. function _findNeighbors($state, $query, $results = array()) {
  2055. if ($state == 'before') {
  2056. $query = array_merge(array('recursive' => 0), $query);
  2057. extract($query);
  2058. $conditions = (array)$conditions;
  2059. if (isset($field) && isset($value)) {
  2060. if (strpos($field, '.') === false) {
  2061. $field = $this->alias . '.' . $field;
  2062. }
  2063. } else {
  2064. $field = $this->alias . '.' . $this->primaryKey;
  2065. $value = $this->id;
  2066. }
  2067. $query['conditions'] = array_merge($conditions, array($field . ' <' => $value));
  2068. $query['order'] = $field . ' DESC';
  2069. $query['limit'] = 1;
  2070. $query['field'] = $field;
  2071. $query['value'] = $value;
  2072. return $query;
  2073. } elseif ($state == 'after') {
  2074. extract($query);
  2075. unset($query['conditions'][$field . ' <']);
  2076. $return = array();
  2077. if (isset($results[0])) {
  2078. $prevVal = Set::extract('/' . str_replace('.', '/', $field), $results[0]);
  2079. $query['conditions'][$field . ' >='] = $prevVal[0];
  2080. $query['conditions'][$field . ' !='] = $value;
  2081. $query['limit'] = 2;
  2082. } else {
  2083. $return['prev'] = null;
  2084. $query['conditions'][$field . ' >'] = $value;
  2085. $query['limit'] = 1;
  2086. }
  2087. $query['order'] = $field . ' ASC';
  2088. $return2 = $this->find('all', $query);
  2089. if (!array_key_exists('prev', $return)) {
  2090. $return['prev'] = $return2[0];
  2091. }
  2092. if (count($return2) == 2) {
  2093. $return['next'] = $return2[1];
  2094. } elseif (count($return2) == 1 && !$return['prev']) {
  2095. $return['next'] = $return2[0];
  2096. } else {
  2097. $return['next'] = null;
  2098. }
  2099. return $return;
  2100. }
  2101. }
  2102. /**
  2103. * In the event of ambiguous results returned (multiple top level results, with different parent_ids)
  2104. * top level results with different parent_ids to the first result will be dropped
  2105. *
  2106. * @param mixed $state
  2107. * @param mixed $query
  2108. * @param array $results
  2109. * @return array Threaded results
  2110. * @access protected
  2111. */
  2112. function _findThreaded($state, $query, $results = array()) {
  2113. if ($state == 'before') {
  2114. return $query;
  2115. } elseif ($state == 'after') {
  2116. $return = $idMap = array();
  2117. $ids = Set::extract($results, '{n}.' . $this->alias . '.' . $this->primaryKey);
  2118. foreach ($results as $result) {
  2119. $result['children'] = array();
  2120. $id = $result[$this->alias][$this->primaryKey];
  2121. $parentId = $result[$this->alias]['parent_id'];
  2122. if (isset($idMap[$id]['children'])) {
  2123. $idMap[$id] = array_merge($result, (array)$idMap[$id]);
  2124. } else {
  2125. $idMap[$id] = array_merge($result, array('children' => array()));
  2126. }
  2127. if (!$parentId || !in_array($parentId, $ids)) {
  2128. $return[] =& $idMap[$id];
  2129. } else {
  2130. $idMap[$parentId]['children'][] =& $idMap[$id];
  2131. }
  2132. }
  2133. if (count($return) > 1) {
  2134. $ids = array_unique(Set::extract('/' . $this->alias . '/parent_id', $return));
  2135. if (count($ids) > 1) {
  2136. $root = $return[0][$this->alias]['parent_id'];
  2137. foreach ($return as $key => $value) {
  2138. if ($value[$this->alias]['parent_id'] != $root) {
  2139. unset($return[$key]);
  2140. }
  2141. }
  2142. }
  2143. }
  2144. return $return;
  2145. }
  2146. }
  2147. /**
  2148. * Passes query results through model and behavior afterFilter() methods.
  2149. *
  2150. * @param array Results to filter
  2151. * @param boolean $primary If this is the primary model results (results from model where the find operation was performed)
  2152. * @return array Set of filtered results
  2153. * @access private
  2154. */
  2155. function __filterResults($results, $primary = true) {
  2156. $return = $this->Behaviors->trigger($this, 'afterFind', array($results, $primary), array('modParams' => true));
  2157. if ($return !== true) {
  2158. $results = $return;
  2159. }
  2160. return $this->afterFind($results, $primary);
  2161. }
  2162. /**
  2163. * This resets the association arrays for the model back
  2164. * to those originally defined in the model. Normally called at the end
  2165. * of each call to Model::find()
  2166. *
  2167. * @return boolean Success
  2168. * @access public
  2169. */
  2170. function resetAssociations() {
  2171. if (!empty($this->__backAssociation)) {
  2172. foreach ($this->__associations as $type) {
  2173. if (isset($this->__backAssociation[$type])) {
  2174. $this->{$type} = $this->__backAssociation[$type];
  2175. }
  2176. }
  2177. $this->__backAssociation = array();
  2178. }
  2179. foreach ($this->__associations as $type) {
  2180. foreach ($this->{$type} as $key => $name) {
  2181. if (!empty($this->{$key}->__backAssociation)) {
  2182. $this->{$key}->resetAssociations();
  2183. }
  2184. }
  2185. }
  2186. $this->__backAssociation = array();
  2187. return true;
  2188. }
  2189. /**
  2190. * Returns false if any fields passed match any (by default, all if $or = false) of their matching values.
  2191. *
  2192. * @param array $fields Field/value pairs to search (if no values specified, they are pulled from $this->data)
  2193. * @param boolean $or If false, all fields specified must match in order for a false return value
  2194. * @return boolean False if any records matching any fields are found
  2195. * @access public
  2196. */
  2197. function isUnique($fields, $or = true) {
  2198. if (!is_array($fields)) {
  2199. $fields = func_get_args();
  2200. if (is_bool($fields[count($fields) - 1])) {
  2201. $or = $fields[count($fields) - 1];
  2202. unset($fields[count($fields) - 1]);
  2203. }
  2204. }
  2205. foreach ($fields as $field => $value) {
  2206. if (is_numeric($field)) {
  2207. unset($fields[$field]);
  2208. $field = $value;
  2209. if (isset($this->data[$this->alias][$field])) {
  2210. $value = $this->data[$this->alias][$field];
  2211. } else {
  2212. $value = null;
  2213. }
  2214. }
  2215. if (strpos($field, '.') === false) {
  2216. unset($fields[$field]);
  2217. $fields[$this->alias . '.' . $field] = $value;
  2218. }
  2219. }
  2220. if ($or) {
  2221. $fields = array('or' => $fields);
  2222. }
  2223. if (!empty($this->id)) {
  2224. $fields[$this->alias . '.' . $this->primaryKey . ' !='] = $this->id;
  2225. }
  2226. return ($this->find('count', array('conditions' => $fields, 'recursive' => -1)) == 0);
  2227. }
  2228. /**
  2229. * Returns a resultset for a given SQL statement. Custom SQL queries should be performed with this method.
  2230. *
  2231. * @param string $sql SQL statement
  2232. * @return array Resultset
  2233. * @access public
  2234. * @link http://book.cakephp.org/view/1027/query
  2235. */
  2236. function query() {
  2237. $params = func_get_args();
  2238. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  2239. return call_user_func_array(array(&$db, 'query'), $params);
  2240. }
  2241. /**
  2242. * Returns true if all fields pass validation. Will validate hasAndBelongsToMany associations
  2243. * that use the 'with' key as well. Since __saveMulti is incapable of exiting a save operation.
  2244. *
  2245. * Will validate the currently set data. Use Model::set() or Model::create() to set the active data.
  2246. *
  2247. * @param string $options An optional array of custom options to be made available in the beforeValidate callback
  2248. * @return boolean True if there are no errors
  2249. * @access public
  2250. * @link http://book.cakephp.org/view/1182/Validating-Data-from-the-Controller
  2251. */
  2252. function validates($options = array()) {
  2253. $errors = $this->invalidFields($options);
  2254. if (empty($errors) && $errors !== false) {
  2255. $errors = $this->__validateWithModels($options);
  2256. }
  2257. if (is_array($errors)) {
  2258. return count($errors) === 0;
  2259. }
  2260. return $errors;
  2261. }
  2262. /**
  2263. * Returns an array of fields that have failed validation. On the current model.
  2264. *
  2265. * @param string $options An optional array of custom options to be made available in the beforeValidate callback
  2266. * @return array Array of invalid fields
  2267. * @see Model::validates()
  2268. * @access public
  2269. * @link http://book.cakephp.org/view/1182/Validating-Data-from-the-Controller
  2270. */
  2271. function invalidFields($options = array()) {
  2272. if (
  2273. !$this->Behaviors->trigger(
  2274. $this,
  2275. 'beforeValidate',
  2276. array($options),
  2277. array('break' => true, 'breakOn' => false)
  2278. ) ||
  2279. $this->beforeValidate($options) === false
  2280. ) {
  2281. return false;
  2282. }
  2283. if (!isset($this->validate) || empty($this->validate)) {
  2284. return $this->validationErrors;
  2285. }
  2286. $data = $this->data;
  2287. $methods = array_map('strtolower', get_class_methods($this));
  2288. $behaviorMethods = array_keys($this->Behaviors->methods());
  2289. if (isset($data[$this->alias])) {
  2290. $data = $data[$this->alias];
  2291. } elseif (!is_array($data)) {
  2292. $data = array();
  2293. }
  2294. $Validation =& Validation::getInstance();
  2295. $exists = $this->exists();
  2296. $_validate = $this->validate;
  2297. $whitelist = $this->whitelist;
  2298. if (!empty($options['fieldList'])) {
  2299. $whitelist = $options['fieldList'];
  2300. }
  2301. if (!empty($whitelist)) {
  2302. $validate = array();
  2303. foreach ((array)$whitelist as $f) {
  2304. if (!empty($this->validate[$f])) {
  2305. $validate[$f] = $this->validate[$f];
  2306. }
  2307. }
  2308. $this->validate = $validate;
  2309. }
  2310. foreach ($this->validate as $fieldName => $ruleSet) {
  2311. if (!is_array($ruleSet) || (is_array($ruleSet) && isset($ruleSet['rule']))) {
  2312. $ruleSet = array($ruleSet);
  2313. }
  2314. $default = array(
  2315. 'allowEmpty' => null,
  2316. 'required' => null,
  2317. 'rule' => 'blank',
  2318. 'last' => false,
  2319. 'on' => null
  2320. );
  2321. foreach ($ruleSet as $index => $validator) {
  2322. if (!is_array($validator)) {
  2323. $validator = array('rule' => $validator);
  2324. }
  2325. $validator = array_merge($default, $validator);
  2326. if (isset($validator['message'])) {
  2327. $message = $validator['message'];
  2328. } else {
  2329. $message = __('This field cannot be left blank', true);
  2330. }
  2331. if (
  2332. empty($validator['on']) || ($validator['on'] == 'create' &&
  2333. !$exists) || ($validator['on'] == 'update' && $exists
  2334. )) {
  2335. $required = (
  2336. (!isset($data[$fieldName]) && $validator['required'] === true) ||
  2337. (
  2338. isset($data[$fieldName]) && (empty($data[$fieldName]) &&
  2339. !is_numeric($data[$fieldName])) && $validator['allowEmpty'] === false
  2340. )
  2341. );
  2342. if ($required) {
  2343. $this->invalidate($fieldName, $message);
  2344. if ($validator['last']) {
  2345. break;
  2346. }
  2347. } elseif (array_key_exists($fieldName, $data)) {
  2348. if (empty($data[$fieldName]) && $data[$fieldName] != '0' && $validator['allowEmpty'] === true) {
  2349. break;
  2350. }
  2351. if (is_array($validator['rule'])) {
  2352. $rule = $validator['rule'][0];
  2353. unset($validator['rule'][0]);
  2354. $ruleParams = array_merge(array($data[$fieldName]), array_values($validator['rule']));
  2355. } else {
  2356. $rule = $validator['rule'];
  2357. $ruleParams = array($data[$fieldName]);
  2358. }
  2359. $valid = true;
  2360. if (in_array(strtolower($rule), $methods)) {
  2361. $ruleParams[] = $validator;
  2362. $ruleParams[0] = array($fieldName => $ruleParams[0]);
  2363. $valid = $this->dispatchMethod($rule, $ruleParams);
  2364. } elseif (in_array($rule, $behaviorMethods) || in_array(strtolower($rule), $behaviorMethods)) {
  2365. $ruleParams[] = $validator;
  2366. $ruleParams[0] = array($fieldName => $ruleParams[0]);
  2367. $valid = $this->Behaviors->dispatchMethod($this, $rule, $ruleParams);
  2368. } elseif (method_exists($Validation, $rule)) {
  2369. $valid = $Validation->dispatchMethod($rule, $ruleParams);
  2370. } elseif (!is_array($validator['rule'])) {
  2371. $valid = preg_match($rule, $data[$fieldName]);
  2372. } elseif (Configure::read('debug') > 0) {
  2373. trigger_error(sprintf(__('Could not find validation handler %s for %s', true), $rule, $fieldName), E_USER_WARNING);
  2374. }
  2375. if (!$valid || (is_string($valid) && strlen($valid) > 0)) {
  2376. if (is_string($valid) && strlen($valid) > 0) {
  2377. $validator['message'] = $valid;
  2378. } elseif (!isset($validator['message'])) {
  2379. if (is_string($index)) {
  2380. $validator['message'] = $index;
  2381. } elseif (is_numeric($index) && count($ruleSet) > 1) {
  2382. $validator['message'] = $index + 1;
  2383. } else {
  2384. $validator['message'] = $message;
  2385. }
  2386. }
  2387. $this->invalidate($fieldName, $validator['message']);
  2388. if ($validator['last']) {
  2389. break;
  2390. }
  2391. }
  2392. }
  2393. }
  2394. }
  2395. }
  2396. $this->validate = $_validate;
  2397. return $this->validationErrors;
  2398. }
  2399. /**
  2400. * Runs validation for hasAndBelongsToMany associations that have 'with' keys
  2401. * set. And data in the set() data set.
  2402. *
  2403. * @param array $options Array of options to use on Valdation of with models
  2404. * @return boolean Failure of validation on with models.
  2405. * @access private
  2406. * @see Model::validates()
  2407. */
  2408. function __validateWithModels($options) {
  2409. $valid = true;
  2410. foreach ($this->hasAndBelongsToMany as $assoc => $association) {
  2411. if (empty($association['with']) || !isset($this->data[$assoc])) {
  2412. continue;
  2413. }
  2414. list($join) = $this->joinModel($this->hasAndBelongsToMany[$assoc]['with']);
  2415. $data = $this->data[$assoc];
  2416. $newData = array();
  2417. foreach ((array)$data as $row) {
  2418. if (isset($row[$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
  2419. $newData[] = $row;
  2420. } elseif (isset($row[$join]) && isset($row[$join][$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
  2421. $newData[] = $row[$join];
  2422. }
  2423. }
  2424. if (empty($newData)) {
  2425. continue;
  2426. }
  2427. foreach ($newData as $data) {
  2428. $data[$this->hasAndBelongsToMany[$assoc]['foreignKey']] = $this->id;
  2429. $this->{$join}->create($data);
  2430. $valid = ($valid && $this->{$join}->validates($options));
  2431. }
  2432. }
  2433. return $valid;
  2434. }
  2435. /**
  2436. * Marks a field as invalid, optionally setting the name of validation
  2437. * rule (in case of multiple validation for field) that was broken.
  2438. *
  2439. * @param string $field The name of the field to invalidate
  2440. * @param mixed $value Name of validation rule that was not failed, or validation message to
  2441. * be returned. If no validation key is provided, defaults to true.
  2442. * @access public
  2443. */
  2444. function invalidate($field, $value = true) {
  2445. if (!is_array($this->validationErrors)) {
  2446. $this->validationErrors = array();
  2447. }
  2448. $this->validationErrors[$field] = $value;
  2449. }
  2450. /**
  2451. * Returns true if given field name is a foreign key in this model.
  2452. *
  2453. * @param string $field Returns true if the input string ends in "_id"
  2454. * @return boolean True if the field is a foreign key listed in the belongsTo array.
  2455. * @access public
  2456. */
  2457. function isForeignKey($field) {
  2458. $foreignKeys = array();
  2459. if (!empty($this->belongsTo)) {
  2460. foreach ($this->belongsTo as $assoc => $data) {
  2461. $foreignKeys[] = $data['foreignKey'];
  2462. }
  2463. }
  2464. return in_array($field, $foreignKeys);
  2465. }
  2466. /**
  2467. * Escapes the field name and prepends the model name. Escaping is done according to the
  2468. * current database driver's rules.
  2469. *
  2470. * @param string $field Field to escape (e.g: id)
  2471. * @param string $alias Alias for the model (e.g: Post)
  2472. * @return string The name of the escaped field for this Model (i.e. id becomes `Post`.`id`).
  2473. * @access public
  2474. */
  2475. function escapeField($field = null, $alias = null) {
  2476. if (empty($alias)) {
  2477. $alias = $this->alias;
  2478. }
  2479. if (empty($field)) {
  2480. $field = $this->primaryKey;
  2481. }
  2482. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  2483. if (strpos($field, $db->name($alias) . '.') === 0) {
  2484. return $field;
  2485. }
  2486. return $db->name($alias . '.' . $field);
  2487. }
  2488. /**
  2489. * Returns the current record's ID
  2490. *
  2491. * @param integer $list Index on which the composed ID is located
  2492. * @return mixed The ID of the current record, false if no ID
  2493. * @access public
  2494. */
  2495. function getID($list = 0) {
  2496. if (empty($this->id) || (is_array($this->id) && isset($this->id[0]) && empty($this->id[0]))) {
  2497. return false;
  2498. }
  2499. if (!is_array($this->id)) {
  2500. return $this->id;
  2501. }
  2502. if (empty($this->id)) {
  2503. return false;
  2504. }
  2505. if (isset($this->id[$list]) && !empty($this->id[$list])) {
  2506. return $this->id[$list];
  2507. } elseif (isset($this->id[$list])) {
  2508. return false;
  2509. }
  2510. foreach ($this->id as $id) {
  2511. return $id;
  2512. }
  2513. return false;
  2514. }
  2515. /**
  2516. * Returns the ID of the last record this model inserted.
  2517. *
  2518. * @return mixed Last inserted ID
  2519. * @access public
  2520. */
  2521. function getLastInsertID() {
  2522. return $this->getInsertID();
  2523. }
  2524. /**
  2525. * Returns the ID of the last record this model inserted.
  2526. *
  2527. * @return mixed Last inserted ID
  2528. * @access public
  2529. */
  2530. function getInsertID() {
  2531. return $this->__insertID;
  2532. }
  2533. /**
  2534. * Sets the ID of the last record this model inserted
  2535. *
  2536. * @param mixed Last inserted ID
  2537. * @access public
  2538. */
  2539. function setInsertID($id) {
  2540. $this->__insertID = $id;
  2541. }
  2542. /**
  2543. * Returns the number of rows returned from the last query.
  2544. *
  2545. * @return int Number of rows
  2546. * @access public
  2547. */
  2548. function getNumRows() {
  2549. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  2550. return $db->lastNumRows();
  2551. }
  2552. /**
  2553. * Returns the number of rows affected by the last query.
  2554. *
  2555. * @return int Number of rows
  2556. * @access public
  2557. */
  2558. function getAffectedRows() {
  2559. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  2560. return $db->lastAffected();
  2561. }
  2562. /**
  2563. * Sets the DataSource to which this model is bound.
  2564. *
  2565. * @param string $dataSource The name of the DataSource, as defined in app/config/database.php
  2566. * @return boolean True on success
  2567. * @access public
  2568. */
  2569. function setDataSource($dataSource = null) {
  2570. $oldConfig = $this->useDbConfig;
  2571. if ($dataSource != null) {
  2572. $this->useDbConfig = $dataSource;
  2573. }
  2574. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  2575. if (!empty($oldConfig) && isset($db->config['prefix'])) {
  2576. $oldDb =& ConnectionManager::getDataSource($oldConfig);
  2577. if (!isset($this->tablePrefix) || (!isset($oldDb->config['prefix']) || $this->tablePrefix == $oldDb->config['prefix'])) {
  2578. $this->tablePrefix = $db->config['prefix'];
  2579. }
  2580. } elseif (isset($db->config['prefix'])) {
  2581. $this->tablePrefix = $db->config['prefix'];
  2582. }
  2583. if (empty($db) || !is_object($db)) {
  2584. return $this->cakeError('missingConnection', array(array('code' => 500, 'className' => $this->alias)));
  2585. }
  2586. }
  2587. /**
  2588. * Gets the DataSource to which this model is bound.
  2589. * Not safe for use with some versions of PHP4, because this class is overloaded.
  2590. *
  2591. * @return object A DataSource object
  2592. * @access public
  2593. */
  2594. function &getDataSource() {
  2595. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  2596. return $db;
  2597. }
  2598. /**
  2599. * Gets all the models with which this model is associated.
  2600. *
  2601. * @param string $type Only result associations of this type
  2602. * @return array Associations
  2603. * @access public
  2604. */
  2605. function getAssociated($type = null) {
  2606. if ($type == null) {
  2607. $associated = array();
  2608. foreach ($this->__associations as $assoc) {
  2609. if (!empty($this->{$assoc})) {
  2610. $models = array_keys($this->{$assoc});
  2611. foreach ($models as $m) {
  2612. $associated[$m] = $assoc;
  2613. }
  2614. }
  2615. }
  2616. return $associated;
  2617. } elseif (in_array($type, $this->__associations)) {
  2618. if (empty($this->{$type})) {
  2619. return array();
  2620. }
  2621. return array_keys($this->{$type});
  2622. } else {
  2623. $assoc = array_merge(
  2624. $this->hasOne,
  2625. $this->hasMany,
  2626. $this->belongsTo,
  2627. $this->hasAndBelongsToMany
  2628. );
  2629. if (array_key_exists($type, $assoc)) {
  2630. foreach ($this->__associations as $a) {
  2631. if (isset($this->{$a}[$type])) {
  2632. $assoc[$type]['association'] = $a;
  2633. break;
  2634. }
  2635. }
  2636. return $assoc[$type];
  2637. }
  2638. return null;
  2639. }
  2640. }
  2641. /**
  2642. * Gets the name and fields to be used by a join model. This allows specifying join fields
  2643. * in the association definition.
  2644. *
  2645. * @param object $model The model to be joined
  2646. * @param mixed $with The 'with' key of the model association
  2647. * @param array $keys Any join keys which must be merged with the keys queried
  2648. * @return array
  2649. * @access public
  2650. */
  2651. function joinModel($assoc, $keys = array()) {
  2652. if (is_string($assoc)) {
  2653. return array($assoc, array_keys($this->{$assoc}->schema()));
  2654. } elseif (is_array($assoc)) {
  2655. $with = key($assoc);
  2656. return array($with, array_unique(array_merge($assoc[$with], $keys)));
  2657. }
  2658. trigger_error(
  2659. sprintf(__('Invalid join model settings in %s', true), $model->alias),
  2660. E_USER_WARNING
  2661. );
  2662. }
  2663. /**
  2664. * Called before each find operation. Return false if you want to halt the find
  2665. * call, otherwise return the (modified) query data.
  2666. *
  2667. * @param array $queryData Data used to execute this query, i.e. conditions, order, etc.
  2668. * @return mixed true if the operation should continue, false if it should abort; or, modified
  2669. * $queryData to continue with new $queryData
  2670. * @access public
  2671. * @link http://book.cakephp.org/view/1048/Callback-Methods#beforeFind-1049
  2672. */
  2673. function beforeFind($queryData) {
  2674. return true;
  2675. }
  2676. /**
  2677. * Called after each find operation. Can be used to modify any results returned by find().
  2678. * Return value should be the (modified) results.
  2679. *
  2680. * @param mixed $results The results of the find operation
  2681. * @param boolean $primary Whether this model is being queried directly (vs. being queried as an association)
  2682. * @return mixed Result of the find operation
  2683. * @access public
  2684. * @link http://book.cakephp.org/view/1048/Callback-Methods#afterFind-1050
  2685. */
  2686. function afterFind($results, $primary = false) {
  2687. return $results;
  2688. }
  2689. /**
  2690. * Called before each save operation, after validation. Return a non-true result
  2691. * to halt the save.
  2692. *
  2693. * @return boolean True if the operation should continue, false if it should abort
  2694. * @access public
  2695. * @link http://book.cakephp.org/view/1048/Callback-Methods#beforeSave-1052
  2696. */
  2697. function beforeSave($options = array()) {
  2698. return true;
  2699. }
  2700. /**
  2701. * Called after each successful save operation.
  2702. *
  2703. * @param boolean $created True if this save created a new record
  2704. * @access public
  2705. * @link http://book.cakephp.org/view/1048/Callback-Methods#afterSave-1053
  2706. */
  2707. function afterSave($created) {
  2708. }
  2709. /**
  2710. * Called before every deletion operation.
  2711. *
  2712. * @param boolean $cascade If true records that depend on this record will also be deleted
  2713. * @return boolean True if the operation should continue, false if it should abort
  2714. * @access public
  2715. * @link http://book.cakephp.org/view/1048/Callback-Methods#beforeDelete-1054
  2716. */
  2717. function beforeDelete($cascade = true) {
  2718. return true;
  2719. }
  2720. /**
  2721. * Called after every deletion operation.
  2722. *
  2723. * @access public
  2724. * @link http://book.cakephp.org/view/1048/Callback-Methods#afterDelete-1055
  2725. */
  2726. function afterDelete() {
  2727. }
  2728. /**
  2729. * Called during validation operations, before validation. Please note that custom
  2730. * validation rules can be defined in $validate.
  2731. *
  2732. * @return boolean True if validate operation should continue, false to abort
  2733. * @param $options array Options passed from model::save(), see $options of model::save().
  2734. * @access public
  2735. * @link http://book.cakephp.org/view/1048/Callback-Methods#beforeValidate-1051
  2736. */
  2737. function beforeValidate($options = array()) {
  2738. return true;
  2739. }
  2740. /**
  2741. * Called when a DataSource-level error occurs.
  2742. *
  2743. * @access public
  2744. * @link http://book.cakephp.org/view/1048/Callback-Methods#onError-1056
  2745. */
  2746. function onError() {
  2747. }
  2748. /**
  2749. * Private method. Clears cache for this model.
  2750. *
  2751. * @param string $type If null this deletes cached views if Cache.check is true
  2752. * Will be used to allow deleting query cache also
  2753. * @return boolean true on delete
  2754. * @access protected
  2755. * @todo
  2756. */
  2757. function _clearCache($type = null) {
  2758. if ($type === null) {
  2759. if (Configure::read('Cache.check') === true) {
  2760. $assoc[] = strtolower(Inflector::pluralize($this->alias));
  2761. $assoc[] = strtolower(Inflector::underscore(Inflector::pluralize($this->alias)));
  2762. foreach ($this->__associations as $key => $association) {
  2763. foreach ($this->$association as $key => $className) {
  2764. $check = strtolower(Inflector::pluralize($className['className']));
  2765. if (!in_array($check, $assoc)) {
  2766. $assoc[] = strtolower(Inflector::pluralize($className['className']));
  2767. $assoc[] = strtolower(Inflector::underscore(Inflector::pluralize($className['className'])));
  2768. }
  2769. }
  2770. }
  2771. clearCache($assoc);
  2772. return true;
  2773. }
  2774. } else {
  2775. //Will use for query cache deleting
  2776. }
  2777. }
  2778. /**
  2779. * Called when serializing a model.
  2780. *
  2781. * @return array Set of object variable names this model has
  2782. * @access private
  2783. */
  2784. function __sleep() {
  2785. $return = array_keys(get_object_vars($this));
  2786. return $return;
  2787. }
  2788. /**
  2789. * Called when de-serializing a model.
  2790. *
  2791. * @access private
  2792. * @todo
  2793. */
  2794. function __wakeup() {
  2795. }
  2796. }
  2797. if (!defined('CAKEPHP_UNIT_TEST_EXECUTION')) {
  2798. Overloadable::overload('Model');
  2799. }