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

/lib/Cake/Model/Model.php

https://bitbucket.org/npitts/easyuat2.0
PHP | 3640 lines | 2049 code | 291 blank | 1300 comment | 606 complexity | 4e72c2161c76a8ea0818b27175dbfb88 MD5 | raw file

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

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