PageRenderTime 80ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/Cake/Model/Model.php

https://bitbucket.org/dosm123/crm
PHP | 3577 lines | 2002 code | 288 blank | 1287 comment | 588 complexity | 01ce8ee31d24225018df828ba2e22cf4 MD5 | raw file
Possible License(s): LGPL-3.0, GPL-3.0, LGPL-2.1
  1. <?php
  2. /**
  3. * Object-relational mapper.
  4. *
  5. * DBO-backed object data model, for mapping database tables to Cake objects.
  6. *
  7. * PHP versions 5
  8. *
  9. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  10. * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. *
  12. * Licensed under The MIT License
  13. * Redistributions of files must retain the above copyright notice.
  14. *
  15. * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  16. * @link http://cakephp.org CakePHP(tm) Project
  17. * @package Cake.Model
  18. * @since CakePHP(tm) v 0.10.0.0
  19. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  20. */
  21. App::uses('ClassRegistry', 'Utility');
  22. App::uses('Validation', 'Utility');
  23. App::uses('String', 'Utility');
  24. App::uses('Set', 'Utility');
  25. App::uses('BehaviorCollection', 'Model');
  26. App::uses('ModelBehavior', 'Model');
  27. App::uses('ConnectionManager', 'Model');
  28. App::uses('Xml', 'Utility');
  29. 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. }
  731. elseif (isset($name, $this->__backAssociation[$type][$name])) {
  732. $className = empty($this->__backAssociation[$type][$name]['className']) ?
  733. $name : $this->__backAssociation[$type][$name]['className'];
  734. break;
  735. } elseif ($type == 'hasAndBelongsToMany') {
  736. foreach ($this->{$type} as $k => $relation) {
  737. if (empty($relation['with'])) {
  738. continue;
  739. }
  740. if (is_array($relation['with'])) {
  741. if (key($relation['with']) === $name) {
  742. $className = $name;
  743. }
  744. } else {
  745. list($plugin, $class) = pluginSplit($relation['with']);
  746. if ($class === $name) {
  747. $className = $relation['with'];
  748. }
  749. }
  750. if ($className) {
  751. $assocKey = $k;
  752. $dynamic = !empty($relation['dynamicWith']);
  753. break(2);
  754. }
  755. }
  756. }
  757. }
  758. if (!$className) {
  759. return false;
  760. }
  761. list($plugin, $className) = pluginSplit($className);
  762. if (!ClassRegistry::isKeySet($className) && !empty($dynamic)) {
  763. $this->{$className} = new AppModel(array(
  764. 'name' => $className,
  765. 'table' => $this->hasAndBelongsToMany[$assocKey]['joinTable'],
  766. 'ds' => $this->useDbConfig
  767. ));
  768. } else {
  769. $this->_constructLinkedModel($name, $className, $plugin);
  770. }
  771. if (!empty($assocKey)) {
  772. $this->hasAndBelongsToMany[$assocKey]['joinTable'] = $this->{$name}->table;
  773. if (count($this->{$name}->schema()) <= 2 && $this->{$name}->primaryKey !== false) {
  774. $this->{$name}->primaryKey = $this->hasAndBelongsToMany[$assocKey]['foreignKey'];
  775. }
  776. }
  777. return true;
  778. }
  779. /**
  780. * Returns the value of the requested variable if it can be set by __isset()
  781. *
  782. * @param string $name variable requested for it's value or reference
  783. * @return mixed value of requested variable if it is set
  784. */
  785. public function __get($name) {
  786. if ($name === 'displayField') {
  787. return $this->displayField = $this->hasField(array('title', 'name', $this->primaryKey));
  788. }
  789. if ($name === 'tablePrefix') {
  790. $this->setDataSource();
  791. if (property_exists($this, 'tablePrefix') && !empty($this->tablePrefix)) {
  792. return $this->tablePrefix;
  793. }
  794. return $this->tablePrefix = null;
  795. }
  796. if (isset($this->{$name})) {
  797. return $this->{$name};
  798. }
  799. }
  800. /**
  801. * Bind model associations on the fly.
  802. *
  803. * If `$reset` is false, association will not be reset
  804. * to the originals defined in the model
  805. *
  806. * Example: Add a new hasOne binding to the Profile model not
  807. * defined in the model source code:
  808. *
  809. * `$this->User->bindModel( array('hasOne' => array('Profile')) );`
  810. *
  811. * Bindings that are not made permanent will be reset by the next Model::find() call on this
  812. * model.
  813. *
  814. * @param array $params Set of bindings (indexed by binding type)
  815. * @param boolean $reset Set to false to make the binding permanent
  816. * @return boolean Success
  817. * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#creating-and-destroying-associations-on-the-fly
  818. */
  819. public function bindModel($params, $reset = true) {
  820. foreach ($params as $assoc => $model) {
  821. if ($reset === true && !isset($this->__backAssociation[$assoc])) {
  822. $this->__backAssociation[$assoc] = $this->{$assoc};
  823. }
  824. foreach ($model as $key => $value) {
  825. $assocName = $key;
  826. if (is_numeric($key)) {
  827. $assocName = $value;
  828. $value = array();
  829. }
  830. $this->{$assoc}[$assocName] = $value;
  831. if (property_exists($this, $assocName)) {
  832. unset($this->{$assocName});
  833. }
  834. if ($reset === false && isset($this->__backAssociation[$assoc])) {
  835. $this->__backAssociation[$assoc][$assocName] = $value;
  836. }
  837. }
  838. }
  839. $this->_createLinks();
  840. return true;
  841. }
  842. /**
  843. * Turn off associations on the fly.
  844. *
  845. * If $reset is false, association will not be reset
  846. * to the originals defined in the model
  847. *
  848. * Example: Turn off the associated Model Support request,
  849. * to temporarily lighten the User model:
  850. *
  851. * `$this->User->unbindModel( array('hasMany' => array('Supportrequest')) );`
  852. *
  853. * unbound models that are not made permanent will reset with the next call to Model::find()
  854. *
  855. * @param array $params Set of bindings to unbind (indexed by binding type)
  856. * @param boolean $reset Set to false to make the unbinding permanent
  857. * @return boolean Success
  858. * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#creating-and-destroying-associations-on-the-fly
  859. */
  860. public function unbindModel($params, $reset = true) {
  861. foreach ($params as $assoc => $models) {
  862. if ($reset === true && !isset($this->__backAssociation[$assoc])) {
  863. $this->__backAssociation[$assoc] = $this->{$assoc};
  864. }
  865. foreach ($models as $model) {
  866. if ($reset === false && isset($this->__backAssociation[$assoc][$model])) {
  867. unset($this->__backAssociation[$assoc][$model]);
  868. }
  869. unset($this->{$assoc}[$model]);
  870. }
  871. }
  872. return true;
  873. }
  874. /**
  875. * Create a set of associations.
  876. *
  877. * @return void
  878. */
  879. protected function _createLinks() {
  880. foreach ($this->_associations as $type) {
  881. if (!is_array($this->{$type})) {
  882. $this->{$type} = explode(',', $this->{$type});
  883. foreach ($this->{$type} as $i => $className) {
  884. $className = trim($className);
  885. unset ($this->{$type}[$i]);
  886. $this->{$type}[$className] = array();
  887. }
  888. }
  889. if (!empty($this->{$type})) {
  890. foreach ($this->{$type} as $assoc => $value) {
  891. $plugin = null;
  892. if (is_numeric($assoc)) {
  893. unset ($this->{$type}[$assoc]);
  894. $assoc = $value;
  895. $value = array();
  896. if (strpos($assoc, '.') !== false) {
  897. list($plugin, $assoc) = pluginSplit($assoc);
  898. $this->{$type}[$assoc] = array('className' => $plugin. '.' . $assoc);
  899. } else {
  900. $this->{$type}[$assoc] = $value;
  901. }
  902. }
  903. $this->_generateAssociation($type, $assoc);
  904. }
  905. }
  906. }
  907. }
  908. /**
  909. * Protected helper method to create associated models of a given class.
  910. *
  911. * @param string $assoc Association name
  912. * @param string $className Class name
  913. * @param string $plugin name of the plugin where $className is located
  914. * examples: public $hasMany = array('Assoc' => array('className' => 'ModelName'));
  915. * usage: $this->Assoc->modelMethods();
  916. *
  917. * public $hasMany = array('ModelName');
  918. * usage: $this->ModelName->modelMethods();
  919. * @return void
  920. */
  921. protected function _constructLinkedModel($assoc, $className = null, $plugin = null) {
  922. if (empty($className)) {
  923. $className = $assoc;
  924. }
  925. if (!isset($this->{$assoc}) || $this->{$assoc}->name !== $className) {
  926. if ($plugin) {
  927. $plugin .= '.';
  928. }
  929. $model = array('class' => $plugin . $className, 'alias' => $assoc);
  930. $this->{$assoc} = ClassRegistry::init($model);
  931. if ($plugin) {
  932. ClassRegistry::addObject($plugin . $className, $this->{$assoc});
  933. }
  934. if ($assoc) {
  935. $this->tableToModel[$this->{$assoc}->table] = $assoc;
  936. }
  937. }
  938. }
  939. /**
  940. * Build an array-based association from string.
  941. *
  942. * @param string $type 'belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany'
  943. * @param string $assocKey
  944. * @return void
  945. */
  946. protected function _generateAssociation($type, $assocKey) {
  947. $class = $assocKey;
  948. $dynamicWith = false;
  949. foreach ($this->_associationKeys[$type] as $key) {
  950. if (!isset($this->{$type}[$assocKey][$key]) || $this->{$type}[$assocKey][$key] === null) {
  951. $data = '';
  952. switch ($key) {
  953. case 'fields':
  954. $data = '';
  955. break;
  956. case 'foreignKey':
  957. $data = (($type == 'belongsTo') ? Inflector::underscore($assocKey) : Inflector::singularize($this->table)) . '_id';
  958. break;
  959. case 'associationForeignKey':
  960. $data = Inflector::singularize($this->{$class}->table) . '_id';
  961. break;
  962. case 'with':
  963. $data = Inflector::camelize(Inflector::singularize($this->{$type}[$assocKey]['joinTable']));
  964. $dynamicWith = true;
  965. break;
  966. case 'joinTable':
  967. $tables = array($this->table, $this->{$class}->table);
  968. sort ($tables);
  969. $data = $tables[0] . '_' . $tables[1];
  970. break;
  971. case 'className':
  972. $data = $class;
  973. break;
  974. case 'unique':
  975. $data = true;
  976. break;
  977. }
  978. $this->{$type}[$assocKey][$key] = $data;
  979. }
  980. if ($dynamicWith) {
  981. $this->{$type}[$assocKey]['dynamicWith'] = true;
  982. }
  983. }
  984. }
  985. /**
  986. * Sets a custom table for your controller class. Used by your controller to select a database table.
  987. *
  988. * @param string $tableName Name of the custom table
  989. * @throws MissingTableException when database table $tableName is not found on data source
  990. * @return void
  991. */
  992. public function setSource($tableName) {
  993. $this->setDataSource($this->useDbConfig);
  994. $db = ConnectionManager::getDataSource($this->useDbConfig);
  995. $db->cacheSources = ($this->cacheSources && $db->cacheSources);
  996. if (method_exists($db, 'listSources')) {
  997. $sources = $db->listSources();
  998. if (is_array($sources) && !in_array(strtolower($this->tablePrefix . $tableName), array_map('strtolower', $sources))) {
  999. throw new MissingTableException(array(
  1000. 'table' => $this->tablePrefix . $tableName,
  1001. 'class' => $this->alias,
  1002. 'ds' => $this->useDbConfig,
  1003. ));
  1004. }
  1005. $this->_schema = null;
  1006. }
  1007. $this->table = $this->useTable = $tableName;
  1008. $this->tableToModel[$this->table] = $this->alias;
  1009. }
  1010. /**
  1011. * This function does two things:
  1012. *
  1013. * 1. it scans the array $one for the primary key,
  1014. * and if that's found, it sets the current id to the value of $one[id].
  1015. * For all other keys than 'id' the keys and values of $one are copied to the 'data' property of this object.
  1016. * 2. Returns an array with all of $one's keys and values.
  1017. * (Alternative indata: two strings, which are mangled to
  1018. * a one-item, two-dimensional array using $one for a key and $two as its value.)
  1019. *
  1020. * @param mixed $one Array or string of data
  1021. * @param string $two Value string for the alternative indata method
  1022. * @return array Data with all of $one's keys and values
  1023. * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html
  1024. */
  1025. public function set($one, $two = null) {
  1026. if (!$one) {
  1027. return;
  1028. }
  1029. if (is_object($one)) {
  1030. if ($one instanceof SimpleXMLElement || $one instanceof DOMNode) {
  1031. $one = $this->_normalizeXmlData(Xml::toArray($one));
  1032. } else {
  1033. $one = Set::reverse($one);
  1034. }
  1035. }
  1036. if (is_array($one)) {
  1037. $data = $one;
  1038. if (empty($one[$this->alias])) {
  1039. if ($this->getAssociated(key($one)) === null) {
  1040. $data = array($this->alias => $one);
  1041. }
  1042. }
  1043. } else {
  1044. $data = array($this->alias => array($one => $two));
  1045. }
  1046. foreach ($data as $modelName => $fieldSet) {
  1047. if (is_array($fieldSet)) {
  1048. foreach ($fieldSet as $fieldName => $fieldValue) {
  1049. if (isset($this->validationErrors[$fieldName])) {
  1050. unset ($this->validationErrors[$fieldName]);
  1051. }
  1052. if ($modelName === $this->alias) {
  1053. if ($fieldName === $this->primaryKey) {
  1054. $this->id = $fieldValue;
  1055. }
  1056. }
  1057. if (is_array($fieldValue) || is_object($fieldValue)) {
  1058. $fieldValue = $this->deconstruct($fieldName, $fieldValue);
  1059. }
  1060. $this->data[$modelName][$fieldName] = $fieldValue;
  1061. }
  1062. }
  1063. }
  1064. return $data;
  1065. }
  1066. /**
  1067. * Normalize Xml::toArray() to use in Model::save()
  1068. *
  1069. * @param array $xml XML as array
  1070. * @return array
  1071. */
  1072. protected function _normalizeXmlData(array $xml) {
  1073. $return = array();
  1074. foreach ($xml as $key => $value) {
  1075. if (is_array($value)) {
  1076. $return[Inflector::camelize($key)] = $this->_normalizeXmlData($value);
  1077. } elseif ($key[0] === '@') {
  1078. $return[substr($key, 1)] = $value;
  1079. } else {
  1080. $return[$key] = $value;
  1081. }
  1082. }
  1083. return $return;
  1084. }
  1085. /**
  1086. * Deconstructs a complex data type (array or object) into a single field value.
  1087. *
  1088. * @param string $field The name of the field to be deconstructed
  1089. * @param mixed $data An array or object to be deconstructed into a field
  1090. * @return mixed The resulting data that should be assigned to a field
  1091. */
  1092. public function deconstruct($field, $data) {
  1093. if (!is_array($data)) {
  1094. return $data;
  1095. }
  1096. $type = $this->getColumnType($field);
  1097. if (in_array($type, array('datetime', 'timestamp', 'date', 'time'))) {
  1098. $useNewDate = (isset($data['year']) || isset($data['month']) ||
  1099. isset($data['day']) || isset($data['hour']) || isset($data['minute']));
  1100. $dateFields = array('Y' => 'year', 'm' => 'month', 'd' => 'day', 'H' => 'hour', 'i' => 'min', 's' => 'sec');
  1101. $timeFields = array('H' => 'hour', 'i' => 'min', 's' => 'sec');
  1102. $date = array();
  1103. if (isset($data['meridian']) && empty($data['meridian'])) {
  1104. return null;
  1105. }
  1106. if (
  1107. isset($data['hour']) &&
  1108. isset($data['meridian']) &&
  1109. !empty($data['hour']) &&
  1110. $data['hour'] != 12 &&
  1111. 'pm' == $data['meridian']
  1112. ) {
  1113. $data['hour'] = $data['hour'] + 12;
  1114. }
  1115. if (isset($data['hour']) && isset($data['meridian']) && $data['hour'] == 12 && 'am' == $data['meridian']) {
  1116. $data['hour'] = '00';
  1117. }
  1118. if ($type == 'time') {
  1119. foreach ($timeFields as $key => $val) {
  1120. if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') {
  1121. $data[$val] = '00';
  1122. } elseif ($data[$val] !== '') {
  1123. $data[$val] = sprintf('%02d', $data[$val]);
  1124. }
  1125. if (!empty($data[$val])) {
  1126. $date[$key] = $data[$val];
  1127. } else {
  1128. return null;
  1129. }
  1130. }
  1131. }
  1132. if ($type == 'datetime' || $type == 'timestamp' || $type == 'date') {
  1133. foreach ($dateFields as $key => $val) {
  1134. if ($val == 'hour' || $val == 'min' || $val == 'sec') {
  1135. if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') {
  1136. $data[$val] = '00';
  1137. } else {
  1138. $data[$val] = sprintf('%02d', $data[$val]);
  1139. }
  1140. }
  1141. if (!isset($data[$val]) || isset($data[$val]) && (empty($data[$val]) || $data[$val][0] === '-')) {
  1142. return null;
  1143. }
  1144. if (isset($data[$val]) && !empty($data[$val])) {
  1145. $date[$key] = $data[$val];
  1146. }
  1147. }
  1148. }
  1149. if ($useNewDate && !empty($date)) {
  1150. $format = $this->getDataSource()->columns[$type]['format'];
  1151. foreach (array('m', 'd', 'H', 'i', 's') as $index) {
  1152. if (isset($date[$index])) {
  1153. $date[$index] = sprintf('%02d', $date[$index]);
  1154. }
  1155. }
  1156. return str_replace(array_keys($date), array_values($date), $format);
  1157. }
  1158. }
  1159. return $data;
  1160. }
  1161. /**
  1162. * Returns an array of table metadata (column names and types) from the database.
  1163. * $field => keys(type, null, default, key, length, extra)
  1164. *
  1165. * @param mixed $field Set to true to reload schema, or a string to return a specific field
  1166. * @return array Array of table metadata
  1167. */
  1168. public function schema($field = false) {
  1169. if ($this->useTable !== false && (!is_array($this->_schema) || $field === true)) {
  1170. $db = $this->getDataSource();
  1171. $db->cacheSources = ($this->cacheSources && $db->cacheSources);
  1172. if (method_exists($db, 'describe') && $this->useTable !== false) {
  1173. $this->_schema = $db->describe($this);
  1174. } elseif ($this->useTable === false) {
  1175. $this->_schema = array();
  1176. }
  1177. }
  1178. if (is_string($field)) {
  1179. if (isset($this->_schema[$field])) {
  1180. return $this->_schema[$field];
  1181. } else {
  1182. return null;
  1183. }
  1184. }
  1185. return $this->_schema;
  1186. }
  1187. /**
  1188. * Returns an associative array of field names and column types.
  1189. *
  1190. * @return array Field types indexed by field name
  1191. */
  1192. public function getColumnTypes() {
  1193. $columns = $this->schema();
  1194. if (empty($columns)) {
  1195. 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);
  1196. }
  1197. $cols = array();
  1198. foreach ($columns as $field => $values) {
  1199. $cols[$field] = $values['type'];
  1200. }
  1201. return $cols;
  1202. }
  1203. /**
  1204. * Returns the column type of a column in the model.
  1205. *
  1206. * @param string $column The name of the model column
  1207. * @return string Column type
  1208. */
  1209. public function getColumnType($column) {
  1210. $db = $this->getDataSource();
  1211. $cols = $this->schema();
  1212. $model = null;
  1213. $column = str_replace(array($db->startQuote, $db->endQuote), '', $column);
  1214. if (strpos($column, '.')) {
  1215. list($model, $column) = explode('.', $column);
  1216. }
  1217. if ($model != $this->alias && isset($this->{$model})) {
  1218. return $this->{$model}->getColumnType($column);
  1219. }
  1220. if (isset($cols[$column]) && isset($cols[$column]['type'])) {
  1221. return $cols[$column]['type'];
  1222. }
  1223. return null;
  1224. }
  1225. /**
  1226. * Returns true if the supplied field exists in the model's database table.
  1227. *
  1228. * @param mixed $name Name of field to look for, or an array of names
  1229. * @param boolean $checkVirtual checks if the field is declared as virtual
  1230. * @return mixed If $name is a string, returns a boolean indicating whether the field exists.
  1231. * If $name is an array of field names, returns the first field that exists,
  1232. * or false if none exist.
  1233. */
  1234. public function hasField($name, $checkVirtual = false) {
  1235. if (is_array($name)) {
  1236. foreach ($name as $n) {
  1237. if ($this->hasField($n, $checkVirtual)) {
  1238. return $n;
  1239. }
  1240. }
  1241. return false;
  1242. }
  1243. if ($checkVirtual && !empty($this->virtualFields)) {
  1244. if ($this->isVirtualField($name)) {
  1245. return true;
  1246. }
  1247. }
  1248. if (empty($this->_schema)) {
  1249. $this->schema();
  1250. }
  1251. if ($this->_schema != null) {
  1252. return isset($this->_schema[$name]);
  1253. }
  1254. return false;
  1255. }
  1256. /**
  1257. * Check that a method is callable on a model. This will check both the model's own methods, its
  1258. * inherited methods and methods that could be callable through behaviors.
  1259. *
  1260. * @param string $method The method to be called.
  1261. * @return boolean True on method being callable.
  1262. */
  1263. public function hasMethod($method) {
  1264. if (method_exists($this, $method)) {
  1265. return true;
  1266. }
  1267. if ($this->Behaviors->hasMethod($method)) {
  1268. return true;
  1269. }
  1270. return false;
  1271. }
  1272. /**
  1273. * Returns true if the supplied field is a model Virtual Field
  1274. *
  1275. * @param string $field Name of field to look for
  1276. * @return boolean indicating whether the field exists as a model virtual field.
  1277. */
  1278. public function isVirtualField($field) {
  1279. if (empty($this->virtualFields) || !is_string($field)) {
  1280. return false;
  1281. }
  1282. if (isset($this->virtualFields[$field])) {
  1283. return true;
  1284. }
  1285. if (strpos($field, '.') !== false) {
  1286. list($model, $field) = explode('.', $field);
  1287. if ($model == $this->alias && isset($this->virtualFields[$field])) {
  1288. return true;
  1289. }
  1290. }
  1291. return false;
  1292. }
  1293. /**
  1294. * Returns the expression for a model virtual field
  1295. *
  1296. * @param string $field Name of field to look for
  1297. * @return mixed If $field is string expression bound to virtual field $field
  1298. * If $field is null, returns an array of all model virtual fields
  1299. * or false if none $field exist.
  1300. */
  1301. public function getVirtualField($field = null) {
  1302. if ($field == null) {
  1303. return empty($this->virtualFields) ? false : $this->virtualFields;
  1304. }
  1305. if ($this->isVirtualField($field)) {
  1306. if (strpos($field, '.') !== false) {
  1307. list($model, $field) = explode('.', $field);
  1308. }
  1309. return $this->virtualFields[$field];
  1310. }
  1311. return false;
  1312. }
  1313. /**
  1314. * Initializes the model for writing a new record, loading the default values
  1315. * for those fields that are not defined in $data, and clearing previous validation errors.
  1316. * Especially helpful for saving data in loops.
  1317. *
  1318. * @param mixed $data Optional data array to assign to the model after it is created. If null or false,
  1319. * schema data defaults are not merged.
  1320. * @param boolean $filterKey If true, overwrites any primary key input with an empty value
  1321. * @return array The current Model::data; after merging $data and/or defaults from database
  1322. * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-create-array-data-array
  1323. */
  1324. public function create($data = array(), $filterKey = false) {
  1325. $defaults = array();
  1326. $this->id = false;
  1327. $this->data = array();
  1328. $this->validationErrors = array();
  1329. if ($data !== null && $data !== false) {
  1330. foreach ($this->schema() as $field => $properties) {
  1331. if ($this->primaryKey !== $field && isset($properties['default']) && $properties['default'] !== '') {
  1332. $defaults[$field] = $properties['default'];
  1333. }
  1334. }
  1335. $this->set($defaults);
  1336. $this->set($data);
  1337. }
  1338. if ($filterKey) {
  1339. $this->set($this->primaryKey, false);
  1340. }
  1341. return $this->data;
  1342. }
  1343. /**
  1344. * Returns a list of fields from the database, and sets the current model
  1345. * data (Model::$data) with the record found.
  1346. *
  1347. * @param mixed $fields String of single field name, or an array of field names.
  1348. * @param mixed $id The ID of the record to read
  1349. * @return array Array of database fields, or false if not found
  1350. * @link http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-read
  1351. */
  1352. public function read($fields = null, $id = null) {
  1353. $this->validationErrors = array();
  1354. if ($id != null) {
  1355. $this->id = $id;
  1356. }
  1357. $id = $this->id;
  1358. if (is_array($this->id)) {
  1359. $id = $this->id[0];
  1360. }
  1361. if ($id !== null && $id !== false) {
  1362. $this->data = $this->find('first', array(
  1363. 'conditions' => array($this->alias . '.' . $this->primaryKey => $id),
  1364. 'fields' => $fields
  1365. ));
  1366. return $this->data;
  1367. } else {
  1368. return false;
  1369. }
  1370. }
  1371. /**
  1372. * Returns the contents of a single field given the supplied conditions, in the
  1373. * supplied order.
  1374. *
  1375. * @param string $name Name of field to get
  1376. * @param array $conditions SQL conditions (defaults to NULL)
  1377. * @param string $order SQL ORDER BY fragment
  1378. * @return string field contents, or false if not found
  1379. * @link http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-field
  1380. */
  1381. public function field($name, $conditions = null, $order = null) {
  1382. if ($conditions === null && $this->id !== false) {
  1383. $conditions = array($this->alias . '.' . $this->primaryKey => $this->id);
  1384. }
  1385. if ($this->recursive >= 1) {
  1386. $recursive = -1;
  1387. } else {
  1388. $recursive = $this->recursive;
  1389. }
  1390. $fields = $name;
  1391. if ($data = $this->find('first', compact('conditions', 'fields', 'order', 'recursive'))) {
  1392. if (strpos($name, '.') === false) {
  1393. if (isset($data[$this->alias][$name])) {
  1394. return $data[$this->alias][$name];
  1395. }
  1396. } else {
  1397. $name = explode('.', $name);
  1398. if (isset($data[$name[0]][$name[1]])) {
  1399. return $data[$name[0]][$name[1]];
  1400. }
  1401. }
  1402. if (isset($data[0]) && count($data[0]) > 0) {
  1403. return array_shift($data[0]);
  1404. }
  1405. } else {
  1406. return false;
  1407. }
  1408. }
  1409. /**
  1410. * Saves the value of a single field to the database, based on the current
  1411. * model ID.
  1412. *
  1413. * @param string $name Name of the table field
  1414. * @param mixed $value Value of the field
  1415. * @param array $validate See $options param in Model::save(). Does not respect 'fieldList' key if passed
  1416. * @return boolean See Model::save()
  1417. * @see Model::save()
  1418. * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-savefield-string-fieldname-string-fieldvalue-validate-false
  1419. */
  1420. public function saveField($name, $value, $validate = false) {
  1421. $id = $this->id;
  1422. $this->create(false);
  1423. if (is_array($validate)) {
  1424. $options = array_merge(array('validate' => false, 'fieldList' => array($name)), $validate);
  1425. } else {
  1426. $options = array('validate' => $validate, 'fieldList' => array($name));
  1427. }
  1428. return $this->save(array($this->alias => array($this->primaryKey => $id, $name => $value)), $options);
  1429. }
  1430. /**
  1431. * Saves model data (based on white-list, if supplied) to the database. By
  1432. * default, validation occurs before save.
  1433. *
  1434. * @param array $data Data to save.
  1435. * @param mixed $validate Either a boolean, or an array.
  1436. * If a boolean, indicates whether or not to validate before saving.
  1437. * If an array, allows control of validate, callbacks, and fieldList
  1438. * @param array $fieldList List of fields to allow to be written
  1439. * @return mixed On success Model::$data if its not empty or true, false on failure
  1440. * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html
  1441. */
  1442. public function save($data = null, $validate = true, $fieldList = array()) {
  1443. $defaults = array('validate' => true, 'fieldList' => array(), 'callbacks' => true);
  1444. $_whitelist = $this->whitelist;
  1445. $fields = array();
  1446. if (!is_array($validate)) {
  1447. $options = array_merge($defaults, compact('validate', 'fieldList', 'callbacks'));
  1448. } else {
  1449. $options = array_merge($defaults, $validate);
  1450. }
  1451. if (!empty($options['fieldList'])) {
  1452. if (!empty($options['fieldList'][$this->alias]) && is_array($options['fieldList'][$this->alias])) {
  1453. $this->whitelist = $options['fieldList'][$this->alias];
  1454. } else {
  1455. $this->whitelist = $options['fieldList'];
  1456. }
  1457. } elseif ($options['fieldList'] === null) {
  1458. $this->whitelist = array();
  1459. }
  1460. $this->set($data);
  1461. if (empty($this->data) && !$this->hasField(array('created', 'updated', 'modified'))) {
  1462. return false;
  1463. }
  1464. foreach (array('created', 'updated', 'modified') as $field) {
  1465. $keyPresentAndEmpty = (
  1466. isset($this->data[$this->alias]) &&
  1467. array_key_exists($field, $this->data[$this->alias]) &&
  1468. $this->data[$this->alias][$field] === null
  1469. );
  1470. if ($keyPresentAndEmpty) {
  1471. unset($this->data[$this->alias][$field]);
  1472. }
  1473. }
  1474. $exists = $this->exists();
  1475. $dateFields = array('modified', 'updated');
  1476. if (!$exists) {
  1477. $dateFields[] = 'created';
  1478. }
  1479. if (isset($this->data[$this->alias])) {
  1480. $fields = array_keys($this->data[$this->alias]);
  1481. }
  1482. if ($options['validate'] && !$this->validates($options)) {
  1483. $this->whitelist = $_whitelist;
  1484. return false;
  1485. }
  1486. $db = $this->getDataSource();
  1487. foreach ($dateFields as $updateCol) {
  1488. if ($this->hasField($updateCol) && !in_array($updateCol, $fields)) {
  1489. $default = array('formatter' => 'date');
  1490. $colType = array_merge($default, $db->columns[$this->getColumnType($updateCol)]);
  1491. if (!array_key_exists('format', $colType)) {
  1492. $time = strtotime('now');
  1493. } else {
  1494. $time = $colType['formatter']($colType['format']);
  1495. }
  1496. if (!empty($this->whitelist)) {
  1497. $this->whitelist[] = $updateCol;
  1498. }
  1499. $this->set($updateCol, $time);
  1500. }
  1501. }
  1502. if ($options['callbacks'] === true || $options['callbacks'] === 'before') {
  1503. $event = new CakeEvent('Model.beforeSave', $this, array($options));
  1504. list($event->break, $event->breakOn) = array(true, array(false, null));
  1505. $this->getEventManager()->dispatch($event);
  1506. if (!$event->result) {
  1507. $this->whitelist = $_whitelist;
  1508. return false;
  1509. }
  1510. }
  1511. if (empty($this->data[$this->alias][$this->primaryKey])) {
  1512. unset($this->data[$this->alias][$this->primaryKey]);
  1513. }
  1514. $fields = $values = array();
  1515. foreach ($this->data as $n => $v) {
  1516. if (isset($this->hasAndBelongsToMany[$n])) {
  1517. if (isset($v[$n])) {
  1518. $v = $v[$n];
  1519. }
  1520. $joined[$n] = $v;
  1521. } else {
  1522. if ($n === $this->alias) {
  1523. foreach (array('created', 'updated', 'modified') as $field) {
  1524. if (array_key_exists($field, $v) && empty($v[$field])) {
  1525. unset($v[$field]);
  1526. }
  1527. }
  1528. foreach ($v as $x => $y) {
  1529. if ($this->hasField($x) && (empty($this->whitelist) || in_array($x, $this->whitelist))) {
  1530. list($fields[], $values[]) = array($x, $y);
  1531. }
  1532. }
  1533. }
  1534. }
  1535. }
  1536. $count = count($fields);
  1537. if (!$exists && $count > 0) {
  1538. $this->id = false;
  1539. }
  1540. $success = true;
  1541. $created = false;
  1542. if ($count > 0) {
  1543. $cache = $this->_prepareUpdateFields(array_combine($fields, $values));
  1544. if (!empty($this->id)) {
  1545. $success = (bool)$db->update($this, $fields, $values);
  1546. } else {
  1547. $fInfo = $this->schema($this->primaryKey);
  1548. $isUUID = ($fInfo['length'] == 36 &&
  1549. ($fInfo['type'] === 'string' || $fInfo['type'] === 'binary')
  1550. );
  1551. if (empty($this->data[$this->alias][$this->primaryKey]) && $isUUID) {
  1552. if (array_key_exists($this->primaryKey, $this->data[$this->alias])) {
  1553. $j = array_search($this->primaryKey, $fields);
  1554. $values[$j] = String::uuid();
  1555. } else {
  1556. list($fields[], $values[]) = array($this->primaryKey, String::uuid());
  1557. }
  1558. }
  1559. if (!$db->create($this, $fields, $values)) {
  1560. $success = $created = false;
  1561. } else {
  1562. $created = true;
  1563. }
  1564. }
  1565. if ($success && !empty($this->belongsTo)) {
  1566. $this->updateCounterCache($cache, $created);
  1567. }
  1568. }
  1569. if (!empty($joined) && $success === true) {
  1570. $this->_saveMulti($joined, $this->id, $db);
  1571. }
  1572. if ($success && $count > 0) {
  1573. if (!empty($this->data)) {
  1574. $success = $this->data;
  1575. if ($created) {
  1576. $this->data[$this->alias][$this->primaryKey] = $this->id;
  1577. }
  1578. }
  1579. if ($options['callbacks'] === true || $options['callbacks'] === 'after') {
  1580. $event = new CakeEvent('Model.afterSave', $this, array($created, $options));
  1581. $this->getEventManager()->dispatch($event);
  1582. }
  1583. if (!empty($this->data)) {
  1584. $success = Set::merge($success, $this->data);
  1585. }
  1586. $this->data = false;
  1587. $this->_clearCache();
  1588. $this->validationErrors = array();
  1589. }
  1590. $this->whitelist = $_whitelist;
  1591. return $success;
  1592. }
  1593. /**
  1594. * Saves model hasAndBelongsToMany data to the database.
  1595. *
  1596. * @param array $joined Data to save
  1597. * @param mixed $id ID of record in this model
  1598. * @param DataSource $db
  1599. * @return void
  1600. */
  1601. protected function _saveMulti($joined, $id, $db) {
  1602. foreach ($joined as $assoc => $data) {
  1603. if (isset($this->hasAndBelongsToMany[$assoc])) {
  1604. list($join) = $this->joinModel($this->hasAndBelongsToMany[$assoc]['with']);
  1605. $keyInfo = $this->{$join}->schema($this->{$join}->primaryKey);
  1606. if ($with = $this->hasAndBelongsToMany[$assoc]['with']) {
  1607. $withModel = is_array($with) ? key($with) : $with;
  1608. list($pluginName, $withModel) = pluginSplit($withModel);
  1609. $dbMulti = $this->{$withModel}->getDataSource();
  1610. } else {
  1611. $dbMulti = $db;
  1612. }
  1613. $isUUID = !empty($this->{$join}->primaryKey) && (
  1614. $keyInfo['length'] == 36 && (
  1615. $keyInfo['type'] === 'string' ||
  1616. $keyInfo['type'] === 'binary'
  1617. )
  1618. );
  1619. $newData = $newValues = $newJoins = array();
  1620. $primaryAdded = false;
  1621. $fields = array(
  1622. $dbMulti->name($this->hasAndBelongsToMany[$assoc]['foreignKey']),
  1623. $dbMulti->name($this->hasAndBelongsToMany[$assoc]['associationForeignKey'])
  1624. );
  1625. $idField = $db->name($this->{$join}->primaryKey);
  1626. if ($isUUID && !in_array($idField, $fields)) {
  1627. $fields[] = $idField;
  1628. $primaryAdded = true;
  1629. }
  1630. foreach ((array)$data as $row) {
  1631. if ((is_string($row) && (strlen($row) == 36 || strlen($row) == 16)) || is_numeric($row)) {
  1632. $newJoins[] = $row;
  1633. $values = array($id, $row);
  1634. if ($isUUID && $primaryAdded) {
  1635. $values[] = String::uuid();
  1636. }
  1637. $newValues[$row] = $values;
  1638. unset($values);
  1639. } elseif (isset($row[$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
  1640. $newData[] = $row;
  1641. } elseif (isset($row[$join]) && isset($row[$join][$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
  1642. $newData[] = $row[$join];
  1643. }
  1644. }
  1645. $keepExisting = $this->hasAndBelongsToMany[$assoc]['unique'] === 'keepExisting';
  1646. if ($this->hasAndBelongsToMany[$assoc]['unique']) {
  1647. $conditions = array(
  1648. $join . '.' . $this->hasAndBelongsToMany[$assoc]['foreignKey'] => $id
  1649. );
  1650. if (!empty($this->hasAndBelongsToMany[$assoc]['conditions'])) {
  1651. $conditions = array_merge($conditions, (array)$this->hasAndBelongsToMany[$assoc]['conditions']);
  1652. }
  1653. $associationForeignKey = $this->{$join}->alias .'.'. $this->hasAndBelongsToMany[$assoc]['associationForeignKey'];
  1654. $links = $this->{$join}->find('all', array(
  1655. 'conditions' => $conditions,
  1656. 'recursive' => empty($this->hasAndBelongsToMany[$assoc]['conditions']) ? -1 : 0,
  1657. 'fields' => $associationForeignKey,
  1658. ));
  1659. $oldLinks = Set::extract($links, "{n}.{$associationForeignKey}");
  1660. if (!empty($oldLinks)) {
  1661. if ($keepExisting && !empty($newJoins)) {
  1662. $conditions[$associationForeignKey] = array_diff($oldLinks, $newJoins);
  1663. } else {
  1664. $conditions[$associationForeignKey] = $oldLinks;
  1665. }
  1666. $dbMulti->delete($this->{$join}, $conditions);
  1667. }
  1668. }
  1669. if (!empty($newData)) {
  1670. foreach ($newData as $data) {
  1671. $data[$this->hasAndBelongsToMany[$assoc]['foreignKey']] = $id;
  1672. $this->{$join}->create($data);
  1673. $this->{$join}->save();
  1674. }
  1675. }
  1676. if (!empty($newValues)) {
  1677. if ($keepExisting && !empty($links)) {
  1678. foreach ($links as $link) {
  1679. $oldJoin = $link[$join][$this->hasAndBelongsToMany[$assoc]['associationForeignKey']];
  1680. if (! in_array($oldJoin, $newJoins) ) {
  1681. $conditions[$associationForeignKey] = $oldJoin;
  1682. $db->delete($this->{$join}, $conditions);
  1683. } else {
  1684. unset($newValues[$oldJoin]);
  1685. }
  1686. }
  1687. $newValues = array_values($newValues);
  1688. }
  1689. if (!empty($newValues)) {
  1690. $dbMulti->insertMulti($this->{$join}, $fields, $newValues);
  1691. }
  1692. }
  1693. }
  1694. }
  1695. }
  1696. /**
  1697. * Updates the counter cache of belongsTo associations after a save or delete operation
  1698. *
  1699. * @param array $keys Optional foreign key data, defaults to the information $this->data
  1700. * @param boolean $created True if a new record was created, otherwise only associations with
  1701. * 'counterScope' defined get updated
  1702. * @return void
  1703. */
  1704. public function updateCounterCache($keys = array(), $created = false) {
  1705. $keys = empty($keys) ? $this->data[$this->alias] : $keys;
  1706. $keys['old'] = isset($keys['old']) ? $keys['old'] : array();
  1707. foreach ($this->belongsTo as $parent => $assoc) {
  1708. if (!empty($assoc['counterCache'])) {
  1709. if (!is_array($assoc['counterCache'])) {
  1710. if (isset($assoc['counterScope'])) {
  1711. $assoc['counterCache'] = array($assoc['counterCache'] => $assoc['counterScope']);
  1712. } else {
  1713. $assoc['counterCache'] = array($assoc['counterCache'] => array());
  1714. }
  1715. }
  1716. $foreignKey = $assoc['foreignKey'];
  1717. $fkQuoted = $this->escapeField($assoc['foreignKey']);
  1718. foreach ($assoc['counterCache'] as $field => $conditions) {
  1719. if (!is_string($field)) {
  1720. $field = Inflector::underscore($this->alias) . '_count';
  1721. }
  1722. if (!$this->{$parent}->hasField($field)) {
  1723. continue;
  1724. }
  1725. if ($conditions === true) {
  1726. $conditions = array();
  1727. } else {
  1728. $conditions = (array)$conditions;
  1729. }
  1730. if (!array_key_exists($foreignKey, $keys)) {
  1731. $keys[$foreignKey] = $this->field($foreignKey);
  1732. }
  1733. $recursive = (empty($conditions) ? -1 : 0);
  1734. if (isset($keys['old'][$foreignKey])) {
  1735. if ($keys['old'][$foreignKey] != $keys[$foreignKey]) {
  1736. $conditions[$fkQuoted] = $keys['old'][$foreignKey];
  1737. $count = intval($this->find('count', compact('conditions', 'recursive')));
  1738. $this->{$parent}->updateAll(
  1739. array($field => $count),
  1740. array($this->{$parent}->escapeField() => $keys['old'][$foreignKey])
  1741. );
  1742. }
  1743. }
  1744. $conditions[$fkQuoted] = $keys[$foreignKey];
  1745. if ($recursive === 0) {
  1746. $conditions = array_merge($conditions, (array)$conditions);
  1747. }
  1748. $count = intval($this->find('count', compact('conditions', 'recursive')));
  1749. $this->{$parent}->updateAll(
  1750. array($field => $count),
  1751. array($this->{$parent}->escapeField() => $keys[$foreignKey])
  1752. );
  1753. }
  1754. }
  1755. }
  1756. }
  1757. /**
  1758. * Helper method for Model::updateCounterCache(). Checks the fields to be updated for
  1759. *
  1760. * @param array $data The fields of the record that will be updated
  1761. * @return array Returns updated foreign key values, along with an 'old' key containing the old
  1762. * values, or empty if no foreign keys are updated.
  1763. */
  1764. protected function _prepareUpdateFields($data) {
  1765. $foreignKeys = array();
  1766. foreach ($this->belongsTo as $assoc => $info) {
  1767. if ($info['counterCache']) {
  1768. $foreignKeys[$assoc] = $info['foreignKey'];
  1769. }
  1770. }
  1771. $included = array_intersect($foreignKeys, array_keys($data));
  1772. if (empty($included) || empty($this->id)) {
  1773. return array();
  1774. }
  1775. $old = $this->find('first', array(
  1776. 'conditions' => array($this->alias . '.' . $this->primaryKey => $this->id),
  1777. 'fields' => array_values($included),
  1778. 'recursive' => -1
  1779. ));
  1780. return array_merge($data, array('old' => $old[$this->alias]));
  1781. }
  1782. /**
  1783. * Backwards compatible passthrough method for:
  1784. * saveMany(), validateMany(), saveAssociated() and validateAssociated()
  1785. *
  1786. * Saves multiple individual records for a single model; Also works with a single record, as well as
  1787. * all its associated records.
  1788. *
  1789. * #### Options
  1790. *
  1791. * - validate: Set to false to disable validation, true to validate each record before saving,
  1792. * 'first' to validate *all* records before any are saved (default),
  1793. * or 'only' to only validate the records, but not save them.
  1794. * - atomic: If true (default), will attempt to save all records in a single transaction.
  1795. * Should be set to false if database/table does not support transactions.
  1796. * - fieldList: Equivalent to the $fieldList parameter in Model::save().
  1797. * It should be an associate array with model name as key and array of fields as value. Eg.
  1798. * {{{
  1799. * array(
  1800. * 'SomeModel' => array('field'),
  1801. * 'AssociatedModel' => array('field', 'otherfield')
  1802. * )
  1803. * }}}
  1804. * - deep: see saveMany/saveAssociated
  1805. *
  1806. * @param array $data Record data to save. This can be either a numerically-indexed array (for saving multiple
  1807. * records of the same type), or an array indexed by association name.
  1808. * @param array $options Options to use when saving record data, See $options above.
  1809. * @return mixed If atomic: True on success, or false on failure.
  1810. * Otherwise: array similar to the $data array passed, but values are set to true/false
  1811. * depending on whether each record saved successfully.
  1812. * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveassociated-array-data-null-array-options-array
  1813. * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveall-array-data-null-array-options-array
  1814. */
  1815. public function saveAll($data = null, $options = array()) {
  1816. $options = array_merge(array('validate' => 'first'), $options);
  1817. if (Set::numeric(array_keys($data))) {
  1818. if ($options['validate'] === 'only') {
  1819. return $this->validateMany($data, $options);
  1820. }
  1821. return $this->saveMany($data, $options);
  1822. }
  1823. if ($options['validate'] === 'only') {
  1824. return $this->validateAssociated($data, $options);
  1825. }
  1826. return $this->saveAssociated($data, $options);
  1827. }
  1828. /**
  1829. * Saves multiple individual records for a single model
  1830. *
  1831. * #### Options
  1832. *
  1833. * - validate: Set to false to disable validation, true to validate each record before saving,
  1834. * 'first' to validate *all* records before any are saved (default),
  1835. * - atomic: If true (default), will attempt to save all records in a single transaction.
  1836. * Should be set to false if database/table does not support transactions.
  1837. * - fieldList: Equivalent to the $fieldList parameter in Model::save()
  1838. * - deep: If set to true, all associated data will be saved as well.
  1839. *
  1840. * @param array $data Record data to save. This should be a numerically-indexed array
  1841. * @param array $options Options to use when saving record data, See $options above.
  1842. * @return mixed If atomic: True on success, or false on failure.
  1843. * Otherwise: array similar to the $data array passed, but values are set to true/false
  1844. * depending on whether each record saved successfully.
  1845. * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-savemany-array-data-null-array-options-array
  1846. */
  1847. public function saveMany($data = null, $options = array()) {
  1848. if (empty($data)) {
  1849. $data = $this->data;
  1850. }
  1851. $options = array_merge(array('validate' => 'first', 'atomic' => true, 'deep' => false), $options);
  1852. $this->validationErrors = $validationErrors = array();
  1853. if (empty($data) && $options['validate'] !== false) {
  1854. $result = $this->save($data, $options);
  1855. return !empty($result);
  1856. }
  1857. if ($options['validate'] === 'first') {
  1858. $validates = $this->validateMany($data, $options);
  1859. if ((!$validates && $options['atomic']) || (!$options['atomic'] && in_array(false, $validates, true))) {
  1860. return $validates;
  1861. }
  1862. }
  1863. if ($options['atomic']) {
  1864. $db = $this->getDataSource();
  1865. $transactionBegun = $db->begin();
  1866. }
  1867. $return = array();
  1868. foreach ($data as $key => $record) {
  1869. $validates = $this->create(null) !== null;
  1870. $saved = false;
  1871. if ($validates) {
  1872. if ($options['deep']) {
  1873. $saved = $this->saveAssociated($record, array_merge($options, array('atomic' => false)));
  1874. } else {
  1875. $saved = $this->save($record, $options);
  1876. }
  1877. }
  1878. $validates = ($validates && ($saved === true || (is_array($saved) && !in_array(false, $saved, true))));
  1879. if (!$validates) {
  1880. $validationErrors[$key] = $this->validationErrors;
  1881. }
  1882. if (!$options['atomic']) {
  1883. $return[$key] = $validates;
  1884. } elseif (!$validates) {
  1885. break;
  1886. }
  1887. }
  1888. $this->validationErrors = $validationErrors;
  1889. if (!$options['atomic']) {
  1890. return $return;
  1891. }
  1892. if ($validates) {
  1893. if ($transactionBegun) {
  1894. return $db->commit() !== false;
  1895. } else {
  1896. return true;
  1897. }
  1898. }
  1899. $db->rollback();
  1900. return false;
  1901. }
  1902. /**
  1903. * Validates multiple individual records for a single model
  1904. *
  1905. * #### Options
  1906. *
  1907. * - atomic: If true (default), returns boolean. If false returns array.
  1908. * - fieldList: Equivalent to the $fieldList parameter in Model::save()
  1909. * - deep: If set to true, all associated data will be validated as well.
  1910. *
  1911. * @param array $data Record data to validate. This should be a numerically-indexed array
  1912. * @param array $options Options to use when validating record data (see above), See also $options of validates().
  1913. * @return boolean True on success, or false on failure.
  1914. * @return mixed If atomic: True on success, or false on failure.
  1915. * Otherwise: array similar to the $data array passed, but values are set to true/false
  1916. * depending on whether each record validated successfully.
  1917. */
  1918. public function validateMany($data, $options = array()) {
  1919. $options = array_merge(array('atomic' => true, 'deep' => false), $options);
  1920. $this->validationErrors = $validationErrors = $return = array();
  1921. foreach ($data as $key => $record) {
  1922. if ($options['deep']) {
  1923. $validates = $this->validateAssociated($record, $options);
  1924. } else {
  1925. $validates = $this->create($record) && $this->validates($options);
  1926. }
  1927. if ($validates === false || (is_array($validates) && in_array(false, $validates, true))) {
  1928. $validationErrors[$key] = $this->validationErrors;
  1929. $validates = false;
  1930. } else {
  1931. $validates = true;
  1932. }
  1933. $return[$key] = $validates;
  1934. }
  1935. $this->validationErrors = $validationErrors;
  1936. if (!$options['atomic']) {
  1937. return $return;
  1938. }
  1939. if (empty($this->validationErrors)) {
  1940. return true;
  1941. }
  1942. return false;
  1943. }
  1944. /**
  1945. * Saves a single record, as well as all its directly associated records.
  1946. *
  1947. * #### Options
  1948. *
  1949. * - `validate` Set to `false` to disable validation, `true` to validate each record before saving,
  1950. * 'first' to validate *all* records before any are saved(default),
  1951. * - `atomic` If true (default), will attempt to save all records in a single transaction.
  1952. * Should be set to false if database/table does not support transactions.
  1953. * - fieldList: Equivalent to the $fieldList parameter in Model::save().
  1954. * It should be an associate array with model name as key and array of fields as value. Eg.
  1955. * {{{
  1956. * array(
  1957. * 'SomeModel' => array('field'),
  1958. * 'AssociatedModel' => array('field', 'otherfield')
  1959. * )
  1960. * }}}
  1961. * - deep: If set to true, not only directly associated data is saved, but deeper nested associated data as well.
  1962. *
  1963. * @param array $data Record data to save. This should be an array indexed by association name.
  1964. * @param array $options Options to use when saving record data, See $options above.
  1965. * @return mixed If atomic: True on success, or false on failure.
  1966. * Otherwise: array similar to the $data array passed, but values are set to true/false
  1967. * depending on whether each record saved successfully.
  1968. * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveassociated-array-data-null-array-options-array
  1969. */
  1970. public function saveAssociated($data = null, $options = array()) {
  1971. if (empty($data)) {
  1972. $data = $this->data;
  1973. }
  1974. $options = array_merge(array('validate' => 'first', 'atomic' => true, 'deep' => false), $options);
  1975. $this->validationErrors = $validationErrors = array();
  1976. if (empty($data) && $options['validate'] !== false) {
  1977. $result = $this->save($data, $options);
  1978. return !empty($result);
  1979. }
  1980. if ($options['validate'] === 'first') {
  1981. $validates = $this->validateAssociated($data, $options);
  1982. if ((!$validates && $options['atomic']) || (!$options['atomic'] && in_array(false, $validates, true))) {
  1983. return $validates;
  1984. }
  1985. }
  1986. if ($options['atomic']) {
  1987. $db = $this->getDataSource();
  1988. $transactionBegun = $db->begin();
  1989. }
  1990. $associations = $this->getAssociated();
  1991. $return = array();
  1992. $validates = true;
  1993. foreach ($data as $association => $values) {
  1994. if (isset($associations[$association]) && $associations[$association] === 'belongsTo') {
  1995. $validates = $this->{$association}->create(null) !== null;
  1996. $saved = false;
  1997. if ($validates) {
  1998. if ($options['deep']) {
  1999. $saved = $this->{$association}->saveAssociated($values, array_merge($options, array('atomic' => false)));
  2000. } else {
  2001. $saved = $this->{$association}->save($values, array_merge($options, array('atomic' => false)));
  2002. }
  2003. $validates = ($saved === true || (is_array($saved) && !in_array(false, $saved, true)));
  2004. }
  2005. if ($validates) {
  2006. if (!empty($data[$this->alias])) {
  2007. $data[$this->alias][$this->belongsTo[$association]['foreignKey']] = $this->{$association}->id;
  2008. } else {
  2009. $data[$this->belongsTo[$association]['foreignKey']] = $this->{$association}->id;
  2010. }
  2011. } else {
  2012. $validationErrors[$association] = $this->{$association}->validationErrors;
  2013. }
  2014. $return[$association] = $validates;
  2015. }
  2016. }
  2017. if ($validates && !($this->create(null) !== null && $this->save($data, $options))) {
  2018. $validationErrors[$this->alias] = $this->validationErrors;
  2019. $validates = false;
  2020. }
  2021. $return[$this->alias] = $validates;
  2022. foreach ($data as $association => $values) {
  2023. if (!$validates) {
  2024. break;
  2025. }
  2026. if (isset($associations[$association])) {
  2027. $type = $associations[$association];
  2028. switch ($type) {
  2029. case 'hasOne':
  2030. $values[$this->{$type}[$association]['foreignKey']] = $this->id;
  2031. $validates = $this->{$association}->create(null) !== null;
  2032. $saved = false;
  2033. if ($validates) {
  2034. if ($options['deep']) {
  2035. $saved = $this->{$association}->saveAssociated($values, array_merge($options, array('atomic' => false)));
  2036. } else {
  2037. $saved = $this->{$association}->save($values, $options);
  2038. }
  2039. }
  2040. $validates = ($validates && ($saved === true || (is_array($saved) && !in_array(false, $saved, true))));
  2041. if (!$validates) {
  2042. $validationErrors[$association] = $this->{$association}->validationErrors;
  2043. }
  2044. $return[$association] = $validates;
  2045. break;
  2046. case 'hasMany':
  2047. foreach ($values as $i => $value) {
  2048. $values[$i][$this->{$type}[$association]['foreignKey']] = $this->id;
  2049. }
  2050. $_return = $this->{$association}->saveMany($values, array_merge($options, array('atomic' => false)));
  2051. if (in_array(false, $_return, true)) {
  2052. $validationErrors[$association] = $this->{$association}->validationErrors;
  2053. $validates = false;
  2054. }
  2055. $return[$association] = $_return;
  2056. break;
  2057. }
  2058. }
  2059. }
  2060. $this->validationErrors = $validationErrors;
  2061. if (isset($validationErrors[$this->alias])) {
  2062. $this->validationErrors = $validationErrors[$this->alias];
  2063. }
  2064. if (!$options['atomic']) {
  2065. return $return;
  2066. }
  2067. if ($validates) {
  2068. if ($transactionBegun) {
  2069. return $db->commit() !== false;
  2070. } else {
  2071. return true;
  2072. }
  2073. }
  2074. $db->rollback();
  2075. return false;
  2076. }
  2077. /**
  2078. * Validates a single record, as well as all its directly associated records.
  2079. *
  2080. * #### Options
  2081. *
  2082. * - atomic: If true (default), returns boolean. If false returns array.
  2083. * - fieldList: Equivalent to the $fieldList parameter in Model::save()
  2084. * - deep: If set to true, not only directly associated data , but deeper nested associated data is validated as well.
  2085. *
  2086. * @param array $data Record data to validate. This should be an array indexed by association name.
  2087. * @param array $options Options to use when validating record data (see above), See also $options of validates().
  2088. * @return array|boolean If atomic: True on success, or false on failure.
  2089. * Otherwise: array similar to the $data array passed, but values are set to true/false
  2090. * depending on whether each record validated successfully.
  2091. */
  2092. public function validateAssociated($data, $options = array()) {
  2093. $options = array_merge(array('atomic' => true, 'deep' => false), $options);
  2094. $this->validationErrors = $validationErrors = $return = array();
  2095. if (!($this->create($data) && $this->validates($options))) {
  2096. $validationErrors[$this->alias] = $this->validationErrors;
  2097. $return[$this->alias] = false;
  2098. } else {
  2099. $return[$this->alias] = true;
  2100. }
  2101. $associations = $this->getAssociated();
  2102. foreach ($data as $association => $values) {
  2103. $validates = true;
  2104. if (isset($associations[$association])) {
  2105. if (in_array($associations[$association], array('belongsTo', 'hasOne'))) {
  2106. if ($options['deep']) {
  2107. $validates = $this->{$association}->validateAssociated($values, $options);
  2108. } else {
  2109. $validates = $this->{$association}->create($values) !== null && $this->{$association}->validates($options);
  2110. }
  2111. if (is_array($validates)) {
  2112. if (in_array(false, $validates, true)) {
  2113. $validates = false;
  2114. } else {
  2115. $validates = true;
  2116. }
  2117. }
  2118. $return[$association] = $validates;
  2119. } elseif ($associations[$association] === 'hasMany') {
  2120. $validates = $this->{$association}->validateMany($values, $options);
  2121. $return[$association] = $validates;
  2122. }
  2123. if (!$validates || (is_array($validates) && in_array(false, $validates, true))) {
  2124. $validationErrors[$association] = $this->{$association}->validationErrors;
  2125. }
  2126. }
  2127. }
  2128. $this->validationErrors = $validationErrors;
  2129. if (isset($validationErrors[$this->alias])) {
  2130. $this->validationErrors = $validationErrors[$this->alias];
  2131. }
  2132. if (!$options['atomic']) {
  2133. return $return;
  2134. }
  2135. if ($return[$this->alias] === false || !empty($this->validationErrors)) {
  2136. return false;
  2137. }
  2138. return true;
  2139. }
  2140. /**
  2141. * Updates multiple model records based on a set of conditions.
  2142. *
  2143. * @param array $fields Set of fields and values, indexed by fields.
  2144. * Fields are treated as SQL snippets, to insert literal values manually escape your data.
  2145. * @param mixed $conditions Conditions to match, true for all records
  2146. * @return boolean True on success, false on failure
  2147. * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-updateall-array-fields-array-conditions
  2148. */
  2149. public function updateAll($fields, $conditions = true) {
  2150. return $this->getDataSource()->update($this, $fields, null, $conditions);
  2151. }
  2152. /**
  2153. * Removes record for given ID. If no ID is given, the current ID is used. Returns true on success.
  2154. *
  2155. * @param mixed $id ID of record to delete
  2156. * @param boolean $cascade Set to true to delete records that depend on this record
  2157. * @return boolean True on success
  2158. * @link http://book.cakephp.org/2.0/en/models/deleting-data.html
  2159. */
  2160. public function delete($id = null, $cascade = true) {
  2161. if (!empty($id)) {
  2162. $this->id = $id;
  2163. }
  2164. $id = $this->id;
  2165. $event = new CakeEvent('Model.beforeDelete', $this, array($cascade));
  2166. list($event->break, $event->breakOn) = array(true, array(false, null));
  2167. $this->getEventManager()->dispatch($event);
  2168. if (!$event->isStopped()) {
  2169. if (!$this->exists()) {
  2170. return false;
  2171. }
  2172. $db = $this->getDataSource();
  2173. $this->_deleteDependent($id, $cascade);
  2174. $this->_deleteLinks($id);
  2175. $this->id = $id;
  2176. $updateCounterCache = false;
  2177. if (!empty($this->belongsTo)) {
  2178. foreach ($this->belongsTo as $parent => $assoc) {
  2179. if (!empty($assoc['counterCache'])) {
  2180. $updateCounterCache = true;
  2181. break;
  2182. }
  2183. }
  2184. $keys = $this->find('first', array(
  2185. 'fields' => $this->_collectForeignKeys(),
  2186. 'conditions' => array($this->alias . '.' . $this->primaryKey => $id),
  2187. 'recursive' => -1,
  2188. 'callbacks' => false
  2189. ));
  2190. }
  2191. if ($db->delete($this, array($this->alias . '.' . $this->primaryKey => $id))) {
  2192. if ($updateCounterCache) {
  2193. $this->updateCounterCache($keys[$this->alias]);
  2194. }
  2195. $this->getEventManager()->dispatch(new CakeEvent('Model.afterDelete', $this));
  2196. $this->_clearCache();
  2197. $this->id = false;
  2198. return true;
  2199. }
  2200. }
  2201. return false;
  2202. }
  2203. /**
  2204. * Cascades model deletes through associated hasMany and hasOne child records.
  2205. *
  2206. * @param string $id ID of record that was deleted
  2207. * @param boolean $cascade Set to true to delete records that depend on this record
  2208. * @return void
  2209. */
  2210. protected function _deleteDependent($id, $cascade) {
  2211. if (!empty($this->__backAssociation)) {
  2212. $savedAssociatons = $this->__backAssociation;
  2213. $this->__backAssociation = array();
  2214. }
  2215. if ($cascade === true) {
  2216. foreach (array_merge($this->hasMany, $this->hasOne) as $assoc => $data) {
  2217. if ($data['dependent'] === true) {
  2218. $model = $this->{$assoc};
  2219. if ($data['foreignKey'] === false && $data['conditions'] && in_array($this->name, $model->getAssociated('belongsTo'))) {
  2220. $model->recursive = 0;
  2221. $conditions = array($this->escapeField(null, $this->name) => $id);
  2222. } else {
  2223. $model->recursive = -1;
  2224. $conditions = array($model->escapeField($data['foreignKey']) => $id);
  2225. if ($data['conditions']) {
  2226. $conditions = array_merge((array)$data['conditions'], $conditions);
  2227. }
  2228. }
  2229. if (isset($data['exclusive']) && $data['exclusive']) {
  2230. $model->deleteAll($conditions);
  2231. } else {
  2232. $records = $model->find('all', array(
  2233. 'conditions' => $conditions, 'fields' => $model->primaryKey
  2234. ));
  2235. if (!empty($records)) {
  2236. foreach ($records as $record) {
  2237. $model->delete($record[$model->alias][$model->primaryKey]);
  2238. }
  2239. }
  2240. }
  2241. }
  2242. }
  2243. }
  2244. if (isset($savedAssociatons)) {
  2245. $this->__backAssociation = $savedAssociatons;
  2246. }
  2247. }
  2248. /**
  2249. * Cascades model deletes through HABTM join keys.
  2250. *
  2251. * @param string $id ID of record that was deleted
  2252. * @return void
  2253. */
  2254. protected function _deleteLinks($id) {
  2255. foreach ($this->hasAndBelongsToMany as $assoc => $data) {
  2256. list($plugin, $joinModel) = pluginSplit($data['with']);
  2257. $records = $this->{$joinModel}->find('all', array(
  2258. 'conditions' => array($this->{$joinModel}->escapeField($data['foreignKey']) => $id),
  2259. 'fields' => $this->{$joinModel}->primaryKey,
  2260. 'recursive' => -1,
  2261. 'callbacks' => false
  2262. ));
  2263. if (!empty($records)) {
  2264. foreach ($records as $record) {
  2265. $this->{$joinModel}->delete($record[$this->{$joinModel}->alias][$this->{$joinModel}->primaryKey]);
  2266. }
  2267. }
  2268. }
  2269. }
  2270. /**
  2271. * Deletes multiple model records based on a set of conditions.
  2272. *
  2273. * @param mixed $conditions Conditions to match
  2274. * @param boolean $cascade Set to true to delete records that depend on this record
  2275. * @param boolean $callbacks Run callbacks
  2276. * @return boolean True on success, false on failure
  2277. * @link http://book.cakephp.org/2.0/en/models/deleting-data.html#deleteall
  2278. */
  2279. public function deleteAll($conditions, $cascade = true, $callbacks = false) {
  2280. if (empty($conditions)) {
  2281. return false;
  2282. }
  2283. $db = $this->getDataSource();
  2284. if (!$cascade && !$callbacks) {
  2285. return $db->delete($this, $conditions);
  2286. } else {
  2287. $ids = $this->find('all', array_merge(array(
  2288. 'fields' => "{$this->alias}.{$this->primaryKey}",
  2289. 'recursive' => 0), compact('conditions'))
  2290. );
  2291. if ($ids === false) {
  2292. return false;
  2293. }
  2294. $ids = Set::extract($ids, "{n}.{$this->alias}.{$this->primaryKey}");
  2295. if (empty($ids)) {
  2296. return true;
  2297. }
  2298. if ($callbacks) {
  2299. $_id = $this->id;
  2300. $result = true;
  2301. foreach ($ids as $id) {
  2302. $result = ($result && $this->delete($id, $cascade));
  2303. }
  2304. $this->id = $_id;
  2305. return $result;
  2306. } else {
  2307. foreach ($ids as $id) {
  2308. $this->_deleteLinks($id);
  2309. if ($cascade) {
  2310. $this->_deleteDependent($id, $cascade);
  2311. }
  2312. }
  2313. return $db->delete($this, array($this->alias . '.' . $this->primaryKey => $ids));
  2314. }
  2315. }
  2316. }
  2317. /**
  2318. * Collects foreign keys from associations.
  2319. *
  2320. * @param string $type
  2321. * @return array
  2322. */
  2323. protected function _collectForeignKeys($type = 'belongsTo') {
  2324. $result = array();
  2325. foreach ($this->{$type} as $assoc => $data) {
  2326. if (isset($data['foreignKey']) && is_string($data['foreignKey'])) {
  2327. $result[$assoc] = $data['foreignKey'];
  2328. }
  2329. }
  2330. return $result;
  2331. }
  2332. /**
  2333. * Returns true if a record with particular ID exists.
  2334. *
  2335. * If $id is not passed it calls Model::getID() to obtain the current record ID,
  2336. * and then performs a Model::find('count') on the currently configured datasource
  2337. * to ascertain the existence of the record in persistent storage.
  2338. *
  2339. * @param mixed $id ID of record to check for existence
  2340. * @return boolean True if such a record exists
  2341. */
  2342. public function exists($id = null) {
  2343. if ($id === null) {
  2344. $id = $this->getID();
  2345. }
  2346. if ($id === false) {
  2347. return false;
  2348. }
  2349. $conditions = array($this->alias . '.' . $this->primaryKey => $id);
  2350. $query = array('conditions' => $conditions, 'recursive' => -1, 'callbacks' => false);
  2351. return ($this->find('count', $query) > 0);
  2352. }
  2353. /**
  2354. * Returns true if a record that meets given conditions exists.
  2355. *
  2356. * @param array $conditions SQL conditions array
  2357. * @return boolean True if such a record exists
  2358. */
  2359. public function hasAny($conditions = null) {
  2360. return ($this->find('count', array('conditions' => $conditions, 'recursive' => -1)) != false);
  2361. }
  2362. /**
  2363. * Queries the datasource and returns a result set array.
  2364. *
  2365. * Also used to perform notation finds, where the first argument is type of find operation to perform
  2366. * (all / first / count / neighbors / list / threaded),
  2367. * second parameter options for finding ( indexed array, including: 'conditions', 'limit',
  2368. * 'recursive', 'page', 'fields', 'offset', 'order')
  2369. *
  2370. * Eg:
  2371. * {{{
  2372. * find('all', array(
  2373. * 'conditions' => array('name' => 'Thomas Anderson'),
  2374. * 'fields' => array('name', 'email'),
  2375. * 'order' => 'field3 DESC',
  2376. * 'recursive' => 2,
  2377. * 'group' => 'type'
  2378. * ));
  2379. * }}}
  2380. *
  2381. * In addition to the standard query keys above, you can provide Datasource, and behavior specific
  2382. * keys. For example, when using a SQL based datasource you can use the joins key to specify additional
  2383. * joins that should be part of the query.
  2384. *
  2385. * {{{
  2386. * find('all', array(
  2387. * 'conditions' => array('name' => 'Thomas Anderson'),
  2388. * 'joins' => array(
  2389. * array(
  2390. * 'alias' => 'Thought',
  2391. * 'table' => 'thoughts',
  2392. * 'type' => 'LEFT',
  2393. * 'conditions' => '`Thought`.`person_id` = `Person`.`id`'
  2394. * )
  2395. * )
  2396. * ));
  2397. * }}}
  2398. *
  2399. * Behaviors and find types can also define custom finder keys which are passed into find().
  2400. *
  2401. * Specifying 'fields' for notation 'list':
  2402. *
  2403. * - If no fields are specified, then 'id' is used for key and 'model->displayField' is used for value.
  2404. * - If a single field is specified, 'id' is used for key and specified field is used for value.
  2405. * - If three fields are specified, they are used (in order) for key, value and group.
  2406. * - Otherwise, first and second fields are used for key and value.
  2407. *
  2408. * Note: find(list) + database views have issues with MySQL 5.0. Try upgrading to MySQL 5.1 if you
  2409. * have issues with database views.
  2410. * @param string $type Type of find operation (all / first / count / neighbors / list / threaded)
  2411. * @param array $query Option fields (conditions / fields / joins / limit / offset / order / page / group / callbacks)
  2412. * @return array Array of records
  2413. * @link http://book.cakephp.org/2.0/en/models/deleting-data.html#deleteall
  2414. */
  2415. public function find($type = 'first', $query = array()) {
  2416. $this->findQueryType = $type;
  2417. $this->id = $this->getID();
  2418. $query = $this->buildQuery($type, $query);
  2419. if (is_null($query)) {
  2420. return null;
  2421. }
  2422. $results = $this->getDataSource()->read($this, $query);
  2423. $this->resetAssociations();
  2424. if ($query['callbacks'] === true || $query['callbacks'] === 'after') {
  2425. $results = $this->_filterResults($results);
  2426. }
  2427. $this->findQueryType = null;
  2428. if ($type === 'all') {
  2429. return $results;
  2430. } else {
  2431. if ($this->findMethods[$type] === true) {
  2432. return $this->{'_find' . ucfirst($type)}('after', $query, $results);
  2433. }
  2434. }
  2435. }
  2436. /**
  2437. * Builds the query array that is used by the data source to generate the query to fetch the data.
  2438. *
  2439. * @param string $type Type of find operation (all / first / count / neighbors / list / threaded)
  2440. * @param array $query Option fields (conditions / fields / joins / limit / offset / order / page / group / callbacks)
  2441. * @return array Query array or null if it could not be build for some reasons
  2442. * @see Model::find()
  2443. */
  2444. public function buildQuery($type = 'first', $query = array()) {
  2445. $query = array_merge(
  2446. array(
  2447. 'conditions' => null, 'fields' => null, 'joins' => array(), 'limit' => null,
  2448. 'offset' => null, 'order' => null, 'page' => 1, 'group' => null, 'callbacks' => true,
  2449. ),
  2450. (array)$query
  2451. );
  2452. if ($type !== 'all') {
  2453. if ($this->findMethods[$type] === true) {
  2454. $query = $this->{'_find' . ucfirst($type)}('before', $query);
  2455. }
  2456. }
  2457. if (!is_numeric($query['page']) || intval($query['page']) < 1) {
  2458. $query['page'] = 1;
  2459. }
  2460. if ($query['page'] > 1 && !empty($query['limit'])) {
  2461. $query['offset'] = ($query['page'] - 1) * $query['limit'];
  2462. }
  2463. if ($query['order'] === null && $this->order !== null) {
  2464. $query['order'] = $this->order;
  2465. }
  2466. $query['order'] = array($query['order']);
  2467. if ($query['callbacks'] === true || $query['callbacks'] === 'before') {
  2468. $event = new CakeEvent('Model.beforeFind', $this, array($query));
  2469. list($event->break, $event->breakOn, $event->modParams) = array(true, array(false, null), 0);
  2470. $this->getEventManager()->dispatch($event);
  2471. if ($event->isStopped()) {
  2472. return null;
  2473. }
  2474. $query = $event->result === true ? $event->data[0] : $event->result;
  2475. }
  2476. return $query;
  2477. }
  2478. /**
  2479. * Handles the before/after filter logic for find('first') operations. Only called by Model::find().
  2480. *
  2481. * @param string $state Either "before" or "after"
  2482. * @param array $query
  2483. * @param array $results
  2484. * @return array
  2485. * @see Model::find()
  2486. */
  2487. protected function _findFirst($state, $query, $results = array()) {
  2488. if ($state === 'before') {
  2489. $query['limit'] = 1;
  2490. return $query;
  2491. } elseif ($state === 'after') {
  2492. if (empty($results[0])) {
  2493. return false;
  2494. }
  2495. return $results[0];
  2496. }
  2497. }
  2498. /**
  2499. * Handles the before/after filter logic for find('count') operations. Only called by Model::find().
  2500. *
  2501. * @param string $state Either "before" or "after"
  2502. * @param array $query
  2503. * @param array $results
  2504. * @return integer The number of records found, or false
  2505. * @see Model::find()
  2506. */
  2507. protected function _findCount($state, $query, $results = array()) {
  2508. if ($state === 'before') {
  2509. $db = $this->getDataSource();
  2510. $query['order'] = false;
  2511. if (!method_exists($db, 'calculate') || !method_exists($db, 'expression')) {
  2512. return $query;
  2513. }
  2514. if (empty($query['fields'])) {
  2515. $query['fields'] = $db->calculate($this, 'count');
  2516. } elseif (is_string($query['fields']) && !preg_match('/count/i', $query['fields'])) {
  2517. $query['fields'] = $db->calculate($this, 'count', array(
  2518. $db->expression($query['fields']), 'count'
  2519. ));
  2520. }
  2521. return $query;
  2522. } elseif ($state === 'after') {
  2523. foreach (array(0, $this->alias) as $key) {
  2524. if (isset($results[0][$key]['count'])) {
  2525. if (($count = count($results)) > 1) {
  2526. return $count;
  2527. } else {
  2528. return intval($results[0][$key]['count']);
  2529. }
  2530. }
  2531. }
  2532. return false;
  2533. }
  2534. }
  2535. /**
  2536. * Handles the before/after filter logic for find('list') operations. Only called by Model::find().
  2537. *
  2538. * @param string $state Either "before" or "after"
  2539. * @param array $query
  2540. * @param array $results
  2541. * @return array Key/value pairs of primary keys/display field values of all records found
  2542. * @see Model::find()
  2543. */
  2544. protected function _findList($state, $query, $results = array()) {
  2545. if ($state === 'before') {
  2546. if (empty($query['fields'])) {
  2547. $query['fields'] = array("{$this->alias}.{$this->primaryKey}", "{$this->alias}.{$this->displayField}");
  2548. $list = array("{n}.{$this->alias}.{$this->primaryKey}", "{n}.{$this->alias}.{$this->displayField}", null);
  2549. } else {
  2550. if (!is_array($query['fields'])) {
  2551. $query['fields'] = String::tokenize($query['fields']);
  2552. }
  2553. if (count($query['fields']) === 1) {
  2554. if (strpos($query['fields'][0], '.') === false) {
  2555. $query['fields'][0] = $this->alias . '.' . $query['fields'][0];
  2556. }
  2557. $list = array("{n}.{$this->alias}.{$this->primaryKey}", '{n}.' . $query['fields'][0], null);
  2558. $query['fields'] = array("{$this->alias}.{$this->primaryKey}", $query['fields'][0]);
  2559. } elseif (count($query['fields']) === 3) {
  2560. for ($i = 0; $i < 3; $i++) {
  2561. if (strpos($query['fields'][$i], '.') === false) {
  2562. $query['fields'][$i] = $this->alias . '.' . $query['fields'][$i];
  2563. }
  2564. }
  2565. $list = array('{n}.' . $query['fields'][0], '{n}.' . $query['fields'][1], '{n}.' . $query['fields'][2]);
  2566. } else {
  2567. for ($i = 0; $i < 2; $i++) {
  2568. if (strpos($query['fields'][$i], '.') === false) {
  2569. $query['fields'][$i] = $this->alias . '.' . $query['fields'][$i];
  2570. }
  2571. }
  2572. $list = array('{n}.' . $query['fields'][0], '{n}.' . $query['fields'][1], null);
  2573. }
  2574. }
  2575. if (!isset($query['recursive']) || $query['recursive'] === null) {
  2576. $query['recursive'] = -1;
  2577. }
  2578. list($query['list']['keyPath'], $query['list']['valuePath'], $query['list']['groupPath']) = $list;
  2579. return $query;
  2580. } elseif ($state === 'after') {
  2581. if (empty($results)) {
  2582. return array();
  2583. }
  2584. $lst = $query['list'];
  2585. return Set::combine($results, $lst['keyPath'], $lst['valuePath'], $lst['groupPath']);
  2586. }
  2587. }
  2588. /**
  2589. * Detects the previous field's value, then uses logic to find the 'wrapping'
  2590. * rows and return them.
  2591. *
  2592. * @param string $state Either "before" or "after"
  2593. * @param mixed $query
  2594. * @param array $results
  2595. * @return array
  2596. */
  2597. protected function _findNeighbors($state, $query, $results = array()) {
  2598. if ($state === 'before') {
  2599. extract($query);
  2600. $conditions = (array)$conditions;
  2601. if (isset($field) && isset($value)) {
  2602. if (strpos($field, '.') === false) {
  2603. $field = $this->alias . '.' . $field;
  2604. }
  2605. } else {
  2606. $field = $this->alias . '.' . $this->primaryKey;
  2607. $value = $this->id;
  2608. }
  2609. $query['conditions'] = array_merge($conditions, array($field . ' <' => $value));
  2610. $query['order'] = $field . ' DESC';
  2611. $query['limit'] = 1;
  2612. $query['field'] = $field;
  2613. $query['value'] = $value;
  2614. return $query;
  2615. } elseif ($state === 'after') {
  2616. extract($query);
  2617. unset($query['conditions'][$field . ' <']);
  2618. $return = array();
  2619. if (isset($results[0])) {
  2620. $prevVal = Set::extract('/' . str_replace('.', '/', $field), $results[0]);
  2621. $query['conditions'][$field . ' >='] = $prevVal[0];
  2622. $query['conditions'][$field . ' !='] = $value;
  2623. $query['limit'] = 2;
  2624. } else {
  2625. $return['prev'] = null;
  2626. $query['conditions'][$field . ' >'] = $value;
  2627. $query['limit'] = 1;
  2628. }
  2629. $query['order'] = $field . ' ASC';
  2630. $return2 = $this->find('all', $query);
  2631. if (!array_key_exists('prev', $return)) {
  2632. $return['prev'] = $return2[0];
  2633. }
  2634. if (count($return2) === 2) {
  2635. $return['next'] = $return2[1];
  2636. } elseif (count($return2) === 1 && !$return['prev']) {
  2637. $return['next'] = $return2[0];
  2638. } else {
  2639. $return['next'] = null;
  2640. }
  2641. return $return;
  2642. }
  2643. }
  2644. /**
  2645. * In the event of ambiguous results returned (multiple top level results, with different parent_ids)
  2646. * top level results with different parent_ids to the first result will be dropped
  2647. *
  2648. * @param mixed $state
  2649. * @param mixed $query
  2650. * @param array $results
  2651. * @return array Threaded results
  2652. */
  2653. protected function _findThreaded($state, $query, $results = array()) {
  2654. if ($state === 'before') {
  2655. return $query;
  2656. } elseif ($state === 'after') {
  2657. $parent = 'parent_id';
  2658. if (isset($query['parent'])) {
  2659. $parent = $query['parent'];
  2660. }
  2661. return Set::nest($results, array(
  2662. 'idPath' => '/' . $this->alias . '/' . $this->primaryKey,
  2663. 'parentPath' => '/' . $this->alias . '/' . $parent
  2664. ));
  2665. }
  2666. }
  2667. /**
  2668. * Passes query results through model and behavior afterFilter() methods.
  2669. *
  2670. * @param array $results Results to filter
  2671. * @param boolean $primary If this is the primary model results (results from model where the find operation was performed)
  2672. * @return array Set of filtered results
  2673. */
  2674. protected function _filterResults($results, $primary = true) {
  2675. $event = new CakeEvent('Model.afterFind', $this, array($results, $primary));
  2676. $event->modParams = 0;
  2677. $this->getEventManager()->dispatch($event);
  2678. return $event->result;
  2679. }
  2680. /**
  2681. * This resets the association arrays for the model back
  2682. * to those originally defined in the model. Normally called at the end
  2683. * of each call to Model::find()
  2684. *
  2685. * @return boolean Success
  2686. */
  2687. public function resetAssociations() {
  2688. if (!empty($this->__backAssociation)) {
  2689. foreach ($this->_associations as $type) {
  2690. if (isset($this->__backAssociation[$type])) {
  2691. $this->{$type} = $this->__backAssociation[$type];
  2692. }
  2693. }
  2694. $this->__backAssociation = array();
  2695. }
  2696. foreach ($this->_associations as $type) {
  2697. foreach ($this->{$type} as $key => $name) {
  2698. if (property_exists($this, $key) && !empty($this->{$key}->__backAssociation)) {
  2699. $this->{$key}->resetAssociations();
  2700. }
  2701. }
  2702. }
  2703. $this->__backAssociation = array();
  2704. return true;
  2705. }
  2706. /**
  2707. * Returns false if any fields passed match any (by default, all if $or = false) of their matching values.
  2708. *
  2709. * @param array $fields Field/value pairs to search (if no values specified, they are pulled from $this->data)
  2710. * @param boolean $or If false, all fields specified must match in order for a false return value
  2711. * @return boolean False if any records matching any fields are found
  2712. */
  2713. public function isUnique($fields, $or = true) {
  2714. if (!is_array($fields)) {
  2715. $fields = func_get_args();
  2716. if (is_bool($fields[count($fields) - 1])) {
  2717. $or = $fields[count($fields) - 1];
  2718. unset($fields[count($fields) - 1]);
  2719. }
  2720. }
  2721. foreach ($fields as $field => $value) {
  2722. if (is_numeric($field)) {
  2723. unset($fields[$field]);
  2724. $field = $value;
  2725. if (isset($this->data[$this->alias][$field])) {
  2726. $value = $this->data[$this->alias][$field];
  2727. } else {
  2728. $value = null;
  2729. }
  2730. }
  2731. if (strpos($field, '.') === false) {
  2732. unset($fields[$field]);
  2733. $fields[$this->alias . '.' . $field] = $value;
  2734. }
  2735. }
  2736. if ($or) {
  2737. $fields = array('or' => $fields);
  2738. }
  2739. if (!empty($this->id)) {
  2740. $fields[$this->alias . '.' . $this->primaryKey . ' !='] = $this->id;
  2741. }
  2742. return ($this->find('count', array('conditions' => $fields, 'recursive' => -1)) == 0);
  2743. }
  2744. /**
  2745. * Returns a resultset for a given SQL statement. Custom SQL queries should be performed with this method.
  2746. *
  2747. * @param string $sql,... SQL statement
  2748. * @return array Resultset
  2749. * @link http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-query
  2750. */
  2751. public function query($sql) {
  2752. $params = func_get_args();
  2753. $db = $this->getDataSource();
  2754. return call_user_func_array(array(&$db, 'query'), $params);
  2755. }
  2756. /**
  2757. * Returns true if all fields pass validation. Will validate hasAndBelongsToMany associations
  2758. * that use the 'with' key as well. Since _saveMulti is incapable of exiting a save operation.
  2759. *
  2760. * Will validate the currently set data. Use Model::set() or Model::create() to set the active data.
  2761. *
  2762. * @param array $options An optional array of custom options to be made available in the beforeValidate callback
  2763. * @return boolean True if there are no errors
  2764. */
  2765. public function validates($options = array()) {
  2766. $errors = $this->invalidFields($options);
  2767. if (empty($errors) && $errors !== false) {
  2768. $errors = $this->_validateWithModels($options);
  2769. }
  2770. if (is_array($errors)) {
  2771. return count($errors) === 0;
  2772. }
  2773. return $errors;
  2774. }
  2775. /**
  2776. * Returns an array of fields that have failed validation. On the current model.
  2777. *
  2778. * @param string $options An optional array of custom options to be made available in the beforeValidate callback
  2779. * @return array Array of invalid fields
  2780. * @see Model::validates()
  2781. */
  2782. public function invalidFields($options = array()) {
  2783. $event = new CakeEvent('Model.beforeValidate', $this, array($options));
  2784. list($event->break, $event->breakOn) = array(true, false);
  2785. $this->getEventManager()->dispatch($event);
  2786. if ($event->isStopped()) {
  2787. return false;
  2788. }
  2789. if (!isset($this->validate) || empty($this->validate)) {
  2790. return $this->validationErrors;
  2791. }
  2792. $data = $this->data;
  2793. $methods = array_map('strtolower', get_class_methods($this));
  2794. $behaviorMethods = array_keys($this->Behaviors->methods());
  2795. if (isset($data[$this->alias])) {
  2796. $data = $data[$this->alias];
  2797. } elseif (!is_array($data)) {
  2798. $data = array();
  2799. }
  2800. $exists = null;
  2801. $_validate = $this->validate;
  2802. $whitelist = $this->whitelist;
  2803. if (!empty($options['fieldList'])) {
  2804. if (!empty($options['fieldList'][$this->alias]) && is_array($options['fieldList'][$this->alias])) {
  2805. $whitelist = $options['fieldList'][$this->alias];
  2806. } else {
  2807. $whitelist = $options['fieldList'];
  2808. }
  2809. }
  2810. if (!empty($whitelist)) {
  2811. $validate = array();
  2812. foreach ((array)$whitelist as $f) {
  2813. if (!empty($this->validate[$f])) {
  2814. $validate[$f] = $this->validate[$f];
  2815. }
  2816. }
  2817. $this->validate = $validate;
  2818. }
  2819. $validationDomain = $this->validationDomain;
  2820. if (empty($validationDomain)) {
  2821. $validationDomain = 'default';
  2822. }
  2823. foreach ($this->validate as $fieldName => $ruleSet) {
  2824. if (!is_array($ruleSet) || (is_array($ruleSet) && isset($ruleSet['rule']))) {
  2825. $ruleSet = array($ruleSet);
  2826. }
  2827. $default = array(
  2828. 'allowEmpty' => null,
  2829. 'required' => null,
  2830. 'rule' => 'blank',
  2831. 'last' => true,
  2832. 'on' => null
  2833. );
  2834. foreach ($ruleSet as $index => $validator) {
  2835. if (!is_array($validator)) {
  2836. $validator = array('rule' => $validator);
  2837. }
  2838. $validator = array_merge($default, $validator);
  2839. if (!empty($validator['on']) || in_array($validator['required'], array('create', 'update'), true)) {
  2840. if ($exists === null) {
  2841. $exists = $this->exists();
  2842. }
  2843. if ($validator['on'] == 'create' && $exists || $validator['on'] == 'update' && !$exists) {
  2844. continue;
  2845. }
  2846. if ($validator['required'] === 'create' && !$exists || $validator['required'] === 'update' && $exists) {
  2847. $validator['required'] = true;
  2848. }
  2849. }
  2850. $valid = true;
  2851. $requiredFail = (
  2852. (!isset($data[$fieldName]) && $validator['required'] === true) ||
  2853. (
  2854. isset($data[$fieldName]) && (empty($data[$fieldName]) &&
  2855. !is_numeric($data[$fieldName])) && $validator['allowEmpty'] === false
  2856. )
  2857. );
  2858. if (!$requiredFail && array_key_exists($fieldName, $data)) {
  2859. if (empty($data[$fieldName]) && $data[$fieldName] != '0' && $validator['allowEmpty'] === true) {
  2860. break;
  2861. }
  2862. if (is_array($validator['rule'])) {
  2863. $rule = $validator['rule'][0];
  2864. unset($validator['rule'][0]);
  2865. $ruleParams = array_merge(array($data[$fieldName]), array_values($validator['rule']));
  2866. } else {
  2867. $rule = $validator['rule'];
  2868. $ruleParams = array($data[$fieldName]);
  2869. }
  2870. if (in_array(strtolower($rule), $methods)) {
  2871. $ruleParams[] = $validator;
  2872. $ruleParams[0] = array($fieldName => $ruleParams[0]);
  2873. $valid = $this->dispatchMethod($rule, $ruleParams);
  2874. } elseif (in_array($rule, $behaviorMethods) || in_array(strtolower($rule), $behaviorMethods)) {
  2875. $ruleParams[] = $validator;
  2876. $ruleParams[0] = array($fieldName => $ruleParams[0]);
  2877. $valid = $this->Behaviors->dispatchMethod($this, $rule, $ruleParams);
  2878. } elseif (method_exists('Validation', $rule)) {
  2879. $valid = call_user_func_array(array('Validation', $rule), $ruleParams);
  2880. } elseif (!is_array($validator['rule'])) {
  2881. $valid = preg_match($rule, $data[$fieldName]);
  2882. } elseif (Configure::read('debug') > 0) {
  2883. trigger_error(__d('cake_dev', 'Could not find validation handler %s for %s', $rule, $fieldName), E_USER_WARNING);
  2884. }
  2885. }
  2886. if ($requiredFail || !$valid || (is_string($valid) && strlen($valid) > 0)) {
  2887. if (is_string($valid)) {
  2888. $message = $valid;
  2889. } elseif (isset($validator['message'])) {
  2890. $args = null;
  2891. if (is_array($validator['message'])) {
  2892. $message = $validator['message'][0];
  2893. $args = array_slice($validator['message'], 1);
  2894. } else {
  2895. $message = $validator['message'];
  2896. }
  2897. if (is_array($validator['rule']) && $args === null) {
  2898. $args = array_slice($ruleSet[$index]['rule'], 1);
  2899. }
  2900. $message = __d($validationDomain, $message, $args);
  2901. } elseif (is_string($index)) {
  2902. if (is_array($validator['rule'])) {
  2903. $args = array_slice($ruleSet[$index]['rule'], 1);
  2904. $message = __d($validationDomain, $index, $args);
  2905. } else {
  2906. $message = __d($validationDomain, $index);
  2907. }
  2908. } elseif (!$requiredFail && is_numeric($index) && count($ruleSet) > 1) {
  2909. $message = $index + 1;
  2910. } else {
  2911. $message = __d('cake_dev', 'This field cannot be left blank');
  2912. }
  2913. $this->invalidate($fieldName, $message);
  2914. if ($validator['last']) {
  2915. break;
  2916. }
  2917. }
  2918. }
  2919. }
  2920. $this->validate = $_validate;
  2921. return $this->validationErrors;
  2922. }
  2923. /**
  2924. * Runs validation for hasAndBelongsToMany associations that have 'with' keys
  2925. * set. And data in the set() data set.
  2926. *
  2927. * @param array $options Array of options to use on Validation of with models
  2928. * @return boolean Failure of validation on with models.
  2929. * @see Model::validates()
  2930. */
  2931. protected function _validateWithModels($options) {
  2932. $valid = true;
  2933. foreach ($this->hasAndBelongsToMany as $assoc => $association) {
  2934. if (empty($association['with']) || !isset($this->data[$assoc])) {
  2935. continue;
  2936. }
  2937. list($join) = $this->joinModel($this->hasAndBelongsToMany[$assoc]['with']);
  2938. $data = $this->data[$assoc];
  2939. $newData = array();
  2940. foreach ((array)$data as $row) {
  2941. if (isset($row[$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
  2942. $newData[] = $row;
  2943. } elseif (isset($row[$join]) && isset($row[$join][$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
  2944. $newData[] = $row[$join];
  2945. }
  2946. }
  2947. if (empty($newData)) {
  2948. continue;
  2949. }
  2950. foreach ($newData as $data) {
  2951. $data[$this->hasAndBelongsToMany[$assoc]['foreignKey']] = $this->id;
  2952. $this->{$join}->create($data);
  2953. $valid = ($valid && $this->{$join}->validates($options));
  2954. }
  2955. }
  2956. return $valid;
  2957. }
  2958. /**
  2959. * Marks a field as invalid, optionally setting the name of validation
  2960. * rule (in case of multiple validation for field) that was broken.
  2961. *
  2962. * @param string $field The name of the field to invalidate
  2963. * @param mixed $value Name of validation rule that was not failed, or validation message to
  2964. * be returned. If no validation key is provided, defaults to true.
  2965. * @return void
  2966. */
  2967. public function invalidate($field, $value = true) {
  2968. if (!is_array($this->validationErrors)) {
  2969. $this->validationErrors = array();
  2970. }
  2971. $this->validationErrors[$field] []= $value;
  2972. }
  2973. /**
  2974. * Returns true if given field name is a foreign key in this model.
  2975. *
  2976. * @param string $field Returns true if the input string ends in "_id"
  2977. * @return boolean True if the field is a foreign key listed in the belongsTo array.
  2978. */
  2979. public function isForeignKey($field) {
  2980. $foreignKeys = array();
  2981. if (!empty($this->belongsTo)) {
  2982. foreach ($this->belongsTo as $assoc => $data) {
  2983. $foreignKeys[] = $data['foreignKey'];
  2984. }
  2985. }
  2986. return in_array($field, $foreignKeys);
  2987. }
  2988. /**
  2989. * Escapes the field name and prepends the model name. Escaping is done according to the
  2990. * current database driver's rules.
  2991. *
  2992. * @param string $field Field to escape (e.g: id)
  2993. * @param string $alias Alias for the model (e.g: Post)
  2994. * @return string The name of the escaped field for this Model (i.e. id becomes `Post`.`id`).
  2995. */
  2996. public function escapeField($field = null, $alias = null) {
  2997. if (empty($alias)) {
  2998. $alias = $this->alias;
  2999. }
  3000. if (empty($field)) {
  3001. $field = $this->primaryKey;
  3002. }
  3003. $db = $this->getDataSource();
  3004. if (strpos($field, $db->name($alias) . '.') === 0) {
  3005. return $field;
  3006. }
  3007. return $db->name($alias . '.' . $field);
  3008. }
  3009. /**
  3010. * Returns the current record's ID
  3011. *
  3012. * @param integer $list Index on which the composed ID is located
  3013. * @return mixed The ID of the current record, false if no ID
  3014. */
  3015. public function getID($list = 0) {
  3016. if (empty($this->id) || (is_array($this->id) && isset($this->id[0]) && empty($this->id[0]))) {
  3017. return false;
  3018. }
  3019. if (!is_array($this->id)) {
  3020. return $this->id;
  3021. }
  3022. if (isset($this->id[$list]) && !empty($this->id[$list])) {
  3023. return $this->id[$list];
  3024. } elseif (isset($this->id[$list])) {
  3025. return false;
  3026. }
  3027. return current($this->id);
  3028. }
  3029. /**
  3030. * Returns the ID of the last record this model inserted.
  3031. *
  3032. * @return mixed Last inserted ID
  3033. */
  3034. public function getLastInsertID() {
  3035. return $this->getInsertID();
  3036. }
  3037. /**
  3038. * Returns the ID of the last record this model inserted.
  3039. *
  3040. * @return mixed Last inserted ID
  3041. */
  3042. public function getInsertID() {
  3043. return $this->_insertID;
  3044. }
  3045. /**
  3046. * Sets the ID of the last record this model inserted
  3047. *
  3048. * @param mixed $id Last inserted ID
  3049. * @return void
  3050. */
  3051. public function setInsertID($id) {
  3052. $this->_insertID = $id;
  3053. }
  3054. /**
  3055. * Returns the number of rows returned from the last query.
  3056. *
  3057. * @return integer Number of rows
  3058. */
  3059. public function getNumRows() {
  3060. return $this->getDataSource()->lastNumRows();
  3061. }
  3062. /**
  3063. * Returns the number of rows affected by the last query.
  3064. *
  3065. * @return integer Number of rows
  3066. */
  3067. public function getAffectedRows() {
  3068. return $this->getDataSource()->lastAffected();
  3069. }
  3070. /**
  3071. * Sets the DataSource to which this model is bound.
  3072. *
  3073. * @param string $dataSource The name of the DataSource, as defined in app/Config/database.php
  3074. * @return boolean True on success
  3075. * @throws MissingConnectionException
  3076. */
  3077. public function setDataSource($dataSource = null) {
  3078. $oldConfig = $this->useDbConfig;
  3079. if ($dataSource != null) {
  3080. $this->useDbConfig = $dataSource;
  3081. }
  3082. $db = ConnectionManager::getDataSource($this->useDbConfig);
  3083. if (!empty($oldConfig) && isset($db->config['prefix'])) {
  3084. $oldDb = ConnectionManager::getDataSource($oldConfig);
  3085. if (!isset($this->tablePrefix) || (!isset($oldDb->config['prefix']) || $this->tablePrefix == $oldDb->config['prefix'])) {
  3086. $this->tablePrefix = $db->config['prefix'];
  3087. }
  3088. } elseif (isset($db->config['prefix'])) {
  3089. $this->tablePrefix = $db->config['prefix'];
  3090. }
  3091. $this->schemaName = $db->getSchemaName();
  3092. if (empty($db) || !is_object($db)) {
  3093. throw new MissingConnectionException(array('class' => $this->name));
  3094. }
  3095. }
  3096. /**
  3097. * Gets the DataSource to which this model is bound.
  3098. *
  3099. * @return DataSource A DataSource object
  3100. */
  3101. public function getDataSource() {
  3102. if (!$this->_sourceConfigured && $this->useTable !== false) {
  3103. $this->_sourceConfigured = true;
  3104. $this->setSource($this->useTable);
  3105. }
  3106. return ConnectionManager::getDataSource($this->useDbConfig);
  3107. }
  3108. /**
  3109. * Get associations
  3110. *
  3111. * @return array
  3112. */
  3113. public function associations() {
  3114. return $this->_associations;
  3115. }
  3116. /**
  3117. * Gets all the models with which this model is associated.
  3118. *
  3119. * @param string $type Only result associations of this type
  3120. * @return array Associations
  3121. */
  3122. public function getAssociated($type = null) {
  3123. if ($type == null) {
  3124. $associated = array();
  3125. foreach ($this->_associations as $assoc) {
  3126. if (!empty($this->{$assoc})) {
  3127. $models = array_keys($this->{$assoc});
  3128. foreach ($models as $m) {
  3129. $associated[$m] = $assoc;
  3130. }
  3131. }
  3132. }
  3133. return $associated;
  3134. } elseif (in_array($type, $this->_associations)) {
  3135. if (empty($this->{$type})) {
  3136. return array();
  3137. }
  3138. return array_keys($this->{$type});
  3139. } else {
  3140. $assoc = array_merge(
  3141. $this->hasOne,
  3142. $this->hasMany,
  3143. $this->belongsTo,
  3144. $this->hasAndBelongsToMany
  3145. );
  3146. if (array_key_exists($type, $assoc)) {
  3147. foreach ($this->_associations as $a) {
  3148. if (isset($this->{$a}[$type])) {
  3149. $assoc[$type]['association'] = $a;
  3150. break;
  3151. }
  3152. }
  3153. return $assoc[$type];
  3154. }
  3155. return null;
  3156. }
  3157. }
  3158. /**
  3159. * Gets the name and fields to be used by a join model. This allows specifying join fields
  3160. * in the association definition.
  3161. *
  3162. * @param string|array $assoc The model to be joined
  3163. * @param array $keys Any join keys which must be merged with the keys queried
  3164. * @return array
  3165. */
  3166. public function joinModel($assoc, $keys = array()) {
  3167. if (is_string($assoc)) {
  3168. list(, $assoc) = pluginSplit($assoc);
  3169. return array($assoc, array_keys($this->{$assoc}->schema()));
  3170. } elseif (is_array($assoc)) {
  3171. $with = key($assoc);
  3172. return array($with, array_unique(array_merge($assoc[$with], $keys)));
  3173. }
  3174. trigger_error(
  3175. __d('cake_dev', 'Invalid join model settings in %s', $model->alias),
  3176. E_USER_WARNING
  3177. );
  3178. }
  3179. /**
  3180. * Called before each find operation. Return false if you want to halt the find
  3181. * call, otherwise return the (modified) query data.
  3182. *
  3183. * @param array $queryData Data used to execute this query, i.e. conditions, order, etc.
  3184. * @return mixed true if the operation should continue, false if it should abort; or, modified
  3185. * $queryData to continue with new $queryData
  3186. * @link http://book.cakephp.org/view/1048/Callback-Methods#beforeFind-1049
  3187. */
  3188. public function beforeFind($queryData) {
  3189. return true;
  3190. }
  3191. /**
  3192. * Called after each find operation. Can be used to modify any results returned by find().
  3193. * Return value should be the (modified) results.
  3194. *
  3195. * @param mixed $results The results of the find operation
  3196. * @param boolean $primary Whether this model is being queried directly (vs. being queried as an association)
  3197. * @return mixed Result of the find operation
  3198. * @link http://book.cakephp.org/view/1048/Callback-Methods#afterFind-1050
  3199. */
  3200. public function afterFind($results, $primary = false) {
  3201. return $results;
  3202. }
  3203. /**
  3204. * Called before each save operation, after validation. Return a non-true result
  3205. * to halt the save.
  3206. *
  3207. * @param array $options
  3208. * @return boolean True if the operation should continue, false if it should abort
  3209. * @link http://book.cakephp.org/view/1048/Callback-Methods#beforeSave-1052
  3210. */
  3211. public function beforeSave($options = array()) {
  3212. return true;
  3213. }
  3214. /**
  3215. * Called after each successful save operation.
  3216. *
  3217. * @param boolean $created True if this save created a new record
  3218. * @return void
  3219. * @link http://book.cakephp.org/view/1048/Callback-Methods#afterSave-1053
  3220. */
  3221. public function afterSave($created) {
  3222. }
  3223. /**
  3224. * Called before every deletion operation.
  3225. *
  3226. * @param boolean $cascade If true records that depend on this record will also be deleted
  3227. * @return boolean True if the operation should continue, false if it should abort
  3228. * @link http://book.cakephp.org/view/1048/Callback-Methods#beforeDelete-1054
  3229. */
  3230. public function beforeDelete($cascade = true) {
  3231. return true;
  3232. }
  3233. /**
  3234. * Called after every deletion operation.
  3235. *
  3236. * @return void
  3237. * @link http://book.cakephp.org/view/1048/Callback-Methods#afterDelete-1055
  3238. */
  3239. public function afterDelete() {
  3240. }
  3241. /**
  3242. * Called during validation operations, before validation. Please note that custom
  3243. * validation rules can be defined in $validate.
  3244. *
  3245. * @param array $options Options passed from model::save(), see $options of model::save().
  3246. * @return boolean True if validate operation should continue, false to abort
  3247. * @link http://book.cakephp.org/view/1048/Callback-Methods#beforeValidate-1051
  3248. */
  3249. public function beforeValidate($options = array()) {
  3250. return true;
  3251. }
  3252. /**
  3253. * Called when a DataSource-level error occurs.
  3254. *
  3255. * @return void
  3256. * @link http://book.cakephp.org/view/1048/Callback-Methods#onError-1056
  3257. */
  3258. public function onError() {
  3259. }
  3260. /**
  3261. * Clears cache for this model.
  3262. *
  3263. * @param string $type If null this deletes cached views if Cache.check is true
  3264. * Will be used to allow deleting query cache also
  3265. * @return boolean true on delete
  3266. * @todo
  3267. */
  3268. protected function _clearCache($type = null) {
  3269. if ($type === null) {
  3270. if (Configure::read('Cache.check') === true) {
  3271. $assoc[] = strtolower(Inflector::pluralize($this->alias));
  3272. $assoc[] = strtolower(Inflector::underscore(Inflector::pluralize($this->alias)));
  3273. foreach ($this->_associations as $key => $association) {
  3274. foreach ($this->$association as $key => $className) {
  3275. $check = strtolower(Inflector::pluralize($className['className']));
  3276. if (!in_array($check, $assoc)) {
  3277. $assoc[] = strtolower(Inflector::pluralize($className['className']));
  3278. $assoc[] = strtolower(Inflector::underscore(Inflector::pluralize($className['className'])));
  3279. }
  3280. }
  3281. }
  3282. clearCache($assoc);
  3283. return true;
  3284. }
  3285. } else {
  3286. //Will use for query cache deleting
  3287. }
  3288. }
  3289. }