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

/lib/Cake/Model/Model.php

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