PageRenderTime 70ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/Vendor/pear-pear.cakephp.org/CakePHP/Cake/Model/Model.php

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