PageRenderTime 64ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/cake/libs/model/model.php

https://github.com/mariuz/firetube
PHP | 2995 lines | 1820 code | 171 blank | 1004 comment | 526 complexity | e42fb00779a59ad6a3ca8fe3f40006cf MD5 | raw file
Possible License(s): LGPL-2.1
  1. <?php
  2. /* SVN FILE: $Id$ */
  3. /**
  4. * Object-relational mapper.
  5. *
  6. * DBO-backed object data model, for mapping database tables to Cake objects.
  7. *
  8. * PHP versions 5
  9. *
  10. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  11. * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  12. *
  13. * Licensed under The MIT License
  14. * Redistributions of files must retain the above copyright notice.
  15. *
  16. * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  17. * @link http://cakephp.org CakePHP(tm) Project
  18. * @package cake
  19. * @subpackage cake.cake.libs.model
  20. * @since CakePHP(tm) v 0.10.0.0
  21. * @version $Revision$
  22. * @modifiedby $LastChangedBy$
  23. * @lastmodified $Date$
  24. * @license http://www.opensource.org/licenses/mit-license.php The MIT License
  25. */
  26. /**
  27. * Included libs
  28. */
  29. App::import('Core', array('ClassRegistry', 'Overloadable', 'Validation', 'Behavior', 'ConnectionManager', 'Set', 'String'));
  30. /**
  31. * Object-relational mapper.
  32. *
  33. * DBO-backed object data model.
  34. * Automatically selects a database table name based on a pluralized lowercase object class name
  35. * (i.e. class 'User' => table 'users'; class 'Man' => table 'men')
  36. * The table is required to have at least 'id auto_increment' primary key.
  37. *
  38. * @package cake
  39. * @subpackage cake.cake.libs.model
  40. * @link http://book.cakephp.org/view/66/Models
  41. */
  42. class Model extends Overloadable {
  43. /**
  44. * The name of the DataSource connection that this Model uses
  45. *
  46. * @var string
  47. * @access public
  48. * @link http://book.cakephp.org/view/435/useDbConfig
  49. */
  50. var $useDbConfig = 'default';
  51. /**
  52. * Custom database table name, or null/false if no table association is desired.
  53. *
  54. * @var string
  55. * @access public
  56. * @link http://book.cakephp.org/view/436/useTable
  57. */
  58. var $useTable = null;
  59. /**
  60. * Custom display field name. Display fields are used by Scaffold, in SELECT boxes' OPTION elements.
  61. *
  62. * @var string
  63. * @access public
  64. * @link http://book.cakephp.org/view/438/displayField
  65. */
  66. var $displayField = null;
  67. /**
  68. * Value of the primary key ID of the record that this model is currently pointing to.
  69. * Automatically set after database insertions.
  70. *
  71. * @var mixed
  72. * @access public
  73. */
  74. var $id = false;
  75. /**
  76. * Container for the data that this model gets from persistent storage (usually, a database).
  77. *
  78. * @var array
  79. * @access public
  80. * @link http://book.cakephp.org/view/441/data
  81. */
  82. var $data = array();
  83. /**
  84. * Table name for this Model.
  85. *
  86. * @var string
  87. * @access public
  88. */
  89. var $table = false;
  90. /**
  91. * The name of the primary key field for this model.
  92. *
  93. * @var string
  94. * @access public
  95. * @link http://book.cakephp.org/view/437/primaryKey
  96. */
  97. var $primaryKey = null;
  98. /**
  99. * Field-by-field table metadata.
  100. *
  101. * @var array
  102. * @access protected
  103. * @link http://book.cakephp.org/view/442/_schema
  104. */
  105. var $_schema = null;
  106. /**
  107. * List of validation rules. Append entries for validation as ('field_name' => '/^perl_compat_regexp$/')
  108. * that have to match with preg_match(). Use these rules with Model::validate()
  109. *
  110. * @var array
  111. * @access public
  112. * @link http://book.cakephp.org/view/443/validate
  113. * @link http://book.cakephp.org/view/125/Data-Validation
  114. */
  115. var $validate = array();
  116. /**
  117. * List of validation errors.
  118. *
  119. * @var array
  120. * @access public
  121. * @link http://book.cakephp.org/view/410/Validating-Data-from-the-Controller
  122. */
  123. var $validationErrors = array();
  124. /**
  125. * Database table prefix for tables in model.
  126. *
  127. * @var string
  128. * @access public
  129. * @link http://book.cakephp.org/view/475/tablePrefix
  130. */
  131. var $tablePrefix = null;
  132. /**
  133. * Name of the model.
  134. *
  135. * @var string
  136. * @access public
  137. * @link http://book.cakephp.org/view/444/name
  138. */
  139. var $name = null;
  140. /**
  141. * Alias name for model.
  142. *
  143. * @var string
  144. * @access public
  145. */
  146. var $alias = null;
  147. /**
  148. * List of table names included in the model description. Used for associations.
  149. *
  150. * @var array
  151. * @access public
  152. */
  153. var $tableToModel = array();
  154. /**
  155. * Whether or not to log transactions for this model.
  156. *
  157. * @var boolean
  158. * @access public
  159. */
  160. var $logTransactions = false;
  161. /**
  162. * Whether or not to enable transactions for this model (i.e. BEGIN/COMMIT/ROLLBACK statements)
  163. *
  164. * @var boolean
  165. * @access public
  166. */
  167. var $transactional = false;
  168. /**
  169. * Whether or not to cache queries for this model. This enables in-memory
  170. * caching only, the results are not stored beyond the current request.
  171. *
  172. * @var boolean
  173. * @access public
  174. * @link http://book.cakephp.org/view/445/cacheQueries
  175. */
  176. var $cacheQueries = false;
  177. /**
  178. * Detailed list of belongsTo associations.
  179. *
  180. * @var array
  181. * @access public
  182. * @link http://book.cakephp.org/view/81/belongsTo
  183. */
  184. var $belongsTo = array();
  185. /**
  186. * Detailed list of hasOne associations.
  187. *
  188. * @var array
  189. * @access public
  190. * @link http://book.cakephp.org/view/80/hasOne
  191. */
  192. var $hasOne = array();
  193. /**
  194. * Detailed list of hasMany associations.
  195. *
  196. * @var array
  197. * @access public
  198. * @link http://book.cakephp.org/view/82/hasMany
  199. */
  200. var $hasMany = array();
  201. /**
  202. * Detailed list of hasAndBelongsToMany associations.
  203. *
  204. * @var array
  205. * @access public
  206. * @link http://book.cakephp.org/view/83/hasAndBelongsToMany-HABTM
  207. */
  208. var $hasAndBelongsToMany = array();
  209. /**
  210. * List of behaviors to load when the model object is initialized. Settings can be
  211. * passed to behaviors by using the behavior name as index. Eg:
  212. *
  213. * var $actsAs = array('Translate', 'MyBehavior' => array('setting1' => 'value1'))
  214. *
  215. * @var array
  216. * @access public
  217. * @link http://book.cakephp.org/view/90/Using-Behaviors
  218. */
  219. var $actsAs = null;
  220. /**
  221. * Holds the Behavior objects currently bound to this model.
  222. *
  223. * @var BehaviorCollection
  224. * @access public
  225. */
  226. var $Behaviors = null;
  227. /**
  228. * Whitelist of fields allowed to be saved.
  229. *
  230. * @var array
  231. * @access public
  232. */
  233. var $whitelist = array();
  234. /**
  235. * Whether or not to cache sources for this model.
  236. *
  237. * @var boolean
  238. * @access public
  239. */
  240. var $cacheSources = true;
  241. /**
  242. * Type of find query currently executing.
  243. *
  244. * @var string
  245. * @access public
  246. */
  247. var $findQueryType = null;
  248. /**
  249. * Number of associations to recurse through during find calls. Fetches only
  250. * the first level by default.
  251. *
  252. * @var integer
  253. * @access public
  254. * @link http://book.cakephp.org/view/439/recursive
  255. */
  256. var $recursive = 1;
  257. /**
  258. * The column name(s) and direction(s) to order find results by default.
  259. *
  260. * var $order = "Post.created DESC";
  261. * var $order = array("Post.view_count DESC", "Post.rating DESC");
  262. *
  263. * @var string
  264. * @access public
  265. * @link http://book.cakephp.org/view/440/order
  266. */
  267. var $order = null;
  268. /**
  269. * Whether or not the model record exists, set by Model::exists().
  270. *
  271. * @var bool
  272. * @access private
  273. */
  274. var $__exists = null;
  275. /**
  276. * Default list of association keys.
  277. *
  278. * @var array
  279. * @access private
  280. */
  281. var $__associationKeys = array(
  282. 'belongsTo' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'counterCache'),
  283. 'hasOne' => array('className', 'foreignKey','conditions', 'fields','order', 'dependent'),
  284. 'hasMany' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'dependent', 'exclusive', 'finderQuery', 'counterQuery'),
  285. 'hasAndBelongsToMany' => array('className', 'joinTable', 'with', 'foreignKey', 'associationForeignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'unique', 'finderQuery', 'deleteQuery', 'insertQuery')
  286. );
  287. /**
  288. * Holds provided/generated association key names and other data for all associations.
  289. *
  290. * @var array
  291. * @access private
  292. */
  293. var $__associations = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
  294. /**
  295. * Holds model associations temporarily to allow for dynamic (un)binding.
  296. *
  297. * @var array
  298. * @access private
  299. */
  300. var $__backAssociation = array();
  301. /**
  302. * The ID of the model record that was last inserted.
  303. *
  304. * @var integer
  305. * @access private
  306. */
  307. var $__insertID = null;
  308. /**
  309. * The number of records returned by the last query.
  310. *
  311. * @var integer
  312. * @access private
  313. */
  314. var $__numRows = null;
  315. /**
  316. * The number of records affected by the last query.
  317. *
  318. * @var integer
  319. * @access private
  320. */
  321. var $__affectedRows = null;
  322. /**
  323. * List of valid finder method options, supplied as the first parameter to find().
  324. *
  325. * @var array
  326. * @access protected
  327. */
  328. var $_findMethods = array(
  329. 'all' => true, 'first' => true, 'count' => true,
  330. 'neighbors' => true, 'list' => true, 'threaded' => true
  331. );
  332. /**
  333. * Constructor. Binds the model's database table to the object.
  334. *
  335. * If `$id` is an array it can be used to pass several options into the model.
  336. *
  337. * - id - The id to start the model on.
  338. * - table - The table to use for this model.
  339. * - ds - The connection name this model is connected to.
  340. * - name - The name of the model eg. Post.
  341. * - alias - The alias of the model, this is used for registering the instance in the `ClassRegistry`.
  342. * eg. `ParentThread`
  343. *
  344. * ### Overriding Model's __construct method.
  345. *
  346. * When overriding Model::__construct() be careful to include and pass in all 3 of the
  347. * arguments to `parent::__construct($id, $table, $ds);`
  348. *
  349. * ### Dynamically creating models
  350. *
  351. * You can dynamically create model instances using the the $id array syntax.
  352. *
  353. * {{{
  354. * $Post = new Model(array('table' => 'posts', 'name' => 'Post', 'ds' => 'connection2'));
  355. * }}}
  356. *
  357. * Would create a model attached to the posts table on connection2. Dynamic model creation is useful
  358. * when you want a model object that contains no associations or attached behaviors.
  359. *
  360. * @param mixed $id Set this ID for this model on startup, can also be an array of options, see above.
  361. * @param string $table Name of database table to use.
  362. * @param string $ds DataSource connection name.
  363. */
  364. function __construct($id = false, $table = null, $ds = null) {
  365. parent::__construct();
  366. if (is_array($id)) {
  367. extract(array_merge(
  368. array(
  369. 'id' => $this->id, 'table' => $this->useTable, 'ds' => $this->useDbConfig,
  370. 'name' => $this->name, 'alias' => $this->alias
  371. ),
  372. $id
  373. ));
  374. }
  375. if ($this->name === null) {
  376. $this->name = (isset($name) ? $name : get_class($this));
  377. }
  378. if ($this->alias === null) {
  379. $this->alias = (isset($alias) ? $alias : $this->name);
  380. }
  381. if ($this->primaryKey === null) {
  382. $this->primaryKey = 'id';
  383. }
  384. ClassRegistry::addObject($this->alias, $this);
  385. $this->id = $id;
  386. unset($id);
  387. if ($table === false) {
  388. $this->useTable = false;
  389. } elseif ($table) {
  390. $this->useTable = $table;
  391. }
  392. if ($ds !== null) {
  393. $this->useDbConfig = $ds;
  394. }
  395. if (is_subclass_of($this, 'AppModel')) {
  396. $appVars = get_class_vars('AppModel');
  397. $merge = array('_findMethods');
  398. if ($this->actsAs !== null || $this->actsAs !== false) {
  399. $merge[] = 'actsAs';
  400. }
  401. $parentClass = get_parent_class($this);
  402. if (strtolower($parentClass) !== 'appmodel') {
  403. $parentVars = get_class_vars($parentClass);
  404. foreach ($merge as $var) {
  405. if (isset($parentVars[$var]) && !empty($parentVars[$var])) {
  406. $appVars[$var] = Set::merge($appVars[$var], $parentVars[$var]);
  407. }
  408. }
  409. }
  410. foreach ($merge as $var) {
  411. if (isset($appVars[$var]) && !empty($appVars[$var]) && is_array($this->{$var})) {
  412. $this->{$var} = Set::merge($appVars[$var], $this->{$var});
  413. }
  414. }
  415. }
  416. $this->Behaviors = new BehaviorCollection();
  417. if ($this->useTable !== false) {
  418. $this->setDataSource($ds);
  419. if ($this->useTable === null) {
  420. $this->useTable = Inflector::tableize($this->name);
  421. }
  422. if (method_exists($this, 'setTablePrefix')) {
  423. $this->setTablePrefix();
  424. }
  425. $this->setSource($this->useTable);
  426. if ($this->displayField == null) {
  427. $this->displayField = $this->hasField(array('title', 'name', $this->primaryKey));
  428. }
  429. } elseif ($this->table === false) {
  430. $this->table = Inflector::tableize($this->name);
  431. }
  432. $this->__createLinks();
  433. $this->Behaviors->init($this->alias, $this->actsAs);
  434. }
  435. /**
  436. * Handles custom method calls, like findBy<field> for DB models,
  437. * and custom RPC calls for remote data sources.
  438. *
  439. * @param string $method Name of method to call.
  440. * @param array $params Parameters for the method.
  441. * @return mixed Whatever is returned by called method
  442. * @access protected
  443. */
  444. function call__($method, $params) {
  445. $result = $this->Behaviors->dispatchMethod($this, $method, $params);
  446. if ($result !== array('unhandled')) {
  447. return $result;
  448. }
  449. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  450. $return = $db->query($method, $params, $this);
  451. if (!PHP5) {
  452. $this->resetAssociations();
  453. }
  454. return $return;
  455. }
  456. /**
  457. * Bind model associations on the fly.
  458. *
  459. * If $permanent is true, association will not be reset
  460. * to the originals defined in the model.
  461. *
  462. * @param mixed $model A model or association name (string) or set of binding options (indexed by model name type)
  463. * @param array $options If $model is a string, this is the list of association properties with which $model will
  464. * be bound
  465. * @param boolean $permanent Set to true to make the binding permanent
  466. * @return void
  467. * @access public
  468. * @todo
  469. */
  470. function bind($model, $options = array(), $permanent = true) {
  471. if (!is_array($model)) {
  472. $model = array($model => $options);
  473. }
  474. foreach ($model as $name => $options) {
  475. if (isset($options['type'])) {
  476. $assoc = $options['type'];
  477. } elseif (isset($options[0])) {
  478. $assoc = $options[0];
  479. } else {
  480. $assoc = 'belongsTo';
  481. }
  482. if (!$permanent) {
  483. $this->__backAssociation[$assoc] = $this->{$assoc};
  484. }
  485. foreach ($model as $key => $value) {
  486. $assocName = $modelName = $key;
  487. if (isset($this->{$assoc}[$assocName])) {
  488. $this->{$assoc}[$assocName] = array_merge($this->{$assoc}[$assocName], $options);
  489. } else {
  490. if (isset($value['className'])) {
  491. $modelName = $value['className'];
  492. }
  493. $this->__constructLinkedModel($assocName, $modelName);
  494. $this->{$assoc}[$assocName] = $model[$assocName];
  495. $this->__generateAssociation($assoc);
  496. }
  497. unset($this->{$assoc}[$assocName]['type'], $this->{$assoc}[$assocName][0]);
  498. }
  499. }
  500. }
  501. /**
  502. * Bind model associations on the fly.
  503. *
  504. * If $reset is false, association will not be reset
  505. * to the originals defined in the model
  506. *
  507. * Example: Add a new hasOne binding to the Profile model not
  508. * defined in the model source code:
  509. * <code>
  510. * $this->User->bindModel( array('hasOne' => array('Profile')) );
  511. * </code>
  512. *
  513. * @param array $params Set of bindings (indexed by binding type)
  514. * @param boolean $reset Set to false to make the binding permanent
  515. * @return boolean Success
  516. * @access public
  517. * @link http://book.cakephp.org/view/86/Creating-and-Destroying-Associations-on-the-Fly
  518. */
  519. function bindModel($params, $reset = true) {
  520. foreach ($params as $assoc => $model) {
  521. if ($reset === true && !isset($this->__backAssociation[$assoc])) {
  522. $this->__backAssociation[$assoc] = $this->{$assoc};
  523. }
  524. foreach ($model as $key => $value) {
  525. $assocName = $key;
  526. if (is_numeric($key)) {
  527. $assocName = $value;
  528. $value = array();
  529. }
  530. $modelName = $assocName;
  531. $this->{$assoc}[$assocName] = $value;
  532. if ($reset === false && isset($this->__backAssociation[$assoc])) {
  533. $this->__backAssociation[$assoc][$assocName] = $value;
  534. }
  535. }
  536. }
  537. $this->__createLinks();
  538. return true;
  539. }
  540. /**
  541. * Turn off associations on the fly.
  542. *
  543. * If $reset is false, association will not be reset
  544. * to the originals defined in the model
  545. *
  546. * Example: Turn off the associated Model Support request,
  547. * to temporarily lighten the User model:
  548. * <code>
  549. * $this->User->unbindModel( array('hasMany' => array('Supportrequest')) );
  550. * </code>
  551. *
  552. * @param array $params Set of bindings to unbind (indexed by binding type)
  553. * @param boolean $reset Set to false to make the unbinding permanent
  554. * @return boolean Success
  555. * @access public
  556. * @link http://book.cakephp.org/view/86/Creating-and-Destroying-Associations-on-the-Fly
  557. */
  558. function unbindModel($params, $reset = true) {
  559. foreach ($params as $assoc => $models) {
  560. if ($reset === true && !isset($this->__backAssociation[$assoc])) {
  561. $this->__backAssociation[$assoc] = $this->{$assoc};
  562. }
  563. foreach ($models as $model) {
  564. if ($reset === false && isset($this->__backAssociation[$assoc][$model])) {
  565. unset($this->__backAssociation[$assoc][$model]);
  566. }
  567. unset($this->{$assoc}[$model]);
  568. }
  569. }
  570. return true;
  571. }
  572. /**
  573. * Create a set of associations.
  574. *
  575. * @return void
  576. * @access private
  577. */
  578. function __createLinks() {
  579. foreach ($this->__associations as $type) {
  580. if (!is_array($this->{$type})) {
  581. $this->{$type} = explode(',', $this->{$type});
  582. foreach ($this->{$type} as $i => $className) {
  583. $className = trim($className);
  584. unset ($this->{$type}[$i]);
  585. $this->{$type}[$className] = array();
  586. }
  587. }
  588. if (!empty($this->{$type})) {
  589. foreach ($this->{$type} as $assoc => $value) {
  590. $plugin = null;
  591. if (is_numeric($assoc)) {
  592. unset ($this->{$type}[$assoc]);
  593. $assoc = $value;
  594. $value = array();
  595. $this->{$type}[$assoc] = $value;
  596. if (strpos($assoc, '.') !== false) {
  597. $value = $this->{$type}[$assoc];
  598. unset($this->{$type}[$assoc]);
  599. list($plugin, $assoc) = explode('.', $assoc);
  600. $this->{$type}[$assoc] = $value;
  601. $plugin = $plugin . '.';
  602. }
  603. }
  604. $className = $assoc;
  605. if (isset($value['className']) && !empty($value['className'])) {
  606. $className = $value['className'];
  607. if (strpos($className, '.') !== false) {
  608. list($plugin, $className) = explode('.', $className);
  609. $plugin = $plugin . '.';
  610. $this->{$type}[$assoc]['className'] = $className;
  611. }
  612. }
  613. $this->__constructLinkedModel($assoc, $plugin . $className);
  614. }
  615. $this->__generateAssociation($type);
  616. }
  617. }
  618. }
  619. /**
  620. * Private helper method to create associated models of a given class.
  621. *
  622. * @param string $assoc Association name
  623. * @param string $className Class name
  624. * @deprecated $this->$className use $this->$assoc instead. $assoc is the 'key' in the associations array;
  625. * examples: var $hasMany = array('Assoc' => array('className' => 'ModelName'));
  626. * usage: $this->Assoc->modelMethods();
  627. *
  628. * var $hasMany = array('ModelName');
  629. * usage: $this->ModelName->modelMethods();
  630. * @return void
  631. * @access private
  632. */
  633. function __constructLinkedModel($assoc, $className = null) {
  634. if (empty($className)) {
  635. $className = $assoc;
  636. }
  637. if (!isset($this->{$assoc}) || $this->{$assoc}->name !== $className) {
  638. $model = array('class' => $className, 'alias' => $assoc);
  639. if (PHP5) {
  640. $this->{$assoc} = ClassRegistry::init($model);
  641. } else {
  642. $this->{$assoc} =& ClassRegistry::init($model);
  643. }
  644. if (strpos($className, '.') !== false) {
  645. ClassRegistry::addObject($className, $this->{$assoc});
  646. }
  647. if ($assoc) {
  648. $this->tableToModel[$this->{$assoc}->table] = $assoc;
  649. }
  650. }
  651. }
  652. /**
  653. * Build an array-based association from string.
  654. *
  655. * @param string $type 'belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany'
  656. * @return void
  657. * @access private
  658. */
  659. function __generateAssociation($type) {
  660. foreach ($this->{$type} as $assocKey => $assocData) {
  661. $class = $assocKey;
  662. $dynamicWith = false;
  663. foreach ($this->__associationKeys[$type] as $key) {
  664. if (!isset($this->{$type}[$assocKey][$key]) || $this->{$type}[$assocKey][$key] === null) {
  665. $data = '';
  666. switch ($key) {
  667. case 'fields':
  668. $data = '';
  669. break;
  670. case 'foreignKey':
  671. $data = (($type == 'belongsTo') ? Inflector::underscore($assocKey) : Inflector::singularize($this->table)) . '_id';
  672. break;
  673. case 'associationForeignKey':
  674. $data = Inflector::singularize($this->{$class}->table) . '_id';
  675. break;
  676. case 'with':
  677. $data = Inflector::camelize(Inflector::singularize($this->{$type}[$assocKey]['joinTable']));
  678. $dynamicWith = true;
  679. break;
  680. case 'joinTable':
  681. $tables = array($this->table, $this->{$class}->table);
  682. sort ($tables);
  683. $data = $tables[0] . '_' . $tables[1];
  684. break;
  685. case 'className':
  686. $data = $class;
  687. break;
  688. case 'unique':
  689. $data = true;
  690. break;
  691. }
  692. $this->{$type}[$assocKey][$key] = $data;
  693. }
  694. }
  695. if (!empty($this->{$type}[$assocKey]['with'])) {
  696. $joinClass = $this->{$type}[$assocKey]['with'];
  697. if (is_array($joinClass)) {
  698. $joinClass = key($joinClass);
  699. }
  700. $plugin = null;
  701. if (strpos($joinClass, '.') !== false) {
  702. list($plugin, $joinClass) = explode('.', $joinClass);
  703. $plugin = $plugin . '.';
  704. $this->{$type}[$assocKey]['with'] = $joinClass;
  705. }
  706. if (!ClassRegistry::isKeySet($joinClass) && $dynamicWith === true) {
  707. $this->{$joinClass} = new AppModel(array(
  708. 'name' => $joinClass,
  709. 'table' => $this->{$type}[$assocKey]['joinTable'],
  710. 'ds' => $this->useDbConfig
  711. ));
  712. } else {
  713. $this->__constructLinkedModel($joinClass, $plugin . $joinClass);
  714. $this->{$type}[$assocKey]['joinTable'] = $this->{$joinClass}->table;
  715. }
  716. if (count($this->{$joinClass}->schema()) <= 2 && $this->{$joinClass}->primaryKey !== false) {
  717. $this->{$joinClass}->primaryKey = $this->{$type}[$assocKey]['foreignKey'];
  718. }
  719. }
  720. }
  721. }
  722. /**
  723. * Sets a custom table for your controller class. Used by your controller to select a database table.
  724. *
  725. * @param string $tableName Name of the custom table
  726. * @return void
  727. * @access public
  728. */
  729. function setSource($tableName) {
  730. $this->setDataSource($this->useDbConfig);
  731. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  732. $db->cacheSources = ($this->cacheSources && $db->cacheSources);
  733. if ($db->isInterfaceSupported('listSources')) {
  734. $sources = $db->listSources();
  735. if (is_array($sources) && !in_array(strtolower($this->tablePrefix . $tableName), array_map('strtolower', $sources))) {
  736. return $this->cakeError('missingTable', array(array(
  737. 'className' => $this->alias,
  738. 'table' => $this->tablePrefix . $tableName
  739. )));
  740. }
  741. $this->_schema = null;
  742. }
  743. $this->table = $this->useTable = $tableName;
  744. $this->tableToModel[$this->table] = $this->alias;
  745. $this->schema();
  746. }
  747. /**
  748. * This function does two things:
  749. *
  750. * 1. it scans the array $one for the primary key,
  751. * and if that's found, it sets the current id to the value of $one[id].
  752. * For all other keys than 'id' the keys and values of $one are copied to the 'data' property of this object.
  753. * 2. Returns an array with all of $one's keys and values.
  754. * (Alternative indata: two strings, which are mangled to
  755. * a one-item, two-dimensional array using $one for a key and $two as its value.)
  756. *
  757. * @param mixed $one Array or string of data
  758. * @param string $two Value string for the alternative indata method
  759. * @return array Data with all of $one's keys and values
  760. * @access public
  761. */
  762. function set($one, $two = null) {
  763. if (!$one) {
  764. return;
  765. }
  766. if (is_object($one)) {
  767. $one = Set::reverse($one);
  768. }
  769. if (is_array($one)) {
  770. $data = $one;
  771. if (empty($one[$this->alias])) {
  772. if ($this->getAssociated(key($one)) === null) {
  773. $data = array($this->alias => $one);
  774. }
  775. }
  776. } else {
  777. $data = array($this->alias => array($one => $two));
  778. }
  779. foreach ($data as $modelName => $fieldSet) {
  780. if (is_array($fieldSet)) {
  781. foreach ($fieldSet as $fieldName => $fieldValue) {
  782. if (isset($this->validationErrors[$fieldName])) {
  783. unset ($this->validationErrors[$fieldName]);
  784. }
  785. if ($modelName === $this->alias) {
  786. if ($fieldName === $this->primaryKey) {
  787. $this->id = $fieldValue;
  788. }
  789. }
  790. if (is_array($fieldValue) || is_object($fieldValue)) {
  791. $fieldValue = $this->deconstruct($fieldName, $fieldValue);
  792. }
  793. $this->data[$modelName][$fieldName] = $fieldValue;
  794. }
  795. }
  796. }
  797. return $data;
  798. }
  799. /**
  800. * Deconstructs a complex data type (array or object) into a single field value.
  801. *
  802. * @param string $field The name of the field to be deconstructed
  803. * @param mixed $data An array or object to be deconstructed into a field
  804. * @return mixed The resulting data that should be assigned to a field
  805. * @access public
  806. */
  807. function deconstruct($field, $data) {
  808. if (!is_array($data)) {
  809. return $data;
  810. }
  811. $copy = $data;
  812. $type = $this->getColumnType($field);
  813. if (in_array($type, array('datetime', 'timestamp', 'date', 'time'))) {
  814. $useNewDate = (isset($data['year']) || isset($data['month']) ||
  815. isset($data['day']) || isset($data['hour']) || isset($data['minute']));
  816. $dateFields = array('Y' => 'year', 'm' => 'month', 'd' => 'day', 'H' => 'hour', 'i' => 'min', 's' => 'sec');
  817. $timeFields = array('H' => 'hour', 'i' => 'min', 's' => 'sec');
  818. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  819. $format = $db->columns[$type]['format'];
  820. $date = array();
  821. if (isset($data['hour']) && isset($data['meridian']) && $data['hour'] != 12 && 'pm' == $data['meridian']) {
  822. $data['hour'] = $data['hour'] + 12;
  823. }
  824. if (isset($data['hour']) && isset($data['meridian']) && $data['hour'] == 12 && 'am' == $data['meridian']) {
  825. $data['hour'] = '00';
  826. }
  827. if ($type == 'time') {
  828. foreach ($timeFields as $key => $val) {
  829. if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') {
  830. $data[$val] = '00';
  831. } elseif ($data[$val] === '') {
  832. $data[$val] = '';
  833. } else {
  834. $data[$val] = sprintf('%02d', $data[$val]);
  835. }
  836. if (!empty($data[$val])) {
  837. $date[$key] = $data[$val];
  838. } else {
  839. return null;
  840. }
  841. }
  842. }
  843. if ($type == 'datetime' || $type == 'timestamp' || $type == 'date') {
  844. foreach ($dateFields as $key => $val) {
  845. if ($val == 'hour' || $val == 'min' || $val == 'sec') {
  846. if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') {
  847. $data[$val] = '00';
  848. } else {
  849. $data[$val] = sprintf('%02d', $data[$val]);
  850. }
  851. }
  852. if (!isset($data[$val]) || isset($data[$val]) && (empty($data[$val]) || $data[$val][0] === '-')) {
  853. return null;
  854. }
  855. if (isset($data[$val]) && !empty($data[$val])) {
  856. $date[$key] = $data[$val];
  857. }
  858. }
  859. }
  860. $date = str_replace(array_keys($date), array_values($date), $format);
  861. if ($useNewDate && !empty($date)) {
  862. return $date;
  863. }
  864. }
  865. return $data;
  866. }
  867. /**
  868. * Returns an array of table metadata (column names and types) from the database.
  869. * $field => keys(type, null, default, key, length, extra)
  870. *
  871. * @param mixed $field Set to true to reload schema, or a string to return a specific field
  872. * @return array Array of table metadata
  873. * @access public
  874. */
  875. function schema($field = false) {
  876. if (!is_array($this->_schema) || $field === true) {
  877. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  878. $db->cacheSources = ($this->cacheSources && $db->cacheSources);
  879. if ($db->isInterfaceSupported('describe') && $this->useTable !== false) {
  880. $this->_schema = $db->describe($this, $field);
  881. } elseif ($this->useTable === false) {
  882. $this->_schema = array();
  883. }
  884. }
  885. if (is_string($field)) {
  886. if (isset($this->_schema[$field])) {
  887. return $this->_schema[$field];
  888. } else {
  889. return null;
  890. }
  891. }
  892. return $this->_schema;
  893. }
  894. /**
  895. * Returns an associative array of field names and column types.
  896. *
  897. * @return array Field types indexed by field name
  898. * @access public
  899. */
  900. function getColumnTypes() {
  901. $columns = $this->schema();
  902. if (empty($columns)) {
  903. trigger_error(__('(Model::getColumnTypes) Unable to build model field data. If you are using a model without a database table, try implementing schema()', true), E_USER_WARNING);
  904. }
  905. $cols = array();
  906. foreach ($columns as $field => $values) {
  907. $cols[$field] = $values['type'];
  908. }
  909. return $cols;
  910. }
  911. /**
  912. * Returns the column type of a column in the model.
  913. *
  914. * @param string $column The name of the model column
  915. * @return string Column type
  916. * @access public
  917. */
  918. function getColumnType($column) {
  919. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  920. $cols = $this->schema();
  921. $model = null;
  922. $column = str_replace(array($db->startQuote, $db->endQuote), '', $column);
  923. if (strpos($column, '.')) {
  924. list($model, $column) = explode('.', $column);
  925. }
  926. if ($model != $this->alias && isset($this->{$model})) {
  927. return $this->{$model}->getColumnType($column);
  928. }
  929. if (isset($cols[$column]) && isset($cols[$column]['type'])) {
  930. return $cols[$column]['type'];
  931. }
  932. return null;
  933. }
  934. /**
  935. * Returns true if the supplied field exists in the model's database table.
  936. *
  937. * @param mixed $name Name of field to look for, or an array of names
  938. * @return mixed If $name is a string, returns a boolean indicating whether the field exists.
  939. * If $name is an array of field names, returns the first field that exists,
  940. * or false if none exist.
  941. * @access public
  942. */
  943. function hasField($name) {
  944. if (is_array($name)) {
  945. foreach ($name as $n) {
  946. if ($this->hasField($n)) {
  947. return $n;
  948. }
  949. }
  950. return false;
  951. }
  952. if (empty($this->_schema)) {
  953. $this->schema();
  954. }
  955. if ($this->_schema != null) {
  956. return isset($this->_schema[$name]);
  957. }
  958. return false;
  959. }
  960. /**
  961. * Initializes the model for writing a new record, loading the default values
  962. * for those fields that are not defined in $data, and clearing previous validation errors.
  963. * Especially helpful for saving data in loops.
  964. *
  965. * @param mixed $data Optional data array to assign to the model after it is created. If null or false,
  966. * schema data defaults are not merged.
  967. * @param boolean $filterKey If true, overwrites any primary key input with an empty value
  968. * @return array The current Model::data; after merging $data and/or defaults from database
  969. * @access public
  970. * @link http://book.cakephp.org/view/75/Saving-Your-Data
  971. */
  972. function create($data = array(), $filterKey = false) {
  973. $defaults = array();
  974. $this->id = false;
  975. $this->data = array();
  976. $this->__exists = null;
  977. $this->validationErrors = array();
  978. if ($data !== null && $data !== false) {
  979. foreach ($this->schema() as $field => $properties) {
  980. if ($this->primaryKey !== $field && isset($properties['default'])) {
  981. $defaults[$field] = $properties['default'];
  982. }
  983. }
  984. $this->set(Set::filter($defaults));
  985. $this->set($data);
  986. }
  987. if ($filterKey) {
  988. $this->set($this->primaryKey, false);
  989. }
  990. return $this->data;
  991. }
  992. /**
  993. * Returns a list of fields from the database, and sets the current model
  994. * data (Model::$data) with the record found.
  995. *
  996. * @param mixed $fields String of single fieldname, or an array of fieldnames.
  997. * @param mixed $id The ID of the record to read
  998. * @return array Array of database fields, or false if not found
  999. * @access public
  1000. */
  1001. function read($fields = null, $id = null) {
  1002. $this->validationErrors = array();
  1003. if ($id != null) {
  1004. $this->id = $id;
  1005. }
  1006. $id = $this->id;
  1007. if (is_array($this->id)) {
  1008. $id = $this->id[0];
  1009. }
  1010. if ($id !== null && $id !== false) {
  1011. $this->data = $this->find('first', array(
  1012. 'conditions' => array($this->alias . '.' . $this->primaryKey => $id),
  1013. 'fields' => $fields
  1014. ));
  1015. return $this->data;
  1016. } else {
  1017. return false;
  1018. }
  1019. }
  1020. /**
  1021. * Returns the contents of a single field given the supplied conditions, in the
  1022. * supplied order.
  1023. *
  1024. * @param string $name Name of field to get
  1025. * @param array $conditions SQL conditions (defaults to NULL)
  1026. * @param string $order SQL ORDER BY fragment
  1027. * @return string field contents, or false if not found
  1028. * @access public
  1029. * @link http://book.cakephp.org/view/453/field
  1030. */
  1031. function field($name, $conditions = null, $order = null) {
  1032. if ($conditions === null && $this->id !== false) {
  1033. $conditions = array($this->alias . '.' . $this->primaryKey => $this->id);
  1034. }
  1035. if ($this->recursive >= 1) {
  1036. $recursive = -1;
  1037. } else {
  1038. $recursive = $this->recursive;
  1039. }
  1040. if ($data = $this->find($conditions, $name, $order, $recursive)) {
  1041. if (strpos($name, '.') === false) {
  1042. if (isset($data[$this->alias][$name])) {
  1043. return $data[$this->alias][$name];
  1044. }
  1045. } else {
  1046. $name = explode('.', $name);
  1047. if (isset($data[$name[0]][$name[1]])) {
  1048. return $data[$name[0]][$name[1]];
  1049. }
  1050. }
  1051. if (!empty($data[0])) {
  1052. $name = key($data[0]);
  1053. return $data[0][$name];
  1054. }
  1055. } else {
  1056. return false;
  1057. }
  1058. }
  1059. /**
  1060. * Saves the value of a single field to the database, based on the current
  1061. * model ID.
  1062. *
  1063. * @param string $name Name of the table field
  1064. * @param mixed $value Value of the field
  1065. * @param array $validate See $options param in Model::save(). Does not respect 'fieldList' key if passed
  1066. * @return mixed See Model::save()
  1067. * @access public
  1068. * @see Model::save()
  1069. * @link http://book.cakephp.org/view/75/Saving-Your-Data
  1070. */
  1071. function saveField($name, $value, $validate = false) {
  1072. $id = $this->id;
  1073. $this->create(false);
  1074. if (is_array($validate)) {
  1075. $options = array_merge(array('validate' => false, 'fieldList' => array($name)), $validate);
  1076. } else {
  1077. $options = array('validate' => $validate, 'fieldList' => array($name));
  1078. }
  1079. return $this->save(array($this->alias => array($this->primaryKey => $id, $name => $value)), $options);
  1080. }
  1081. /**
  1082. * Saves model data (based on white-list, if supplied) to the database. By
  1083. * default, validation occurs before save.
  1084. *
  1085. * @param array $data Data to save.
  1086. * @param mixed $validate Either a boolean, or an array.
  1087. * If a boolean, indicates whether or not to validate before saving.
  1088. * If an array, allows control of validate, callbacks, and fieldList
  1089. * @param array $fieldList List of fields to allow to be written
  1090. * @return mixed On success Model::$data if its not empty or true, false on failure
  1091. * @access public
  1092. * @link http://book.cakephp.org/view/75/Saving-Your-Data
  1093. */
  1094. function save($data = null, $validate = true, $fieldList = array()) {
  1095. $defaults = array('validate' => true, 'fieldList' => array(), 'callbacks' => true);
  1096. $_whitelist = $this->whitelist;
  1097. $fields = array();
  1098. if (!is_array($validate)) {
  1099. $options = array_merge($defaults, compact('validate', 'fieldList', 'callbacks'));
  1100. } else {
  1101. $options = array_merge($defaults, $validate);
  1102. }
  1103. if (!empty($options['fieldList'])) {
  1104. $this->whitelist = $options['fieldList'];
  1105. } elseif ($options['fieldList'] === null) {
  1106. $this->whitelist = array();
  1107. }
  1108. $this->set($data);
  1109. if (empty($this->data) && !$this->hasField(array('created', 'updated', 'modified'))) {
  1110. return false;
  1111. }
  1112. foreach (array('created', 'updated', 'modified') as $field) {
  1113. $keyPresentAndEmpty = (
  1114. isset($this->data[$this->alias]) &&
  1115. array_key_exists($field, $this->data[$this->alias]) &&
  1116. $this->data[$this->alias][$field] === null
  1117. );
  1118. if ($keyPresentAndEmpty) {
  1119. unset($this->data[$this->alias][$field]);
  1120. }
  1121. }
  1122. $this->exists();
  1123. $dateFields = array('modified', 'updated');
  1124. if (!$this->__exists) {
  1125. $dateFields[] = 'created';
  1126. }
  1127. if (isset($this->data[$this->alias])) {
  1128. $fields = array_keys($this->data[$this->alias]);
  1129. }
  1130. if ($options['validate'] && !$this->validates($options)) {
  1131. $this->whitelist = $_whitelist;
  1132. return false;
  1133. }
  1134. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  1135. foreach ($dateFields as $updateCol) {
  1136. if ($this->hasField($updateCol) && !in_array($updateCol, $fields)) {
  1137. $default = array('formatter' => 'date');
  1138. $colType = array_merge($default, $db->columns[$this->getColumnType($updateCol)]);
  1139. if (!array_key_exists('format', $colType)) {
  1140. $time = strtotime('now');
  1141. } else {
  1142. $time = $colType['formatter']($colType['format']);
  1143. }
  1144. if (!empty($this->whitelist)) {
  1145. $this->whitelist[] = $updateCol;
  1146. }
  1147. $this->set($updateCol, $time);
  1148. }
  1149. }
  1150. if ($options['callbacks'] === true || $options['callbacks'] === 'before') {
  1151. $result = $this->Behaviors->trigger($this, 'beforeSave', array($options), array(
  1152. 'break' => true, 'breakOn' => false
  1153. ));
  1154. if (!$result || !$this->beforeSave($options)) {
  1155. $this->whitelist = $_whitelist;
  1156. return false;
  1157. }
  1158. }
  1159. $fields = $values = array();
  1160. if (isset($this->data[$this->alias][$this->primaryKey]) && empty($this->data[$this->alias][$this->primaryKey])) {
  1161. unset($this->data[$this->alias][$this->primaryKey]);
  1162. }
  1163. foreach ($this->data as $n => $v) {
  1164. if (isset($this->hasAndBelongsToMany[$n])) {
  1165. if (isset($v[$n])) {
  1166. $v = $v[$n];
  1167. }
  1168. $joined[$n] = $v;
  1169. } else {
  1170. if ($n === $this->alias) {
  1171. foreach (array('created', 'updated', 'modified') as $field) {
  1172. if (array_key_exists($field, $v) && empty($v[$field])) {
  1173. unset($v[$field]);
  1174. }
  1175. }
  1176. foreach ($v as $x => $y) {
  1177. if ($this->hasField($x) && (empty($this->whitelist) || in_array($x, $this->whitelist))) {
  1178. list($fields[], $values[]) = array($x, $y);
  1179. }
  1180. }
  1181. }
  1182. }
  1183. }
  1184. $count = count($fields);
  1185. if (!$this->__exists && $count > 0) {
  1186. $this->id = false;
  1187. }
  1188. $success = true;
  1189. $created = false;
  1190. if ($count > 0) {
  1191. $cache = $this->_prepareUpdateFields(array_combine($fields, $values));
  1192. if (!empty($this->id)) {
  1193. $success = (bool)$db->update($this, $fields, $values);
  1194. } else {
  1195. foreach ($this->_schema as $field => $properties) {
  1196. if ($this->primaryKey === $field) {
  1197. $fInfo = $this->_schema[$field];
  1198. $isUUID = ($fInfo['length'] == 36 &&
  1199. ($fInfo['type'] === 'string' || $fInfo['type'] === 'binary')
  1200. );
  1201. if (empty($this->data[$this->alias][$this->primaryKey]) && $isUUID) {
  1202. if (array_key_exists($this->primaryKey, $this->data[$this->alias])) {
  1203. $j = array_search($this->primaryKey, $fields);
  1204. $values[$j] = String::uuid();
  1205. } else {
  1206. list($fields[], $values[]) = array($this->primaryKey, String::uuid());
  1207. }
  1208. }
  1209. break;
  1210. }
  1211. }
  1212. if (!$db->create($this, $fields, $values)) {
  1213. $success = $created = false;
  1214. } else {
  1215. $created = true;
  1216. }
  1217. }
  1218. if ($success && !empty($this->belongsTo)) {
  1219. $this->updateCounterCache($cache, $created);
  1220. }
  1221. }
  1222. if (!empty($joined) && $success === true) {
  1223. $this->__saveMulti($joined, $this->id);
  1224. }
  1225. if ($success && $count > 0) {
  1226. if (!empty($this->data)) {
  1227. $success = $this->data;
  1228. }
  1229. if ($options['callbacks'] === true || $options['callbacks'] === 'after') {
  1230. $this->Behaviors->trigger($this, 'afterSave', array($created, $options));
  1231. $this->afterSave($created);
  1232. }
  1233. if (!empty($this->data)) {
  1234. $success = Set::merge($success, $this->data);
  1235. }
  1236. $this->data = false;
  1237. $this->__exists = null;
  1238. $this->_clearCache();
  1239. $this->validationErrors = array();
  1240. }
  1241. $this->whitelist = $_whitelist;
  1242. return $success;
  1243. }
  1244. /**
  1245. * Saves model hasAndBelongsToMany data to the database.
  1246. *
  1247. * @param array $joined Data to save
  1248. * @param mixed $id ID of record in this model
  1249. * @access private
  1250. */
  1251. function __saveMulti($joined, $id) {
  1252. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  1253. foreach ($joined as $assoc => $data) {
  1254. if (isset($this->hasAndBelongsToMany[$assoc])) {
  1255. list($join) = $this->joinModel($this->hasAndBelongsToMany[$assoc]['with']);
  1256. $isUUID = !empty($this->{$join}->primaryKey) && (
  1257. $this->{$join}->_schema[$this->{$join}->primaryKey]['length'] == 36 && (
  1258. $this->{$join}->_schema[$this->{$join}->primaryKey]['type'] === 'string' ||
  1259. $this->{$join}->_schema[$this->{$join}->primaryKey]['type'] === 'binary'
  1260. )
  1261. );
  1262. $newData = $newValues = array();
  1263. $primaryAdded = false;
  1264. $fields = array(
  1265. $db->name($this->hasAndBelongsToMany[$assoc]['foreignKey']),
  1266. $db->name($this->hasAndBelongsToMany[$assoc]['associationForeignKey'])
  1267. );
  1268. $idField = $db->name($this->{$join}->primaryKey);
  1269. if ($isUUID && !in_array($idField, $fields)) {
  1270. $fields[] = $idField;
  1271. $primaryAdded = true;
  1272. }
  1273. foreach ((array)$data as $row) {
  1274. if ((is_string($row) && (strlen($row) == 36 || strlen($row) == 16)) || is_numeric($row)) {
  1275. $values = array(
  1276. $db->value($id, $this->getColumnType($this->primaryKey)),
  1277. $db->value($row)
  1278. );
  1279. if ($isUUID && $primaryAdded) {
  1280. $values[] = $db->value(String::uuid());
  1281. }
  1282. $values = implode(',', $values);
  1283. $newValues[] = "({$values})";
  1284. unset($values);
  1285. } elseif (isset($row[$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
  1286. $newData[] = $row;
  1287. } elseif (isset($row[$join]) && isset($row[$join][$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
  1288. $newData[] = $row[$join];
  1289. }
  1290. }
  1291. if ($this->hasAndBelongsToMany[$assoc]['unique']) {
  1292. $conditions = array(
  1293. $join . '.' . $this->hasAndBelongsToMany[$assoc]['foreignKey'] => $id
  1294. );
  1295. if (!empty($this->hasAndBelongsToMany[$assoc]['conditions'])) {
  1296. $conditions = array_merge($conditions, (array)$this->hasAndBelongsToMany[$assoc]['conditions']);
  1297. }
  1298. $links = $this->{$join}->find('all', array(
  1299. 'conditions' => $conditions,
  1300. 'recursive' => empty($this->hasAndBelongsToMany[$assoc]['conditions']) ? -1 : 0,
  1301. 'fields' => $this->hasAndBelongsToMany[$assoc]['associationForeignKey']
  1302. ));
  1303. $associationForeignKey = "{$join}." . $this->hasAndBelongsToMany[$assoc]['associationForeignKey'];
  1304. $oldLinks = Set::extract($links, "{n}.{$associationForeignKey}");
  1305. if (!empty($oldLinks)) {
  1306. $conditions[$associationForeignKey] = $oldLinks;
  1307. $db->delete($this->{$join}, $conditions);
  1308. }
  1309. }
  1310. if (!empty($newData)) {
  1311. foreach ($newData as $data) {
  1312. $data[$this->hasAndBelongsToMany[$assoc]['foreignKey']] = $id;
  1313. $this->{$join}->create($data);
  1314. $this->{$join}->save();
  1315. }
  1316. }
  1317. if (!empty($newValues)) {
  1318. $fields = implode(',', $fields);
  1319. $db->insertMulti($this->{$join}, $fields, $newValues);
  1320. }
  1321. }
  1322. }
  1323. }
  1324. /**
  1325. * Updates the counter cache of belongsTo associations after a save or delete operation
  1326. *
  1327. * @param array $keys Optional foreign key data, defaults to the information $this->data
  1328. * @param boolean $created True if a new record was created, otherwise only associations with
  1329. * 'counterScope' defined get updated
  1330. * @return void
  1331. * @access public
  1332. */
  1333. function updateCounterCache($keys = array(), $created = false) {
  1334. $keys = empty($keys) ? $this->data[$this->alias] : $keys;
  1335. $keys['old'] = isset($keys['old']) ? $keys['old'] : array();
  1336. foreach ($this->belongsTo as $parent => $assoc) {
  1337. $foreignKey = $assoc['foreignKey'];
  1338. $fkQuoted = $this->escapeField($assoc['foreignKey']);
  1339. if (!empty($assoc['counterCache'])) {
  1340. if ($assoc['counterCache'] === true) {
  1341. $assoc['counterCache'] = Inflector::underscore($this->alias) . '_count';
  1342. }
  1343. if (!$this->{$parent}->hasField($assoc['counterCache'])) {
  1344. continue;
  1345. }
  1346. if (!array_key_exists($foreignKey, $keys)) {
  1347. $keys[$foreignKey] = $this->field($foreignKey);
  1348. }
  1349. $recursive = (isset($assoc['counterScope']) ? 1 : -1);
  1350. $conditions = ($recursive == 1) ? (array)$assoc['counterScope'] : array();
  1351. if (isset($keys['old'][$foreignKey])) {
  1352. if ($keys['old'][$foreignKey] != $keys[$foreignKey]) {
  1353. $conditions[$fkQuoted] = $keys['old'][$foreignKey];
  1354. $count = intval($this->find('count', compact('conditions', 'recursive')));
  1355. $this->{$parent}->updateAll(
  1356. array($assoc['counterCache'] => $count),
  1357. array($this->{$parent}->escapeField() => $keys['old'][$foreignKey])
  1358. );
  1359. }
  1360. }
  1361. $conditions[$fkQuoted] = $keys[$foreignKey];
  1362. if ($recursive == 1) {
  1363. $conditions = array_merge($conditions, (array)$assoc['counterScope']);
  1364. }
  1365. $count = intval($this->find('count', compact('conditions', 'recursive')));
  1366. $this->{$parent}->updateAll(
  1367. array($assoc['counterCache'] => $count),
  1368. array($this->{$parent}->escapeField() => $keys[$foreignKey])
  1369. );
  1370. }
  1371. }
  1372. }
  1373. /**
  1374. * Helper method for Model::updateCounterCache(). Checks the fields to be updated for
  1375. *
  1376. * @param array $data The fields of the record that will be updated
  1377. * @return array Returns updated foreign key values, along with an 'old' key containing the old
  1378. * values, or empty if no foreign keys are updated.
  1379. * @access protected
  1380. */
  1381. function _prepareUpdateFields($data) {
  1382. $foreignKeys = array();
  1383. foreach ($this->belongsTo as $assoc => $info) {
  1384. if ($info['counterCache']) {
  1385. $foreignKeys[$assoc] = $info['foreignKey'];
  1386. }
  1387. }
  1388. $included = array_intersect($foreignKeys, array_keys($data));
  1389. if (empty($included) || empty($this->id)) {
  1390. return array();
  1391. }
  1392. $old = $this->find('first', array(
  1393. 'conditions' => array($this->primaryKey => $this->id),
  1394. 'fields' => array_values($included),
  1395. 'recursive' => -1
  1396. ));
  1397. return array_merge($data, array('old' => $old[$this->alias]));
  1398. }
  1399. /**
  1400. * Saves multiple individual records for a single model; Also works with a single record, as well as
  1401. * all its associated records.
  1402. *
  1403. * #### Options
  1404. *
  1405. * - validate: Set to false to disable validation, true to validate each record before
  1406. * saving, 'first' to validate *all* records before any are saved, or 'only' to only
  1407. * validate the records, but not save them.
  1408. * - atomic: If true (default), will attempt to save all records in a single transaction.
  1409. * Should be set to false if database/table does not support transactions.
  1410. * If false, we return an array similar to the $data array passed, but values are set to true/false
  1411. * depending on whether each record saved successfully.
  1412. * - fieldList: Equivalent to the $fieldList parameter in Model::save()
  1413. *
  1414. * @param array $data Record data to save. This can be either a numerically-indexed array (for saving multiple
  1415. * records of the same type), or an array indexed by association name.
  1416. * @param array $options Options to use when saving record data, See $options above.
  1417. * @return mixed True on success, or false on failure
  1418. * @access public
  1419. * @link http://book.cakephp.org/view/84/Saving-Related-Model-Data-hasOne-hasMany-belongsTo
  1420. * @link http://book.cakephp.org/view/75/Saving-Your-Data
  1421. */
  1422. function saveAll($data = null, $options = array()) {
  1423. if (empty($data)) {
  1424. $data = $this->data;
  1425. }
  1426. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  1427. $options = array_merge(array('validate' => true, 'atomic' => true), $options);
  1428. $this->validationErrors = $validationErrors = array();
  1429. $validates = true;
  1430. $return = array();
  1431. if ($options['atomic'] && $options['validate'] !== 'only') {
  1432. $db->begin($this);
  1433. }
  1434. if (Set::numeric(array_keys($data))) {
  1435. while ($validates) {
  1436. foreach ($data as $key => $record) {
  1437. if (!$currentValidates = $this->__save($record, $options)) {
  1438. $validationErrors[$key] = $this->validationErrors;
  1439. }
  1440. if ($options['validate'] === 'only' || $options['validate'] === 'first') {
  1441. $validating = true;
  1442. if ($options['atomic']) {
  1443. $validates = $validates && $currentValidates;
  1444. } else {
  1445. $validates = $currentValidates;
  1446. }
  1447. } else {
  1448. $validating = false;
  1449. $validates = $currentValidates;
  1450. }
  1451. if (!$options['atomic']) {
  1452. $return[] = $validates;
  1453. } elseif (!$validates && !$validating) {
  1454. break;
  1455. }
  1456. }
  1457. $this->validationErrors = $validationErrors;
  1458. switch (true) {
  1459. case ($options['validate'] === 'only'):
  1460. return ($options['atomic'] ? $validates : $return);
  1461. break;
  1462. case ($options['validate'] === 'first'):
  1463. $options['validate'] = true;
  1464. continue;
  1465. break;
  1466. default:
  1467. if ($options['atomic']) {
  1468. if ($validates && ($db->commit($this) !== false)) {
  1469. return true;
  1470. }
  1471. $db->rollback($this);
  1472. return false;
  1473. }
  1474. return $return;
  1475. break;
  1476. }
  1477. }
  1478. return $return;
  1479. }
  1480. $associations = $this->getAssociated();
  1481. while ($validates) {
  1482. foreach ($data as $association => $values) {
  1483. if (isset($associations[$association])) {
  1484. switch ($associations[$association]) {
  1485. case 'belongsTo':
  1486. if ($this->{$association}->__save($values, $options)) {
  1487. $data[$this->alias][$this->belongsTo[$association]['foreignKey']] = $this->{$association}->id;
  1488. } else {
  1489. $validationErrors[$association] = $this->{$association}->validationErrors;
  1490. $validates = false;
  1491. }
  1492. if (!$options['atomic']) {
  1493. $return[$association][] = $validates;
  1494. }
  1495. break;
  1496. }
  1497. }
  1498. }
  1499. if (!$this->__save($data, $options)) {
  1500. $validationErrors[$this->alias] = $this->validationErrors;
  1501. $validates = false;
  1502. }
  1503. if (!$options['atomic']) {
  1504. $return[$this->alias] = $validates;
  1505. }
  1506. $validating = ($options['validate'] === 'only' || $options['validate'] === 'first');
  1507. foreach ($data as $association => $values) {
  1508. if (!$validates && !$validating) {
  1509. break;
  1510. }
  1511. if (isset($associations[$association])) {
  1512. $type = $associations[$association];
  1513. switch ($type) {
  1514. case 'hasOne':
  1515. $values[$this->{$type}[$association]['foreignKey']] = $this->id;
  1516. if (!$this->{$association}->__save($values, $options)) {
  1517. $validationErrors[$association] = $this->{$association}->validationErrors;
  1518. $validates = false;
  1519. }
  1520. if (!$options['atomic']) {
  1521. $return[$association][] = $validates;
  1522. }
  1523. break;
  1524. case 'hasMany':
  1525. foreach ($values as $i => $value) {
  1526. $values[$i][$this->{$type}[$association]['foreignKey']] = $this->id;
  1527. }
  1528. $_options = array_merge($options, array('atomic' => false));
  1529. if ($_options['validate'] === 'first') {
  1530. $_options['validate'] = 'only';
  1531. }
  1532. $_return = $this->{$association}->saveAll($values, $_options);
  1533. if ($_return === false || (is_array($_return) && in_array(false, $_return, true))) {
  1534. $validationErrors[$association] = $this->{$association}->validationErrors;
  1535. $validates = false;
  1536. }
  1537. if (is_array($_return)) {
  1538. foreach ($_return as $val) {
  1539. if (!isset($return[$association])) {
  1540. $return[$association] = array();
  1541. } elseif (!is_array($return[$association])) {
  1542. $return[$association] = array($return[$association]);
  1543. }
  1544. $return[$association][] = $val;
  1545. }
  1546. } else {
  1547. $return[$association] = $_return;
  1548. }
  1549. break;
  1550. }
  1551. }
  1552. }
  1553. $this->validationErrors = $validationErrors;
  1554. if (isset($validationErrors[$this->alias])) {
  1555. $this->validationErrors = $validationErrors[$this->alias];
  1556. }
  1557. switch (true) {
  1558. case ($options['validate'] === 'only'):
  1559. return ($options['atomic'] ? $validates : $return);
  1560. break;
  1561. case ($options['validate'] === 'first'):
  1562. $options['validate'] = true;
  1563. continue;
  1564. break;
  1565. default:
  1566. if ($options['atomic']) {
  1567. if ($validates) {
  1568. return ($db->commit($this) !== false);
  1569. } else {
  1570. $db->rollback($this);
  1571. }
  1572. }
  1573. return $return;
  1574. break;
  1575. }
  1576. }
  1577. }
  1578. /**
  1579. * Private helper method used by saveAll.
  1580. *
  1581. * @return boolean Success
  1582. * @access private
  1583. * @see Model::saveAll()
  1584. */
  1585. function __save($data, $options) {
  1586. if ($options['validate'] === 'first' || $options['validate'] === 'only') {
  1587. if (!($this->create($data) && $this->validates($options))) {
  1588. return false;
  1589. }
  1590. } elseif (!($this->create(null) !== null && $this->save($data, $options))) {
  1591. return false;
  1592. }
  1593. return true;
  1594. }
  1595. /**
  1596. * Updates multiple model records based on a set of conditions.
  1597. *
  1598. * @param array $fields Set of fields and values, indexed by fields.
  1599. * Fields are treated as SQL snippets, to insert literal values manually escape your data.
  1600. * @param mixed $conditions Conditions to match, true for all records
  1601. * @return boolean True on success, false on failure
  1602. * @access public
  1603. * @link http://book.cakephp.org/view/75/Saving-Your-Data
  1604. */
  1605. function updateAll($fields, $conditions = true) {
  1606. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  1607. return $db->update($this, $fields, null, $conditions);
  1608. }
  1609. /**
  1610. * Alias for del().
  1611. *
  1612. * @param mixed $id ID of record to delete
  1613. * @param boolean $cascade Set to true to delete records that depend on this record
  1614. * @return boolean True on success
  1615. * @access public
  1616. * @see Model::del()
  1617. * @link http://book.cakephp.org/view/691/remove
  1618. */
  1619. function remove($id = null, $cascade = true) {
  1620. return $this->del($id, $cascade);
  1621. }
  1622. /**
  1623. * Removes record for given ID. If no ID is given, the current ID is used. Returns true on success.
  1624. *
  1625. * @param mixed $id ID of record to delete
  1626. * @param boolean $cascade Set to true to delete records that depend on this record
  1627. * @return boolean True on success
  1628. * @access public
  1629. * @link http://book.cakephp.org/view/690/del
  1630. */
  1631. function del($id = null, $cascade = true) {
  1632. if (!empty($id)) {
  1633. $this->id = $id;
  1634. }
  1635. $id = $this->id;
  1636. if ($this->beforeDelete($cascade)) {
  1637. $filters = $this->Behaviors->trigger($this, 'beforeDelete', array($cascade), array(
  1638. 'break' => true, 'breakOn' => false
  1639. ));
  1640. if (!$filters || !$this->exists()) {
  1641. return false;
  1642. }
  1643. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  1644. $this->_deleteDependent($id, $cascade);
  1645. $this->_deleteLinks($id);
  1646. $this->id = $id;
  1647. if (!empty($this->belongsTo)) {
  1648. $keys = $this->find('first', array('fields' => $this->__collectForeignKeys()));
  1649. }
  1650. if ($db->delete($this, array($this->alias . '.' . $this->primaryKey => $id))) {
  1651. if (!empty($this->belongsTo)) {
  1652. $this->updateCounterCache($keys[$this->alias]);
  1653. }
  1654. $this->Behaviors->trigger($this, 'afterDelete');
  1655. $this->afterDelete();
  1656. $this->_clearCache();
  1657. $this->id = false;
  1658. $this->__exists = null;
  1659. return true;
  1660. }
  1661. }
  1662. return false;
  1663. }
  1664. /**
  1665. * Alias for del().
  1666. *
  1667. * @param mixed $id ID of record to delete
  1668. * @param boolean $cascade Set to true to delete records that depend on this record
  1669. * @return boolean True on success
  1670. * @access public
  1671. * @see Model::del()
  1672. */
  1673. function delete($id = null, $cascade = true) {
  1674. return $this->del($id, $cascade);
  1675. }
  1676. /**
  1677. * Cascades model deletes through associated hasMany and hasOne child records.
  1678. *
  1679. * @param string $id ID of record that was deleted
  1680. * @param boolean $cascade Set to true to delete records that depend on this record
  1681. * @return void
  1682. * @access protected
  1683. */
  1684. function _deleteDependent($id, $cascade) {
  1685. if (!empty($this->__backAssociation)) {
  1686. $savedAssociatons = $this->__backAssociation;
  1687. $this->__backAssociation = array();
  1688. }
  1689. foreach (array_merge($this->hasMany, $this->hasOne) as $assoc => $data) {
  1690. if ($data['dependent'] === true && $cascade === true) {
  1691. $model =& $this->{$assoc};
  1692. $conditions = array($model->escapeField($data['foreignKey']) => $id);
  1693. if ($data['conditions']) {
  1694. $conditions = array_merge($data['conditions'], $conditions);
  1695. }
  1696. $model->recursive = -1;
  1697. if (isset($data['exclusive']) && $data['exclusive']) {
  1698. $model->deleteAll($conditions);
  1699. } else {
  1700. $records = $model->find('all', array('conditions' => $conditions, 'fields' => $model->primaryKey));
  1701. if (!empty($records)) {
  1702. foreach ($records as $record) {
  1703. $model->delete($record[$model->alias][$model->primaryKey]);
  1704. }
  1705. }
  1706. }
  1707. }
  1708. }
  1709. if (isset($savedAssociatons)) {
  1710. $this->__backAssociation = $savedAssociatons;
  1711. }
  1712. }
  1713. /**
  1714. * Cascades model deletes through HABTM join keys.
  1715. *
  1716. * @param string $id ID of record that was deleted
  1717. * @return void
  1718. * @access protected
  1719. */
  1720. function _deleteLinks($id) {
  1721. foreach ($this->hasAndBelongsToMany as $assoc => $data) {
  1722. $joinModel = $data['with'];
  1723. $records = $this->{$joinModel}->find('all', array(
  1724. 'conditions' => array_merge(array($this->{$joinModel}->escapeField($data['foreignKey']) => $id)),
  1725. 'fields' => $this->{$joinModel}->primaryKey,
  1726. 'recursive' => -1
  1727. ));
  1728. if (!empty($records)) {
  1729. foreach ($records as $record) {
  1730. $this->{$joinModel}->delete($record[$this->{$joinModel}->alias][$this->{$joinModel}->primaryKey]);
  1731. }
  1732. }
  1733. }
  1734. }
  1735. /**
  1736. * Deletes multiple model records based on a set of conditions.
  1737. *
  1738. * @param mixed $conditions Conditions to match
  1739. * @param boolean $cascade Set to true to delete records that depend on this record
  1740. * @param boolean $callbacks Run callbacks (not being used)
  1741. * @return boolean True on success, false on failure
  1742. * @access public
  1743. * @link http://book.cakephp.org/view/692/deleteAll
  1744. */
  1745. function deleteAll($conditions, $cascade = true, $callbacks = false) {
  1746. if (empty($conditions)) {
  1747. return false;
  1748. }
  1749. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  1750. if (!$cascade && !$callbacks) {
  1751. return $db->delete($this, $conditions);
  1752. } else {
  1753. $ids = Set::extract(
  1754. $this->find('all', array_merge(array('fields' => "{$this->alias}.{$this->primaryKey}", 'recursive' => 0), compact('conditions'))),
  1755. "{n}.{$this->alias}.{$this->primaryKey}"
  1756. );
  1757. if (empty($ids)) {
  1758. return true;
  1759. }
  1760. if ($callbacks) {
  1761. $_id = $this->id;
  1762. $result = true;
  1763. foreach ($ids as $id) {
  1764. $result = ($result && $this->delete($id, $cascade));
  1765. }
  1766. $this->id = $_id;
  1767. return $result;
  1768. } else {
  1769. foreach ($ids as $id) {
  1770. $this->_deleteLinks($id);
  1771. if ($cascade) {
  1772. $this->_deleteDependent($id, $cascade);
  1773. }
  1774. }
  1775. return $db->delete($this, array($this->alias . '.' . $this->primaryKey => $ids));
  1776. }
  1777. }
  1778. }
  1779. /**
  1780. * Collects foreign keys from associations.
  1781. *
  1782. * @return array
  1783. * @access private
  1784. */
  1785. function __collectForeignKeys($type = 'belongsTo') {
  1786. $result = array();
  1787. foreach ($this->{$type} as $assoc => $data) {
  1788. if (isset($data['foreignKey']) && is_string($data['foreignKey'])) {
  1789. $result[$assoc] = $data['foreignKey'];
  1790. }
  1791. }
  1792. return $result;
  1793. }
  1794. /**
  1795. * Returns true if a record with the currently set ID exists.
  1796. *
  1797. * @param boolean $reset if true will force database query
  1798. * @return boolean True if such a record exists
  1799. * @access public
  1800. */
  1801. function exists($reset = false) {
  1802. if (is_array($reset)) {
  1803. extract($reset, EXTR_OVERWRITE);
  1804. }
  1805. if ($this->getID() === false || $this->useTable === false) {
  1806. return false;
  1807. }
  1808. if (!empty($this->__exists) && $reset !== true) {
  1809. return $this->__exists;
  1810. }
  1811. $conditions = array($this->alias . '.' . $this->primaryKey => $this->getID());
  1812. $query = array('conditions' => $conditions, 'recursive' => -1, 'callbacks' => false);
  1813. if (is_array($reset)) {
  1814. $query = array_merge($query, $reset);
  1815. }
  1816. return $this->__exists = ($this->find('count', $query) > 0);
  1817. }
  1818. /**
  1819. * Returns true if a record that meets given conditions exists.
  1820. *
  1821. * @param array $conditions SQL conditions array
  1822. * @return boolean True if such a record exists
  1823. * @access public
  1824. */
  1825. function hasAny($conditions = null) {
  1826. return ($this->find('count', array('conditions' => $conditions, 'recursive' => -1)) != false);
  1827. }
  1828. /**
  1829. * Returns a result set array.
  1830. *
  1831. * Also used to perform new-notation finds, where the first argument is type of find operation to perform
  1832. * (all / first / count / neighbors / list / threaded ),
  1833. * second parameter options for finding ( indexed array, including: 'conditions', 'limit',
  1834. * 'recursive', 'page', 'fields', 'offset', 'order')
  1835. *
  1836. * Eg:
  1837. * {{{
  1838. * find('all', array(
  1839. * 'conditions' => array('name' => 'Thomas Anderson'),
  1840. * 'fields' => array('name', 'email'),
  1841. * 'order' => 'field3 DESC',
  1842. * 'recursive' => 2,
  1843. * 'group' => 'type'
  1844. * ));
  1845. * }}}
  1846. *
  1847. * Specifying 'fields' for new-notation 'list':
  1848. *
  1849. * - If no fields are specified, then 'id' is used for key and 'model->displayField' is used for value.
  1850. * - If a single field is specified, 'id' is used for key and specified field is used for value.
  1851. * - If three fields are specified, they are used (in order) for key, value and group.
  1852. * - Otherwise, first and second fields are used for key and value.
  1853. *
  1854. * @param array $conditions SQL conditions array, or type of find operation (all / first / count / neighbors / list / threaded)
  1855. * @param mixed $fields Either a single string of a field name, or an array of field names, or options for matching
  1856. * @param string $order SQL ORDER BY conditions (e.g. "price DESC" or "name ASC")
  1857. * @param integer $recursive The number of levels deep to fetch associated records
  1858. * @return array Array of records
  1859. * @access public
  1860. * @link http://book.cakephp.org/view/449/find
  1861. */
  1862. function find($conditions = null, $fields = array(), $order = null, $recursive = null) {
  1863. if (!is_string($conditions) || (is_string($conditions) && !array_key_exists($conditions, $this->_findMethods))) {
  1864. $type = 'first';
  1865. $query = array_merge(compact('conditions', 'fields', 'order', 'recursive'), array('limit' => 1));
  1866. } else {
  1867. list($type, $query) = array($conditions, $fields);
  1868. }
  1869. $this->findQueryType = $type;
  1870. $this->id = $this->getID();
  1871. $query = array_merge(
  1872. array(
  1873. 'conditions' => null, 'fields' => null, 'joins' => array(), 'limit' => null,
  1874. 'offset' => null, 'order' => null, 'page' => null, 'group' => null, 'callbacks' => true
  1875. ),
  1876. (array)$query
  1877. );
  1878. if ($type != 'all') {
  1879. if ($this->_findMethods[$type] === true) {
  1880. $query = $this->{'_find' . ucfirst($type)}('before', $query);
  1881. }
  1882. }
  1883. if (!is_numeric($query['page']) || intval($query['page']) < 1) {
  1884. $query['page'] = 1;
  1885. }
  1886. if ($query['page'] > 1 && !empty($query['limit'])) {
  1887. $query['offset'] = ($query['page'] - 1) * $query['limit'];
  1888. }
  1889. if ($query['order'] === null && $this->order !== null) {
  1890. $query['order'] = $this->order;
  1891. }
  1892. $query['order'] = array($query['order']);
  1893. if ($query['callbacks'] === true || $query['callbacks'] === 'before') {
  1894. $return = $this->Behaviors->trigger($this, 'beforeFind', array($query), array(
  1895. 'break' => true, 'breakOn' => false, 'modParams' => true
  1896. ));
  1897. $query = (is_array($return)) ? $return : $query;
  1898. if ($return === false) {
  1899. return null;
  1900. }
  1901. $return = $this->beforeFind($query);
  1902. $query = (is_array($return)) ? $return : $query;
  1903. if ($return === false) {
  1904. return null;
  1905. }
  1906. }
  1907. if (!$db =& ConnectionManager::getDataSource($this->useDbConfig)) {
  1908. return false;
  1909. }
  1910. $results = $db->read($this, $query);
  1911. $this->resetAssociations();
  1912. $this->findQueryType = null;
  1913. if ($query['callbacks'] === true || $query['callbacks'] === 'after') {
  1914. $results = $this->__filterResults($results);
  1915. }
  1916. if ($type === 'all') {
  1917. return $results;
  1918. } else {
  1919. if ($this->_findMethods[$type] === true) {
  1920. return $this->{'_find' . ucfirst($type)}('after', $query, $results);
  1921. }
  1922. }
  1923. }
  1924. /**
  1925. * Handles the before/after filter logic for find('first') operations. Only called by Model::find().
  1926. *
  1927. * @param string $state Either "before" or "after"
  1928. * @param array $query
  1929. * @param array $data
  1930. * @return array
  1931. * @access protected
  1932. * @see Model::find()
  1933. */
  1934. function _findFirst($state, $query, $results = array()) {
  1935. if ($state == 'before') {
  1936. $query['limit'] = 1;
  1937. if (empty($query['conditions']) && !empty($this->id)) {
  1938. $query['conditions'] = array($this->escapeField() => $this->id);
  1939. }
  1940. return $query;
  1941. } elseif ($state == 'after') {
  1942. if (empty($results[0])) {
  1943. return false;
  1944. }
  1945. return $results[0];
  1946. }
  1947. }
  1948. /**
  1949. * Handles the before/after filter logic for find('count') operations. Only called by Model::find().
  1950. *
  1951. * @param string $state Either "before" or "after"
  1952. * @param array $query
  1953. * @param array $data
  1954. * @return int The number of records found, or false
  1955. * @access protected
  1956. * @see Model::find()
  1957. */
  1958. function _findCount($state, $query, $results = array()) {
  1959. if ($state == 'before') {
  1960. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  1961. if (empty($query['fields'])) {
  1962. $query['fields'] = $db->calculate($this, 'count');
  1963. } elseif (is_string($query['fields']) && !preg_match('/count/i', $query['fields'])) {
  1964. $query['fields'] = $db->calculate($this, 'count', array(
  1965. $db->expression($query['fields']), 'count'
  1966. ));
  1967. }
  1968. $query['order'] = false;
  1969. return $query;
  1970. } elseif ($state == 'after') {
  1971. if (isset($results[0][0]['count'])) {
  1972. return intval($results[0][0]['count']);
  1973. } elseif (isset($results[0][$this->alias]['count'])) {
  1974. return intval($results[0][$this->alias]['count']);
  1975. }
  1976. return false;
  1977. }
  1978. }
  1979. /**
  1980. * Handles the before/after filter logic for find('list') operations. Only called by Model::find().
  1981. *
  1982. * @param string $state Either "before" or "after"
  1983. * @param array $query
  1984. * @param array $data
  1985. * @return array Key/value pairs of primary keys/display field values of all records found
  1986. * @access protected
  1987. * @see Model::find()
  1988. */
  1989. function _findList($state, $query, $results = array()) {
  1990. if ($state == 'before') {
  1991. if (empty($query['fields'])) {
  1992. $query['fields'] = array("{$this->alias}.{$this->primaryKey}", "{$this->alias}.{$this->displayField}");
  1993. $list = array("{n}.{$this->alias}.{$this->primaryKey}", "{n}.{$this->alias}.{$this->displayField}", null);
  1994. } else {
  1995. if (!is_array($query['fields'])) {
  1996. $query['fields'] = String::tokenize($query['fields']);
  1997. }
  1998. if (count($query['fields']) == 1) {
  1999. if (strpos($query['fields'][0], '.') === false) {
  2000. $query['fields'][0] = $this->alias . '.' . $query['fields'][0];
  2001. }
  2002. $list = array("{n}.{$this->alias}.{$this->primaryKey}", '{n}.' . $query['fields'][0], null);
  2003. $query['fields'] = array("{$this->alias}.{$this->primaryKey}", $query['fields'][0]);
  2004. } elseif (count($query['fields']) == 3) {
  2005. for ($i = 0; $i < 3; $i++) {
  2006. if (strpos($query['fields'][$i], '.') === false) {
  2007. $query['fields'][$i] = $this->alias . '.' . $query['fields'][$i];
  2008. }
  2009. }
  2010. $list = array('{n}.' . $query['fields'][0], '{n}.' . $query['fields'][1], '{n}.' . $query['fields'][2]);
  2011. } else {
  2012. for ($i = 0; $i < 2; $i++) {
  2013. if (strpos($query['fields'][$i], '.') === false) {
  2014. $query['fields'][$i] = $this->alias . '.' . $query['fields'][$i];
  2015. }
  2016. }
  2017. $list = array('{n}.' . $query['fields'][0], '{n}.' . $query['fields'][1], null);
  2018. }
  2019. }
  2020. if (!isset($query['recursive']) || $query['recursive'] === null) {
  2021. $query['recursive'] = -1;
  2022. }
  2023. list($query['list']['keyPath'], $query['list']['valuePath'], $query['list']['groupPath']) = $list;
  2024. return $query;
  2025. } elseif ($state == 'after') {
  2026. if (empty($results)) {
  2027. return array();
  2028. }
  2029. $lst = $query['list'];
  2030. return Set::combine($results, $lst['keyPath'], $lst['valuePath'], $lst['groupPath']);
  2031. }
  2032. }
  2033. /**
  2034. * Detects the previous field's value, then uses logic to find the 'wrapping'
  2035. * rows and return them.
  2036. *
  2037. * @param string $state Either "before" or "after"
  2038. * @param mixed $query
  2039. * @param array $results
  2040. * @return array
  2041. * @access protected
  2042. */
  2043. function _findNeighbors($state, $query, $results = array()) {
  2044. if ($state == 'before') {
  2045. $query = array_merge(array('recursive' => 0), $query);
  2046. extract($query);
  2047. $conditions = (array)$conditions;
  2048. if (isset($field) && isset($value)) {
  2049. if (strpos($field, '.') === false) {
  2050. $field = $this->alias . '.' . $field;
  2051. }
  2052. } else {
  2053. $field = $this->alias . '.' . $this->primaryKey;
  2054. $value = $this->id;
  2055. }
  2056. $query['conditions'] = array_merge($conditions, array($field . ' <' => $value));
  2057. $query['order'] = $field . ' DESC';
  2058. $query['limit'] = 1;
  2059. $query['field'] = $field;
  2060. $query['value'] = $value;
  2061. return $query;
  2062. } elseif ($state == 'after') {
  2063. extract($query);
  2064. unset($query['conditions'][$field . ' <']);
  2065. $return = array();
  2066. if (isset($results[0])) {
  2067. $prevVal = Set::extract('/' . str_replace('.', '/', $field), $results[0]);
  2068. $query['conditions'][$field . ' >='] = $prevVal[0];
  2069. $query['conditions'][$field . ' !='] = $value;
  2070. $query['limit'] = 2;
  2071. } else {
  2072. $return['prev'] = null;
  2073. $query['conditions'][$field . ' >'] = $value;
  2074. $query['limit'] = 1;
  2075. }
  2076. $query['order'] = $field . ' ASC';
  2077. $return2 = $this->find('all', $query);
  2078. if (!array_key_exists('prev', $return)) {
  2079. $return['prev'] = $return2[0];
  2080. }
  2081. if (count($return2) == 2) {
  2082. $return['next'] = $return2[1];
  2083. } elseif (count($return2) == 1 && !$return['prev']) {
  2084. $return['next'] = $return2[0];
  2085. } else {
  2086. $return['next'] = null;
  2087. }
  2088. return $return;
  2089. }
  2090. }
  2091. /**
  2092. * In the event of ambiguous results returned (multiple top level results, with different parent_ids)
  2093. * top level results with different parent_ids to the first result will be dropped
  2094. *
  2095. * @param mixed $state
  2096. * @param mixed $query
  2097. * @param array $results
  2098. * @return array Threaded results
  2099. * @access protected
  2100. */
  2101. function _findThreaded($state, $query, $results = array()) {
  2102. if ($state == 'before') {
  2103. return $query;
  2104. } elseif ($state == 'after') {
  2105. $return = $idMap = array();
  2106. $ids = Set::extract($results, '{n}.' . $this->alias . '.' . $this->primaryKey);
  2107. foreach ($results as $result) {
  2108. $result['children'] = array();
  2109. $id = $result[$this->alias][$this->primaryKey];
  2110. $parentId = $result[$this->alias]['parent_id'];
  2111. if (isset($idMap[$id]['children'])) {
  2112. $idMap[$id] = array_merge($result, (array)$idMap[$id]);
  2113. } else {
  2114. $idMap[$id] = array_merge($result, array('children' => array()));
  2115. }
  2116. if (!$parentId || !in_array($parentId, $ids)) {
  2117. $return[] =& $idMap[$id];
  2118. } else {
  2119. $idMap[$parentId]['children'][] =& $idMap[$id];
  2120. }
  2121. }
  2122. if (count($return) > 1) {
  2123. $ids = array_unique(Set::extract('/' . $this->alias . '/parent_id', $return));
  2124. if (count($ids) > 1) {
  2125. $root = $return[0][$this->alias]['parent_id'];
  2126. foreach ($return as $key => $value) {
  2127. if ($value[$this->alias]['parent_id'] != $root) {
  2128. unset($return[$key]);
  2129. }
  2130. }
  2131. }
  2132. }
  2133. return $return;
  2134. }
  2135. }
  2136. /**
  2137. * Passes query results through model and behavior afterFilter() methods.
  2138. *
  2139. * @param array Results to filter
  2140. * @param boolean $primary If this is the primary model results (results from model where the find operation was performed)
  2141. * @return array Set of filtered results
  2142. * @access private
  2143. */
  2144. function __filterResults($results, $primary = true) {
  2145. $return = $this->Behaviors->trigger($this, 'afterFind', array($results, $primary), array('modParams' => true));
  2146. if ($return !== true) {
  2147. $results = $return;
  2148. }
  2149. return $this->afterFind($results, $primary);
  2150. }
  2151. /**
  2152. * This resets the association arrays for the model back
  2153. * to those originally defined in the model. Normally called at the end
  2154. * of each call to Model::find()
  2155. *
  2156. * @return boolean Success
  2157. * @access public
  2158. */
  2159. function resetAssociations() {
  2160. if (!empty($this->__backAssociation)) {
  2161. foreach ($this->__associations as $type) {
  2162. if (isset($this->__backAssociation[$type])) {
  2163. $this->{$type} = $this->__backAssociation[$type];
  2164. }
  2165. }
  2166. $this->__backAssociation = array();
  2167. }
  2168. foreach ($this->__associations as $type) {
  2169. foreach ($this->{$type} as $key => $name) {
  2170. if (!empty($this->{$key}->__backAssociation)) {
  2171. $this->{$key}->resetAssociations();
  2172. }
  2173. }
  2174. }
  2175. $this->__backAssociation = array();
  2176. return true;
  2177. }
  2178. /**
  2179. * Returns false if any fields passed match any (by default, all if $or = false) of their matching values.
  2180. *
  2181. * @param array $fields Field/value pairs to search (if no values specified, they are pulled from $this->data)
  2182. * @param boolean $or If false, all fields specified must match in order for a false return value
  2183. * @return boolean False if any records matching any fields are found
  2184. * @access public
  2185. */
  2186. function isUnique($fields, $or = true) {
  2187. if (!is_array($fields)) {
  2188. $fields = func_get_args();
  2189. if (is_bool($fields[count($fields) - 1])) {
  2190. $or = $fields[count($fields) - 1];
  2191. unset($fields[count($fields) - 1]);
  2192. }
  2193. }
  2194. foreach ($fields as $field => $value) {
  2195. if (is_numeric($field)) {
  2196. unset($fields[$field]);
  2197. $field = $value;
  2198. if (isset($this->data[$this->alias][$field])) {
  2199. $value = $this->data[$this->alias][$field];
  2200. } else {
  2201. $value = null;
  2202. }
  2203. }
  2204. if (strpos($field, '.') === false) {
  2205. unset($fields[$field]);
  2206. $fields[$this->alias . '.' . $field] = $value;
  2207. }
  2208. }
  2209. if ($or) {
  2210. $fields = array('or' => $fields);
  2211. }
  2212. if (!empty($this->id)) {
  2213. $fields[$this->alias . '.' . $this->primaryKey . ' !='] = $this->id;
  2214. }
  2215. return ($this->find('count', array('conditions' => $fields, 'recursive' => -1)) == 0);
  2216. }
  2217. /**
  2218. * Returns a resultset for a given SQL statement. Custom SQL queries should be performed with this method.
  2219. *
  2220. * @param string $sql SQL statement
  2221. * @return array Resultset
  2222. * @access public
  2223. * @link http://book.cakephp.org/view/456/query
  2224. */
  2225. function query() {
  2226. $params = func_get_args();
  2227. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  2228. return call_user_func_array(array(&$db, 'query'), $params);
  2229. }
  2230. /**
  2231. * Returns true if all fields pass validation. Will validate hasAndBelongsToMany associations
  2232. * that use the 'with' key as well. Since __saveMulti is incapable of exiting a save operation.
  2233. *
  2234. * Will validate the currently set data. Use Model::set() or Model::create() to set the active data.
  2235. *
  2236. * @param string $options An optional array of custom options to be made available in the beforeValidate callback
  2237. * @return boolean True if there are no errors
  2238. * @access public
  2239. * @link http://book.cakephp.org/view/410/Validating-Data-from-the-Controller
  2240. */
  2241. function validates($options = array()) {
  2242. $errors = $this->invalidFields($options);
  2243. if (empty($errors) && $errors !== false) {
  2244. $errors = $this->__validateWithModels($options);
  2245. }
  2246. if (is_array($errors)) {
  2247. return count($errors) === 0;
  2248. }
  2249. return $errors;
  2250. }
  2251. /**
  2252. * Returns an array of fields that have failed validation. On the current model.
  2253. *
  2254. * @param string $options An optional array of custom options to be made available in the beforeValidate callback
  2255. * @return array Array of invalid fields
  2256. * @see Model::validates()
  2257. * @access public
  2258. * @link http://book.cakephp.org/view/410/Validating-Data-from-the-Controller
  2259. */
  2260. function invalidFields($options = array()) {
  2261. if (
  2262. !$this->Behaviors->trigger(
  2263. $this,
  2264. 'beforeValidate',
  2265. array($options),
  2266. array('break' => true, 'breakOn' => false)
  2267. ) ||
  2268. $this->beforeValidate($options) === false
  2269. ) {
  2270. return false;
  2271. }
  2272. if (!isset($this->validate) || empty($this->validate)) {
  2273. return $this->validationErrors;
  2274. }
  2275. $data = $this->data;
  2276. $methods = array_map('strtolower', get_class_methods($this));
  2277. $behaviorMethods = array_keys($this->Behaviors->methods());
  2278. if (isset($data[$this->alias])) {
  2279. $data = $data[$this->alias];
  2280. } elseif (!is_array($data)) {
  2281. $data = array();
  2282. }
  2283. $Validation =& Validation::getInstance();
  2284. $this->exists();
  2285. $_validate = $this->validate;
  2286. $whitelist = $this->whitelist;
  2287. if (!empty($options['fieldList'])) {
  2288. $whitelist = $options['fieldList'];
  2289. }
  2290. if (!empty($whitelist)) {
  2291. $validate = array();
  2292. foreach ((array)$whitelist as $f) {
  2293. if (!empty($this->validate[$f])) {
  2294. $validate[$f] = $this->validate[$f];
  2295. }
  2296. }
  2297. $this->validate = $validate;
  2298. }
  2299. foreach ($this->validate as $fieldName => $ruleSet) {
  2300. if (!is_array($ruleSet) || (is_array($ruleSet) && isset($ruleSet['rule']))) {
  2301. $ruleSet = array($ruleSet);
  2302. }
  2303. $default = array(
  2304. 'allowEmpty' => null,
  2305. 'required' => null,
  2306. 'rule' => 'blank',
  2307. 'last' => false,
  2308. 'on' => null
  2309. );
  2310. foreach ($ruleSet as $index => $validator) {
  2311. if (!is_array($validator)) {
  2312. $validator = array('rule' => $validator);
  2313. }
  2314. $validator = array_merge($default, $validator);
  2315. if (isset($validator['message'])) {
  2316. $message = $validator['message'];
  2317. } else {
  2318. $message = __('This field cannot be left blank', true);
  2319. }
  2320. if (
  2321. empty($validator['on']) || ($validator['on'] == 'create' &&
  2322. !$this->__exists) || ($validator['on'] == 'update' && $this->__exists
  2323. )) {
  2324. $required = (
  2325. (!isset($data[$fieldName]) && $validator['required'] === true) ||
  2326. (
  2327. isset($data[$fieldName]) && (empty($data[$fieldName]) &&
  2328. !is_numeric($data[$fieldName])) && $validator['allowEmpty'] === false
  2329. )
  2330. );
  2331. if ($required) {
  2332. $this->invalidate($fieldName, $message);
  2333. if ($validator['last']) {
  2334. break;
  2335. }
  2336. } elseif (array_key_exists($fieldName, $data)) {
  2337. if (empty($data[$fieldName]) && $data[$fieldName] != '0' && $validator['allowEmpty'] === true) {
  2338. break;
  2339. }
  2340. if (is_array($validator['rule'])) {
  2341. $rule = $validator['rule'][0];
  2342. unset($validator['rule'][0]);
  2343. $ruleParams = array_merge(array($data[$fieldName]), array_values($validator['rule']));
  2344. } else {
  2345. $rule = $validator['rule'];
  2346. $ruleParams = array($data[$fieldName]);
  2347. }
  2348. $valid = true;
  2349. if (in_array(strtolower($rule), $methods)) {
  2350. $ruleParams[] = $validator;
  2351. $ruleParams[0] = array($fieldName => $ruleParams[0]);
  2352. $valid = $this->dispatchMethod($rule, $ruleParams);
  2353. } elseif (in_array($rule, $behaviorMethods) || in_array(strtolower($rule), $behaviorMethods)) {
  2354. $ruleParams[] = $validator;
  2355. $ruleParams[0] = array($fieldName => $ruleParams[0]);
  2356. $valid = $this->Behaviors->dispatchMethod($this, $rule, $ruleParams);
  2357. } elseif (method_exists($Validation, $rule)) {
  2358. $valid = $Validation->dispatchMethod($rule, $ruleParams);
  2359. } elseif (!is_array($validator['rule'])) {
  2360. $valid = preg_match($rule, $data[$fieldName]);
  2361. }
  2362. if (!$valid || (is_string($valid) && strlen($valid) > 0)) {
  2363. if (is_string($valid) && strlen($valid) > 0) {
  2364. $validator['message'] = $valid;
  2365. } elseif (!isset($validator['message'])) {
  2366. if (is_string($index)) {
  2367. $validator['message'] = $index;
  2368. } elseif (is_numeric($index) && count($ruleSet) > 1) {
  2369. $validator['message'] = $index + 1;
  2370. } else {
  2371. $validator['message'] = $message;
  2372. }
  2373. }
  2374. $this->invalidate($fieldName, $validator['message']);
  2375. if ($validator['last']) {
  2376. break;
  2377. }
  2378. }
  2379. }
  2380. }
  2381. }
  2382. }
  2383. $this->validate = $_validate;
  2384. return $this->validationErrors;
  2385. }
  2386. /**
  2387. * Runs validation for hasAndBelongsToMany associations that have 'with' keys
  2388. * set. And data in the set() data set.
  2389. *
  2390. * @param array $options Array of options to use on Valdation of with models
  2391. * @return boolean Failure of validation on with models.
  2392. * @access private
  2393. * @see Model::validates()
  2394. */
  2395. function __validateWithModels($options) {
  2396. $valid = true;
  2397. foreach ($this->hasAndBelongsToMany as $assoc => $association) {
  2398. if (empty($association['with']) || !isset($this->data[$assoc])) {
  2399. continue;
  2400. }
  2401. list($join) = $this->joinModel($this->hasAndBelongsToMany[$assoc]['with']);
  2402. $data = $this->data[$assoc];
  2403. $newData = array();
  2404. foreach ((array)$data as $row) {
  2405. if (isset($row[$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
  2406. $newData[] = $row;
  2407. } elseif (isset($row[$join]) && isset($row[$join][$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
  2408. $newData[] = $row[$join];
  2409. }
  2410. }
  2411. if (empty($newData)) {
  2412. continue;
  2413. }
  2414. foreach ($newData as $data) {
  2415. $data[$this->hasAndBelongsToMany[$assoc]['foreignKey']] = $this->id;
  2416. $this->{$join}->create($data);
  2417. $valid = ($valid && $this->{$join}->validates($options));
  2418. }
  2419. }
  2420. return $valid;
  2421. }
  2422. /**
  2423. * Marks a field as invalid, optionally setting the name of validation
  2424. * rule (in case of multiple validation for field) that was broken.
  2425. *
  2426. * @param string $field The name of the field to invalidate
  2427. * @param mixed $value Name of validation rule that was not failed, or validation message to
  2428. * be returned. If no validation key is provided, defaults to true.
  2429. * @access public
  2430. */
  2431. function invalidate($field, $value = true) {
  2432. if (!is_array($this->validationErrors)) {
  2433. $this->validationErrors = array();
  2434. }
  2435. $this->validationErrors[$field] = $value;
  2436. }
  2437. /**
  2438. * Returns true if given field name is a foreign key in this model.
  2439. *
  2440. * @param string $field Returns true if the input string ends in "_id"
  2441. * @return boolean True if the field is a foreign key listed in the belongsTo array.
  2442. * @access public
  2443. */
  2444. function isForeignKey($field) {
  2445. $foreignKeys = array();
  2446. if (!empty($this->belongsTo)) {
  2447. foreach ($this->belongsTo as $assoc => $data) {
  2448. $foreignKeys[] = $data['foreignKey'];
  2449. }
  2450. }
  2451. return in_array($field, $foreignKeys);
  2452. }
  2453. /**
  2454. * Returns the display field for this model.
  2455. *
  2456. * @return string The name of the display field for this Model (i.e. 'name', 'title').
  2457. * @access public
  2458. * @deprecated
  2459. */
  2460. function getDisplayField() {
  2461. return $this->displayField;
  2462. }
  2463. /**
  2464. * Escapes the field name and prepends the model name. Escaping is done according to the current database driver's rules.
  2465. *
  2466. * @param string $field Field to escape (e.g: id)
  2467. * @param string $alias Alias for the model (e.g: Post)
  2468. * @return string The name of the escaped field for this Model (i.e. id becomes `Post`.`id`).
  2469. * @access public
  2470. */
  2471. function escapeField($field = null, $alias = null) {
  2472. if (empty($alias)) {
  2473. $alias = $this->alias;
  2474. }
  2475. if (empty($field)) {
  2476. $field = $this->primaryKey;
  2477. }
  2478. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  2479. if (strpos($field, $db->name($alias) . '.') === 0) {
  2480. return $field;
  2481. }
  2482. return $db->name($alias . '.' . $field);
  2483. }
  2484. /**
  2485. * Returns the current record's ID
  2486. *
  2487. * @param integer $list Index on which the composed ID is located
  2488. * @return mixed The ID of the current record, false if no ID
  2489. * @access public
  2490. */
  2491. function getID($list = 0) {
  2492. if (empty($this->id) || (is_array($this->id) && isset($this->id[0]) && empty($this->id[0]))) {
  2493. return false;
  2494. }
  2495. if (!is_array($this->id)) {
  2496. return $this->id;
  2497. }
  2498. if (empty($this->id)) {
  2499. return false;
  2500. }
  2501. if (isset($this->id[$list]) && !empty($this->id[$list])) {
  2502. return $this->id[$list];
  2503. } elseif (isset($this->id[$list])) {
  2504. return false;
  2505. }
  2506. foreach ($this->id as $id) {
  2507. return $id;
  2508. }
  2509. return false;
  2510. }
  2511. /**
  2512. * Returns the ID of the last record this model inserted.
  2513. *
  2514. * @return mixed Last inserted ID
  2515. * @access public
  2516. */
  2517. function getLastInsertID() {
  2518. return $this->getInsertID();
  2519. }
  2520. /**
  2521. * Returns the ID of the last record this model inserted.
  2522. *
  2523. * @return mixed Last inserted ID
  2524. * @access public
  2525. */
  2526. function getInsertID() {
  2527. return $this->__insertID;
  2528. }
  2529. /**
  2530. * Sets the ID of the last record this model inserted
  2531. *
  2532. * @param mixed Last inserted ID
  2533. * @access public
  2534. */
  2535. function setInsertID($id) {
  2536. $this->__insertID = $id;
  2537. }
  2538. /**
  2539. * Returns the number of rows returned from the last query.
  2540. *
  2541. * @return int Number of rows
  2542. * @access public
  2543. */
  2544. function getNumRows() {
  2545. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  2546. return $db->lastNumRows();
  2547. }
  2548. /**
  2549. * Returns the number of rows affected by the last query.
  2550. *
  2551. * @return int Number of rows
  2552. * @access public
  2553. */
  2554. function getAffectedRows() {
  2555. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  2556. return $db->lastAffected();
  2557. }
  2558. /**
  2559. * Sets the DataSource to which this model is bound.
  2560. *
  2561. * @param string $dataSource The name of the DataSource, as defined in app/config/database.php
  2562. * @return boolean True on success
  2563. * @access public
  2564. */
  2565. function setDataSource($dataSource = null) {
  2566. $oldConfig = $this->useDbConfig;
  2567. if ($dataSource != null) {
  2568. $this->useDbConfig = $dataSource;
  2569. }
  2570. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  2571. if (!empty($oldConfig) && isset($db->config['prefix'])) {
  2572. $oldDb =& ConnectionManager::getDataSource($oldConfig);
  2573. if (!isset($this->tablePrefix) || (!isset($oldDb->config['prefix']) || $this->tablePrefix == $oldDb->config['prefix'])) {
  2574. $this->tablePrefix = $db->config['prefix'];
  2575. }
  2576. } elseif (isset($db->config['prefix'])) {
  2577. $this->tablePrefix = $db->config['prefix'];
  2578. }
  2579. if (empty($db) || !is_object($db)) {
  2580. return $this->cakeError('missingConnection', array(array('className' => $this->alias)));
  2581. }
  2582. }
  2583. /**
  2584. * Gets the DataSource to which this model is bound.
  2585. * Not safe for use with some versions of PHP4, because this class is overloaded.
  2586. *
  2587. * @return object A DataSource object
  2588. * @access public
  2589. */
  2590. function &getDataSource() {
  2591. $db =& ConnectionManager::getDataSource($this->useDbConfig);
  2592. return $db;
  2593. }
  2594. /**
  2595. * Gets all the models with which this model is associated.
  2596. *
  2597. * @param string $type Only result associations of this type
  2598. * @return array Associations
  2599. * @access public
  2600. */
  2601. function getAssociated($type = null) {
  2602. if ($type == null) {
  2603. $associated = array();
  2604. foreach ($this->__associations as $assoc) {
  2605. if (!empty($this->{$assoc})) {
  2606. $models = array_keys($this->{$assoc});
  2607. foreach ($models as $m) {
  2608. $associated[$m] = $assoc;
  2609. }
  2610. }
  2611. }
  2612. return $associated;
  2613. } elseif (in_array($type, $this->__associations)) {
  2614. if (empty($this->{$type})) {
  2615. return array();
  2616. }
  2617. return array_keys($this->{$type});
  2618. } else {
  2619. $assoc = array_merge($this->hasOne, $this->hasMany, $this->belongsTo, $this->hasAndBelongsToMany);
  2620. if (array_key_exists($type, $assoc)) {
  2621. foreach ($this->__associations as $a) {
  2622. if (isset($this->{$a}[$type])) {
  2623. $assoc[$type]['association'] = $a;
  2624. break;
  2625. }
  2626. }
  2627. return $assoc[$type];
  2628. }
  2629. return null;
  2630. }
  2631. }
  2632. /**
  2633. * Gets the name and fields to be used by a join model. This allows specifying join fields in the association definition.
  2634. *
  2635. * @param object $model The model to be joined
  2636. * @param mixed $with The 'with' key of the model association
  2637. * @param array $keys Any join keys which must be merged with the keys queried
  2638. * @return array
  2639. * @access public
  2640. */
  2641. function joinModel($assoc, $keys = array()) {
  2642. if (is_string($assoc)) {
  2643. return array($assoc, array_keys($this->{$assoc}->schema()));
  2644. } elseif (is_array($assoc)) {
  2645. $with = key($assoc);
  2646. return array($with, array_unique(array_merge($assoc[$with], $keys)));
  2647. } else {
  2648. trigger_error(sprintf(__('Invalid join model settings in %s', true), $model->alias), E_USER_WARNING);
  2649. }
  2650. }
  2651. /**
  2652. * Called before each find operation. Return false if you want to halt the find
  2653. * call, otherwise return the (modified) query data.
  2654. *
  2655. * @param array $queryData Data used to execute this query, i.e. conditions, order, etc.
  2656. * @return mixed true if the operation should continue, false if it should abort; or, modified $queryData to continue with new $queryData
  2657. * @access public
  2658. * @link http://book.cakephp.org/view/680/beforeFind
  2659. */
  2660. function beforeFind($queryData) {
  2661. return true;
  2662. }
  2663. /**
  2664. * Called after each find operation. Can be used to modify any results returned by find().
  2665. * Return value should be the (modified) results.
  2666. *
  2667. * @param mixed $results The results of the find operation
  2668. * @param boolean $primary Whether this model is being queried directly (vs. being queried as an association)
  2669. * @return mixed Result of the find operation
  2670. * @access public
  2671. * @link http://book.cakephp.org/view/681/afterFind
  2672. */
  2673. function afterFind($results, $primary = false) {
  2674. return $results;
  2675. }
  2676. /**
  2677. * Called before each save operation, after validation. Return a non-true result
  2678. * to halt the save.
  2679. *
  2680. * @return boolean True if the operation should continue, false if it should abort
  2681. * @access public
  2682. * @link http://book.cakephp.org/view/683/beforeSave
  2683. */
  2684. function beforeSave($options = array()) {
  2685. return true;
  2686. }
  2687. /**
  2688. * Called after each successful save operation.
  2689. *
  2690. * @param boolean $created True if this save created a new record
  2691. * @access public
  2692. * @link http://book.cakephp.org/view/684/afterSave
  2693. */
  2694. function afterSave($created) {
  2695. }
  2696. /**
  2697. * Called before every deletion operation.
  2698. *
  2699. * @param boolean $cascade If true records that depend on this record will also be deleted
  2700. * @return boolean True if the operation should continue, false if it should abort
  2701. * @access public
  2702. * @link http://book.cakephp.org/view/685/beforeDelete
  2703. */
  2704. function beforeDelete($cascade = true) {
  2705. return true;
  2706. }
  2707. /**
  2708. * Called after every deletion operation.
  2709. *
  2710. * @access public
  2711. * @link http://book.cakephp.org/view/686/afterDelete
  2712. */
  2713. function afterDelete() {
  2714. }
  2715. /**
  2716. * Called during validation operations, before validation. Please note that custom
  2717. * validation rules can be defined in $validate.
  2718. *
  2719. * @return boolean True if validate operation should continue, false to abort
  2720. * @param $options array Options passed from model::save(), see $options of model::save().
  2721. * @access public
  2722. * @link http://book.cakephp.org/view/682/beforeValidate
  2723. */
  2724. function beforeValidate($options = array()) {
  2725. return true;
  2726. }
  2727. /**
  2728. * Called when a DataSource-level error occurs.
  2729. *
  2730. * @access public
  2731. * @link http://book.cakephp.org/view/687/onError
  2732. */
  2733. function onError() {
  2734. }
  2735. /**
  2736. * Private method. Clears cache for this model.
  2737. *
  2738. * @param string $type If null this deletes cached views if Cache.check is true
  2739. * Will be used to allow deleting query cache also
  2740. * @return boolean true on delete
  2741. * @access protected
  2742. * @todo
  2743. */
  2744. function _clearCache($type = null) {
  2745. if ($type === null) {
  2746. if (Configure::read('Cache.check') === true) {
  2747. $assoc[] = strtolower(Inflector::pluralize($this->alias));
  2748. $assoc[] = strtolower(Inflector::underscore(Inflector::pluralize($this->alias)));
  2749. foreach ($this->__associations as $key => $association) {
  2750. foreach ($this->$association as $key => $className) {
  2751. $check = strtolower(Inflector::pluralize($className['className']));
  2752. if (!in_array($check, $assoc)) {
  2753. $assoc[] = strtolower(Inflector::pluralize($className['className']));
  2754. $assoc[] = strtolower(Inflector::underscore(Inflector::pluralize($className['className'])));
  2755. }
  2756. }
  2757. }
  2758. clearCache($assoc);
  2759. return true;
  2760. }
  2761. } else {
  2762. //Will use for query cache deleting
  2763. }
  2764. }
  2765. /**
  2766. * Called when serializing a model.
  2767. *
  2768. * @return array Set of object variable names this model has
  2769. * @access private
  2770. */
  2771. function __sleep() {
  2772. $return = array_keys(get_object_vars($this));
  2773. return $return;
  2774. }
  2775. /**
  2776. * Called when de-serializing a model.
  2777. *
  2778. * @access private
  2779. * @todo
  2780. */
  2781. function __wakeup() {
  2782. }
  2783. /**
  2784. * @deprecated
  2785. * @see Model::find('all')
  2786. */
  2787. function findAll($conditions = null, $fields = null, $order = null, $limit = null, $page = 1, $recursive = null) {
  2788. //trigger_error(__('(Model::findAll) Deprecated, use Model::find("all")', true), E_USER_WARNING);
  2789. return $this->find('all', compact('conditions', 'fields', 'order', 'limit', 'page', 'recursive'));
  2790. }
  2791. /**
  2792. * @deprecated
  2793. * @see Model::find('count')
  2794. */
  2795. function findCount($conditions = null, $recursive = 0) {
  2796. //trigger_error(__('(Model::findCount) Deprecated, use Model::find("count")', true), E_USER_WARNING);
  2797. return $this->find('count', compact('conditions', 'recursive'));
  2798. }
  2799. /**
  2800. * @deprecated
  2801. * @see Model::find('threaded')
  2802. */
  2803. function findAllThreaded($conditions = null, $fields = null, $order = null) {
  2804. //trigger_error(__('(Model::findAllThreaded) Deprecated, use Model::find("threaded")', true), E_USER_WARNING);
  2805. return $this->find('threaded', compact('conditions', 'fields', 'order'));
  2806. }
  2807. /**
  2808. * @deprecated
  2809. * @see Model::find('neighbors')
  2810. */
  2811. function findNeighbours($conditions = null, $field, $value) {
  2812. //trigger_error(__('(Model::findNeighbours) Deprecated, use Model::find("neighbors")', true), E_USER_WARNING);
  2813. $query = compact('conditions', 'field', 'value');
  2814. $query['fields'] = $field;
  2815. if (is_array($field)) {
  2816. $query['field'] = $field[0];
  2817. }
  2818. return $this->find('neighbors', $query);
  2819. }
  2820. }
  2821. if (!defined('CAKEPHP_UNIT_TEST_EXECUTION')) {
  2822. Overloadable::overload('Model');
  2823. }
  2824. ?>