PageRenderTime 73ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/cake/libs/model/model.php

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