PageRenderTime 88ms CodeModel.GetById 12ms RepoModel.GetById 1ms app.codeStats 1ms

/lib/Cake/Model/Model.php

https://bitbucket.org/pyroka/hms
PHP | 3402 lines | 1821 code | 274 blank | 1307 comment | 519 complexity | ec78d99d5d7a3b80abf65c9497d61628 MD5 | raw file
Possible License(s): LGPL-2.1

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

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