1: <?php
2: /**
3: * Object-relational mapper.
4: *
5: * DBO-backed object data model, for mapping database tables to Cake objects.
6: *
7: * PHP versions 5
8: *
9: * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
10: * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
11: *
12: * Licensed under The MIT License
13: * Redistributions of files must retain the above copyright notice.
14: *
15: * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
16: * @link http://cakephp.org CakePHP(tm) Project
17: * @package Cake.Model
18: * @since CakePHP(tm) v 0.10.0.0
19: * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
20: */
21:
22: App::uses('ClassRegistry', 'Utility');
23: App::uses('Validation', 'Utility');
24: App::uses('String', 'Utility');
25: App::uses('Hash', 'Utility');
26: App::uses('BehaviorCollection', 'Model');
27: App::uses('ModelBehavior', 'Model');
28: App::uses('ModelValidator', 'Model');
29: App::uses('ConnectionManager', 'Model');
30: App::uses('Xml', 'Utility');
31: App::uses('CakeEvent', 'Event');
32: App::uses('CakeEventListener', 'Event');
33: App::uses('CakeEventManager', 'Event');
34:
35: /**
36: * Object-relational mapper.
37: *
38: * DBO-backed object data model.
39: * Automatically selects a database table name based on a pluralized lowercase object class name
40: * (i.e. class 'User' => table 'users'; class 'Man' => table 'men')
41: * The table is required to have at least 'id auto_increment' primary key.
42: *
43: * @package Cake.Model
44: * @link http://book.cakephp.org/2.0/en/models.html
45: */
46: class Model extends Object implements CakeEventListener {
47:
48: /**
49: * The name of the DataSource connection that this Model uses
50: *
51: * The value must be an attribute name that you defined in `app/Config/database.php`
52: * or created using `ConnectionManager::create()`.
53: *
54: * @var string
55: * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#usedbconfig
56: */
57: public $useDbConfig = 'default';
58:
59: /**
60: * Custom database table name, or null/false if no table association is desired.
61: *
62: * @var string
63: * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#usetable
64: */
65: public $useTable = null;
66:
67: /**
68: * Custom display field name. Display fields are used by Scaffold, in SELECT boxes' OPTION elements.
69: *
70: * This field is also used in `find('list')` when called with no extra parameters in the fields list
71: *
72: * @var string
73: * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#displayfield
74: */
75: public $displayField = null;
76:
77: /**
78: * Value of the primary key ID of the record that this model is currently pointing to.
79: * Automatically set after database insertions.
80: *
81: * @var mixed
82: */
83: public $id = false;
84:
85: /**
86: * Container for the data that this model gets from persistent storage (usually, a database).
87: *
88: * @var array
89: * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#data
90: */
91: public $data = array();
92:
93: /**
94: * Holds physical schema/database name for this model. Automatically set during Model creation.
95: *
96: * @var string
97: * @access public
98: */
99: public $schemaName = null;
100:
101: /**
102: * Table name for this Model.
103: *
104: * @var string
105: */
106: public $table = false;
107:
108: /**
109: * The name of the primary key field for this model.
110: *
111: * @var string
112: * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#primaryKey
113: */
114: public $primaryKey = null;
115:
116: /**
117: * Field-by-field table metadata.
118: *
119: * @var array
120: */
121: protected $_schema = null;
122:
123: /**
124: * List of validation rules. It must be an array with the field name as key and using
125: * as value one of the following possibilities
126: *
127: * ### Validating using regular expressions
128: *
129: * {{{
130: * public $validate = array(
131: * 'name' => '/^[a-z].+$/i'
132: * );
133: * }}}
134: *
135: * ### Validating using methods (no parameters)
136: *
137: * {{{
138: * public $validate = array(
139: * 'name' => 'notEmpty'
140: * );
141: * }}}
142: *
143: * ### Validating using methods (with parameters)
144: *
145: * {{{
146: * public $validate = array(
147: * 'age' => array(
148: * 'rule' => array('between', 5, 25)
149: * )
150: * );
151: * }}}
152: *
153: * ### Validating using custom method
154: *
155: * {{{
156: * public $validate = array(
157: * 'password' => array(
158: * 'rule' => array('customValidation')
159: * )
160: * );
161: * public function customValidation($data) {
162: * // $data will contain array('password' => 'value')
163: * if (isset($this->data[$this->alias]['password2'])) {
164: * return $this->data[$this->alias]['password2'] === current($data);
165: * }
166: * return true;
167: * }
168: * }}}
169: *
170: * ### Validations with messages
171: *
172: * The messages will be used in Model::$validationErrors and can be used in the FormHelper
173: *
174: * {{{
175: * public $validate = array(
176: * 'age' => array(
177: * 'rule' => array('between', 5, 25),
178: * 'message' => array('The age must be between %d and %d.')
179: * )
180: * );
181: * }}}
182: *
183: * ### Multiple validations to the same field
184: *
185: * {{{
186: * public $validate = array(
187: * 'login' => array(
188: * array(
189: * 'rule' => 'alphaNumeric',
190: * 'message' => 'Only alphabets and numbers allowed',
191: * 'last' => true
192: * ),
193: * array(
194: * 'rule' => array('minLength', 8),
195: * 'message' => array('Minimum length of %d characters')
196: * )
197: * )
198: * );
199: * }}}
200: *
201: * ### Valid keys in validations
202: *
203: * - `rule`: String with method name, regular expression (started by slash) or array with method and parameters
204: * - `message`: String with the message or array if have multiple parameters. See http://php.net/sprintf
205: * - `last`: Boolean value to indicate if continue validating the others rules if the current fail [Default: true]
206: * - `required`: Boolean value to indicate if the field must be present on save
207: * - `allowEmpty`: Boolean value to indicate if the field can be empty
208: * - `on`: Possible values: `update`, `create`. Indicate to apply this rule only on update or create
209: *
210: * @var array
211: * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#validate
212: * @link http://book.cakephp.org/2.0/en/models/data-validation.html
213: */
214: public $validate = array();
215:
216: /**
217: * List of validation errors.
218: *
219: * @var array
220: */
221: public $validationErrors = array();
222:
223: /**
224: * Name of the validation string domain to use when translating validation errors.
225: *
226: * @var string
227: */
228: public $validationDomain = null;
229:
230: /**
231: * Database table prefix for tables in model.
232: *
233: * @var string
234: * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#tableprefix
235: */
236: public $tablePrefix = null;
237:
238: /**
239: * Name of the model.
240: *
241: * @var string
242: * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#name
243: */
244: public $name = null;
245:
246: /**
247: * Alias name for model.
248: *
249: * @var string
250: */
251: public $alias = null;
252:
253: /**
254: * List of table names included in the model description. Used for associations.
255: *
256: * @var array
257: */
258: public $tableToModel = array();
259:
260: /**
261: * Whether or not to cache queries for this model. This enables in-memory
262: * caching only, the results are not stored beyond the current request.
263: *
264: * @var boolean
265: * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#cachequeries
266: */
267: public $cacheQueries = false;
268:
269: /**
270: * Detailed list of belongsTo associations.
271: *
272: * ### Basic usage
273: *
274: * `public $belongsTo = array('Group', 'Department');`
275: *
276: * ### Detailed configuration
277: *
278: * {{{
279: * public $belongsTo = array(
280: * 'Group',
281: * 'Department' => array(
282: * 'className' => 'Department',
283: * 'foreignKey' => 'department_id'
284: * )
285: * );
286: * }}}
287: *
288: * ### Possible keys in association
289: *
290: * - `className`: the classname of the model being associated to the current model.
291: * If you're defining a 'Profile belongsTo User' relationship, the className key should equal 'User.'
292: * - `foreignKey`: the name of the foreign key found in the current model. This is
293: * especially handy if you need to define multiple belongsTo relationships. The default
294: * value for this key is the underscored, singular name of the other model, suffixed with '_id'.
295: * - `conditions`: An SQL fragment used to filter related model records. It's good
296: * practice to use model names in SQL fragments: 'User.active = 1' is always
297: * better than just 'active = 1.'
298: * - `type`: the type of the join to use in the SQL query, default is LEFT which
299: * may not fit your needs in all situations, INNER may be helpful when you want
300: * everything from your main and associated models or nothing at all!(effective
301: * when used with some conditions of course). (NB: type value is in lower case - i.e. left, inner)
302: * - `fields`: A list of fields to be retrieved when the associated model data is
303: * fetched. Returns all fields by default.
304: * - `order`: An SQL fragment that defines the sorting order for the returned associated rows.
305: * - `counterCache`: If set to true the associated Model will automatically increase or
306: * decrease the "[singular_model_name]_count" field in the foreign table whenever you do
307: * a save() or delete(). If its a string then its the field name to use. The value in the
308: * counter field represents the number of related rows.
309: * - `counterScope`: Optional conditions array to use for updating counter cache field.
310: *
311: * @var array
312: * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#belongsto
313: */
314: public $belongsTo = array();
315:
316: /**
317: * Detailed list of hasOne associations.
318: *
319: * ### Basic usage
320: *
321: * `public $hasOne = array('Profile', 'Address');`
322: *
323: * ### Detailed configuration
324: *
325: * {{{
326: * public $hasOne = array(
327: * 'Profile',
328: * 'Address' => array(
329: * 'className' => 'Address',
330: * 'foreignKey' => 'user_id'
331: * )
332: * );
333: * }}}
334: *
335: * ### Possible keys in association
336: *
337: * - `className`: the classname of the model being associated to the current model.
338: * If you're defining a 'User hasOne Profile' relationship, the className key should equal 'Profile.'
339: * - `foreignKey`: the name of the foreign key found in the other model. This is
340: * especially handy if you need to define multiple hasOne relationships.
341: * The default value for this key is the underscored, singular name of the
342: * current model, suffixed with '_id'. In the example above it would default to 'user_id'.
343: * - `conditions`: An SQL fragment used to filter related model records. It's good
344: * practice to use model names in SQL fragments: "Profile.approved = 1" is
345: * always better than just "approved = 1."
346: * - `fields`: A list of fields to be retrieved when the associated model data is
347: * fetched. Returns all fields by default.
348: * - `order`: An SQL fragment that defines the sorting order for the returned associated rows.
349: * - `dependent`: When the dependent key is set to true, and the model's delete()
350: * method is called with the cascade parameter set to true, associated model
351: * records are also deleted. In this case we set it true so that deleting a
352: * User will also delete her associated Profile.
353: *
354: * @var array
355: * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasone
356: */
357: public $hasOne = array();
358:
359: /**
360: * Detailed list of hasMany associations.
361: *
362: * ### Basic usage
363: *
364: * `public $hasMany = array('Comment', 'Task');`
365: *
366: * ### Detailed configuration
367: *
368: * {{{
369: * public $hasMany = array(
370: * 'Comment',
371: * 'Task' => array(
372: * 'className' => 'Task',
373: * 'foreignKey' => 'user_id'
374: * )
375: * );
376: * }}}
377: *
378: * ### Possible keys in association
379: *
380: * - `className`: the classname of the model being associated to the current model.
381: * If you're defining a 'User hasMany Comment' relationship, the className key should equal 'Comment.'
382: * - `foreignKey`: the name of the foreign key found in the other model. This is
383: * especially handy if you need to define multiple hasMany relationships. The default
384: * value for this key is the underscored, singular name of the actual model, suffixed with '_id'.
385: * - `conditions`: An SQL fragment used to filter related model records. It's good
386: * practice to use model names in SQL fragments: "Comment.status = 1" is always
387: * better than just "status = 1."
388: * - `fields`: A list of fields to be retrieved when the associated model data is
389: * fetched. Returns all fields by default.
390: * - `order`: An SQL fragment that defines the sorting order for the returned associated rows.
391: * - `limit`: The maximum number of associated rows you want returned.
392: * - `offset`: The number of associated rows to skip over (given the current
393: * conditions and order) before fetching and associating.
394: * - `dependent`: When dependent is set to true, recursive model deletion is
395: * possible. In this example, Comment records will be deleted when their
396: * associated User record has been deleted.
397: * - `exclusive`: When exclusive is set to true, recursive model deletion does
398: * the delete with a deleteAll() call, instead of deleting each entity separately.
399: * This greatly improves performance, but may not be ideal for all circumstances.
400: * - `finderQuery`: A complete SQL query CakePHP can use to fetch associated model
401: * records. This should be used in situations that require very custom results.
402: *
403: * @var array
404: * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasmany
405: */
406: public $hasMany = array();
407:
408: /**
409: * Detailed list of hasAndBelongsToMany associations.
410: *
411: * ### Basic usage
412: *
413: * `public $hasAndBelongsToMany = array('Role', 'Address');`
414: *
415: * ### Detailed configuration
416: *
417: * {{{
418: * public $hasAndBelongsToMany = array(
419: * 'Role',
420: * 'Address' => array(
421: * 'className' => 'Address',
422: * 'foreignKey' => 'user_id',
423: * 'associationForeignKey' => 'address_id',
424: * 'joinTable' => 'addresses_users'
425: * )
426: * );
427: * }}}
428: *
429: * ### Possible keys in association
430: *
431: * - `className`: the classname of the model being associated to the current model.
432: * If you're defining a 'Recipe HABTM Tag' relationship, the className key should equal 'Tag.'
433: * - `joinTable`: The name of the join table used in this association (if the
434: * current table doesn't adhere to the naming convention for HABTM join tables).
435: * - `with`: Defines the name of the model for the join table. By default CakePHP
436: * will auto-create a model for you. Using the example above it would be called
437: * RecipesTag. By using this key you can override this default name. The join
438: * table model can be used just like any "regular" model to access the join table directly.
439: * - `foreignKey`: the name of the foreign key found in the current model.
440: * This is especially handy if you need to define multiple HABTM relationships.
441: * The default value for this key is the underscored, singular name of the
442: * current model, suffixed with '_id'.
443: * - `associationForeignKey`: the name of the foreign key found in the other model.
444: * This is especially handy if you need to define multiple HABTM relationships.
445: * The default value for this key is the underscored, singular name of the other
446: * model, suffixed with '_id'.
447: * - `unique`: If true (default value) cake will first delete existing relationship
448: * records in the foreign keys table before inserting new ones, when updating a
449: * record. So existing associations need to be passed again when updating.
450: * To prevent deletion of existing relationship records, set this key to a string 'keepExisting'.
451: * - `conditions`: An SQL fragment used to filter related model records. It's good
452: * practice to use model names in SQL fragments: "Comment.status = 1" is always
453: * better than just "status = 1."
454: * - `fields`: A list of fields to be retrieved when the associated model data is
455: * fetched. Returns all fields by default.
456: * - `order`: An SQL fragment that defines the sorting order for the returned associated rows.
457: * - `limit`: The maximum number of associated rows you want returned.
458: * - `offset`: The number of associated rows to skip over (given the current
459: * conditions and order) before fetching and associating.
460: * - `finderQuery`, `deleteQuery`, `insertQuery`: A complete SQL query CakePHP
461: * can use to fetch, delete, or create new associated model records. This should
462: * be used in situations that require very custom results.
463: *
464: * @var array
465: * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasandbelongstomany-habtm
466: */
467: public $hasAndBelongsToMany = array();
468:
469: /**
470: * List of behaviors to load when the model object is initialized. Settings can be
471: * passed to behaviors by using the behavior name as index. Eg:
472: *
473: * public $actsAs = array('Translate', 'MyBehavior' => array('setting1' => 'value1'))
474: *
475: * @var array
476: * @link http://book.cakephp.org/2.0/en/models/behaviors.html#using-behaviors
477: */
478: public $actsAs = null;
479:
480: /**
481: * Holds the Behavior objects currently bound to this model.
482: *
483: * @var BehaviorCollection
484: */
485: public $Behaviors = null;
486:
487: /**
488: * Whitelist of fields allowed to be saved.
489: *
490: * @var array
491: */
492: public $whitelist = array();
493:
494: /**
495: * Whether or not to cache sources for this model.
496: *
497: * @var boolean
498: */
499: public $cacheSources = true;
500:
501: /**
502: * Type of find query currently executing.
503: *
504: * @var string
505: */
506: public $findQueryType = null;
507:
508: /**
509: * Number of associations to recurse through during find calls. Fetches only
510: * the first level by default.
511: *
512: * @var integer
513: * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#recursive
514: */
515: public $recursive = 1;
516:
517: /**
518: * The column name(s) and direction(s) to order find results by default.
519: *
520: * public $order = "Post.created DESC";
521: * public $order = array("Post.view_count DESC", "Post.rating DESC");
522: *
523: * @var string
524: * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#order
525: */
526: public $order = null;
527:
528: /**
529: * Array of virtual fields this model has. Virtual fields are aliased
530: * SQL expressions. Fields added to this property will be read as other fields in a model
531: * but will not be saveable.
532: *
533: * `public $virtualFields = array('two' => '1 + 1');`
534: *
535: * Is a simplistic example of how to set virtualFields
536: *
537: * @var array
538: * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#virtualfields
539: */
540: public $virtualFields = array();
541:
542: /**
543: * Default list of association keys.
544: *
545: * @var array
546: */
547: protected $_associationKeys = array(
548: 'belongsTo' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'counterCache'),
549: 'hasOne' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'dependent'),
550: 'hasMany' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'dependent', 'exclusive', 'finderQuery', 'counterQuery'),
551: 'hasAndBelongsToMany' => array('className', 'joinTable', 'with', 'foreignKey', 'associationForeignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'unique', 'finderQuery', 'deleteQuery', 'insertQuery')
552: );
553:
554: /**
555: * Holds provided/generated association key names and other data for all associations.
556: *
557: * @var array
558: */
559: protected $_associations = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
560:
561: // @codingStandardsIgnoreStart
562:
563: /**
564: * Holds model associations temporarily to allow for dynamic (un)binding.
565: *
566: * @var array
567: */
568: public $__backAssociation = array();
569:
570: /**
571: * Back inner association
572: *
573: * @var array
574: */
575: public $__backInnerAssociation = array();
576:
577: /**
578: * Back original association
579: *
580: * @var array
581: */
582: public $__backOriginalAssociation = array();
583:
584: /**
585: * Back containable association
586: *
587: * @var array
588: */
589: public $__backContainableAssociation = array();
590:
591: // @codingStandardsIgnoreEnd
592:
593: /**
594: * The ID of the model record that was last inserted.
595: *
596: * @var integer
597: */
598: protected $_insertID = null;
599:
600: /**
601: * Has the datasource been configured.
602: *
603: * @var boolean
604: * @see Model::getDataSource
605: */
606: protected $_sourceConfigured = false;
607:
608: /**
609: * List of valid finder method options, supplied as the first parameter to find().
610: *
611: * @var array
612: */
613: public $findMethods = array(
614: 'all' => true, 'first' => true, 'count' => true,
615: 'neighbors' => true, 'list' => true, 'threaded' => true
616: );
617:
618: /**
619: * Instance of the CakeEventManager this model is using
620: * to dispatch inner events.
621: *
622: * @var CakeEventManager
623: */
624: protected $_eventManager = null;
625:
626: /**
627: * Instance of the ModelValidator
628: *
629: * @var ModelValidator
630: */
631: protected $_validator = null;
632:
633: /**
634: * Constructor. Binds the model's database table to the object.
635: *
636: * If `$id` is an array it can be used to pass several options into the model.
637: *
638: * - id - The id to start the model on.
639: * - table - The table to use for this model.
640: * - ds - The connection name this model is connected to.
641: * - name - The name of the model eg. Post.
642: * - alias - The alias of the model, this is used for registering the instance in the `ClassRegistry`.
643: * eg. `ParentThread`
644: *
645: * ### Overriding Model's __construct method.
646: *
647: * When overriding Model::__construct() be careful to include and pass in all 3 of the
648: * arguments to `parent::__construct($id, $table, $ds);`
649: *
650: * ### Dynamically creating models
651: *
652: * You can dynamically create model instances using the $id array syntax.
653: *
654: * {{{
655: * $Post = new Model(array('table' => 'posts', 'name' => 'Post', 'ds' => 'connection2'));
656: * }}}
657: *
658: * Would create a model attached to the posts table on connection2. Dynamic model creation is useful
659: * when you want a model object that contains no associations or attached behaviors.
660: *
661: * @param integer|string|array $id Set this ID for this model on startup, can also be an array of options, see above.
662: * @param string $table Name of database table to use.
663: * @param string $ds DataSource connection name.
664: */
665: public function __construct($id = false, $table = null, $ds = null) {
666: parent::__construct();
667:
668: if (is_array($id)) {
669: extract(array_merge(
670: array(
671: 'id' => $this->id, 'table' => $this->useTable, 'ds' => $this->useDbConfig,
672: 'name' => $this->name, 'alias' => $this->alias
673: ),
674: $id
675: ));
676: }
677:
678: if ($this->name === null) {
679: $this->name = (isset($name) ? $name : get_class($this));
680: }
681:
682: if ($this->alias === null) {
683: $this->alias = (isset($alias) ? $alias : $this->name);
684: }
685:
686: if ($this->primaryKey === null) {
687: $this->primaryKey = 'id';
688: }
689:
690: ClassRegistry::addObject($this->alias, $this);
691:
692: $this->id = $id;
693: unset($id);
694:
695: if ($table === false) {
696: $this->useTable = false;
697: } elseif ($table) {
698: $this->useTable = $table;
699: }
700:
701: if ($ds !== null) {
702: $this->useDbConfig = $ds;
703: }
704:
705: if (is_subclass_of($this, 'AppModel')) {
706: $merge = array('actsAs', 'findMethods');
707: $parentClass = get_parent_class($this);
708: if ($parentClass !== 'AppModel') {
709: $this->_mergeVars($merge, $parentClass);
710: }
711: $this->_mergeVars($merge, 'AppModel');
712: }
713: $this->_mergeVars(array('findMethods'), 'Model');
714:
715: $this->Behaviors = new BehaviorCollection();
716:
717: if ($this->useTable !== false) {
718:
719: if ($this->useTable === null) {
720: $this->useTable = Inflector::tableize($this->name);
721: }
722:
723: if ($this->displayField == null) {
724: unset($this->displayField);
725: }
726: $this->table = $this->useTable;
727: $this->tableToModel[$this->table] = $this->alias;
728: } elseif ($this->table === false) {
729: $this->table = Inflector::tableize($this->name);
730: }
731:
732: if ($this->tablePrefix === null) {
733: unset($this->tablePrefix);
734: }
735:
736: $this->_createLinks();
737: $this->Behaviors->init($this->alias, $this->actsAs);
738: }
739:
740: /**
741: * Returns a list of all events that will fire in the model during it's lifecycle.
742: * You can override this function to add you own listener callbacks
743: *
744: * @return array
745: */
746: public function implementedEvents() {
747: return array(
748: 'Model.beforeFind' => array('callable' => 'beforeFind', 'passParams' => true),
749: 'Model.afterFind' => array('callable' => 'afterFind', 'passParams' => true),
750: 'Model.beforeValidate' => array('callable' => 'beforeValidate', 'passParams' => true),
751: 'Model.afterValidate' => array('callable' => 'afterValidate'),
752: 'Model.beforeSave' => array('callable' => 'beforeSave', 'passParams' => true),
753: 'Model.afterSave' => array('callable' => 'afterSave', 'passParams' => true),
754: 'Model.beforeDelete' => array('callable' => 'beforeDelete', 'passParams' => true),
755: 'Model.afterDelete' => array('callable' => 'afterDelete'),
756: );
757: }
758:
759: /**
760: * Returns the CakeEventManager manager instance that is handling any callbacks.
761: * You can use this instance to register any new listeners or callbacks to the
762: * model events, or create your own events and trigger them at will.
763: *
764: * @return CakeEventManager
765: */
766: public function getEventManager() {
767: if (empty($this->_eventManager)) {
768: $this->_eventManager = new CakeEventManager();
769: $this->_eventManager->attach($this->Behaviors);
770: $this->_eventManager->attach($this);
771: }
772: return $this->_eventManager;
773: }
774:
775: /**
776: * Handles custom method calls, like findBy<field> for DB models,
777: * and custom RPC calls for remote data sources.
778: *
779: * @param string $method Name of method to call.
780: * @param array $params Parameters for the method.
781: * @return mixed Whatever is returned by called method
782: */
783: public function __call($method, $params) {
784: $result = $this->Behaviors->dispatchMethod($this, $method, $params);
785: if ($result !== array('unhandled')) {
786: return $result;
787: }
788: $return = $this->getDataSource()->query($method, $params, $this);
789: return $return;
790: }
791:
792: /**
793: * Handles the lazy loading of model associations by looking in the association arrays for the requested variable
794: *
795: * @param string $name variable tested for existence in class
796: * @return boolean true if the variable exists (if is a not loaded model association it will be created), false otherwise
797: */
798: public function __isset($name) {
799: $className = false;
800:
801: foreach ($this->_associations as $type) {
802: if (isset($name, $this->{$type}[$name])) {
803: $className = empty($this->{$type}[$name]['className']) ? $name : $this->{$type}[$name]['className'];
804: break;
805: } elseif (isset($name, $this->__backAssociation[$type][$name])) {
806: $className = empty($this->__backAssociation[$type][$name]['className']) ?
807: $name : $this->__backAssociation[$type][$name]['className'];
808: break;
809: } elseif ($type == 'hasAndBelongsToMany') {
810: foreach ($this->{$type} as $k => $relation) {
811: if (empty($relation['with'])) {
812: continue;
813: }
814: if (is_array($relation['with'])) {
815: if (key($relation['with']) === $name) {
816: $className = $name;
817: }
818: } else {
819: list($plugin, $class) = pluginSplit($relation['with']);
820: if ($class === $name) {
821: $className = $relation['with'];
822: }
823: }
824: if ($className) {
825: $assocKey = $k;
826: $dynamic = !empty($relation['dynamicWith']);
827: break(2);
828: }
829: }
830: }
831: }
832:
833: if (!$className) {
834: return false;
835: }
836:
837: list($plugin, $className) = pluginSplit($className);
838:
839: if (!ClassRegistry::isKeySet($className) && !empty($dynamic)) {
840: $this->{$className} = new AppModel(array(
841: 'name' => $className,
842: 'table' => $this->hasAndBelongsToMany[$assocKey]['joinTable'],
843: 'ds' => $this->useDbConfig
844: ));
845: } else {
846: $this->_constructLinkedModel($name, $className, $plugin);
847: }
848:
849: if (!empty($assocKey)) {
850: $this->hasAndBelongsToMany[$assocKey]['joinTable'] = $this->{$name}->table;
851: if (count($this->{$name}->schema()) <= 2 && $this->{$name}->primaryKey !== false) {
852: $this->{$name}->primaryKey = $this->hasAndBelongsToMany[$assocKey]['foreignKey'];
853: }
854: }
855:
856: return true;
857: }
858:
859: /**
860: * Returns the value of the requested variable if it can be set by __isset()
861: *
862: * @param string $name variable requested for it's value or reference
863: * @return mixed value of requested variable if it is set
864: */
865: public function __get($name) {
866: if ($name === 'displayField') {
867: return $this->displayField = $this->hasField(array('title', 'name', $this->primaryKey));
868: }
869: if ($name === 'tablePrefix') {
870: $this->setDataSource();
871: if (property_exists($this, 'tablePrefix') && !empty($this->tablePrefix)) {
872: return $this->tablePrefix;
873: }
874: return $this->tablePrefix = null;
875: }
876: if (isset($this->{$name})) {
877: return $this->{$name};
878: }
879: }
880:
881: /**
882: * Bind model associations on the fly.
883: *
884: * If `$reset` is false, association will not be reset
885: * to the originals defined in the model
886: *
887: * Example: Add a new hasOne binding to the Profile model not
888: * defined in the model source code:
889: *
890: * `$this->User->bindModel( array('hasOne' => array('Profile')) );`
891: *
892: * Bindings that are not made permanent will be reset by the next Model::find() call on this
893: * model.
894: *
895: * @param array $params Set of bindings (indexed by binding type)
896: * @param boolean $reset Set to false to make the binding permanent
897: * @return boolean Success
898: * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#creating-and-destroying-associations-on-the-fly
899: */
900: public function bindModel($params, $reset = true) {
901: foreach ($params as $assoc => $model) {
902: if ($reset === true && !isset($this->__backAssociation[$assoc])) {
903: $this->__backAssociation[$assoc] = $this->{$assoc};
904: }
905: foreach ($model as $key => $value) {
906: $assocName = $key;
907:
908: if (is_numeric($key)) {
909: $assocName = $value;
910: $value = array();
911: }
912: $this->{$assoc}[$assocName] = $value;
913: if (property_exists($this, $assocName)) {
914: unset($this->{$assocName});
915: }
916: if ($reset === false && isset($this->__backAssociation[$assoc])) {
917: $this->__backAssociation[$assoc][$assocName] = $value;
918: }
919: }
920: }
921: $this->_createLinks();
922: return true;
923: }
924:
925: /**
926: * Turn off associations on the fly.
927: *
928: * If $reset is false, association will not be reset
929: * to the originals defined in the model
930: *
931: * Example: Turn off the associated Model Support request,
932: * to temporarily lighten the User model:
933: *
934: * `$this->User->unbindModel( array('hasMany' => array('Supportrequest')) );`
935: *
936: * unbound models that are not made permanent will reset with the next call to Model::find()
937: *
938: * @param array $params Set of bindings to unbind (indexed by binding type)
939: * @param boolean $reset Set to false to make the unbinding permanent
940: * @return boolean Success
941: * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#creating-and-destroying-associations-on-the-fly
942: */
943: public function unbindModel($params, $reset = true) {
944: foreach ($params as $assoc => $models) {
945: if ($reset === true && !isset($this->__backAssociation[$assoc])) {
946: $this->__backAssociation[$assoc] = $this->{$assoc};
947: }
948: foreach ($models as $model) {
949: if ($reset === false && isset($this->__backAssociation[$assoc][$model])) {
950: unset($this->__backAssociation[$assoc][$model]);
951: }
952: unset($this->{$assoc}[$model]);
953: }
954: }
955: return true;
956: }
957:
958: /**
959: * Create a set of associations.
960: *
961: * @return void
962: */
963: protected function _createLinks() {
964: foreach ($this->_associations as $type) {
965: if (!is_array($this->{$type})) {
966: $this->{$type} = explode(',', $this->{$type});
967:
968: foreach ($this->{$type} as $i => $className) {
969: $className = trim($className);
970: unset ($this->{$type}[$i]);
971: $this->{$type}[$className] = array();
972: }
973: }
974:
975: if (!empty($this->{$type})) {
976: foreach ($this->{$type} as $assoc => $value) {
977: $plugin = null;
978:
979: if (is_numeric($assoc)) {
980: unset($this->{$type}[$assoc]);
981: $assoc = $value;
982: $value = array();
983:
984: if (strpos($assoc, '.') !== false) {
985: list($plugin, $assoc) = pluginSplit($assoc, true);
986: $this->{$type}[$assoc] = array('className' => $plugin . $assoc);
987: } else {
988: $this->{$type}[$assoc] = $value;
989: }
990: }
991: $this->_generateAssociation($type, $assoc);
992: }
993: }
994: }
995: }
996:
997: /**
998: * Protected helper method to create associated models of a given class.
999: *
1000: * @param string $assoc Association name
1001: * @param string $className Class name
1002: * @param string $plugin name of the plugin where $className is located
1003: * examples: public $hasMany = array('Assoc' => array('className' => 'ModelName'));
1004: * usage: $this->Assoc->modelMethods();
1005: *
1006: * public $hasMany = array('ModelName');
1007: * usage: $this->ModelName->modelMethods();
1008: * @return void
1009: */
1010: protected function _constructLinkedModel($assoc, $className = null, $plugin = null) {
1011: if (empty($className)) {
1012: $className = $assoc;
1013: }
1014:
1015: if (!isset($this->{$assoc}) || $this->{$assoc}->name !== $className) {
1016: if ($plugin) {
1017: $plugin .= '.';
1018: }
1019: $model = array('class' => $plugin . $className, 'alias' => $assoc);
1020: $this->{$assoc} = ClassRegistry::init($model);
1021: if ($plugin) {
1022: ClassRegistry::addObject($plugin . $className, $this->{$assoc});
1023: }
1024: if ($assoc) {
1025: $this->tableToModel[$this->{$assoc}->table] = $assoc;
1026: }
1027: }
1028: }
1029:
1030: /**
1031: * Build an array-based association from string.
1032: *
1033: * @param string $type 'belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany'
1034: * @param string $assocKey
1035: * @return void
1036: */
1037: protected function _generateAssociation($type, $assocKey) {
1038: $class = $assocKey;
1039: $dynamicWith = false;
1040:
1041: foreach ($this->_associationKeys[$type] as $key) {
1042:
1043: if (!isset($this->{$type}[$assocKey][$key]) || $this->{$type}[$assocKey][$key] === null) {
1044: $data = '';
1045:
1046: switch ($key) {
1047: case 'fields':
1048: $data = '';
1049: break;
1050:
1051: case 'foreignKey':
1052: $data = (($type == 'belongsTo') ? Inflector::underscore($assocKey) : Inflector::singularize($this->table)) . '_id';
1053: break;
1054:
1055: case 'associationForeignKey':
1056: $data = Inflector::singularize($this->{$class}->table) . '_id';
1057: break;
1058:
1059: case 'with':
1060: $data = Inflector::camelize(Inflector::singularize($this->{$type}[$assocKey]['joinTable']));
1061: $dynamicWith = true;
1062: break;
1063:
1064: case 'joinTable':
1065: $tables = array($this->table, $this->{$class}->table);
1066: sort ($tables);
1067: $data = $tables[0] . '_' . $tables[1];
1068: break;
1069:
1070: case 'className':
1071: $data = $class;
1072: break;
1073:
1074: case 'unique':
1075: $data = true;
1076: break;
1077: }
1078: $this->{$type}[$assocKey][$key] = $data;
1079: }
1080:
1081: if ($dynamicWith) {
1082: $this->{$type}[$assocKey]['dynamicWith'] = true;
1083: }
1084:
1085: }
1086: }
1087:
1088: /**
1089: * Sets a custom table for your model class. Used by your controller to select a database table.
1090: *
1091: * @param string $tableName Name of the custom table
1092: * @throws MissingTableException when database table $tableName is not found on data source
1093: * @return void
1094: */
1095: public function setSource($tableName) {
1096: $this->setDataSource($this->useDbConfig);
1097: $db = ConnectionManager::getDataSource($this->useDbConfig);
1098: $db->cacheSources = ($this->cacheSources && $db->cacheSources);
1099:
1100: if (method_exists($db, 'listSources')) {
1101: $sources = $db->listSources();
1102: if (is_array($sources) && !in_array(strtolower($this->tablePrefix . $tableName), array_map('strtolower', $sources))) {
1103: throw new MissingTableException(array(
1104: 'table' => $this->tablePrefix . $tableName,
1105: 'class' => $this->alias,
1106: 'ds' => $this->useDbConfig,
1107: ));
1108: }
1109: $this->_schema = null;
1110: }
1111: $this->table = $this->useTable = $tableName;
1112: $this->tableToModel[$this->table] = $this->alias;
1113: }
1114:
1115: /**
1116: * This function does two things:
1117: *
1118: * 1. it scans the array $one for the primary key,
1119: * and if that's found, it sets the current id to the value of $one[id].
1120: * For all other keys than 'id' the keys and values of $one are copied to the 'data' property of this object.
1121: * 2. Returns an array with all of $one's keys and values.
1122: * (Alternative indata: two strings, which are mangled to
1123: * a one-item, two-dimensional array using $one for a key and $two as its value.)
1124: *
1125: * @param string|array|SimpleXmlElement|DomNode $one Array or string of data
1126: * @param string $two Value string for the alternative indata method
1127: * @return array Data with all of $one's keys and values
1128: * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html
1129: */
1130: public function set($one, $two = null) {
1131: if (!$one) {
1132: return;
1133: }
1134: if (is_object($one)) {
1135: if ($one instanceof SimpleXMLElement || $one instanceof DOMNode) {
1136: $one = $this->_normalizeXmlData(Xml::toArray($one));
1137: } else {
1138: $one = Set::reverse($one);
1139: }
1140: }
1141:
1142: if (is_array($one)) {
1143: $data = $one;
1144: if (empty($one[$this->alias])) {
1145: $data = $this->_setAliasData($one);
1146: }
1147: } else {
1148: $data = array($this->alias => array($one => $two));
1149: }
1150:
1151: foreach ($data as $modelName => $fieldSet) {
1152: if (is_array($fieldSet)) {
1153:
1154: foreach ($fieldSet as $fieldName => $fieldValue) {
1155: if (isset($this->validationErrors[$fieldName])) {
1156: unset($this->validationErrors[$fieldName]);
1157: }
1158:
1159: if ($modelName === $this->alias) {
1160: if ($fieldName === $this->primaryKey) {
1161: $this->id = $fieldValue;
1162: }
1163: }
1164: if (is_array($fieldValue) || is_object($fieldValue)) {
1165: $fieldValue = $this->deconstruct($fieldName, $fieldValue);
1166: }
1167: $this->data[$modelName][$fieldName] = $fieldValue;
1168: }
1169: }
1170: }
1171: return $data;
1172: }
1173:
1174: /**
1175: * Move values to alias
1176: *
1177: * @param array $data
1178: * @return array
1179: */
1180: protected function _setAliasData($data) {
1181: $models = array_keys($this->getAssociated());
1182: $schema = array_keys((array)$this->schema());
1183: foreach ($data as $field => $value) {
1184: if (in_array($field, $schema) || !in_array($field, $models)) {
1185: $data[$this->alias][$field] = $value;
1186: unset($data[$field]);
1187: }
1188: }
1189: return $data;
1190: }
1191:
1192: /**
1193: * Normalize Xml::toArray() to use in Model::save()
1194: *
1195: * @param array $xml XML as array
1196: * @return array
1197: */
1198: protected function _normalizeXmlData(array $xml) {
1199: $return = array();
1200: foreach ($xml as $key => $value) {
1201: if (is_array($value)) {
1202: $return[Inflector::camelize($key)] = $this->_normalizeXmlData($value);
1203: } elseif ($key[0] === '@') {
1204: $return[substr($key, 1)] = $value;
1205: } else {
1206: $return[$key] = $value;
1207: }
1208: }
1209: return $return;
1210: }
1211:
1212: /**
1213: * Deconstructs a complex data type (array or object) into a single field value.
1214: *
1215: * @param string $field The name of the field to be deconstructed
1216: * @param array|object $data An array or object to be deconstructed into a field
1217: * @return mixed The resulting data that should be assigned to a field
1218: */
1219: public function deconstruct($field, $data) {
1220: if (!is_array($data)) {
1221: return $data;
1222: }
1223:
1224: $type = $this->getColumnType($field);
1225:
1226: if (in_array($type, array('datetime', 'timestamp', 'date', 'time'))) {
1227: $useNewDate = (isset($data['year']) || isset($data['month']) ||
1228: isset($data['day']) || isset($data['hour']) || isset($data['minute']));
1229:
1230: $dateFields = array('Y' => 'year', 'm' => 'month', 'd' => 'day', 'H' => 'hour', 'i' => 'min', 's' => 'sec');
1231: $timeFields = array('H' => 'hour', 'i' => 'min', 's' => 'sec');
1232: $date = array();
1233:
1234: if (isset($data['meridian']) && empty($data['meridian'])) {
1235: return null;
1236: }
1237:
1238: if (
1239: isset($data['hour']) &&
1240: isset($data['meridian']) &&
1241: !empty($data['hour']) &&
1242: $data['hour'] != 12 &&
1243: 'pm' == $data['meridian']
1244: ) {
1245: $data['hour'] = $data['hour'] + 12;
1246: }
1247: if (isset($data['hour']) && isset($data['meridian']) && $data['hour'] == 12 && 'am' == $data['meridian']) {
1248: $data['hour'] = '00';
1249: }
1250: if ($type == 'time') {
1251: foreach ($timeFields as $key => $val) {
1252: if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') {
1253: $data[$val] = '00';
1254: } elseif ($data[$val] !== '') {
1255: $data[$val] = sprintf('%02d', $data[$val]);
1256: }
1257: if (!empty($data[$val])) {
1258: $date[$key] = $data[$val];
1259: } else {
1260: return null;
1261: }
1262: }
1263: }
1264:
1265: if ($type == 'datetime' || $type == 'timestamp' || $type == 'date') {
1266: foreach ($dateFields as $key => $val) {
1267: if ($val == 'hour' || $val == 'min' || $val == 'sec') {
1268: if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') {
1269: $data[$val] = '00';
1270: } else {
1271: $data[$val] = sprintf('%02d', $data[$val]);
1272: }
1273: }
1274: if (!isset($data[$val]) || isset($data[$val]) && (empty($data[$val]) || $data[$val][0] === '-')) {
1275: return null;
1276: }
1277: if (isset($data[$val]) && !empty($data[$val])) {
1278: $date[$key] = $data[$val];
1279: }
1280: }
1281: }
1282:
1283: if ($useNewDate && !empty($date)) {
1284: $format = $this->getDataSource()->columns[$type]['format'];
1285: foreach (array('m', 'd', 'H', 'i', 's') as $index) {
1286: if (isset($date[$index])) {
1287: $date[$index] = sprintf('%02d', $date[$index]);
1288: }
1289: }
1290: return str_replace(array_keys($date), array_values($date), $format);
1291: }
1292: }
1293: return $data;
1294: }
1295:
1296: /**
1297: * Returns an array of table metadata (column names and types) from the database.
1298: * $field => keys(type, null, default, key, length, extra)
1299: *
1300: * @param boolean|string $field Set to true to reload schema, or a string to return a specific field
1301: * @return array Array of table metadata
1302: */
1303: public function schema($field = false) {
1304: if ($this->useTable !== false && (!is_array($this->_schema) || $field === true)) {
1305: $db = $this->getDataSource();
1306: $db->cacheSources = ($this->cacheSources && $db->cacheSources);
1307: if (method_exists($db, 'describe')) {
1308: $this->_schema = $db->describe($this);
1309: }
1310: }
1311: if (is_string($field)) {
1312: if (isset($this->_schema[$field])) {
1313: return $this->_schema[$field];
1314: } else {
1315: return null;
1316: }
1317: }
1318: return $this->_schema;
1319: }
1320:
1321: /**
1322: * Returns an associative array of field names and column types.
1323: *
1324: * @return array Field types indexed by field name
1325: */
1326: public function getColumnTypes() {
1327: $columns = $this->schema();
1328: if (empty($columns)) {
1329: trigger_error(__d('cake_dev', '(Model::getColumnTypes) Unable to build model field data. If you are using a model without a database table, try implementing schema()'), E_USER_WARNING);
1330: }
1331: $cols = array();
1332: foreach ($columns as $field => $values) {
1333: $cols[$field] = $values['type'];
1334: }
1335: return $cols;
1336: }
1337:
1338: /**
1339: * Returns the column type of a column in the model.
1340: *
1341: * @param string $column The name of the model column
1342: * @return string Column type
1343: */
1344: public function getColumnType($column) {
1345: $db = $this->getDataSource();
1346: $cols = $this->schema();
1347: $model = null;
1348:
1349: $startQuote = isset($db->startQuote) ? $db->startQuote : null;
1350: $endQuote = isset($db->endQuote) ? $db->endQuote : null;
1351: $column = str_replace(array($startQuote, $endQuote), '', $column);
1352:
1353: if (strpos($column, '.')) {
1354: list($model, $column) = explode('.', $column);
1355: }
1356: if ($model != $this->alias && isset($this->{$model})) {
1357: return $this->{$model}->getColumnType($column);
1358: }
1359: if (isset($cols[$column]) && isset($cols[$column]['type'])) {
1360: return $cols[$column]['type'];
1361: }
1362: return null;
1363: }
1364:
1365: /**
1366: * Returns true if the supplied field exists in the model's database table.
1367: *
1368: * @param string|array $name Name of field to look for, or an array of names
1369: * @param boolean $checkVirtual checks if the field is declared as virtual
1370: * @return mixed If $name is a string, returns a boolean indicating whether the field exists.
1371: * If $name is an array of field names, returns the first field that exists,
1372: * or false if none exist.
1373: */
1374: public function hasField($name, $checkVirtual = false) {
1375: if (is_array($name)) {
1376: foreach ($name as $n) {
1377: if ($this->hasField($n, $checkVirtual)) {
1378: return $n;
1379: }
1380: }
1381: return false;
1382: }
1383:
1384: if ($checkVirtual && !empty($this->virtualFields)) {
1385: if ($this->isVirtualField($name)) {
1386: return true;
1387: }
1388: }
1389:
1390: if (empty($this->_schema)) {
1391: $this->schema();
1392: }
1393:
1394: if ($this->_schema != null) {
1395: return isset($this->_schema[$name]);
1396: }
1397: return false;
1398: }
1399:
1400: /**
1401: * Check that a method is callable on a model. This will check both the model's own methods, its
1402: * inherited methods and methods that could be callable through behaviors.
1403: *
1404: * @param string $method The method to be called.
1405: * @return boolean True on method being callable.
1406: */
1407: public function hasMethod($method) {
1408: if (method_exists($this, $method)) {
1409: return true;
1410: }
1411: if ($this->Behaviors->hasMethod($method)) {
1412: return true;
1413: }
1414: return false;
1415: }
1416:
1417: /**
1418: * Returns true if the supplied field is a model Virtual Field
1419: *
1420: * @param string $field Name of field to look for
1421: * @return boolean indicating whether the field exists as a model virtual field.
1422: */
1423: public function isVirtualField($field) {
1424: if (empty($this->virtualFields) || !is_string($field)) {
1425: return false;
1426: }
1427: if (isset($this->virtualFields[$field])) {
1428: return true;
1429: }
1430: if (strpos($field, '.') !== false) {
1431: list($model, $field) = explode('.', $field);
1432: if ($model == $this->alias && isset($this->virtualFields[$field])) {
1433: return true;
1434: }
1435: }
1436: return false;
1437: }
1438:
1439: /**
1440: * Returns the expression for a model virtual field
1441: *
1442: * @param string $field Name of field to look for
1443: * @return mixed If $field is string expression bound to virtual field $field
1444: * If $field is null, returns an array of all model virtual fields
1445: * or false if none $field exist.
1446: */
1447: public function getVirtualField($field = null) {
1448: if ($field == null) {
1449: return empty($this->virtualFields) ? false : $this->virtualFields;
1450: }
1451: if ($this->isVirtualField($field)) {
1452: if (strpos($field, '.') !== false) {
1453: list($model, $field) = explode('.', $field);
1454: }
1455: return $this->virtualFields[$field];
1456: }
1457: return false;
1458: }
1459:
1460: /**
1461: * Initializes the model for writing a new record, loading the default values
1462: * for those fields that are not defined in $data, and clearing previous validation errors.
1463: * Especially helpful for saving data in loops.
1464: *
1465: * @param boolean|array $data Optional data array to assign to the model after it is created. If null or false,
1466: * schema data defaults are not merged.
1467: * @param boolean $filterKey If true, overwrites any primary key input with an empty value
1468: * @return array The current Model::data; after merging $data and/or defaults from database
1469: * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-create-array-data-array
1470: */
1471: public function create($data = array(), $filterKey = false) {
1472: $defaults = array();
1473: $this->id = false;
1474: $this->data = array();
1475: $this->validationErrors = array();
1476:
1477: if ($data !== null && $data !== false) {
1478: $schema = (array)$this->schema();
1479: foreach ($schema as $field => $properties) {
1480: if ($this->primaryKey !== $field && isset($properties['default']) && $properties['default'] !== '') {
1481: $defaults[$field] = $properties['default'];
1482: }
1483: }
1484: $this->set($defaults);
1485: $this->set($data);
1486: }
1487: if ($filterKey) {
1488: $this->set($this->primaryKey, false);
1489: }
1490: return $this->data;
1491: }
1492:
1493: /**
1494: * Returns a list of fields from the database, and sets the current model
1495: * data (Model::$data) with the record found.
1496: *
1497: * @param string|array $fields String of single field name, or an array of field names.
1498: * @param integer|string $id The ID of the record to read
1499: * @return array Array of database fields, or false if not found
1500: * @link http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-read
1501: */
1502: public function read($fields = null, $id = null) {
1503: $this->validationErrors = array();
1504:
1505: if ($id != null) {
1506: $this->id = $id;
1507: }
1508:
1509: $id = $this->id;
1510:
1511: if (is_array($this->id)) {
1512: $id = $this->id[0];
1513: }
1514:
1515: if ($id !== null && $id !== false) {
1516: $this->data = $this->find('first', array(
1517: 'conditions' => array($this->alias . '.' . $this->primaryKey => $id),
1518: 'fields' => $fields
1519: ));
1520: return $this->data;
1521: } else {
1522: return false;
1523: }
1524: }
1525:
1526: /**
1527: * Returns the contents of a single field given the supplied conditions, in the
1528: * supplied order.
1529: *
1530: * @param string $name Name of field to get
1531: * @param array $conditions SQL conditions (defaults to NULL)
1532: * @param string $order SQL ORDER BY fragment
1533: * @return string field contents, or false if not found
1534: * @link http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-field
1535: */
1536: public function field($name, $conditions = null, $order = null) {
1537: if ($conditions === null && $this->id !== false) {
1538: $conditions = array($this->alias . '.' . $this->primaryKey => $this->id);
1539: }
1540: if ($this->recursive >= 1) {
1541: $recursive = -1;
1542: } else {
1543: $recursive = $this->recursive;
1544: }
1545: $fields = $name;
1546: if ($data = $this->find('first', compact('conditions', 'fields', 'order', 'recursive'))) {
1547: if (strpos($name, '.') === false) {
1548: if (isset($data[$this->alias][$name])) {
1549: return $data[$this->alias][$name];
1550: }
1551: } else {
1552: $name = explode('.', $name);
1553: if (isset($data[$name[0]][$name[1]])) {
1554: return $data[$name[0]][$name[1]];
1555: }
1556: }
1557: if (isset($data[0]) && count($data[0]) > 0) {
1558: return array_shift($data[0]);
1559: }
1560: } else {
1561: return false;
1562: }
1563: }
1564:
1565: /**
1566: * Saves the value of a single field to the database, based on the current
1567: * model ID.
1568: *
1569: * @param string $name Name of the table field
1570: * @param mixed $value Value of the field
1571: * @param boolean|array $validate Either a boolean, or an array.
1572: * If a boolean, indicates whether or not to validate before saving.
1573: * If an array, allows control of 'validate' and 'callbacks' options.
1574: * @return boolean See Model::save()
1575: * @see Model::save()
1576: * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-savefield-string-fieldname-string-fieldvalue-validate-false
1577: */
1578: public function saveField($name, $value, $validate = false) {
1579: $id = $this->id;
1580: $this->create(false);
1581:
1582: if (is_array($validate)) {
1583: $options = array_merge(array('validate' => false, 'fieldList' => array($name)), $validate);
1584: } else {
1585: $options = array('validate' => $validate, 'fieldList' => array($name));
1586: }
1587: return $this->save(array($this->alias => array($this->primaryKey => $id, $name => $value)), $options);
1588: }
1589:
1590: /**
1591: * Saves model data (based on white-list, if supplied) to the database. By
1592: * default, validation occurs before save.
1593: *
1594: * @param array $data Data to save.
1595: * @param boolean|array $validate Either a boolean, or an array.
1596: * If a boolean, indicates whether or not to validate before saving.
1597: * If an array, allows control of validate, callbacks, and fieldList
1598: * @param array $fieldList List of fields to allow to be written
1599: * @return mixed On success Model::$data if its not empty or true, false on failure
1600: * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html
1601: */
1602: public function save($data = null, $validate = true, $fieldList = array()) {
1603: $defaults = array('validate' => true, 'fieldList' => array(), 'callbacks' => true);
1604: $_whitelist = $this->whitelist;
1605: $fields = array();
1606:
1607: if (!is_array($validate)) {
1608: $options = array_merge($defaults, compact('validate', 'fieldList', 'callbacks'));
1609: } else {
1610: $options = array_merge($defaults, $validate);
1611: }
1612:
1613: if (!empty($options['fieldList'])) {
1614: if (!empty($options['fieldList'][$this->alias]) && is_array($options['fieldList'][$this->alias])) {
1615: $this->whitelist = $options['fieldList'][$this->alias];
1616: } else {
1617: $this->whitelist = $options['fieldList'];
1618: }
1619: } elseif ($options['fieldList'] === null) {
1620: $this->whitelist = array();
1621: }
1622: $this->set($data);
1623:
1624: if (empty($this->data) && !$this->hasField(array('created', 'updated', 'modified'))) {
1625: return false;
1626: }
1627:
1628: foreach (array('created', 'updated', 'modified') as $field) {
1629: $keyPresentAndEmpty = (
1630: isset($this->data[$this->alias]) &&
1631: array_key_exists($field, $this->data[$this->alias]) &&
1632: $this->data[$this->alias][$field] === null
1633: );
1634: if ($keyPresentAndEmpty) {
1635: unset($this->data[$this->alias][$field]);
1636: }
1637: }
1638:
1639: $exists = $this->exists();
1640: $dateFields = array('modified', 'updated');
1641:
1642: if (!$exists) {
1643: $dateFields[] = 'created';
1644: }
1645: if (isset($this->data[$this->alias])) {
1646: $fields = array_keys($this->data[$this->alias]);
1647: }
1648: if ($options['validate'] && !$this->validates($options)) {
1649: $this->whitelist = $_whitelist;
1650: return false;
1651: }
1652:
1653: $db = $this->getDataSource();
1654:
1655: foreach ($dateFields as $updateCol) {
1656: if ($this->hasField($updateCol) && !in_array($updateCol, $fields)) {
1657: $default = array('formatter' => 'date');
1658: $colType = array_merge($default, $db->columns[$this->getColumnType($updateCol)]);
1659: if (!array_key_exists('format', $colType)) {
1660: $time = strtotime('now');
1661: } else {
1662: $time = call_user_func($colType['formatter'], $colType['format']);
1663: }
1664: if (!empty($this->whitelist)) {
1665: $this->whitelist[] = $updateCol;
1666: }
1667: $this->set($updateCol, $time);
1668: }
1669: }
1670:
1671: if ($options['callbacks'] === true || $options['callbacks'] === 'before') {
1672: $event = new CakeEvent('Model.beforeSave', $this, array($options));
1673: list($event->break, $event->breakOn) = array(true, array(false, null));
1674: $this->getEventManager()->dispatch($event);
1675: if (!$event->result) {
1676: $this->whitelist = $_whitelist;
1677: return false;
1678: }
1679: }
1680:
1681: if (empty($this->data[$this->alias][$this->primaryKey])) {
1682: unset($this->data[$this->alias][$this->primaryKey]);
1683: }
1684: $fields = $values = array();
1685:
1686: foreach ($this->data as $n => $v) {
1687: if (isset($this->hasAndBelongsToMany[$n])) {
1688: if (isset($v[$n])) {
1689: $v = $v[$n];
1690: }
1691: $joined[$n] = $v;
1692: } else {
1693: if ($n === $this->alias) {
1694: foreach (array('created', 'updated', 'modified') as $field) {
1695: if (array_key_exists($field, $v) && empty($v[$field])) {
1696: unset($v[$field]);
1697: }
1698: }
1699:
1700: foreach ($v as $x => $y) {
1701: if ($this->hasField($x) && (empty($this->whitelist) || in_array($x, $this->whitelist))) {
1702: list($fields[], $values[]) = array($x, $y);
1703: }
1704: }
1705: }
1706: }
1707: }
1708: $count = count($fields);
1709:
1710: if (!$exists && $count > 0) {
1711: $this->id = false;
1712: }
1713: $success = true;
1714: $created = false;
1715:
1716: if ($count > 0) {
1717: $cache = $this->_prepareUpdateFields(array_combine($fields, $values));
1718:
1719: if (!empty($this->id)) {
1720: $success = (bool)$db->update($this, $fields, $values);
1721: } else {
1722: $fInfo = $this->schema($this->primaryKey);
1723: $isUUID = ($fInfo['length'] == 36 &&
1724: ($fInfo['type'] === 'string' || $fInfo['type'] === 'binary')
1725: );
1726: if (empty($this->data[$this->alias][$this->primaryKey]) && $isUUID) {
1727: if (array_key_exists($this->primaryKey, $this->data[$this->alias])) {
1728: $j = array_search($this->primaryKey, $fields);
1729: $values[$j] = String::uuid();
1730: } else {
1731: list($fields[], $values[]) = array($this->primaryKey, String::uuid());
1732: }
1733: }
1734:
1735: if (!$db->create($this, $fields, $values)) {
1736: $success = $created = false;
1737: } else {
1738: $created = true;
1739: }
1740: }
1741:
1742: if ($success && !empty($this->belongsTo)) {
1743: $this->updateCounterCache($cache, $created);
1744: }
1745: }
1746:
1747: if (!empty($joined) && $success === true) {
1748: $this->_saveMulti($joined, $this->id, $db);
1749: }
1750:
1751: if ($success && $count === 0) {
1752: $success = false;
1753: }
1754:
1755: if ($success && $count > 0) {
1756: if (!empty($this->data)) {
1757: if ($created) {
1758: $this->data[$this->alias][$this->primaryKey] = $this->id;
1759: }
1760: }
1761: if ($options['callbacks'] === true || $options['callbacks'] === 'after') {
1762: $event = new CakeEvent('Model.afterSave', $this, array($created, $options));
1763: $this->getEventManager()->dispatch($event);
1764: }
1765: if (!empty($this->data)) {
1766: $success = $this->data;
1767: }
1768: $this->data = false;
1769: $this->_clearCache();
1770: $this->validationErrors = array();
1771: }
1772: $this->whitelist = $_whitelist;
1773: return $success;
1774: }
1775:
1776: /**
1777: * Saves model hasAndBelongsToMany data to the database.
1778: *
1779: * @param array $joined Data to save
1780: * @param integer|string $id ID of record in this model
1781: * @param DataSource $db
1782: * @return void
1783: */
1784: protected function _saveMulti($joined, $id, $db) {
1785: foreach ($joined as $assoc => $data) {
1786:
1787: if (isset($this->hasAndBelongsToMany[$assoc])) {
1788: list($join) = $this->joinModel($this->hasAndBelongsToMany[$assoc]['with']);
1789:
1790: $keyInfo = $this->{$join}->schema($this->{$join}->primaryKey);
1791: if ($with = $this->hasAndBelongsToMany[$assoc]['with']) {
1792: $withModel = is_array($with) ? key($with) : $with;
1793: list($pluginName, $withModel) = pluginSplit($withModel);
1794: $dbMulti = $this->{$withModel}->getDataSource();
1795: } else {
1796: $dbMulti = $db;
1797: }
1798:
1799: $isUUID = !empty($this->{$join}->primaryKey) && (
1800: $keyInfo['length'] == 36 && (
1801: $keyInfo['type'] === 'string' ||
1802: $keyInfo['type'] === 'binary'
1803: )
1804: );
1805:
1806: $newData = $newValues = $newJoins = array();
1807: $primaryAdded = false;
1808:
1809: $fields = array(
1810: $dbMulti->name($this->hasAndBelongsToMany[$assoc]['foreignKey']),
1811: $dbMulti->name($this->hasAndBelongsToMany[$assoc]['associationForeignKey'])
1812: );
1813:
1814: $idField = $db->name($this->{$join}->primaryKey);
1815: if ($isUUID && !in_array($idField, $fields)) {
1816: $fields[] = $idField;
1817: $primaryAdded = true;
1818: }
1819:
1820: foreach ((array)$data as $row) {
1821: if ((is_string($row) && (strlen($row) == 36 || strlen($row) == 16)) || is_numeric($row)) {
1822: $newJoins[] = $row;
1823: $values = array($id, $row);
1824: if ($isUUID && $primaryAdded) {
1825: $values[] = String::uuid();
1826: }
1827: $newValues[$row] = $values;
1828: unset($values);
1829: } elseif (isset($row[$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
1830: if (!empty($row[$this->{$join}->primaryKey])) {
1831: $newJoins[] = $row[$this->hasAndBelongsToMany[$assoc]['associationForeignKey']];
1832: }
1833: $newData[] = $row;
1834: } elseif (isset($row[$join]) && isset($row[$join][$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
1835: if (!empty($row[$join][$this->{$join}->primaryKey])) {
1836: $newJoins[] = $row[$join][$this->hasAndBelongsToMany[$assoc]['associationForeignKey']];
1837: }
1838: $newData[] = $row[$join];
1839: }
1840: }
1841:
1842: $keepExisting = $this->hasAndBelongsToMany[$assoc]['unique'] === 'keepExisting';
1843: if ($this->hasAndBelongsToMany[$assoc]['unique']) {
1844: $conditions = array(
1845: $join . '.' . $this->hasAndBelongsToMany[$assoc]['foreignKey'] => $id
1846: );
1847: if (!empty($this->hasAndBelongsToMany[$assoc]['conditions'])) {
1848: $conditions = array_merge($conditions, (array)$this->hasAndBelongsToMany[$assoc]['conditions']);
1849: }
1850: $associationForeignKey = $this->{$join}->alias . '.' . $this->hasAndBelongsToMany[$assoc]['associationForeignKey'];
1851: $links = $this->{$join}->find('all', array(
1852: 'conditions' => $conditions,
1853: 'recursive' => empty($this->hasAndBelongsToMany[$assoc]['conditions']) ? -1 : 0,
1854: 'fields' => $associationForeignKey,
1855: ));
1856:
1857: $oldLinks = Hash::extract($links, "{n}.{$associationForeignKey}");
1858: if (!empty($oldLinks)) {
1859: if ($keepExisting && !empty($newJoins)) {
1860: $conditions[$associationForeignKey] = array_diff($oldLinks, $newJoins);
1861: } else {
1862: $conditions[$associationForeignKey] = $oldLinks;
1863: }
1864: $dbMulti->delete($this->{$join}, $conditions);
1865: }
1866: }
1867:
1868: if (!empty($newData)) {
1869: foreach ($newData as $data) {
1870: $data[$this->hasAndBelongsToMany[$assoc]['foreignKey']] = $id;
1871: if (empty($data[$this->{$join}->primaryKey])) {
1872: $this->{$join}->create();
1873: }
1874: $this->{$join}->save($data);
1875: }
1876: }
1877:
1878: if (!empty($newValues)) {
1879: if ($keepExisting && !empty($links)) {
1880: foreach ($links as $link) {
1881: $oldJoin = $link[$join][$this->hasAndBelongsToMany[$assoc]['associationForeignKey']];
1882: if (! in_array($oldJoin, $newJoins) ) {
1883: $conditions[$associationForeignKey] = $oldJoin;
1884: $db->delete($this->{$join}, $conditions);
1885: } else {
1886: unset($newValues[$oldJoin]);
1887: }
1888: }
1889: $newValues = array_values($newValues);
1890: }
1891: if (!empty($newValues)) {
1892: $dbMulti->insertMulti($this->{$join}, $fields, $newValues);
1893: }
1894: }
1895: }
1896: }
1897: }
1898:
1899: /**
1900: * Updates the counter cache of belongsTo associations after a save or delete operation
1901: *
1902: * @param array $keys Optional foreign key data, defaults to the information $this->data
1903: * @param boolean $created True if a new record was created, otherwise only associations with
1904: * 'counterScope' defined get updated
1905: * @return void
1906: */
1907: public function updateCounterCache($keys = array(), $created = false) {
1908: $keys = empty($keys) ? $this->data[$this->alias] : $keys;
1909: $keys['old'] = isset($keys['old']) ? $keys['old'] : array();
1910:
1911: foreach ($this->belongsTo as $parent => $assoc) {
1912: if (!empty($assoc['counterCache'])) {
1913: if (!is_array($assoc['counterCache'])) {
1914: if (isset($assoc['counterScope'])) {
1915: $assoc['counterCache'] = array($assoc['counterCache'] => $assoc['counterScope']);
1916: } else {
1917: $assoc['counterCache'] = array($assoc['counterCache'] => array());
1918: }
1919: }
1920:
1921: $foreignKey = $assoc['foreignKey'];
1922: $fkQuoted = $this->escapeField($assoc['foreignKey']);
1923:
1924: foreach ($assoc['counterCache'] as $field => $conditions) {
1925: if (!is_string($field)) {
1926: $field = Inflector::underscore($this->alias) . '_count';
1927: }
1928: if (!$this->{$parent}->hasField($field)) {
1929: continue;
1930: }
1931: if ($conditions === true) {
1932: $conditions = array();
1933: } else {
1934: $conditions = (array)$conditions;
1935: }
1936:
1937: if (!array_key_exists($foreignKey, $keys)) {
1938: $keys[$foreignKey] = $this->field($foreignKey);
1939: }
1940: $recursive = (empty($conditions) ? -1 : 0);
1941:
1942: if (isset($keys['old'][$foreignKey])) {
1943: if ($keys['old'][$foreignKey] != $keys[$foreignKey]) {
1944: $conditions[$fkQuoted] = $keys['old'][$foreignKey];
1945: $count = intval($this->find('count', compact('conditions', 'recursive')));
1946:
1947: $this->{$parent}->updateAll(
1948: array($field => $count),
1949: array($this->{$parent}->escapeField() => $keys['old'][$foreignKey])
1950: );
1951: }
1952: }
1953: $conditions[$fkQuoted] = $keys[$foreignKey];
1954:
1955: if ($recursive === 0) {
1956: $conditions = array_merge($conditions, (array)$conditions);
1957: }
1958: $count = intval($this->find('count', compact('conditions', 'recursive')));
1959:
1960: $this->{$parent}->updateAll(
1961: array($field => $count),
1962: array($this->{$parent}->escapeField() => $keys[$foreignKey])
1963: );
1964: }
1965: }
1966: }
1967: }
1968:
1969: /**
1970: * Helper method for Model::updateCounterCache(). Checks the fields to be updated for
1971: *
1972: * @param array $data The fields of the record that will be updated
1973: * @return array Returns updated foreign key values, along with an 'old' key containing the old
1974: * values, or empty if no foreign keys are updated.
1975: */
1976: protected function _prepareUpdateFields($data) {
1977: $foreignKeys = array();
1978: foreach ($this->belongsTo as $assoc => $info) {
1979: if ($info['counterCache']) {
1980: $foreignKeys[$assoc] = $info['foreignKey'];
1981: }
1982: }
1983: $included = array_intersect($foreignKeys, array_keys($data));
1984:
1985: if (empty($included) || empty($this->id)) {
1986: return array();
1987: }
1988: $old = $this->find('first', array(
1989: 'conditions' => array($this->alias . '.' . $this->primaryKey => $this->id),
1990: 'fields' => array_values($included),
1991: 'recursive' => -1
1992: ));
1993: return array_merge($data, array('old' => $old[$this->alias]));
1994: }
1995:
1996: /**
1997: * Backwards compatible passthrough method for:
1998: * saveMany(), validateMany(), saveAssociated() and validateAssociated()
1999: *
2000: * Saves multiple individual records for a single model; Also works with a single record, as well as
2001: * all its associated records.
2002: *
2003: * #### Options
2004: *
2005: * - validate: Set to false to disable validation, true to validate each record before saving,
2006: * 'first' to validate *all* records before any are saved (default),
2007: * or 'only' to only validate the records, but not save them.
2008: * - atomic: If true (default), will attempt to save all records in a single transaction.
2009: * Should be set to false if database/table does not support transactions.
2010: * - fieldList: Equivalent to the $fieldList parameter in Model::save().
2011: * It should be an associate array with model name as key and array of fields as value. Eg.
2012: * {{{
2013: * array(
2014: * 'SomeModel' => array('field'),
2015: * 'AssociatedModel' => array('field', 'otherfield')
2016: * )
2017: * }}}
2018: * - deep: see saveMany/saveAssociated
2019: *
2020: * @param array $data Record data to save. This can be either a numerically-indexed array (for saving multiple
2021: * records of the same type), or an array indexed by association name.
2022: * @param array $options Options to use when saving record data, See $options above.
2023: * @return mixed If atomic: True on success, or false on failure.
2024: * Otherwise: array similar to the $data array passed, but values are set to true/false
2025: * depending on whether each record saved successfully.
2026: * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveassociated-array-data-null-array-options-array
2027: * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveall-array-data-null-array-options-array
2028: */
2029: public function saveAll($data = array(), $options = array()) {
2030: $options = array_merge(array('validate' => 'first'), $options);
2031: if (Hash::numeric(array_keys($data))) {
2032: if ($options['validate'] === 'only') {
2033: return $this->validateMany($data, $options);
2034: }
2035: return $this->saveMany($data, $options);
2036: }
2037: if ($options['validate'] === 'only') {
2038: return $this->validateAssociated($data, $options);
2039: }
2040: return $this->saveAssociated($data, $options);
2041: }
2042:
2043: /**
2044: * Saves multiple individual records for a single model
2045: *
2046: * #### Options
2047: *
2048: * - validate: Set to false to disable validation, true to validate each record before saving,
2049: * 'first' to validate *all* records before any are saved (default),
2050: * - atomic: If true (default), will attempt to save all records in a single transaction.
2051: * Should be set to false if database/table does not support transactions.
2052: * - fieldList: Equivalent to the $fieldList parameter in Model::save()
2053: * - deep: If set to true, all associated data will be saved as well.
2054: *
2055: * @param array $data Record data to save. This should be a numerically-indexed array
2056: * @param array $options Options to use when saving record data, See $options above.
2057: * @return mixed If atomic: True on success, or false on failure.
2058: * Otherwise: array similar to the $data array passed, but values are set to true/false
2059: * depending on whether each record saved successfully.
2060: * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-savemany-array-data-null-array-options-array
2061: */
2062: public function saveMany($data = null, $options = array()) {
2063: if (empty($data)) {
2064: $data = $this->data;
2065: }
2066:
2067: $options = array_merge(array('validate' => 'first', 'atomic' => true, 'deep' => false), $options);
2068: $this->validationErrors = $validationErrors = array();
2069:
2070: if (empty($data) && $options['validate'] !== false) {
2071: $result = $this->save($data, $options);
2072: if (!$options['atomic']) {
2073: return array(!empty($result));
2074: }
2075: return !empty($result);
2076: }
2077:
2078: if ($options['validate'] === 'first') {
2079: $validates = $this->validateMany($data, $options);
2080: if ((!$validates && $options['atomic']) || (!$options['atomic'] && in_array(false, $validates, true))) {
2081: return $validates;
2082: }
2083: $options['validate'] = false;
2084: }
2085:
2086: if ($options['atomic']) {
2087: $db = $this->getDataSource();
2088: $transactionBegun = $db->begin();
2089: }
2090: $return = array();
2091: foreach ($data as $key => $record) {
2092: $validates = $this->create(null) !== null;
2093: $saved = false;
2094: if ($validates) {
2095: if ($options['deep']) {
2096: $saved = $this->saveAssociated($record, array_merge($options, array('atomic' => false)));
2097: } else {
2098: $saved = $this->save($record, $options);
2099: }
2100: }
2101: $validates = ($validates && ($saved === true || (is_array($saved) && !in_array(false, $saved, true))));
2102: if (!$validates) {
2103: $validationErrors[$key] = $this->validationErrors;
2104: }
2105: if (!$options['atomic']) {
2106: $return[$key] = $validates;
2107: } elseif (!$validates) {
2108: break;
2109: }
2110: }
2111: $this->validationErrors = $validationErrors;
2112:
2113: if (!$options['atomic']) {
2114: return $return;
2115: }
2116: if ($validates) {
2117: if ($transactionBegun) {
2118: return $db->commit() !== false;
2119: } else {
2120: return true;
2121: }
2122: }
2123: $db->rollback();
2124: return false;
2125: }
2126:
2127: /**
2128: * Validates multiple individual records for a single model
2129: *
2130: * #### Options
2131: *
2132: * - atomic: If true (default), returns boolean. If false returns array.
2133: * - fieldList: Equivalent to the $fieldList parameter in Model::save()
2134: * - deep: If set to true, all associated data will be validated as well.
2135: *
2136: * Warning: This method could potentially change the passed argument `$data`,
2137: * If you do not want this to happen, make a copy of `$data` before passing it
2138: * to this method
2139: *
2140: * @param array $data Record data to validate. This should be a numerically-indexed array
2141: * @param array $options Options to use when validating record data (see above), See also $options of validates().
2142: * @return boolean True on success, or false on failure.
2143: * @return mixed If atomic: True on success, or false on failure.
2144: * Otherwise: array similar to the $data array passed, but values are set to true/false
2145: * depending on whether each record validated successfully.
2146: */
2147: public function validateMany(&$data, $options = array()) {
2148: return $this->validator()->validateMany($data, $options);
2149: }
2150:
2151: /**
2152: * Saves a single record, as well as all its directly associated records.
2153: *
2154: * #### Options
2155: *
2156: * - `validate` Set to `false` to disable validation, `true` to validate each record before saving,
2157: * 'first' to validate *all* records before any are saved(default),
2158: * - `atomic` If true (default), will attempt to save all records in a single transaction.
2159: * Should be set to false if database/table does not support transactions.
2160: * - fieldList: Equivalent to the $fieldList parameter in Model::save().
2161: * It should be an associate array with model name as key and array of fields as value. Eg.
2162: * {{{
2163: * array(
2164: * 'SomeModel' => array('field'),
2165: * 'AssociatedModel' => array('field', 'otherfield')
2166: * )
2167: * }}}
2168: * - deep: If set to true, not only directly associated data is saved, but deeper nested associated data as well.
2169: *
2170: * @param array $data Record data to save. This should be an array indexed by association name.
2171: * @param array $options Options to use when saving record data, See $options above.
2172: * @return mixed If atomic: True on success, or false on failure.
2173: * Otherwise: array similar to the $data array passed, but values are set to true/false
2174: * depending on whether each record saved successfully.
2175: * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveassociated-array-data-null-array-options-array
2176: */
2177: public function saveAssociated($data = null, $options = array()) {
2178: if (empty($data)) {
2179: $data = $this->data;
2180: }
2181:
2182: $options = array_merge(array('validate' => 'first', 'atomic' => true, 'deep' => false), $options);
2183: $this->validationErrors = $validationErrors = array();
2184:
2185: if (empty($data) && $options['validate'] !== false) {
2186: $result = $this->save($data, $options);
2187: if (!$options['atomic']) {
2188: return array(!empty($result));
2189: }
2190: return !empty($result);
2191: }
2192:
2193: if ($options['validate'] === 'first') {
2194: $validates = $this->validateAssociated($data, $options);
2195: if ((!$validates && $options['atomic']) || (!$options['atomic'] && in_array(false, Hash::flatten($validates), true))) {
2196: return $validates;
2197: }
2198: $options['validate'] = false;
2199: }
2200: if ($options['atomic']) {
2201: $db = $this->getDataSource();
2202: $transactionBegun = $db->begin();
2203: }
2204:
2205: $associations = $this->getAssociated();
2206: $return = array();
2207: $validates = true;
2208: foreach ($data as $association => $values) {
2209: $notEmpty = !empty($values[$association]) || (!isset($values[$association]) && !empty($values));
2210: if (isset($associations[$association]) && $associations[$association] === 'belongsTo' && $notEmpty) {
2211: $validates = $this->{$association}->create(null) !== null;
2212: $saved = false;
2213: if ($validates) {
2214: if ($options['deep']) {
2215: $saved = $this->{$association}->saveAssociated($values, array_merge($options, array('atomic' => false)));
2216: } else {
2217: $saved = $this->{$association}->save($values, array_merge($options, array('atomic' => false)));
2218: }
2219: $validates = ($saved === true || (is_array($saved) && !in_array(false, $saved, true)));
2220: }
2221: if ($validates) {
2222: $key = $this->belongsTo[$association]['foreignKey'];
2223: if (isset($data[$this->alias])) {
2224: $data[$this->alias][$key] = $this->{$association}->id;
2225: } else {
2226: $data = array_merge(array($key => $this->{$association}->id), $data, array($key => $this->{$association}->id));
2227: }
2228: } else {
2229: $validationErrors[$association] = $this->{$association}->validationErrors;
2230: }
2231: $return[$association] = $validates;
2232: }
2233: }
2234: if ($validates && !($this->create(null) !== null && $this->save($data, $options))) {
2235: $validationErrors[$this->alias] = $this->validationErrors;
2236: $validates = false;
2237: }
2238: $return[$this->alias] = $validates;
2239:
2240: foreach ($data as $association => $values) {
2241: if (!$validates) {
2242: break;
2243: }
2244: $notEmpty = !empty($values[$association]) || (!isset($values[$association]) && !empty($values));
2245: if (isset($associations[$association]) && $notEmpty) {
2246: $type = $associations[$association];
2247: $key = $this->{$type}[$association]['foreignKey'];
2248: switch ($type) {
2249: case 'hasOne':
2250: if (isset($values[$association])) {
2251: $values[$association][$key] = $this->id;
2252: } else {
2253: $values = array_merge(array($key => $this->id), $values, array($key => $this->id));
2254: }
2255: $validates = $this->{$association}->create(null) !== null;
2256: $saved = false;
2257: if ($validates) {
2258: if ($options['deep']) {
2259: $saved = $this->{$association}->saveAssociated($values, array_merge($options, array('atomic' => false)));
2260: } else {
2261: $saved = $this->{$association}->save($values, $options);
2262: }
2263: }
2264: $validates = ($validates && ($saved === true || (is_array($saved) && !in_array(false, $saved, true))));
2265: if (!$validates) {
2266: $validationErrors[$association] = $this->{$association}->validationErrors;
2267: }
2268: $return[$association] = $validates;
2269: break;
2270: case 'hasMany':
2271: foreach ($values as $i => $value) {
2272: if (isset($values[$i][$association])) {
2273: $values[$i][$association][$key] = $this->id;
2274: } else {
2275: $values[$i] = array_merge(array($key => $this->id), $value, array($key => $this->id));
2276: }
2277: }
2278: $_return = $this->{$association}->saveMany($values, array_merge($options, array('atomic' => false)));
2279: if (in_array(false, $_return, true)) {
2280: $validationErrors[$association] = $this->{$association}->validationErrors;
2281: $validates = false;
2282: }
2283: $return[$association] = $_return;
2284: break;
2285: }
2286: }
2287: }
2288: $this->validationErrors = $validationErrors;
2289:
2290: if (isset($validationErrors[$this->alias])) {
2291: $this->validationErrors = $validationErrors[$this->alias];
2292: unset($validationErrors[$this->alias]);
2293: $this->validationErrors = array_merge($this->validationErrors, $validationErrors);
2294: }
2295:
2296: if (!$options['atomic']) {
2297: return $return;
2298: }
2299: if ($validates) {
2300: if ($transactionBegun) {
2301: return $db->commit() !== false;
2302: } else {
2303: return true;
2304: }
2305: }
2306: $db->rollback();
2307: return false;
2308: }
2309:
2310: /**
2311: * Validates a single record, as well as all its directly associated records.
2312: *
2313: * #### Options
2314: *
2315: * - atomic: If true (default), returns boolean. If false returns array.
2316: * - fieldList: Equivalent to the $fieldList parameter in Model::save()
2317: * - deep: If set to true, not only directly associated data , but deeper nested associated data is validated as well.
2318: *
2319: * Warning: This method could potentially change the passed argument `$data`,
2320: * If you do not want this to happen, make a copy of `$data` before passing it
2321: * to this method
2322: *
2323: * @param array $data Record data to validate. This should be an array indexed by association name.
2324: * @param array $options Options to use when validating record data (see above), See also $options of validates().
2325: * @return array|boolean If atomic: True on success, or false on failure.
2326: * Otherwise: array similar to the $data array passed, but values are set to true/false
2327: * depending on whether each record validated successfully.
2328: */
2329: public function validateAssociated(&$data, $options = array()) {
2330: return $this->validator()->validateAssociated($data, $options);
2331: }
2332:
2333: /**
2334: * Updates multiple model records based on a set of conditions.
2335: *
2336: * @param array $fields Set of fields and values, indexed by fields.
2337: * Fields are treated as SQL snippets, to insert literal values manually escape your data.
2338: * @param mixed $conditions Conditions to match, true for all records
2339: * @return boolean True on success, false on failure
2340: * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-updateall-array-fields-array-conditions
2341: */
2342: public function updateAll($fields, $conditions = true) {
2343: return $this->getDataSource()->update($this, $fields, null, $conditions);
2344: }
2345:
2346: /**
2347: * Removes record for given ID. If no ID is given, the current ID is used. Returns true on success.
2348: *
2349: * @param integer|string $id ID of record to delete
2350: * @param boolean $cascade Set to true to delete records that depend on this record
2351: * @return boolean True on success
2352: * @link http://book.cakephp.org/2.0/en/models/deleting-data.html
2353: */
2354: public function delete($id = null, $cascade = true) {
2355: if (!empty($id)) {
2356: $this->id = $id;
2357: }
2358: $id = $this->id;
2359:
2360: $event = new CakeEvent('Model.beforeDelete', $this, array($cascade));
2361: list($event->break, $event->breakOn) = array(true, array(false, null));
2362: $this->getEventManager()->dispatch($event);
2363: if (!$event->isStopped()) {
2364: if (!$this->exists()) {
2365: return false;
2366: }
2367: $db = $this->getDataSource();
2368:
2369: $this->_deleteDependent($id, $cascade);
2370: $this->_deleteLinks($id);
2371: $this->id = $id;
2372:
2373: $updateCounterCache = false;
2374: if (!empty($this->belongsTo)) {
2375: foreach ($this->belongsTo as $assoc) {
2376: if (!empty($assoc['counterCache'])) {
2377: $updateCounterCache = true;
2378: break;
2379: }
2380: }
2381: if ($updateCounterCache) {
2382: $keys = $this->find('first', array(
2383: 'fields' => $this->_collectForeignKeys(),
2384: 'conditions' => array($this->alias . '.' . $this->primaryKey => $id),
2385: 'recursive' => -1,
2386: 'callbacks' => false
2387: ));
2388: }
2389: }
2390:
2391: if ($db->delete($this, array($this->alias . '.' . $this->primaryKey => $id))) {
2392: if ($updateCounterCache) {
2393: $this->updateCounterCache($keys[$this->alias]);
2394: }
2395: $this->getEventManager()->dispatch(new CakeEvent('Model.afterDelete', $this));
2396: $this->_clearCache();
2397: $this->id = false;
2398: return true;
2399: }
2400: }
2401: return false;
2402: }
2403:
2404: /**
2405: * Cascades model deletes through associated hasMany and hasOne child records.
2406: *
2407: * @param string $id ID of record that was deleted
2408: * @param boolean $cascade Set to true to delete records that depend on this record
2409: * @return void
2410: */
2411: protected function _deleteDependent($id, $cascade) {
2412: if (!empty($this->__backAssociation)) {
2413: $savedAssociatons = $this->__backAssociation;
2414: $this->__backAssociation = array();
2415: }
2416: if ($cascade === true) {
2417: foreach (array_merge($this->hasMany, $this->hasOne) as $assoc => $data) {
2418: if ($data['dependent'] === true) {
2419:
2420: $model = $this->{$assoc};
2421:
2422: if ($data['foreignKey'] === false && $data['conditions'] && in_array($this->name, $model->getAssociated('belongsTo'))) {
2423: $model->recursive = 0;
2424: $conditions = array($this->escapeField(null, $this->name) => $id);
2425: } else {
2426: $model->recursive = -1;
2427: $conditions = array($model->escapeField($data['foreignKey']) => $id);
2428: if ($data['conditions']) {
2429: $conditions = array_merge((array)$data['conditions'], $conditions);
2430: }
2431: }
2432:
2433: if (isset($data['exclusive']) && $data['exclusive']) {
2434: $model->deleteAll($conditions);
2435: } else {
2436: $records = $model->find('all', array(
2437: 'conditions' => $conditions, 'fields' => $model->primaryKey
2438: ));
2439:
2440: if (!empty($records)) {
2441: foreach ($records as $record) {
2442: $model->delete($record[$model->alias][$model->primaryKey]);
2443: }
2444: }
2445: }
2446: }
2447: }
2448: }
2449: if (isset($savedAssociatons)) {
2450: $this->__backAssociation = $savedAssociatons;
2451: }
2452: }
2453:
2454: /**
2455: * Cascades model deletes through HABTM join keys.
2456: *
2457: * @param string $id ID of record that was deleted
2458: * @return void
2459: */
2460: protected function _deleteLinks($id) {
2461: foreach ($this->hasAndBelongsToMany as $data) {
2462: list($plugin, $joinModel) = pluginSplit($data['with']);
2463: $records = $this->{$joinModel}->find('all', array(
2464: 'conditions' => array($this->{$joinModel}->escapeField($data['foreignKey']) => $id),
2465: 'fields' => $this->{$joinModel}->primaryKey,
2466: 'recursive' => -1,
2467: 'callbacks' => false
2468: ));
2469: if (!empty($records)) {
2470: foreach ($records as $record) {
2471: $this->{$joinModel}->delete($record[$this->{$joinModel}->alias][$this->{$joinModel}->primaryKey]);
2472: }
2473: }
2474: }
2475: }
2476:
2477: /**
2478: * Deletes multiple model records based on a set of conditions.
2479: *
2480: * @param mixed $conditions Conditions to match
2481: * @param boolean $cascade Set to true to delete records that depend on this record
2482: * @param boolean $callbacks Run callbacks
2483: * @return boolean True on success, false on failure
2484: * @link http://book.cakephp.org/2.0/en/models/deleting-data.html#deleteall
2485: */
2486: public function deleteAll($conditions, $cascade = true, $callbacks = false) {
2487: if (empty($conditions)) {
2488: return false;
2489: }
2490: $db = $this->getDataSource();
2491:
2492: if (!$cascade && !$callbacks) {
2493: return $db->delete($this, $conditions);
2494: } else {
2495: $ids = $this->find('all', array_merge(array(
2496: 'fields' => "{$this->alias}.{$this->primaryKey}",
2497: 'recursive' => 0), compact('conditions'))
2498: );
2499: if ($ids === null) {
2500: return false;
2501: }
2502:
2503: $ids = Hash::extract($ids, "{n}.{$this->alias}.{$this->primaryKey}");
2504: if (empty($ids)) {
2505: return true;
2506: }
2507:
2508: if ($callbacks) {
2509: $_id = $this->id;
2510: $result = true;
2511: foreach ($ids as $id) {
2512: $result = ($result && $this->delete($id, $cascade));
2513: }
2514: $this->id = $_id;
2515: return $result;
2516: } else {
2517: foreach ($ids as $id) {
2518: $this->_deleteLinks($id);
2519: if ($cascade) {
2520: $this->_deleteDependent($id, $cascade);
2521: }
2522: }
2523: return $db->delete($this, array($this->alias . '.' . $this->primaryKey => $ids));
2524: }
2525: }
2526: }
2527:
2528: /**
2529: * Collects foreign keys from associations.
2530: *
2531: * @param string $type
2532: * @return array
2533: */
2534: protected function _collectForeignKeys($type = 'belongsTo') {
2535: $result = array();
2536:
2537: foreach ($this->{$type} as $assoc => $data) {
2538: if (isset($data['foreignKey']) && is_string($data['foreignKey'])) {
2539: $result[$assoc] = $data['foreignKey'];
2540: }
2541: }
2542: return $result;
2543: }
2544:
2545: /**
2546: * Returns true if a record with particular ID exists.
2547: *
2548: * If $id is not passed it calls Model::getID() to obtain the current record ID,
2549: * and then performs a Model::find('count') on the currently configured datasource
2550: * to ascertain the existence of the record in persistent storage.
2551: *
2552: * @param integer|string $id ID of record to check for existence
2553: * @return boolean True if such a record exists
2554: */
2555: public function exists($id = null) {
2556: if ($id === null) {
2557: $id = $this->getID();
2558: }
2559: if ($id === false) {
2560: return false;
2561: }
2562: $conditions = array($this->alias . '.' . $this->primaryKey => $id);
2563: $query = array('conditions' => $conditions, 'recursive' => -1, 'callbacks' => false);
2564: return ($this->find('count', $query) > 0);
2565: }
2566:
2567: /**
2568: * Returns true if a record that meets given conditions exists.
2569: *
2570: * @param array $conditions SQL conditions array
2571: * @return boolean True if such a record exists
2572: */
2573: public function hasAny($conditions = null) {
2574: return ($this->find('count', array('conditions' => $conditions, 'recursive' => -1)) != false);
2575: }
2576:
2577: /**
2578: * Queries the datasource and returns a result set array.
2579: *
2580: * Also used to perform notation finds, where the first argument is type of find operation to perform
2581: * (all / first / count / neighbors / list / threaded),
2582: * second parameter options for finding ( indexed array, including: 'conditions', 'limit',
2583: * 'recursive', 'page', 'fields', 'offset', 'order')
2584: *
2585: * Eg:
2586: * {{{
2587: * find('all', array(
2588: * 'conditions' => array('name' => 'Thomas Anderson'),
2589: * 'fields' => array('name', 'email'),
2590: * 'order' => 'field3 DESC',
2591: * 'recursive' => 2,
2592: * 'group' => 'type'
2593: * ));
2594: * }}}
2595: *
2596: * In addition to the standard query keys above, you can provide Datasource, and behavior specific
2597: * keys. For example, when using a SQL based datasource you can use the joins key to specify additional
2598: * joins that should be part of the query.
2599: *
2600: * {{{
2601: * find('all', array(
2602: * 'conditions' => array('name' => 'Thomas Anderson'),
2603: * 'joins' => array(
2604: * array(
2605: * 'alias' => 'Thought',
2606: * 'table' => 'thoughts',
2607: * 'type' => 'LEFT',
2608: * 'conditions' => '`Thought`.`person_id` = `Person`.`id`'
2609: * )
2610: * )
2611: * ));
2612: * }}}
2613: *
2614: * Behaviors and find types can also define custom finder keys which are passed into find().
2615: *
2616: * Specifying 'fields' for notation 'list':
2617: *
2618: * - If no fields are specified, then 'id' is used for key and 'model->displayField' is used for value.
2619: * - If a single field is specified, 'id' is used for key and specified field is used for value.
2620: * - If three fields are specified, they are used (in order) for key, value and group.
2621: * - Otherwise, first and second fields are used for key and value.
2622: *
2623: * Note: find(list) + database views have issues with MySQL 5.0. Try upgrading to MySQL 5.1 if you
2624: * have issues with database views.
2625: *
2626: * Note: find(count) has its own return values.
2627: *
2628: * @param string $type Type of find operation (all / first / count / neighbors / list / threaded)
2629: * @param array $query Option fields (conditions / fields / joins / limit / offset / order / page / group / callbacks)
2630: * @return array Array of records, or Null on failure.
2631: * @link http://book.cakephp.org/2.0/en/models/retrieving-your-data.html
2632: */
2633: public function find($type = 'first', $query = array()) {
2634: $this->findQueryType = $type;
2635: $this->id = $this->getID();
2636:
2637: $query = $this->buildQuery($type, $query);
2638: if (is_null($query)) {
2639: return null;
2640: }
2641:
2642: $results = $this->getDataSource()->read($this, $query);
2643: $this->resetAssociations();
2644:
2645: if ($query['callbacks'] === true || $query['callbacks'] === 'after') {
2646: $results = $this->_filterResults($results);
2647: }
2648:
2649: $this->findQueryType = null;
2650:
2651: if ($type === 'all') {
2652: return $results;
2653: }
2654:
2655: if ($this->findMethods[$type] === true) {
2656: return $this->{'_find' . ucfirst($type)}('after', $query, $results);
2657: }
2658: }
2659:
2660: /**
2661: * Builds the query array that is used by the data source to generate the query to fetch the data.
2662: *
2663: * @param string $type Type of find operation (all / first / count / neighbors / list / threaded)
2664: * @param array $query Option fields (conditions / fields / joins / limit / offset / order / page / group / callbacks)
2665: * @return array Query array or null if it could not be build for some reasons
2666: * @see Model::find()
2667: */
2668: public function buildQuery($type = 'first', $query = array()) {
2669: $query = array_merge(
2670: array(
2671: 'conditions' => null, 'fields' => null, 'joins' => array(), 'limit' => null,
2672: 'offset' => null, 'order' => null, 'page' => 1, 'group' => null, 'callbacks' => true,
2673: ),
2674: (array)$query
2675: );
2676:
2677: if ($type !== 'all') {
2678: if ($this->findMethods[$type] === true) {
2679: $query = $this->{'_find' . ucfirst($type)}('before', $query);
2680: }
2681: }
2682:
2683: if (!is_numeric($query['page']) || intval($query['page']) < 1) {
2684: $query['page'] = 1;
2685: }
2686: if ($query['page'] > 1 && !empty($query['limit'])) {
2687: $query['offset'] = ($query['page'] - 1) * $query['limit'];
2688: }
2689: if ($query['order'] === null && $this->order !== null) {
2690: $query['order'] = $this->order;
2691: }
2692: $query['order'] = array($query['order']);
2693:
2694: if ($query['callbacks'] === true || $query['callbacks'] === 'before') {
2695: $event = new CakeEvent('Model.beforeFind', $this, array($query));
2696: list($event->break, $event->breakOn, $event->modParams) = array(true, array(false, null), 0);
2697: $this->getEventManager()->dispatch($event);
2698: if ($event->isStopped()) {
2699: return null;
2700: }
2701: $query = $event->result === true ? $event->data[0] : $event->result;
2702: }
2703:
2704: return $query;
2705: }
2706:
2707: /**
2708: * Handles the before/after filter logic for find('first') operations. Only called by Model::find().
2709: *
2710: * @param string $state Either "before" or "after"
2711: * @param array $query
2712: * @param array $results
2713: * @return array
2714: * @see Model::find()
2715: */
2716: protected function _findFirst($state, $query, $results = array()) {
2717: if ($state === 'before') {
2718: $query['limit'] = 1;
2719: return $query;
2720: } elseif ($state === 'after') {
2721: if (empty($results[0])) {
2722: return array();
2723: }
2724: return $results[0];
2725: }
2726: }
2727:
2728: /**
2729: * Handles the before/after filter logic for find('count') operations. Only called by Model::find().
2730: *
2731: * @param string $state Either "before" or "after"
2732: * @param array $query
2733: * @param array $results
2734: * @return integer The number of records found, or false
2735: * @see Model::find()
2736: */
2737: protected function _findCount($state, $query, $results = array()) {
2738: if ($state === 'before') {
2739: if (!empty($query['type']) && isset($this->findMethods[$query['type']]) && $query['type'] !== 'count' ) {
2740: $query['operation'] = 'count';
2741: $query = $this->{'_find' . ucfirst($query['type'])}('before', $query);
2742: }
2743: $db = $this->getDataSource();
2744: $query['order'] = false;
2745: if (!method_exists($db, 'calculate')) {
2746: return $query;
2747: }
2748: if (!empty($query['fields']) && is_array($query['fields'])) {
2749: if (!preg_match('/^count/i', current($query['fields']))) {
2750: unset($query['fields']);
2751: }
2752: }
2753: if (empty($query['fields'])) {
2754: $query['fields'] = $db->calculate($this, 'count');
2755: } elseif (method_exists($db, 'expression') && is_string($query['fields']) && !preg_match('/count/i', $query['fields'])) {
2756: $query['fields'] = $db->calculate($this, 'count', array(
2757: $db->expression($query['fields']), 'count'
2758: ));
2759: }
2760: return $query;
2761: } elseif ($state === 'after') {
2762: foreach (array(0, $this->alias) as $key) {
2763: if (isset($results[0][$key]['count'])) {
2764: if ($query['group']) {
2765: return count($results);
2766: } else {
2767: return intval($results[0][$key]['count']);
2768: }
2769: }
2770: }
2771: return false;
2772: }
2773: }
2774:
2775: /**
2776: * Handles the before/after filter logic for find('list') operations. Only called by Model::find().
2777: *
2778: * @param string $state Either "before" or "after"
2779: * @param array $query
2780: * @param array $results
2781: * @return array Key/value pairs of primary keys/display field values of all records found
2782: * @see Model::find()
2783: */
2784: protected function _findList($state, $query, $results = array()) {
2785: if ($state === 'before') {
2786: if (empty($query['fields'])) {
2787: $query['fields'] = array("{$this->alias}.{$this->primaryKey}", "{$this->alias}.{$this->displayField}");
2788: $list = array("{n}.{$this->alias}.{$this->primaryKey}", "{n}.{$this->alias}.{$this->displayField}", null);
2789: } else {
2790: if (!is_array($query['fields'])) {
2791: $query['fields'] = String::tokenize($query['fields']);
2792: }
2793:
2794: if (count($query['fields']) === 1) {
2795: if (strpos($query['fields'][0], '.') === false) {
2796: $query['fields'][0] = $this->alias . '.' . $query['fields'][0];
2797: }
2798:
2799: $list = array("{n}.{$this->alias}.{$this->primaryKey}", '{n}.' . $query['fields'][0], null);
2800: $query['fields'] = array("{$this->alias}.{$this->primaryKey}", $query['fields'][0]);
2801: } elseif (count($query['fields']) === 3) {
2802: for ($i = 0; $i < 3; $i++) {
2803: if (strpos($query['fields'][$i], '.') === false) {
2804: $query['fields'][$i] = $this->alias . '.' . $query['fields'][$i];
2805: }
2806: }
2807:
2808: $list = array('{n}.' . $query['fields'][0], '{n}.' . $query['fields'][1], '{n}.' . $query['fields'][2]);
2809: } else {
2810: for ($i = 0; $i < 2; $i++) {
2811: if (strpos($query['fields'][$i], '.') === false) {
2812: $query['fields'][$i] = $this->alias . '.' . $query['fields'][$i];
2813: }
2814: }
2815:
2816: $list = array('{n}.' . $query['fields'][0], '{n}.' . $query['fields'][1], null);
2817: }
2818: }
2819: if (!isset($query['recursive']) || $query['recursive'] === null) {
2820: $query['recursive'] = -1;
2821: }
2822: list($query['list']['keyPath'], $query['list']['valuePath'], $query['list']['groupPath']) = $list;
2823: return $query;
2824: } elseif ($state === 'after') {
2825: if (empty($results)) {
2826: return array();
2827: }
2828: $lst = $query['list'];
2829: return Hash::combine($results, $lst['keyPath'], $lst['valuePath'], $lst['groupPath']);
2830: }
2831: }
2832:
2833: /**
2834: * Detects the previous field's value, then uses logic to find the 'wrapping'
2835: * rows and return them.
2836: *
2837: * @param string $state Either "before" or "after"
2838: * @param array $query
2839: * @param array $results
2840: * @return array
2841: */
2842: protected function _findNeighbors($state, $query, $results = array()) {
2843: if ($state === 'before') {
2844: extract($query);
2845: $conditions = (array)$conditions;
2846: if (isset($field) && isset($value)) {
2847: if (strpos($field, '.') === false) {
2848: $field = $this->alias . '.' . $field;
2849: }
2850: } else {
2851: $field = $this->alias . '.' . $this->primaryKey;
2852: $value = $this->id;
2853: }
2854: $query['conditions'] = array_merge($conditions, array($field . ' <' => $value));
2855: $query['order'] = $field . ' DESC';
2856: $query['limit'] = 1;
2857: $query['field'] = $field;
2858: $query['value'] = $value;
2859: return $query;
2860: } elseif ($state === 'after') {
2861: extract($query);
2862: unset($query['conditions'][$field . ' <']);
2863: $return = array();
2864: if (isset($results[0])) {
2865: $prevVal = Hash::get($results[0], $field);
2866: $query['conditions'][$field . ' >='] = $prevVal;
2867: $query['conditions'][$field . ' !='] = $value;
2868: $query['limit'] = 2;
2869: } else {
2870: $return['prev'] = null;
2871: $query['conditions'][$field . ' >'] = $value;
2872: $query['limit'] = 1;
2873: }
2874: $query['order'] = $field . ' ASC';
2875: $neighbors = $this->find('all', $query);
2876: if (!array_key_exists('prev', $return)) {
2877: $return['prev'] = isset($neighbors[0]) ? $neighbors[0] : null;
2878: }
2879: if (count($neighbors) === 2) {
2880: $return['next'] = $neighbors[1];
2881: } elseif (count($neighbors) === 1 && !$return['prev']) {
2882: $return['next'] = $neighbors[0];
2883: } else {
2884: $return['next'] = null;
2885: }
2886: return $return;
2887: }
2888: }
2889:
2890: /**
2891: * In the event of ambiguous results returned (multiple top level results, with different parent_ids)
2892: * top level results with different parent_ids to the first result will be dropped
2893: *
2894: * @param string $state
2895: * @param mixed $query
2896: * @param array $results
2897: * @return array Threaded results
2898: */
2899: protected function _findThreaded($state, $query, $results = array()) {
2900: if ($state === 'before') {
2901: return $query;
2902: } elseif ($state === 'after') {
2903: $parent = 'parent_id';
2904: if (isset($query['parent'])) {
2905: $parent = $query['parent'];
2906: }
2907: return Hash::nest($results, array(
2908: 'idPath' => '{n}.' . $this->alias . '.' . $this->primaryKey,
2909: 'parentPath' => '{n}.' . $this->alias . '.' . $parent
2910: ));
2911: }
2912: }
2913:
2914: /**
2915: * Passes query results through model and behavior afterFilter() methods.
2916: *
2917: * @param array $results Results to filter
2918: * @param boolean $primary If this is the primary model results (results from model where the find operation was performed)
2919: * @return array Set of filtered results
2920: */
2921: protected function _filterResults($results, $primary = true) {
2922: $event = new CakeEvent('Model.afterFind', $this, array($results, $primary));
2923: $event->modParams = 0;
2924: $this->getEventManager()->dispatch($event);
2925: return $event->result;
2926: }
2927:
2928: /**
2929: * This resets the association arrays for the model back
2930: * to those originally defined in the model. Normally called at the end
2931: * of each call to Model::find()
2932: *
2933: * @return boolean Success
2934: */
2935: public function resetAssociations() {
2936: if (!empty($this->__backAssociation)) {
2937: foreach ($this->_associations as $type) {
2938: if (isset($this->__backAssociation[$type])) {
2939: $this->{$type} = $this->__backAssociation[$type];
2940: }
2941: }
2942: $this->__backAssociation = array();
2943: }
2944:
2945: foreach ($this->_associations as $type) {
2946: foreach ($this->{$type} as $key => $name) {
2947: if (property_exists($this, $key) && !empty($this->{$key}->__backAssociation)) {
2948: $this->{$key}->resetAssociations();
2949: }
2950: }
2951: }
2952: $this->__backAssociation = array();
2953: return true;
2954: }
2955:
2956: /**
2957: * Returns false if any fields passed match any (by default, all if $or = false) of their matching values.
2958: *
2959: * @param array $fields Field/value pairs to search (if no values specified, they are pulled from $this->data)
2960: * @param boolean $or If false, all fields specified must match in order for a false return value
2961: * @return boolean False if any records matching any fields are found
2962: */
2963: public function isUnique($fields, $or = true) {
2964: if (!is_array($fields)) {
2965: $fields = func_get_args();
2966: if (is_bool($fields[count($fields) - 1])) {
2967: $or = $fields[count($fields) - 1];
2968: unset($fields[count($fields) - 1]);
2969: }
2970: }
2971:
2972: foreach ($fields as $field => $value) {
2973: if (is_numeric($field)) {
2974: unset($fields[$field]);
2975:
2976: $field = $value;
2977: if (isset($this->data[$this->alias][$field])) {
2978: $value = $this->data[$this->alias][$field];
2979: } else {
2980: $value = null;
2981: }
2982: }
2983:
2984: if (strpos($field, '.') === false) {
2985: unset($fields[$field]);
2986: $fields[$this->alias . '.' . $field] = $value;
2987: }
2988: }
2989: if ($or) {
2990: $fields = array('or' => $fields);
2991: }
2992: if (!empty($this->id)) {
2993: $fields[$this->alias . '.' . $this->primaryKey . ' !='] = $this->id;
2994: }
2995: return ($this->find('count', array('conditions' => $fields, 'recursive' => -1)) == 0);
2996: }
2997:
2998: /**
2999: * Returns a resultset for a given SQL statement. Custom SQL queries should be performed with this method.
3000: *
3001: * @param string $sql,... SQL statement
3002: * @return mixed Resultset array or boolean indicating success / failure depending on the query executed
3003: * @link http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-query
3004: */
3005: public function query($sql) {
3006: $params = func_get_args();
3007: $db = $this->getDataSource();
3008: return call_user_func_array(array(&$db, 'query'), $params);
3009: }
3010:
3011: /**
3012: * Returns true if all fields pass validation. Will validate hasAndBelongsToMany associations
3013: * that use the 'with' key as well. Since _saveMulti is incapable of exiting a save operation.
3014: *
3015: * Will validate the currently set data. Use Model::set() or Model::create() to set the active data.
3016: *
3017: * @param array $options An optional array of custom options to be made available in the beforeValidate callback
3018: * @return boolean True if there are no errors
3019: */
3020: public function validates($options = array()) {
3021: return $this->validator()->validates($options);
3022: }
3023:
3024: /**
3025: * Returns an array of fields that have failed validation. On the current model.
3026: *
3027: * @param string $options An optional array of custom options to be made available in the beforeValidate callback
3028: * @return array Array of invalid fields
3029: * @see Model::validates()
3030: */
3031: public function invalidFields($options = array()) {
3032: return $this->validator()->errors($options);
3033: }
3034:
3035: /**
3036: * Marks a field as invalid, optionally setting the name of validation
3037: * rule (in case of multiple validation for field) that was broken.
3038: *
3039: * @param string $field The name of the field to invalidate
3040: * @param mixed $value Name of validation rule that was not failed, or validation message to
3041: * be returned. If no validation key is provided, defaults to true.
3042: * @return void
3043: */
3044: public function invalidate($field, $value = true) {
3045: $this->validator()->invalidate($field, $value);
3046: }
3047:
3048: /**
3049: * Returns true if given field name is a foreign key in this model.
3050: *
3051: * @param string $field Returns true if the input string ends in "_id"
3052: * @return boolean True if the field is a foreign key listed in the belongsTo array.
3053: */
3054: public function isForeignKey($field) {
3055: $foreignKeys = array();
3056: if (!empty($this->belongsTo)) {
3057: foreach ($this->belongsTo as $data) {
3058: $foreignKeys[] = $data['foreignKey'];
3059: }
3060: }
3061: return in_array($field, $foreignKeys);
3062: }
3063:
3064: /**
3065: * Escapes the field name and prepends the model name. Escaping is done according to the
3066: * current database driver's rules.
3067: *
3068: * @param string $field Field to escape (e.g: id)
3069: * @param string $alias Alias for the model (e.g: Post)
3070: * @return string The name of the escaped field for this Model (i.e. id becomes `Post`.`id`).
3071: */
3072: public function escapeField($field = null, $alias = null) {
3073: if (empty($alias)) {
3074: $alias = $this->alias;
3075: }
3076: if (empty($field)) {
3077: $field = $this->primaryKey;
3078: }
3079: $db = $this->getDataSource();
3080: if (strpos($field, $db->name($alias) . '.') === 0) {
3081: return $field;
3082: }
3083: return $db->name($alias . '.' . $field);
3084: }
3085:
3086: /**
3087: * Returns the current record's ID
3088: *
3089: * @param integer $list Index on which the composed ID is located
3090: * @return mixed The ID of the current record, false if no ID
3091: */
3092: public function getID($list = 0) {
3093: if (empty($this->id) || (is_array($this->id) && isset($this->id[0]) && empty($this->id[0]))) {
3094: return false;
3095: }
3096:
3097: if (!is_array($this->id)) {
3098: return $this->id;
3099: }
3100:
3101: if (isset($this->id[$list]) && !empty($this->id[$list])) {
3102: return $this->id[$list];
3103: } elseif (isset($this->id[$list])) {
3104: return false;
3105: }
3106:
3107: return current($this->id);
3108: }
3109:
3110: /**
3111: * Returns the ID of the last record this model inserted.
3112: *
3113: * @return mixed Last inserted ID
3114: */
3115: public function getLastInsertID() {
3116: return $this->getInsertID();
3117: }
3118:
3119: /**
3120: * Returns the ID of the last record this model inserted.
3121: *
3122: * @return mixed Last inserted ID
3123: */
3124: public function getInsertID() {
3125: return $this->_insertID;
3126: }
3127:
3128: /**
3129: * Sets the ID of the last record this model inserted
3130: *
3131: * @param integer|string $id Last inserted ID
3132: * @return void
3133: */
3134: public function setInsertID($id) {
3135: $this->_insertID = $id;
3136: }
3137:
3138: /**
3139: * Returns the number of rows returned from the last query.
3140: *
3141: * @return integer Number of rows
3142: */
3143: public function getNumRows() {
3144: return $this->getDataSource()->lastNumRows();
3145: }
3146:
3147: /**
3148: * Returns the number of rows affected by the last query.
3149: *
3150: * @return integer Number of rows
3151: */
3152: public function getAffectedRows() {
3153: return $this->getDataSource()->lastAffected();
3154: }
3155:
3156: /**
3157: * Sets the DataSource to which this model is bound.
3158: *
3159: * @param string $dataSource The name of the DataSource, as defined in app/Config/database.php
3160: * @return void
3161: * @throws MissingConnectionException
3162: */
3163: public function setDataSource($dataSource = null) {
3164: $oldConfig = $this->useDbConfig;
3165:
3166: if ($dataSource != null) {
3167: $this->useDbConfig = $dataSource;
3168: }
3169: $db = ConnectionManager::getDataSource($this->useDbConfig);
3170: if (!empty($oldConfig) && isset($db->config['prefix'])) {
3171: $oldDb = ConnectionManager::getDataSource($oldConfig);
3172:
3173: if (!isset($this->tablePrefix) || (!isset($oldDb->config['prefix']) || $this->tablePrefix == $oldDb->config['prefix'])) {
3174: $this->tablePrefix = $db->config['prefix'];
3175: }
3176: } elseif (isset($db->config['prefix'])) {
3177: $this->tablePrefix = $db->config['prefix'];
3178: }
3179:
3180: $this->schemaName = $db->getSchemaName();
3181: }
3182:
3183: /**
3184: * Gets the DataSource to which this model is bound.
3185: *
3186: * @return DataSource A DataSource object
3187: */
3188: public function getDataSource() {
3189: if (!$this->_sourceConfigured && $this->useTable !== false) {
3190: $this->_sourceConfigured = true;
3191: $this->setSource($this->useTable);
3192: }
3193: return ConnectionManager::getDataSource($this->useDbConfig);
3194: }
3195:
3196: /**
3197: * Get associations
3198: *
3199: * @return array
3200: */
3201: public function associations() {
3202: return $this->_associations;
3203: }
3204:
3205: /**
3206: * Gets all the models with which this model is associated.
3207: *
3208: * @param string $type Only result associations of this type
3209: * @return array Associations
3210: */
3211: public function getAssociated($type = null) {
3212: if ($type == null) {
3213: $associated = array();
3214: foreach ($this->_associations as $assoc) {
3215: if (!empty($this->{$assoc})) {
3216: $models = array_keys($this->{$assoc});
3217: foreach ($models as $m) {
3218: $associated[$m] = $assoc;
3219: }
3220: }
3221: }
3222: return $associated;
3223: } elseif (in_array($type, $this->_associations)) {
3224: if (empty($this->{$type})) {
3225: return array();
3226: }
3227: return array_keys($this->{$type});
3228: } else {
3229: $assoc = array_merge(
3230: $this->hasOne,
3231: $this->hasMany,
3232: $this->belongsTo,
3233: $this->hasAndBelongsToMany
3234: );
3235: if (array_key_exists($type, $assoc)) {
3236: foreach ($this->_associations as $a) {
3237: if (isset($this->{$a}[$type])) {
3238: $assoc[$type]['association'] = $a;
3239: break;
3240: }
3241: }
3242: return $assoc[$type];
3243: }
3244: return null;
3245: }
3246: }
3247:
3248: /**
3249: * Gets the name and fields to be used by a join model. This allows specifying join fields
3250: * in the association definition.
3251: *
3252: * @param string|array $assoc The model to be joined
3253: * @param array $keys Any join keys which must be merged with the keys queried
3254: * @return array
3255: */
3256: public function joinModel($assoc, $keys = array()) {
3257: if (is_string($assoc)) {
3258: list(, $assoc) = pluginSplit($assoc);
3259: return array($assoc, array_keys($this->{$assoc}->schema()));
3260: } elseif (is_array($assoc)) {
3261: $with = key($assoc);
3262: return array($with, array_unique(array_merge($assoc[$with], $keys)));
3263: }
3264: trigger_error(
3265: __d('cake_dev', 'Invalid join model settings in %s. The association parameter has the wrong type, expecting a string or array, but was passed type: %s', $this->alias, gettype($assoc)),
3266: E_USER_WARNING
3267: );
3268: }
3269:
3270: /**
3271: * Called before each find operation. Return false if you want to halt the find
3272: * call, otherwise return the (modified) query data.
3273: *
3274: * @param array $queryData Data used to execute this query, i.e. conditions, order, etc.
3275: * @return mixed true if the operation should continue, false if it should abort; or, modified
3276: * $queryData to continue with new $queryData
3277: * @link http://book.cakephp.org/2.0/en/models/callback-methods.html#beforefind
3278: */
3279: public function beforeFind($queryData) {
3280: return true;
3281: }
3282:
3283: /**
3284: * Called after each find operation. Can be used to modify any results returned by find().
3285: * Return value should be the (modified) results.
3286: *
3287: * @param mixed $results The results of the find operation
3288: * @param boolean $primary Whether this model is being queried directly (vs. being queried as an association)
3289: * @return mixed Result of the find operation
3290: * @link http://book.cakephp.org/2.0/en/models/callback-methods.html#afterfind
3291: */
3292: public function afterFind($results, $primary = false) {
3293: return $results;
3294: }
3295:
3296: /**
3297: * Called before each save operation, after validation. Return a non-true result
3298: * to halt the save.
3299: *
3300: * @param array $options
3301: * @return boolean True if the operation should continue, false if it should abort
3302: * @link http://book.cakephp.org/2.0/en/models/callback-methods.html#beforesave
3303: */
3304: public function beforeSave($options = array()) {
3305: return true;
3306: }
3307:
3308: /**
3309: * Called after each successful save operation.
3310: *
3311: * @param boolean $created True if this save created a new record
3312: * @return void
3313: * @link http://book.cakephp.org/2.0/en/models/callback-methods.html#aftersave
3314: */
3315: public function afterSave($created) {
3316: }
3317:
3318: /**
3319: * Called before every deletion operation.
3320: *
3321: * @param boolean $cascade If true records that depend on this record will also be deleted
3322: * @return boolean True if the operation should continue, false if it should abort
3323: * @link http://book.cakephp.org/2.0/en/models/callback-methods.html#beforedelete
3324: */
3325: public function beforeDelete($cascade = true) {
3326: return true;
3327: }
3328:
3329: /**
3330: * Called after every deletion operation.
3331: *
3332: * @return void
3333: * @link http://book.cakephp.org/2.0/en/models/callback-methods.html#afterdelete
3334: */
3335: public function afterDelete() {
3336: }
3337:
3338: /**
3339: * Called during validation operations, before validation. Please note that custom
3340: * validation rules can be defined in $validate.
3341: *
3342: * @param array $options Options passed from model::save(), see $options of model::save().
3343: * @return boolean True if validate operation should continue, false to abort
3344: * @link http://book.cakephp.org/2.0/en/models/callback-methods.html#beforevalidate
3345: */
3346: public function beforeValidate($options = array()) {
3347: return true;
3348: }
3349:
3350: /**
3351: * Called after data has been checked for errors
3352: *
3353: * @return void
3354: */
3355: public function afterValidate() {
3356: }
3357:
3358: /**
3359: * Called when a DataSource-level error occurs.
3360: *
3361: * @return void
3362: * @link http://book.cakephp.org/2.0/en/models/callback-methods.html#onerror
3363: */
3364: public function onError() {
3365: }
3366:
3367: /**
3368: * Clears cache for this model.
3369: *
3370: * @param string $type If null this deletes cached views if Cache.check is true
3371: * Will be used to allow deleting query cache also
3372: * @return boolean true on delete
3373: */
3374: protected function _clearCache($type = null) {
3375: if ($type === null) {
3376: if (Configure::read('Cache.check') === true) {
3377: $assoc[] = strtolower(Inflector::pluralize($this->alias));
3378: $assoc[] = strtolower(Inflector::underscore(Inflector::pluralize($this->alias)));
3379: foreach ($this->_associations as $key => $association) {
3380: foreach ($this->$association as $key => $className) {
3381: $check = strtolower(Inflector::pluralize($className['className']));
3382: if (!in_array($check, $assoc)) {
3383: $assoc[] = strtolower(Inflector::pluralize($className['className']));
3384: $assoc[] = strtolower(Inflector::underscore(Inflector::pluralize($className['className'])));
3385: }
3386: }
3387: }
3388: clearCache($assoc);
3389: return true;
3390: }
3391: } else {
3392: //Will use for query cache deleting
3393: }
3394: }
3395:
3396: /**
3397: * Retunrs an instance of a model validator for this class
3398: *
3399: * @return ModelValidator
3400: */
3401: public function validator($instance = null) {
3402: if ($instance instanceof ModelValidator) {
3403: return $this->_validator = $instance;
3404: }
3405:
3406: if (empty($this->_validator) && is_null($instance)) {
3407: $this->_validator = new ModelValidator($this);
3408: }
3409:
3410: return $this->_validator;
3411: }
3412:
3413: }
3414: