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

/lib/Cake/Model/Model.php

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