PageRenderTime 38ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/Cake/Model/Model.php

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