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