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

/lib/Cake/Model/Model.php

http://github.com/cakephp/cakephp
PHP | 2052 lines | 1019 code | 179 blank | 854 comment | 314 complexity | 6706afad395d68d06e1d66f4a37b1197 MD5 | raw file
Possible License(s): JSON

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * Object-relational mapper.
  4. *
  5. * DBO-backed object data model, for mapping database tables to Cake objects.
  6. *
  7. * PHP versions 5
  8. *
  9. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  10. * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. *
  12. * Licensed under The MIT License
  13. * Redistributions of files must retain the above copyright notice.
  14. *
  15. * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  16. * @link http://cakephp.org CakePHP(tm) Project
  17. * @package Cake.Model
  18. * @since CakePHP(tm) v 0.10.0.0
  19. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  20. */
  21. App::uses('ClassRegistry', 'Utility');
  22. App::uses('Validation', 'Utility');
  23. App::uses('String', 'Utility');
  24. App::uses('Set', 'Utility');
  25. App::uses('BehaviorCollection', 'Model');
  26. App::uses('ModelBehavior', 'Model');
  27. App::uses('ConnectionManager', 'Model');
  28. App::uses('Xml', 'Utility');
  29. /**
  30. * Object-relational mapper.
  31. *
  32. * DBO-backed object data model.
  33. * Automatically selects a database table name based on a pluralized lowercase object class name
  34. * (i.e. class 'User' => table 'users'; class 'Man' => table 'men')
  35. * The table is required to have at least 'id auto_increment' primary key.
  36. *
  37. * @package Cake.Model
  38. * @link http://book.cakephp.org/2.0/en/models.html
  39. */
  40. class Model extends Object {
  41. /**
  42. * The name of the DataSource connection that this Model uses
  43. *
  44. * The value must be an attribute name that you defined in `app/Config/database.php`
  45. * or created using `ConnectionManager::create()`.
  46. *
  47. * @var string
  48. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#usedbconfig
  49. */
  50. public $useDbConfig = 'default';
  51. /**
  52. * Custom database table name, or null/false if no table association is desired.
  53. *
  54. * @var string
  55. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#useTable
  56. */
  57. public $useTable = null;
  58. /**
  59. * Custom display field name. Display fields are used by Scaffold, in SELECT boxes' OPTION elements.
  60. *
  61. * This field is also used in `find('list')` when called with no extra parameters in the fields list
  62. *
  63. * @var string
  64. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#displayField
  65. */
  66. public $displayField = null;
  67. /**
  68. * Value of the primary key ID of the record that this model is currently pointing to.
  69. * Automatically set after database insertions.
  70. *
  71. * @var mixed
  72. */
  73. public $id = false;
  74. /**
  75. * Container for the data that this model gets from persistent storage (usually, a database).
  76. *
  77. * @var array
  78. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#data
  79. */
  80. public $data = array();
  81. /**
  82. * Table name for this Model.
  83. *
  84. * @var string
  85. */
  86. public $table = false;
  87. /**
  88. * The name of the primary key field for this model.
  89. *
  90. * @var string
  91. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#primaryKey
  92. */
  93. public $primaryKey = null;
  94. /**
  95. * Field-by-field table metadata.
  96. *
  97. * @var array
  98. */
  99. protected $_schema = null;
  100. /**
  101. * List of validation rules. It must be an array with the field name as key and using
  102. * as value one of the following possibilities
  103. *
  104. * ### Validating using regular expressions
  105. *
  106. * {{{
  107. * public $validate = array(
  108. * 'name' => '/^[a-z].+$/i'
  109. * );
  110. * }}}
  111. *
  112. * ### Validating using methods (no parameters)
  113. *
  114. * {{{
  115. * public $validate = array(
  116. * 'name' => 'notEmpty'
  117. * );
  118. * }}}
  119. *
  120. * ### Validating using methods (with parameters)
  121. *
  122. * {{{
  123. * public $validate = array(
  124. * 'age' => array(
  125. * 'rule' => array('between', 5, 25)
  126. * )
  127. * );
  128. * }}}
  129. *
  130. * ### Validating using custom method
  131. *
  132. * {{{
  133. * public $validate = array(
  134. * 'password' => array(
  135. * 'rule' => array('customValidation')
  136. * )
  137. * );
  138. * public function customValidation($data) {
  139. * // $data will contain array('password' => 'value')
  140. * if (isset($this->data[$this->alias]['password2'])) {
  141. * return $this->data[$this->alias]['password2'] === current($data);
  142. * }
  143. * return true;
  144. * }
  145. * }}}
  146. *
  147. * ### Validations with messages
  148. *
  149. * The messages will be used in Model::$validationErrors and can be used in the FormHelper
  150. *
  151. * {{{
  152. * public $validate = array(
  153. * 'age' => array(
  154. * 'rule' => array('between', 5, 25),
  155. * 'message' => array('The age must be between %d and %d.')
  156. * )
  157. * );
  158. * }}}
  159. *
  160. * ### Multiple validations to the same field
  161. *
  162. * {{{
  163. * public $validate = array(
  164. * 'login' => array(
  165. * array(
  166. * 'rule' => 'alphaNumeric',
  167. * 'message' => 'Only alphabets and numbers allowed',
  168. * 'last' => true
  169. * ),
  170. * array(
  171. * 'rule' => array('minLength', 8),
  172. * 'message' => array('Minimum length of %d characters')
  173. * )
  174. * )
  175. * );
  176. * }}}
  177. *
  178. * ### Valid keys in validations
  179. *
  180. * - `rule`: String with method name, regular expression (started by slash) or array with method and parameters
  181. * - `message`: String with the message or array if have multiple parameters. See http://php.net/sprintf
  182. * - `last`: Boolean value to indicate if continue validating the others rules if the current fail [Default: true]
  183. * - `required`: Boolean value to indicate if the field must be present on save
  184. * - `allowEmpty`: Boolean value to indicate if the field can be empty
  185. * - `on`: Possible values: `update`, `create`. Indicate to apply this rule only on update or create
  186. *
  187. * @var array
  188. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#validate
  189. * @link http://book.cakephp.org/2.0/en/models/data-validation.html
  190. */
  191. public $validate = array();
  192. /**
  193. * List of validation errors.
  194. *
  195. * @var array
  196. */
  197. public $validationErrors = array();
  198. /**
  199. * Name of the validation string domain to use when translating validation errors.
  200. *
  201. * @var string
  202. */
  203. public $validationDomain = null;
  204. /**
  205. * Database table prefix for tables in model.
  206. *
  207. * @var string
  208. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#tableprefix
  209. */
  210. public $tablePrefix = null;
  211. /**
  212. * Name of the model.
  213. *
  214. * @var string
  215. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#name
  216. */
  217. public $name = null;
  218. /**
  219. * Alias name for model.
  220. *
  221. * @var string
  222. */
  223. public $alias = null;
  224. /**
  225. * List of table names included in the model description. Used for associations.
  226. *
  227. * @var array
  228. */
  229. public $tableToModel = array();
  230. /**
  231. * Whether or not to cache queries for this model. This enables in-memory
  232. * caching only, the results are not stored beyond the current request.
  233. *
  234. * @var boolean
  235. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#cacheQueries
  236. */
  237. public $cacheQueries = false;
  238. /**
  239. * Detailed list of belongsTo associations.
  240. *
  241. * ### Basic usage
  242. *
  243. * `public $belongsTo = array('Group', 'Department');`
  244. *
  245. * ### Detailed configuration
  246. *
  247. * {{{
  248. * public $belongsTo = array(
  249. * 'Group',
  250. * 'Department' => array(
  251. * 'className' => 'Department',
  252. * 'foreignKey' => 'department_id'
  253. * )
  254. * );
  255. * }}}
  256. *
  257. * ### Possible keys in association
  258. *
  259. * - `className`: the classname of the model being associated to the current model.
  260. * If you’re defining a ‘Profile belongsTo User’ relationship, the className key should equal ‘User.’
  261. * - `foreignKey`: the name of the foreign key found in the current model. This is
  262. * especially handy if you need to define multiple belongsTo relationships. The default
  263. * value for this key is the underscored, singular name of the other model, suffixed with ‘_id’.
  264. * - `conditions`: An SQL fragment used to filter related model records. It’s good
  265. * practice to use model names in SQL fragments: “User.active = 1” is always
  266. * better than just “active = 1.”
  267. * - `type`: the type of the join to use in the SQL query, default is LEFT which
  268. * may not fit your needs in all situations, INNER may be helpful when you want
  269. * everything from your main and associated models or nothing at all!(effective
  270. * when used with some conditions of course). (NB: type value is in lower case - i.e. left, inner)
  271. * - `fields`: A list of fields to be retrieved when the associated model data is
  272. * fetched. Returns all fields by default.
  273. * - `order`: An SQL fragment that defines the sorting order for the returned associated rows.
  274. * - `counterCache`: If set to true the associated Model will automatically increase or
  275. * decrease the “[singular_model_name]_count” field in the foreign table whenever you do
  276. * a save() or delete(). If its a string then its the field name to use. The value in the
  277. * counter field represents the number of related rows.
  278. * - `counterScope`: Optional conditions array to use for updating counter cache field.
  279. *
  280. * @var array
  281. * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#belongsto
  282. */
  283. public $belongsTo = array();
  284. /**
  285. * Detailed list of hasOne associations.
  286. *
  287. * ### Basic usage
  288. *
  289. * `public $hasOne = array('Profile', 'Address');`
  290. *
  291. * ### Detailed configuration
  292. *
  293. * {{{
  294. * public $hasOne = array(
  295. * 'Profile',
  296. * 'Address' => array(
  297. * 'className' => 'Address',
  298. * 'foreignKey' => 'user_id'
  299. * )
  300. * );
  301. * }}}
  302. *
  303. * ### Possible keys in association
  304. *
  305. * - `className`: the classname of the model being associated to the current model.
  306. * If you’re defining a ‘User hasOne Profile’ relationship, the className key should equal ‘Profile.’
  307. * - `foreignKey`: the name of the foreign key found in the other model. This is
  308. * especially handy if you need to define multiple hasOne relationships.
  309. * The default value for this key is the underscored, singular name of the
  310. * current model, suffixed with ‘_id’. In the example above it would default to 'user_id'.
  311. * - `conditions`: An SQL fragment used to filter related model records. It’s good
  312. * practice to use model names in SQL fragments: “Profile.approved = 1” is
  313. * always better than just “approved = 1.”
  314. * - `fields`: A list of fields to be retrieved when the associated model data is
  315. * fetched. Returns all fields by default.
  316. * - `order`: An SQL fragment that defines the sorting order for the returned associated rows.
  317. * - `dependent`: When the dependent key is set to true, and the model’s delete()
  318. * method is called with the cascade parameter set to true, associated model
  319. * records are also deleted. In this case we set it true so that deleting a
  320. * User will also delete her associated Profile.
  321. *
  322. * @var array
  323. * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasone
  324. */
  325. public $hasOne = array();
  326. /**
  327. * Detailed list of hasMany associations.
  328. *
  329. * ### Basic usage
  330. *
  331. * `public $hasMany = array('Comment', 'Task');`
  332. *
  333. * ### Detailed configuration
  334. *
  335. * {{{
  336. * public $hasMany = array(
  337. * 'Comment',
  338. * 'Task' => array(
  339. * 'className' => 'Task',
  340. * 'foreignKey' => 'user_id'
  341. * )
  342. * );
  343. * }}}
  344. *
  345. * ### Possible keys in association
  346. *
  347. * - `className`: the classname of the model being associated to the current model.
  348. * If you’re defining a ‘User hasMany Comment’ relationship, the className key should equal ‘Comment.’
  349. * - `foreignKey`: the name of the foreign key found in the other model. This is
  350. * especially handy if you need to define multiple hasMany relationships. The default
  351. * value for this key is the underscored, singular name of the actual model, suffixed with ‘_id’.
  352. * - `conditions`: An SQL fragment used to filter related model records. It’s good
  353. * practice to use model names in SQL fragments: “Comment.status = 1” is always
  354. * better than just “status = 1.”
  355. * - `fields`: A list of fields to be retrieved when the associated model data is
  356. * fetched. Returns all fields by default.
  357. * - `order`: An SQL fragment that defines the sorting order for the returned associated rows.
  358. * - `limit`: The maximum number of associated rows you want returned.
  359. * - `offset`: The number of associated rows to skip over (given the current
  360. * conditions and order) before fetching and associating.
  361. * - `dependent`: When dependent is set to true, recursive model deletion is
  362. * possible. In this example, Comment records will be deleted when their
  363. * associated User record has been deleted.
  364. * - `exclusive`: When exclusive is set to true, recursive model deletion does
  365. * the delete with a deleteAll() call, instead of deleting each entity separately.
  366. * This greatly improves performance, but may not be ideal for all circumstances.
  367. * - `finderQuery`: A complete SQL query CakePHP can use to fetch associated model
  368. * records. This should be used in situations that require very custom results.
  369. *
  370. * @var array
  371. * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasmany
  372. */
  373. public $hasMany = array();
  374. /**
  375. * Detailed list of hasAndBelongsToMany associations.
  376. *
  377. * ### Basic usage
  378. *
  379. * `public $hasAndBelongsToMany = array('Role', 'Address');`
  380. *
  381. * ### Detailed configuration
  382. *
  383. * {{{
  384. * public $hasAndBelongsToMany = array(
  385. * 'Role',
  386. * 'Address' => array(
  387. * 'className' => 'Address',
  388. * 'foreignKey' => 'user_id',
  389. * 'associationForeignKey' => 'address_id',
  390. * 'joinTable' => 'addresses_users'
  391. * )
  392. * );
  393. * }}}
  394. *
  395. * ### Possible keys in association
  396. *
  397. * - `className`: the classname of the model being associated to the current model.
  398. * If you're defining a ‘Recipe HABTM Tag' relationship, the className key should equal ‘Tag.'
  399. * - `joinTable`: The name of the join table used in this association (if the
  400. * current table doesn't adhere to the naming convention for HABTM join tables).
  401. * - `with`: Defines the name of the model for the join table. By default CakePHP
  402. * will auto-create a model for you. Using the example above it would be called
  403. * RecipesTag. By using this key you can override this default name. The join
  404. * table model can be used just like any "regular" model to access the join table directly.
  405. * - `foreignKey`: the name of the foreign key found in the current model.
  406. * This is especially handy if you need to define multiple HABTM relationships.
  407. * The default value for this key is the underscored, singular name of the
  408. * current model, suffixed with ‘_id'.
  409. * - `associationForeignKey`: the name of the foreign key found in the other model.
  410. * This is especially handy if you need to define multiple HABTM relationships.
  411. * The default value for this key is the underscored, singular name of the other
  412. * model, suffixed with ‘_id'.
  413. * - `unique`: If true (default value) cake will first delete existing relationship
  414. * records in the foreign keys table before inserting new ones, when updating a
  415. * record. So existing associations need to be passed again when updating.
  416. * - `conditions`: An SQL fragment used to filter related model records. It's good
  417. * practice to use model names in SQL fragments: "Comment.status = 1" is always
  418. * better than just "status = 1."
  419. * - `fields`: A list of fields to be retrieved when the associated model data is
  420. * fetched. Returns all fields by default.
  421. * - `order`: An SQL fragment that defines the sorting order for the returned associated rows.
  422. * - `limit`: The maximum number of associated rows you want returned.
  423. * - `offset`: The number of associated rows to skip over (given the current
  424. * conditions and order) before fetching and associating.
  425. * - `finderQuery`, `deleteQuery`, `insertQuery`: A complete SQL query CakePHP
  426. * can use to fetch, delete, or create new associated model records. This should
  427. * be used in situations that require very custom results.
  428. *
  429. * @var array
  430. * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasandbelongstomany-habtm
  431. */
  432. public $hasAndBelongsToMany = array();
  433. /**
  434. * List of behaviors to load when the model object is initialized. Settings can be
  435. * passed to behaviors by using the behavior name as index. Eg:
  436. *
  437. * public $actsAs = array('Translate', 'MyBehavior' => array('setting1' => 'value1'))
  438. *
  439. * @var array
  440. * @link http://book.cakephp.org/2.0/en/models/behaviors.html#using-behaviors
  441. */
  442. public $actsAs = null;
  443. /**
  444. * Holds the Behavior objects currently bound to this model.
  445. *
  446. * @var BehaviorCollection
  447. */
  448. public $Behaviors = null;
  449. /**
  450. * Whitelist of fields allowed to be saved.
  451. *
  452. * @var array
  453. */
  454. public $whitelist = array();
  455. /**
  456. * Whether or not to cache sources for this model.
  457. *
  458. * @var boolean
  459. */
  460. public $cacheSources = true;
  461. /**
  462. * Type of find query currently executing.
  463. *
  464. * @var string
  465. */
  466. public $findQueryType = null;
  467. /**
  468. * Number of associations to recurse through during find calls. Fetches only
  469. * the first level by default.
  470. *
  471. * @var integer
  472. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#recursive
  473. */
  474. public $recursive = 1;
  475. /**
  476. * The column name(s) and direction(s) to order find results by default.
  477. *
  478. * public $order = "Post.created DESC";
  479. * public $order = array("Post.view_count DESC", "Post.rating DESC");
  480. *
  481. * @var string
  482. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#order
  483. */
  484. public $order = null;
  485. /**
  486. * Array of virtual fields this model has. Virtual fields are aliased
  487. * SQL expressions. Fields added to this property will be read as other fields in a model
  488. * but will not be saveable.
  489. *
  490. * `public $virtualFields = array('two' => '1 + 1');`
  491. *
  492. * Is a simplistic example of how to set virtualFields
  493. *
  494. * @var array
  495. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#virtualfields
  496. */
  497. public $virtualFields = array();
  498. /**
  499. * Default list of association keys.
  500. *
  501. * @var array
  502. */
  503. protected $_associationKeys = array(
  504. 'belongsTo' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'counterCache'),
  505. 'hasOne' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'dependent'),
  506. 'hasMany' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'dependent', 'exclusive', 'finderQuery', 'counterQuery'),
  507. 'hasAndBelongsToMany' => array('className', 'joinTable', 'with', 'foreignKey', 'associationForeignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'unique', 'finderQuery', 'deleteQuery', 'insertQuery')
  508. );
  509. /**
  510. * Holds provided/generated association key names and other data for all associations.
  511. *
  512. * @var array
  513. */
  514. protected $_associations = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
  515. /**
  516. * Holds model associations temporarily to allow for dynamic (un)binding.
  517. *
  518. * @var array
  519. */
  520. public $__backAssociation = array();
  521. /**
  522. * Back inner association
  523. *
  524. * @var array
  525. */
  526. public $__backInnerAssociation = array();
  527. /**
  528. * Back original association
  529. *
  530. * @var array
  531. */
  532. public $__backOriginalAssociation = array();
  533. /**
  534. * Back containable association
  535. *
  536. * @var array
  537. */
  538. public $__backContainableAssociation = array();
  539. /**
  540. * The ID of the model record that was last inserted.
  541. *
  542. * @var integer
  543. */
  544. protected $_insertID = null;
  545. /**
  546. * Has the datasource been configured.
  547. *
  548. * @var boolean
  549. * @see Model::getDataSource
  550. */
  551. protected $_sourceConfigured = false;
  552. /**
  553. * List of valid finder method options, supplied as the first parameter to find().
  554. *
  555. * @var array
  556. */
  557. public $findMethods = array(
  558. 'all' => true, 'first' => true, 'count' => true,
  559. 'neighbors' => true, 'list' => true, 'threaded' => true
  560. );
  561. /**
  562. * Constructor. Binds the model's database table to the object.
  563. *
  564. * If `$id` is an array it can be used to pass several options into the model.
  565. *
  566. * - id - The id to start the model on.
  567. * - table - The table to use for this model.
  568. * - ds - The connection name this model is connected to.
  569. * - name - The name of the model eg. Post.
  570. * - alias - The alias of the model, this is used for registering the instance in the `ClassRegistry`.
  571. * eg. `ParentThread`
  572. *
  573. * ### Overriding Model's __construct method.
  574. *
  575. * When overriding Model::__construct() be careful to include and pass in all 3 of the
  576. * arguments to `parent::__construct($id, $table, $ds);`
  577. *
  578. * ### Dynamically creating models
  579. *
  580. * You can dynamically create model instances using the $id array syntax.
  581. *
  582. * {{{
  583. * $Post = new Model(array('table' => 'posts', 'name' => 'Post', 'ds' => 'connection2'));
  584. * }}}
  585. *
  586. * Would create a model attached to the posts table on connection2. Dynamic model creation is useful
  587. * when you want a model object that contains no associations or attached behaviors.
  588. *
  589. * @param mixed $id Set this ID for this model on startup, can also be an array of options, see above.
  590. * @param string $table Name of database table to use.
  591. * @param string $ds DataSource connection name.
  592. */
  593. public function __construct($id = false, $table = null, $ds = null) {
  594. parent::__construct();
  595. if (is_array($id)) {
  596. extract(array_merge(
  597. array(
  598. 'id' => $this->id, 'table' => $this->useTable, 'ds' => $this->useDbConfig,
  599. 'name' => $this->name, 'alias' => $this->alias
  600. ),
  601. $id
  602. ));
  603. }
  604. if ($this->name === null) {
  605. $this->name = (isset($name) ? $name : get_class($this));
  606. }
  607. if ($this->alias === null) {
  608. $this->alias = (isset($alias) ? $alias : $this->name);
  609. }
  610. if ($this->primaryKey === null) {
  611. $this->primaryKey = 'id';
  612. }
  613. ClassRegistry::addObject($this->alias, $this);
  614. $this->id = $id;
  615. unset($id);
  616. if ($table === false) {
  617. $this->useTable = false;
  618. } elseif ($table) {
  619. $this->useTable = $table;
  620. }
  621. if ($ds !== null) {
  622. $this->useDbConfig = $ds;
  623. }
  624. if (is_subclass_of($this, 'AppModel')) {
  625. $merge = array('actsAs', 'findMethods');
  626. $parentClass = get_parent_class($this);
  627. if ($parentClass !== 'AppModel') {
  628. $this->_mergeVars($merge, $parentClass);
  629. }
  630. $this->_mergeVars($merge, 'AppModel');
  631. }
  632. $this->Behaviors = new BehaviorCollection();
  633. if ($this->useTable !== false) {
  634. if ($this->useTable === null) {
  635. $this->useTable = Inflector::tableize($this->name);
  636. }
  637. if ($this->displayField == null) {
  638. unset($this->displayField);
  639. }
  640. $this->table = $this->useTable;
  641. $this->tableToModel[$this->table] = $this->alias;
  642. } elseif ($this->table === false) {
  643. $this->table = Inflector::tableize($this->name);
  644. }
  645. if ($this->tablePrefix === null) {
  646. unset($this->tablePrefix);
  647. }
  648. $this->_createLinks();
  649. $this->Behaviors->init($this->alias, $this->actsAs);
  650. }
  651. /**
  652. * Handles custom method calls, like findBy<field> for DB models,
  653. * and custom RPC calls for remote data sources.
  654. *
  655. * @param string $method Name of method to call.
  656. * @param array $params Parameters for the method.
  657. * @return mixed Whatever is returned by called method
  658. */
  659. public function __call($method, $params) {
  660. $result = $this->Behaviors->dispatchMethod($this, $method, $params);
  661. if ($result !== array('unhandled')) {
  662. return $result;
  663. }
  664. $return = $this->getDataSource()->query($method, $params, $this);
  665. return $return;
  666. }
  667. /**
  668. * Handles the lazy loading of model associations by looking in the association arrays for the requested variable
  669. *
  670. * @param string $name variable tested for existence in class
  671. * @return boolean true if the variable exists (if is a not loaded model association it will be created), false otherwise
  672. */
  673. public function __isset($name) {
  674. $className = false;
  675. foreach ($this->_associations as $type) {
  676. if (isset($name, $this->{$type}[$name])) {
  677. $className = empty($this->{$type}[$name]['className']) ? $name : $this->{$type}[$name]['className'];
  678. break;
  679. }
  680. elseif (isset($name, $this->__backAssociation[$type][$name])) {
  681. $className = empty($this->__backAssociation[$type][$name]['className']) ?
  682. $name : $this->__backAssociation[$type][$name]['className'];
  683. break;
  684. } else if ($type == 'hasAndBelongsToMany') {
  685. foreach ($this->{$type} as $k => $relation) {
  686. if (empty($relation['with'])) {
  687. continue;
  688. }
  689. if (is_array($relation['with'])) {
  690. if (key($relation['with']) === $name) {
  691. $className = $name;
  692. }
  693. } else {
  694. list($plugin, $class) = pluginSplit($relation['with']);
  695. if ($class === $name) {
  696. $className = $relation['with'];
  697. }
  698. }
  699. if ($className) {
  700. $assocKey = $k;
  701. $dynamic = !empty($relation['dynamicWith']);
  702. break(2);
  703. }
  704. }
  705. }
  706. }
  707. if (!$className) {
  708. return false;
  709. }
  710. list($plugin, $className) = pluginSplit($className);
  711. if (!ClassRegistry::isKeySet($className) && !empty($dynamic)) {
  712. $this->{$className} = new AppModel(array(
  713. 'name' => $className,
  714. 'table' => $this->hasAndBelongsToMany[$assocKey]['joinTable'],
  715. 'ds' => $this->useDbConfig
  716. ));
  717. } else {
  718. $this->_constructLinkedModel($name, $className, $plugin);
  719. }
  720. if (!empty($assocKey)) {
  721. $this->hasAndBelongsToMany[$assocKey]['joinTable'] = $this->{$name}->table;
  722. if (count($this->{$name}->schema()) <= 2 && $this->{$name}->primaryKey !== false) {
  723. $this->{$name}->primaryKey = $this->hasAndBelongsToMany[$assocKey]['foreignKey'];
  724. }
  725. }
  726. return true;
  727. }
  728. /**
  729. * Returns the value of the requested variable if it can be set by __isset()
  730. *
  731. * @param string $name variable requested for it's value or reference
  732. * @return mixed value of requested variable if it is set
  733. */
  734. public function __get($name) {
  735. if ($name === 'displayField') {
  736. return $this->displayField = $this->hasField(array('title', 'name', $this->primaryKey));
  737. }
  738. if ($name === 'tablePrefix') {
  739. $this->setDataSource();
  740. if (property_exists($this, 'tablePrefix')) {
  741. return $this->tablePrefix;
  742. }
  743. return $this->tablePrefix = null;
  744. }
  745. if (isset($this->{$name})) {
  746. return $this->{$name};
  747. }
  748. }
  749. /**
  750. * Bind model associations on the fly.
  751. *
  752. * If `$reset` is false, association will not be reset
  753. * to the originals defined in the model
  754. *
  755. * Example: Add a new hasOne binding to the Profile model not
  756. * defined in the model source code:
  757. *
  758. * `$this->User->bindModel( array('hasOne' => array('Profile')) );`
  759. *
  760. * Bindings that are not made permanent will be reset by the next Model::find() call on this
  761. * model.
  762. *
  763. * @param array $params Set of bindings (indexed by binding type)
  764. * @param boolean $reset Set to false to make the binding permanent
  765. * @return boolean Success
  766. * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#creating-and-destroying-associations-on-the-fly
  767. */
  768. public function bindModel($params, $reset = true) {
  769. foreach ($params as $assoc => $model) {
  770. if ($reset === true && !isset($this->__backAssociation[$assoc])) {
  771. $this->__backAssociation[$assoc] = $this->{$assoc};
  772. }
  773. foreach ($model as $key => $value) {
  774. $assocName = $key;
  775. if (is_numeric($key)) {
  776. $assocName = $value;
  777. $value = array();
  778. }
  779. $modelName = $assocName;
  780. $this->{$assoc}[$assocName] = $value;
  781. if (property_exists($this, $assocName)) {
  782. unset($this->{$assocName});
  783. }
  784. if ($reset === false && isset($this->__backAssociation[$assoc])) {
  785. $this->__backAssociation[$assoc][$assocName] = $value;
  786. }
  787. }
  788. }
  789. $this->_createLinks();
  790. return true;
  791. }
  792. /**
  793. * Turn off associations on the fly.
  794. *
  795. * If $reset is false, association will not be reset
  796. * to the originals defined in the model
  797. *
  798. * Example: Turn off the associated Model Support request,
  799. * to temporarily lighten the User model:
  800. *
  801. * `$this->User->unbindModel( array('hasMany' => array('Supportrequest')) );`
  802. *
  803. * unbound models that are not made permanent will reset with the next call to Model::find()
  804. *
  805. * @param array $params Set of bindings to unbind (indexed by binding type)
  806. * @param boolean $reset Set to false to make the unbinding permanent
  807. * @return boolean Success
  808. * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#creating-and-destroying-associations-on-the-fly
  809. */
  810. public function unbindModel($params, $reset = true) {
  811. foreach ($params as $assoc => $models) {
  812. if ($reset === true && !isset($this->__backAssociation[$assoc])) {
  813. $this->__backAssociation[$assoc] = $this->{$assoc};
  814. }
  815. foreach ($models as $model) {
  816. if ($reset === false && isset($this->__backAssociation[$assoc][$model])) {
  817. unset($this->__backAssociation[$assoc][$model]);
  818. }
  819. unset($this->{$assoc}[$model]);
  820. }
  821. }
  822. return true;
  823. }
  824. /**
  825. * Create a set of associations.
  826. *
  827. * @return void
  828. */
  829. protected function _createLinks() {
  830. foreach ($this->_associations as $type) {
  831. if (!is_array($this->{$type})) {
  832. $this->{$type} = explode(',', $this->{$type});
  833. foreach ($this->{$type} as $i => $className) {
  834. $className = trim($className);
  835. unset ($this->{$type}[$i]);
  836. $this->{$type}[$className] = array();
  837. }
  838. }
  839. if (!empty($this->{$type})) {
  840. foreach ($this->{$type} as $assoc => $value) {
  841. $plugin = null;
  842. if (is_numeric($assoc)) {
  843. unset ($this->{$type}[$assoc]);
  844. $assoc = $value;
  845. $value = array();
  846. if (strpos($assoc, '.') !== false) {
  847. list($plugin, $assoc) = pluginSplit($assoc);
  848. $this->{$type}[$assoc] = array('className' => $plugin. '.' . $assoc);
  849. } else {
  850. $this->{$type}[$assoc] = $value;
  851. }
  852. }
  853. $this->_generateAssociation($type, $assoc);
  854. }
  855. }
  856. }
  857. }
  858. /**
  859. * Protected helper method to create associated models of a given class.
  860. *
  861. * @param string $assoc Association name
  862. * @param string $className Class name
  863. * @param string $plugin name of the plugin where $className is located
  864. * examples: public $hasMany = array('Assoc' => array('className' => 'ModelName'));
  865. * usage: $this->Assoc->modelMethods();
  866. *
  867. * public $hasMany = array('ModelName');
  868. * usage: $this->ModelName->modelMethods();
  869. * @return void
  870. */
  871. protected function _constructLinkedModel($assoc, $className = null, $plugin = null) {
  872. if (empty($className)) {
  873. $className = $assoc;
  874. }
  875. if (!isset($this->{$assoc}) || $this->{$assoc}->name !== $className) {
  876. if ($plugin) {
  877. $plugin .= '.';
  878. }
  879. $model = array('class' => $plugin . $className, 'alias' => $assoc);
  880. $this->{$assoc} = ClassRegistry::init($model);
  881. if ($plugin) {
  882. ClassRegistry::addObject($plugin . $className, $this->{$assoc});
  883. }
  884. if ($assoc) {
  885. $this->tableToModel[$this->{$assoc}->table] = $assoc;
  886. }
  887. }
  888. }
  889. /**
  890. * Build an array-based association from string.
  891. *
  892. * @param string $type 'belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany'
  893. * @param string $assocKey
  894. * @return void
  895. */
  896. protected function _generateAssociation($type, $assocKey) {
  897. $class = $assocKey;
  898. $dynamicWith = false;
  899. foreach ($this->_associationKeys[$type] as $key) {
  900. if (!isset($this->{$type}[$assocKey][$key]) || $this->{$type}[$assocKey][$key] === null) {
  901. $data = '';
  902. switch ($key) {
  903. case 'fields':
  904. $data = '';
  905. break;
  906. case 'foreignKey':
  907. $data = (($type == 'belongsTo') ? Inflector::underscore($assocKey) : Inflector::singularize($this->table)) . '_id';
  908. break;
  909. case 'associationForeignKey':
  910. $data = Inflector::singularize($this->{$class}->table) . '_id';
  911. break;
  912. case 'with':
  913. $data = Inflector::camelize(Inflector::singularize($this->{$type}[$assocKey]['joinTable']));
  914. $dynamicWith = true;
  915. break;
  916. case 'joinTable':
  917. $tables = array($this->table, $this->{$class}->table);
  918. sort ($tables);
  919. $data = $tables[0] . '_' . $tables[1];
  920. break;
  921. case 'className':
  922. $data = $class;
  923. break;
  924. case 'unique':
  925. $data = true;
  926. break;
  927. }
  928. $this->{$type}[$assocKey][$key] = $data;
  929. }
  930. if ($dynamicWith) {
  931. $this->{$type}[$assocKey]['dynamicWith'] = true;
  932. }
  933. }
  934. }
  935. /**
  936. * Sets a custom table for your controller class. Used by your controller to select a database table.
  937. *
  938. * @param string $tableName Name of the custom table
  939. * @throws MissingTableException when database table $tableName is not found on data source
  940. * @return void
  941. */
  942. public function setSource($tableName) {
  943. $this->setDataSource($this->useDbConfig);
  944. $db = ConnectionManager::getDataSource($this->useDbConfig);
  945. $db->cacheSources = ($this->cacheSources && $db->cacheSources);
  946. if (method_exists($db, 'listSources')) {
  947. $sources = $db->listSources();
  948. if (is_array($sources) && !in_array(strtolower($this->tablePrefix . $tableName), array_map('strtolower', $sources))) {
  949. throw new MissingTableException(array(
  950. 'table' => $this->tablePrefix . $tableName,
  951. 'class' => $this->alias
  952. ));
  953. }
  954. $this->_schema = null;
  955. }
  956. $this->table = $this->useTable = $tableName;
  957. $this->tableToModel[$this->table] = $this->alias;
  958. }
  959. /**
  960. * This function does two things:
  961. *
  962. * 1. it scans the array $one for the primary key,
  963. * and if that's found, it sets the current id to the value of $one[id].
  964. * For all other keys than 'id' the keys and values of $one are copied to the 'data' property of this object.
  965. * 2. Returns an array with all of $one's keys and values.
  966. * (Alternative indata: two strings, which are mangled to
  967. * a one-item, two-dimensional array using $one for a key and $two as its value.)
  968. *
  969. * @param mixed $one Array or string of data
  970. * @param string $two Value string for the alternative indata method
  971. * @return array Data with all of $one's keys and values
  972. * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html
  973. */
  974. public function set($one, $two = null) {
  975. if (!$one) {
  976. return;
  977. }
  978. if (is_object($one)) {
  979. if ($one instanceof SimpleXMLElement || $one instanceof DOMNode) {
  980. $one = $this->_normalizeXmlData(Xml::toArray($one));
  981. } else {
  982. $one = Set::reverse($one);
  983. }
  984. }
  985. if (is_array($one)) {
  986. $data = $one;
  987. if (empty($one[$this->alias])) {
  988. if ($this->getAssociated(key($one)) === null) {
  989. $data = array($this->alias => $one);
  990. }
  991. }
  992. } else {
  993. $data = array($this->alias => array($one => $two));
  994. }
  995. foreach ($data as $modelName => $fieldSet) {
  996. if (is_array($fieldSet)) {
  997. foreach ($fieldSet as $fieldName => $fieldValue) {
  998. if (isset($this->validationErrors[$fieldName])) {
  999. unset ($this->validationErrors[$fieldName]);
  1000. }
  1001. if ($modelName === $this->alias) {
  1002. if ($fieldName === $this->primaryKey) {
  1003. $this->id = $fieldValue;
  1004. }
  1005. }
  1006. if (is_array($fieldValue) || is_object($fieldValue)) {
  1007. $fieldValue = $this->deconstruct($fieldName, $fieldValue);
  1008. }
  1009. $this->data[$modelName][$fieldName] = $fieldValue;
  1010. }
  1011. }
  1012. }
  1013. return $data;
  1014. }
  1015. /**
  1016. * Normalize Xml::toArray() to use in Model::save()
  1017. *
  1018. * @param array $xml XML as array
  1019. * @return array
  1020. */
  1021. protected function _normalizeXmlData(array $xml) {
  1022. $return = array();
  1023. foreach ($xml as $key => $value) {
  1024. if (is_array($value)) {
  1025. $return[Inflector::camelize($key)] = $this->_normalizeXmlData($value);
  1026. } elseif ($key[0] === '@') {
  1027. $return[substr($key, 1)] = $value;
  1028. } else {
  1029. $return[$key] = $value;
  1030. }
  1031. }
  1032. return $return;
  1033. }
  1034. /**
  1035. * Deconstructs a complex data type (array or object) into a single field value.
  1036. *
  1037. * @param string $field The name of the field to be deconstructed
  1038. * @param mixed $data An array or object to be deconstructed into a field
  1039. * @return mixed The resulting data that should be assigned to a field
  1040. */
  1041. public function deconstruct($field, $data) {
  1042. if (!is_array($data)) {
  1043. return $data;
  1044. }
  1045. $copy = $data;
  1046. $type = $this->getColumnType($field);
  1047. if (in_array($type, array('datetime', 'timestamp', 'date', 'time'))) {
  1048. $useNewDate = (isset($data['year']) || isset($data['month']) ||
  1049. isset($data['day']) || isset($data['hour']) || isset($data['minute']));
  1050. $dateFields = array('Y' => 'year', 'm' => 'month', 'd' => 'day', 'H' => 'hour', 'i' => 'min', 's' => 'sec');
  1051. $timeFields = array('H' => 'hour', 'i' => 'min', 's' => 'sec');
  1052. $date = array();
  1053. if (isset($data['meridian']) && empty($data['meridian'])) {
  1054. return null;
  1055. }
  1056. if (
  1057. isset($data['hour']) &&
  1058. isset($data['meridian']) &&
  1059. !empty($data['hour']) &&
  1060. $data['hour'] != 12 &&
  1061. 'pm' == $data['meridian']
  1062. ) {
  1063. $data['hour'] = $data['hour'] + 12;
  1064. }
  1065. if (isset($data['hour']) && isset($data['meridian']) && $data['hour'] == 12 && 'am' == $data['meridian']) {
  1066. $data['hour'] = '00';
  1067. }
  1068. if ($type == 'time') {
  1069. foreach ($timeFields as $key => $val) {
  1070. if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') {
  1071. $data[$val] = '00';
  1072. } elseif ($data[$val] !== '') {
  1073. $data[$val] = sprintf('%02d', $data[$val]);
  1074. }
  1075. if (!empty($data[$val])) {
  1076. $date[$key] = $data[$val];
  1077. } else {
  1078. return null;
  1079. }
  1080. }
  1081. }
  1082. if ($type == 'datetime' || $type == 'timestamp' || $type == 'date') {
  1083. foreach ($dateFields as $key => $val) {
  1084. if ($val == 'hour' || $val == 'min' || $val == 'sec') {
  1085. if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') {
  1086. $data[$val] = '00';
  1087. } else {
  1088. $data[$val] = sprintf('%02d', $data[$val]);
  1089. }
  1090. }
  1091. if (!isset($data[$val]) || isset($data[$val]) && (empty($data[$val]) || $data[$val][0] === '-')) {
  1092. return null;
  1093. }
  1094. if (isset($data[$val]) && !empty($data[$val])) {
  1095. $date[$key] = $data[$val];
  1096. }
  1097. }
  1098. }
  1099. if ($useNewDate && !empty($date)) {
  1100. $format = $this->getDataSource()->columns[$type]['format'];
  1101. foreach (array('m', 'd', 'H', 'i', 's') as $index) {
  1102. if (isset($date[$index])) {
  1103. $date[$index] = sprintf('%02d', $date[$index]);
  1104. }
  1105. }
  1106. return str_replace(array_keys($date), array_values($date), $format);
  1107. }
  1108. }
  1109. return $data;
  1110. }
  1111. /**
  1112. * Returns an array of table metadata (column names and types) from the database.
  1113. * $field => keys(type, null, default, key, length, extra)
  1114. *
  1115. * @param mixed $field Set to true to reload schema, or a string to return a specific field
  1116. * @return array Array of table metadata
  1117. */
  1118. public function schema($field = false) {
  1119. if (!is_array($this->_schema) || $field === true) {
  1120. $db = $this->getDataSource();
  1121. $db->cacheSources = ($this->cacheSources && $db->cacheSources);
  1122. if (method_exists($db, 'describe') && $this->useTable !== false) {
  1123. $this->_schema = $db->describe($this);
  1124. } elseif ($this->useTable === false) {
  1125. $this->_schema = array();
  1126. }
  1127. }
  1128. if (is_string($field)) {
  1129. if (isset($this->_schema[$field])) {
  1130. return $this->_schema[$field];
  1131. } else {
  1132. return null;
  1133. }
  1134. }
  1135. return $this->_schema;
  1136. }
  1137. /**
  1138. * Returns an associative array of field names and column types.
  1139. *
  1140. * @return array Field types indexed by field name
  1141. */
  1142. public function getColumnTypes() {
  1143. $columns = $this->schema();
  1144. if (empty($columns)) {
  1145. trigger_error(__d('cake_dev', '(Model::getColumnTypes) Unable to build model field data. If you are using a model without a database table, try implementing schema()'), E_USER_WARNING);
  1146. }
  1147. $cols = array();
  1148. foreach ($columns as $field => $values) {
  1149. $cols[$field] = $values['type'];
  1150. }
  1151. return $cols;
  1152. }
  1153. /**
  1154. * Returns the column type of a column in the model.
  1155. *
  1156. * @param string $column The name of the model column
  1157. * @return string Column type
  1158. */
  1159. public function getColumnType($column) {
  1160. $db = $this->getDataSource();
  1161. $cols = $this->schema();
  1162. $model = null;
  1163. $column = str_replace(array($db->startQuote, $db->endQuote), '', $column);
  1164. if (strpos($column, '.')) {
  1165. list($model, $column) = explode('.', $column);
  1166. }
  1167. if ($model != $this->alias && isset($this->{$model})) {
  1168. return $this->{$model}->getColumnType($column);
  1169. }
  1170. if (isset($cols[$column]) && isset($cols[$column]['type'])) {
  1171. return $cols[$column]['type'];
  1172. }
  1173. return null;
  1174. }
  1175. /**
  1176. * Returns true if the supplied field exists in the model's database table.
  1177. *
  1178. * @param mixed $name Name of field to look for, or an array of names
  1179. * @param boolean $checkVirtual checks if the field is declared as virtual
  1180. * @return mixed If $name is a string, returns a boolean indicating whether the field exists.
  1181. * If $name is an array of field names, returns the first field that exists,
  1182. * or false if none exist.
  1183. */
  1184. public function hasField($name, $checkVirtual = false) {
  1185. if (is_array($name)) {
  1186. foreach ($name as $n) {
  1187. if ($this->hasField($n, $checkVirtual)) {
  1188. return $n;
  1189. }
  1190. }
  1191. return false;
  1192. }
  1193. if ($checkVirtual && !empty($this->virtualFields)) {
  1194. if ($this->isVirtualField($name)) {
  1195. return true;
  1196. }
  1197. }
  1198. if (empty($this->_schema)) {
  1199. $this->schema();
  1200. }
  1201. if ($this->_schema != null) {
  1202. return isset($this->_schema[$name]);
  1203. }
  1204. return false;
  1205. }
  1206. /**
  1207. * Check that a method is callable on a model. This will check both the model's own methods, its
  1208. * inherited methods and methods that could be callable through behaviors.
  1209. *
  1210. * @param string $method The method to be called.
  1211. * @return boolean True on method being callable.
  1212. */
  1213. public function hasMethod($method) {
  1214. if (method_exists($this, $method)) {
  1215. return true;
  1216. }
  1217. if ($this->Behaviors->hasMethod($method)) {
  1218. return true;
  1219. }
  1220. return false;
  1221. }
  1222. /**
  1223. * Returns true if the supplied field is a model Virtual Field
  1224. *
  1225. * @param string $field Name of field to look for
  1226. * @return boolean indicating whether the field exists as a model virtual field.
  1227. */
  1228. public function isVirtualField($field) {
  1229. if (empty($this->virtualFields) || !is_string($field)) {
  1230. return false;
  1231. }
  1232. if (isset($this->virtualFields[$field])) {
  1233. return true;
  1234. }
  1235. if (strpos($field, '.') !== false) {
  1236. list($model, $field) = explode('.', $field);
  1237. if ($model == $this->alias && isset($this->virtualFields[$field])) {
  1238. return true;
  1239. }
  1240. }
  1241. return false;
  1242. }
  1243. /**
  1244. * Returns the expression for a model virtual field
  1245. *
  1246. * @param string $field Name of field to look for
  1247. * @return mixed If $field is string expression bound to virtual field $field
  1248. * If $field is null, returns an array of all model virtual fields
  1249. * or false if none $field exist.
  1250. */
  1251. public function getVirtualField($field = null) {
  1252. if ($field == null) {
  1253. return empty($this->virtualFields) ? false : $this->virtualFields;
  1254. }
  1255. if ($this->isVirtualField($field)) {
  1256. if (strpos($field, '.') !== false) {
  1257. list($model, $field) = explode('.', $field);
  1258. }
  1259. return $this->virtualFields[$field];
  1260. }
  1261. return false;
  1262. }
  1263. /**
  1264. * Initializes the model for writing a new record, loading the default values
  1265. * for those fields that are not defined in $data, and clearing previous validation errors.
  1266. * Especially helpful for saving data in loops.
  1267. *
  1268. * @param mixed $data Optional data array to assign to the model after it is created. If null or false,
  1269. * schema data defaults are not merged.
  1270. * @param boolean $filterKey If true, overwrites any primary key input with an empty value
  1271. * @return array The current Model::data; after merging $data and/or defaults from database
  1272. * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-create-array-data-array
  1273. */
  1274. public function create($data = array(), $filterKey = false) {
  1275. $defaults = array();
  1276. $this->id = false;
  1277. $this->data = array();
  1278. $this->validationErrors = array();
  1279. if ($data !== null && $data !== false) {
  1280. foreach ($this->schema() as $field => $properties) {
  1281. if ($this->primaryKey !== $field && isset($properties['default']) && $properties['default'] !== '') {
  1282. $defaults[$field] = $properties['default'];
  1283. }
  1284. }
  1285. $this->set($defaults);
  1286. $this->set($data);
  1287. }
  1288. if ($filterKey) {
  1289. $this->set($this->primaryKey, false);
  1290. }
  1291. return $this->data;
  1292. }
  1293. /**
  1294. * Returns a list of fields from the database, and sets the current model
  1295. * data (Model::$data) with the record found.
  1296. *
  1297. * @param mixed $fields String of single field name, or an array of field names.
  1298. * @param mixed $id The ID of the record to read
  1299. * @return array Array of database fields, or false if not found
  1300. * @link http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-read
  1301. */
  1302. public function read($fields = null, $id = null) {
  1303. $this->validationErrors = array();
  1304. if ($id != null) {
  1305. $this->id = $id;
  1306. }
  1307. $id = $this->id;
  1308. if (is_array($this->id)) {
  1309. $id = $this->id[0];
  1310. }
  1311. if ($id !== null && $id !== false) {
  1312. $this->data = $this->find('first', array(
  1313. 'conditions' => array($this->alias . '.' . $this->primaryKey => $id),
  1314. 'fields' => $fields
  1315. ));
  1316. return $this->data;
  1317. } else {
  1318. return false;
  1319. }
  1320. }
  1321. /**
  1322. * Returns the contents of a single field given the supplied conditions, in the
  1323. * supplied order.
  1324. *
  1325. * @param string $name Name of field to get
  1326. * @param array $conditions SQL conditions (defaults to NULL)
  1327. * @param string $order SQL ORDER BY fragment
  1328. * @return string field contents, or false if not found
  1329. * @link http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-field
  1330. */
  1331. public function field($name, $conditions = null, $order = null) {
  1332. if ($conditions === null && $this->id !== false) {
  1333. $conditions = array($this->alias . '.' . $this->primaryKey => $this->id);
  1334. }
  1335. if ($this->recursive >= 1) {
  1336. $recursive = -1;
  1337. } else {
  1338. $recursive = $this->recursive;
  1339. }
  1340. $fields = $name;
  1341. if ($data = $this->find('first', compact('conditions', 'fields', 'order', 'recursive'))) {
  1342. if (strpos($name, '.') === false) {
  1343. if (isset($data[$this->alias][$name])) {
  1344. return $data[$this->alias][$name];
  1345. }
  1346. } else {
  1347. $name = explode('.', $name);
  1348. if (isset($data[$name[0]][$name[1]])) {
  1349. return $data[$name[0]][$name[1]];
  1350. }
  1351. }
  1352. if (isset($data[0]) && count($data[0]) > 0) {
  1353. return array_shift($data[0]);
  1354. }
  1355. } else {
  1356. return false;
  1357. }
  1358. }
  1359. /**
  1360. * Saves the value of a single field to the database, based on the current
  1361. * model ID.
  1362. *
  1363. * @param string $name Name of the table field
  1364. * @param mixed $value Value of the field
  1365. * @param array $validate See $options param in Model::save(). Does not respect 'fieldList' key if passed
  1366. * @return boolean See Model::save()
  1367. * @see Model::save()
  1368. * @link http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-read
  1369. */
  1370. public function saveField($name, $value, $validate = false) {
  1371. $id = $this->id;
  1372. $this->create(false);
  1373. if (is_array($validate)) {
  1374. $options = array_merge(array('validate' => false, 'fieldList' => array($name)), $validate);
  1375. } else {
  1376. $options = array('validate' => $validate, 'fieldList' => array($name));
  1377. }
  1378. return $this->save(array($this->alias => array($this->primaryKey => $id, $name => $value)), $options);
  1379. }
  1380. /**
  1381. * Saves model data (based on white-list, if supplied) to the database. By
  1382. * default, validation occurs before save.
  1383. *
  1384. * @param array $data Data to save.
  1385. * @param mixed $validate Either a boolean, or an array.
  1386. * If a boolean, indicates whether or not to validate before saving.
  1387. * If an array, allows control of validate, callbacks, and fieldList
  1388. * @param array $fieldList List of fields to allow to be written
  1389. * @return mixed On success Model::$data if its not empty or true, false on failure
  1390. * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html
  1391. */
  1392. public function save($data = null, $validate = true, $fieldList = array()) {
  1393. $defaults = array('validate' => true, 'fieldList' => array(), 'callbacks' => true);
  1394. $_whitelist = $this->whitelist;
  1395. $fields = array();
  1396. if (!is_array($validate)) {
  1397. $options = array_merge($defaults, compact('validate', 'fieldList', 'callbacks'));
  1398. } else {
  1399. $options = array_merge($defaults, $validate);
  1400. }
  1401. if (!empty($options['fieldList'])) {
  1402. $this->whitelist = $options['fieldList'];
  1403. } elseif ($options['fieldList'] === null) {
  1404. $this->whitelist = array();
  1405. }
  1406. $this->set($data);
  1407. if (empty($this->data) && !$this->hasField(array('created', 'updated', 'modified'))) {
  1408. return false;
  1409. }
  1410. foreach (array('created', 'updated', 'modified') as $field) {
  1411. $keyPresentAndEmpty = (
  1412. isset($this->data[$this->alias]) &&
  1413. array_key_exists($field, $this->data[$this->alias]) &&
  1414. $this->data[$this->alias][$field] === null
  1415. );
  1416. if ($keyPresentAndEmpty) {
  1417. unset($this->data[$this->alias][$field]);
  1418. }
  1419. }
  1420. $exists = $this->exists();
  1421. $dateFields = array('modified', 'updated');
  1422. if (!$exists) {
  1423. $dateFields[] = 'created';
  1424. }
  1425. if (isset($this->data[$this->alias])) {
  1426. $fields = array_keys($this->data[$this->alias]);
  1427. }
  1428. if ($options['validate'] && !$this->validates($options)) {
  1429. $this->whitelist = $_whitelist;
  1430. return false;
  1431. }
  1432. $db = $this->getDataSource();
  1433. foreach ($dateFields as $updateCol) {
  1434. if ($this->hasField($updateCol) && !in_array($updateCol, $fields)) {
  1435. $default = array('formatter' => 'date');
  1436. $colType = array_merge($default, $db->columns[$this->getColumnType($updateCol)]);
  1437. if (!array_key_exists('format', $colType)) {
  1438. $time = strtotime('now');
  1439. } else {
  1440. $time = $colType['formatter']($colType['format']);
  1441. }
  1442. if (!empty($this->whitelist)) {
  1443. $this->whitelist[] = $updateCol;
  1444. }
  1445. $this->set($updateCol, $time);
  1446. }
  1447. }
  1448. if ($options['callbacks'] === true || $options['callbacks'] === 'before') {
  1449. $result = $this->Behaviors->trigger('beforeSave', array(&$this, $options), array(
  1450. 'break' => true, 'breakOn' => array(false, null)
  1451. ));
  1452. if (!$result || !$this->beforeSave($options)) {
  1453. $this->whitelist = $_whitelist;
  1454. return false;
  1455. }
  1456. }
  1457. if (empty($this->data[$this->alias][$this->primaryKey])) {
  1458. unset($this->data[$this->alias][$this->primaryKey]);
  1459. }
  1460. $fields = $values = array();
  1461. foreach ($this->data as $n => $v) {
  1462. if (isset($this->hasAndBelongsToMany[$n])) {
  1463. if (isset($v[$n])) {
  1464. $v = $v[$n];
  1465. }
  1466. $joined[$n] = $v;
  1467. } else {
  1468. if ($n === $this->alias) {
  1469. foreach (array('created', 'updated', 'modified') as $field) {
  1470. if (array_key_exists($field, $v) && empty($v[$field])) {

Large files files are truncated, but you can click here to view the full file