PageRenderTime 613ms CodeModel.GetById 25ms RepoModel.GetById 28ms app.codeStats 2ms

/lib/Cake/Model/Model.php

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