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 (https://cakephp.org)
8: * Copyright (c) Cake Software Foundation, Inc. (https://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. (https://cakefoundation.org)
15: * @link https://cakephp.org CakePHP(tm) Project
16: * @package Cake.Model
17: * @since CakePHP(tm) v 0.10.0.0
18: * @license https://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 https://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 https://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|false
62: * @link https://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|false
72: * @link https://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|false
88: * @link https://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 https://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 https://book.cakephp.org/2.0/en/models/model-attributes.html#validate
210: * @link https://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 https://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 https://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 https://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 https://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 https://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 https://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 https://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 https://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 https://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 https://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 https://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|string
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|false $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 https://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 https://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|false $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 https://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]) || substr($data[$val], 0, 1) === '-')) {
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 https://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|false Array of database fields, or false if not found
1618: * @link https://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|array $order SQL ORDER BY fragment.
1652: * @return string|false Field content, or false if not found.
1653: * @link https://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 && !in_array($this->id, array(false, null), true)) {
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: * @deprecated 3.0.0 To ease migration to the new major, do not use this method anymore.
1699: * Stateful model usage will be removed. Use the existing save() methods instead.
1700: * @see Model::save()
1701: * @link https://book.cakephp.org/2.0/en/models/saving-your-data.html#model-savefield-string-fieldname-string-fieldvalue-validate-false
1702: */
1703: public function saveField($name, $value, $validate = false) {
1704: $id = $this->id;
1705: $this->create(false);
1706:
1707: $options = array('validate' => $validate, 'fieldList' => array($name));
1708: if (is_array($validate)) {
1709: $options = $validate + array('validate' => false, 'fieldList' => array($name));
1710: }
1711:
1712: return $this->save(array($this->alias => array($this->primaryKey => $id, $name => $value)), $options);
1713: }
1714:
1715: /**
1716: * Saves model data (based on white-list, if supplied) to the database. By
1717: * default, validation occurs before save. Passthrough method to _doSave() with
1718: * transaction handling.
1719: *
1720: * @param array $data Data to save.
1721: * @param bool|array $validate Either a boolean, or an array.
1722: * If a boolean, indicates whether or not to validate before saving.
1723: * If an array, can have following keys:
1724: *
1725: * - atomic: If true (default), will attempt to save the record in a single transaction.
1726: * - validate: Set to true/false to enable or disable validation.
1727: * - fieldList: An array of fields you want to allow for saving.
1728: * - callbacks: Set to false to disable callbacks. Using 'before' or 'after'
1729: * will enable only those callbacks.
1730: * - `counterCache`: Boolean to control updating of counter caches (if any)
1731: *
1732: * @param array $fieldList List of fields to allow to be saved
1733: * @return mixed On success Model::$data if its not empty or true, false on failure
1734: * @throws Exception
1735: * @throws PDOException
1736: * @triggers Model.beforeSave $this, array($options)
1737: * @triggers Model.afterSave $this, array($created, $options)
1738: * @link https://book.cakephp.org/2.0/en/models/saving-your-data.html
1739: */
1740: public function save($data = null, $validate = true, $fieldList = array()) {
1741: $defaults = array(
1742: 'validate' => true, 'fieldList' => array(),
1743: 'callbacks' => true, 'counterCache' => true,
1744: 'atomic' => true
1745: );
1746:
1747: if (!is_array($validate)) {
1748: $options = compact('validate', 'fieldList') + $defaults;
1749: } else {
1750: $options = $validate + $defaults;
1751: }
1752:
1753: if (!$options['atomic']) {
1754: return $this->_doSave($data, $options);
1755: }
1756:
1757: $db = $this->getDataSource();
1758: $transactionBegun = $db->begin();
1759: try {
1760: $success = $this->_doSave($data, $options);
1761: if ($transactionBegun) {
1762: if ($success) {
1763: $db->commit();
1764: } else {
1765: $db->rollback();
1766: }
1767: }
1768: return $success;
1769: } catch (Exception $e) {
1770: if ($transactionBegun) {
1771: $db->rollback();
1772: }
1773: throw $e;
1774: }
1775: }
1776:
1777: /**
1778: * Saves model data (based on white-list, if supplied) to the database. By
1779: * default, validation occurs before save.
1780: *
1781: * @param array $data Data to save.
1782: * @param array $options can have following keys:
1783: *
1784: * - validate: Set to true/false to enable or disable validation.
1785: * - fieldList: An array of fields you want to allow for saving.
1786: * - callbacks: Set to false to disable callbacks. Using 'before' or 'after'
1787: * will enable only those callbacks.
1788: * - `counterCache`: Boolean to control updating of counter caches (if any)
1789: *
1790: * @return mixed On success Model::$data if its not empty or true, false on failure
1791: * @throws PDOException
1792: * @link https://book.cakephp.org/2.0/en/models/saving-your-data.html
1793: */
1794: protected function _doSave($data = null, $options = array()) {
1795: $_whitelist = $this->whitelist;
1796: $fields = array();
1797:
1798: if (!empty($options['fieldList'])) {
1799: if (!empty($options['fieldList'][$this->alias]) && is_array($options['fieldList'][$this->alias])) {
1800: $this->whitelist = $options['fieldList'][$this->alias];
1801: } elseif (Hash::dimensions($options['fieldList']) < 2) {
1802: $this->whitelist = $options['fieldList'];
1803: }
1804: } elseif ($options['fieldList'] === null) {
1805: $this->whitelist = array();
1806: }
1807:
1808: $this->set($data);
1809:
1810: if (empty($this->data) && !$this->hasField(array('created', 'updated', 'modified'))) {
1811: $this->whitelist = $_whitelist;
1812: return false;
1813: }
1814:
1815: foreach (array('created', 'updated', 'modified') as $field) {
1816: $keyPresentAndEmpty = (
1817: isset($this->data[$this->alias]) &&
1818: array_key_exists($field, $this->data[$this->alias]) &&
1819: $this->data[$this->alias][$field] === null
1820: );
1821:
1822: if ($keyPresentAndEmpty) {
1823: unset($this->data[$this->alias][$field]);
1824: }
1825: }
1826:
1827: $exists = $this->exists($this->getID());
1828: $dateFields = array('modified', 'updated');
1829:
1830: if (!$exists) {
1831: $dateFields[] = 'created';
1832: }
1833:
1834: if (isset($this->data[$this->alias])) {
1835: $fields = array_keys($this->data[$this->alias]);
1836: }
1837:
1838: if ($options['validate'] && !$this->validates($options)) {
1839: $this->whitelist = $_whitelist;
1840: return false;
1841: }
1842:
1843: $db = $this->getDataSource();
1844: $now = time();
1845:
1846: foreach ($dateFields as $updateCol) {
1847: $fieldHasValue = in_array($updateCol, $fields);
1848: $fieldInWhitelist = (
1849: count($this->whitelist) === 0 ||
1850: in_array($updateCol, $this->whitelist)
1851: );
1852: if (($fieldHasValue && $fieldInWhitelist) || !$this->hasField($updateCol)) {
1853: continue;
1854: }
1855:
1856: $default = array('formatter' => 'date');
1857: $colType = array_merge($default, $db->columns[$this->getColumnType($updateCol)]);
1858:
1859: $time = $now;
1860: if (array_key_exists('format', $colType)) {
1861: $time = call_user_func($colType['formatter'], $colType['format']);
1862: }
1863:
1864: if (!empty($this->whitelist)) {
1865: $this->whitelist[] = $updateCol;
1866: }
1867: $this->set($updateCol, $time);
1868: }
1869:
1870: if ($options['callbacks'] === true || $options['callbacks'] === 'before') {
1871: $event = new CakeEvent('Model.beforeSave', $this, array($options));
1872: list($event->break, $event->breakOn) = array(true, array(false, null));
1873: $this->getEventManager()->dispatch($event);
1874: if (!$event->result) {
1875: $this->whitelist = $_whitelist;
1876: return false;
1877: }
1878: }
1879:
1880: if (empty($this->data[$this->alias][$this->primaryKey])) {
1881: unset($this->data[$this->alias][$this->primaryKey]);
1882: }
1883: $joined = $fields = $values = array();
1884:
1885: foreach ($this->data as $n => $v) {
1886: if (isset($this->hasAndBelongsToMany[$n])) {
1887: if (isset($v[$n])) {
1888: $v = $v[$n];
1889: }
1890: $joined[$n] = $v;
1891: } elseif ($n === $this->alias) {
1892: foreach (array('created', 'updated', 'modified') as $field) {
1893: if (array_key_exists($field, $v) && empty($v[$field])) {
1894: unset($v[$field]);
1895: }
1896: }
1897:
1898: foreach ($v as $x => $y) {
1899: if ($this->hasField($x) && (empty($this->whitelist) || in_array($x, $this->whitelist))) {
1900: list($fields[], $values[]) = array($x, $y);
1901: }
1902: }
1903: }
1904: }
1905:
1906: if (empty($fields) && empty($joined)) {
1907: $this->whitelist = $_whitelist;
1908: return false;
1909: }
1910:
1911: $count = count($fields);
1912:
1913: if (!$exists && $count > 0) {
1914: $this->id = false;
1915: }
1916:
1917: $success = true;
1918: $created = false;
1919:
1920: if ($count > 0) {
1921: $cache = $this->_prepareUpdateFields(array_combine($fields, $values));
1922:
1923: if (!empty($this->id)) {
1924: $this->__safeUpdateMode = true;
1925: try {
1926: $success = (bool)$db->update($this, $fields, $values);
1927: } catch (Exception $e) {
1928: $this->__safeUpdateMode = false;
1929: throw $e;
1930: }
1931: $this->__safeUpdateMode = false;
1932: } else {
1933: if (empty($this->data[$this->alias][$this->primaryKey]) && $this->_isUUIDField($this->primaryKey)) {
1934: if (array_key_exists($this->primaryKey, $this->data[$this->alias])) {
1935: $j = array_search($this->primaryKey, $fields);
1936: $values[$j] = CakeText::uuid();
1937: } else {
1938: list($fields[], $values[]) = array($this->primaryKey, CakeText::uuid());
1939: }
1940: }
1941:
1942: if (!$db->create($this, $fields, $values)) {
1943: $success = false;
1944: } else {
1945: $created = true;
1946: }
1947: }
1948:
1949: if ($success && $options['counterCache'] && !empty($this->belongsTo)) {
1950: $this->updateCounterCache($cache, $created);
1951: }
1952: }
1953:
1954: if ($success && !empty($joined)) {
1955: $this->_saveMulti($joined, $this->id, $db);
1956: }
1957:
1958: if (!$success) {
1959: $this->whitelist = $_whitelist;
1960: return $success;
1961: }
1962:
1963: if ($count > 0) {
1964: if ($created) {
1965: $this->data[$this->alias][$this->primaryKey] = $this->id;
1966: }
1967:
1968: if ($options['callbacks'] === true || $options['callbacks'] === 'after') {
1969: $event = new CakeEvent('Model.afterSave', $this, array($created, $options));
1970: $this->getEventManager()->dispatch($event);
1971: }
1972: }
1973:
1974: if (!empty($this->data)) {
1975: $success = $this->data;
1976: }
1977:
1978: $this->_clearCache();
1979: $this->validationErrors = array();
1980: $this->whitelist = $_whitelist;
1981: $this->data = false;
1982:
1983: return $success;
1984: }
1985:
1986: /**
1987: * Check if the passed in field is a UUID field
1988: *
1989: * @param string $field the field to check
1990: * @return bool
1991: */
1992: protected function _isUUIDField($field) {
1993: $field = $this->schema($field);
1994: return $field !== null && $field['length'] == 36 && in_array($field['type'], array('string', 'binary', 'uuid'));
1995: }
1996:
1997: /**
1998: * Saves model hasAndBelongsToMany data to the database.
1999: *
2000: * @param array $joined Data to save
2001: * @param int|string $id ID of record in this model
2002: * @param DataSource $db Datasource instance.
2003: * @return void
2004: */
2005: protected function _saveMulti($joined, $id, $db) {
2006: foreach ($joined as $assoc => $data) {
2007: if (!isset($this->hasAndBelongsToMany[$assoc])) {
2008: continue;
2009: }
2010:
2011: $habtm = $this->hasAndBelongsToMany[$assoc];
2012:
2013: list($join) = $this->joinModel($habtm['with']);
2014:
2015: $Model = $this->{$join};
2016:
2017: if (!empty($habtm['with'])) {
2018: $withModel = is_array($habtm['with']) ? key($habtm['with']) : $habtm['with'];
2019: list(, $withModel) = pluginSplit($withModel);
2020: $dbMulti = $this->{$withModel}->getDataSource();
2021: } else {
2022: $dbMulti = $db;
2023: }
2024:
2025: $isUUID = !empty($Model->primaryKey) && $Model->_isUUIDField($Model->primaryKey);
2026:
2027: $newData = $newValues = $newJoins = array();
2028: $primaryAdded = false;
2029:
2030: $fields = array(
2031: $dbMulti->name($habtm['foreignKey']),
2032: $dbMulti->name($habtm['associationForeignKey'])
2033: );
2034:
2035: $idField = $db->name($Model->primaryKey);
2036: if ($isUUID && !in_array($idField, $fields)) {
2037: $fields[] = $idField;
2038: $primaryAdded = true;
2039: }
2040:
2041: foreach ((array)$data as $row) {
2042: if ((is_string($row) && (strlen($row) === 36 || strlen($row) === 16)) || is_numeric($row)) {
2043: $newJoins[] = $row;
2044: $values = array($id, $row);
2045:
2046: if ($isUUID && $primaryAdded) {
2047: $values[] = CakeText::uuid();
2048: }
2049:
2050: $newValues[$row] = $values;
2051: unset($values);
2052: } elseif (isset($row[$habtm['associationForeignKey']])) {
2053: if (!empty($row[$Model->primaryKey])) {
2054: $newJoins[] = $row[$habtm['associationForeignKey']];
2055: }
2056:
2057: $newData[] = $row;
2058: } elseif (isset($row[$join]) && isset($row[$join][$habtm['associationForeignKey']])) {
2059: if (!empty($row[$join][$Model->primaryKey])) {
2060: $newJoins[] = $row[$join][$habtm['associationForeignKey']];
2061: }
2062:
2063: $newData[] = $row[$join];
2064: }
2065: }
2066:
2067: $keepExisting = $habtm['unique'] === 'keepExisting';
2068: if ($habtm['unique']) {
2069: $conditions = array(
2070: $join . '.' . $habtm['foreignKey'] => $id
2071: );
2072:
2073: if (!empty($habtm['conditions'])) {
2074: $conditions = array_merge($conditions, (array)$habtm['conditions']);
2075: }
2076:
2077: $associationForeignKey = $Model->alias . '.' . $habtm['associationForeignKey'];
2078: $links = $Model->find('all', array(
2079: 'conditions' => $conditions,
2080: 'recursive' => empty($habtm['conditions']) ? -1 : 0,
2081: 'fields' => $associationForeignKey,
2082: ));
2083:
2084: $oldLinks = Hash::extract($links, "{n}.{$associationForeignKey}");
2085: if (!empty($oldLinks)) {
2086: if ($keepExisting && !empty($newJoins)) {
2087: $conditions[$associationForeignKey] = array_diff($oldLinks, $newJoins);
2088: } else {
2089: $conditions[$associationForeignKey] = $oldLinks;
2090: }
2091:
2092: $dbMulti->delete($Model, $conditions);
2093: }
2094: }
2095:
2096: if (!empty($newData)) {
2097: foreach ($newData as $data) {
2098: $data[$habtm['foreignKey']] = $id;
2099: if (empty($data[$Model->primaryKey])) {
2100: $Model->create();
2101: }
2102:
2103: $Model->save($data, array('atomic' => false));
2104: }
2105: }
2106:
2107: if (!empty($newValues)) {
2108: if ($keepExisting && !empty($links)) {
2109: foreach ($links as $link) {
2110: $oldJoin = $link[$join][$habtm['associationForeignKey']];
2111: if (!in_array($oldJoin, $newJoins)) {
2112: $conditions[$associationForeignKey] = $oldJoin;
2113: $db->delete($Model, $conditions);
2114: } else {
2115: unset($newValues[$oldJoin]);
2116: }
2117: }
2118:
2119: $newValues = array_values($newValues);
2120: }
2121:
2122: if (!empty($newValues)) {
2123: $dbMulti->insertMulti($Model, $fields, $newValues);
2124: }
2125: }
2126: }
2127: }
2128:
2129: /**
2130: * Updates the counter cache of belongsTo associations after a save or delete operation
2131: *
2132: * @param array $keys Optional foreign key data, defaults to the information $this->data
2133: * @param bool $created True if a new record was created, otherwise only associations with
2134: * 'counterScope' defined get updated
2135: * @return void
2136: */
2137: public function updateCounterCache($keys = array(), $created = false) {
2138: if (empty($keys) && isset($this->data[$this->alias])) {
2139: $keys = $this->data[$this->alias];
2140: }
2141: $keys['old'] = isset($keys['old']) ? $keys['old'] : array();
2142:
2143: foreach ($this->belongsTo as $parent => $assoc) {
2144: if (empty($assoc['counterCache'])) {
2145: continue;
2146: }
2147:
2148: $Model = $this->{$parent};
2149:
2150: if (!is_array($assoc['counterCache'])) {
2151: if (isset($assoc['counterScope'])) {
2152: $assoc['counterCache'] = array($assoc['counterCache'] => $assoc['counterScope']);
2153: } else {
2154: $assoc['counterCache'] = array($assoc['counterCache'] => array());
2155: }
2156: }
2157:
2158: $foreignKey = $assoc['foreignKey'];
2159: $fkQuoted = $this->escapeField($assoc['foreignKey']);
2160:
2161: foreach ($assoc['counterCache'] as $field => $conditions) {
2162: if (!is_string($field)) {
2163: $field = Inflector::underscore($this->alias) . '_count';
2164: }
2165:
2166: if (!$Model->hasField($field)) {
2167: continue;
2168: }
2169:
2170: if ($conditions === true) {
2171: $conditions = array();
2172: } else {
2173: $conditions = (array)$conditions;
2174: }
2175:
2176: if (!array_key_exists($foreignKey, $keys)) {
2177: $keys[$foreignKey] = $this->field($foreignKey);
2178: }
2179:
2180: $recursive = (empty($conditions) ? -1 : 0);
2181:
2182: if (isset($keys['old'][$foreignKey]) && $keys['old'][$foreignKey] != $keys[$foreignKey]) {
2183: $conditions[$fkQuoted] = $keys['old'][$foreignKey];
2184: $count = (int)$this->find('count', compact('conditions', 'recursive'));
2185:
2186: $Model->updateAll(
2187: array($field => $count),
2188: array($Model->escapeField() => $keys['old'][$foreignKey])
2189: );
2190: }
2191:
2192: $conditions[$fkQuoted] = $keys[$foreignKey];
2193:
2194: if ($recursive === 0) {
2195: $conditions = array_merge($conditions, (array)$conditions);
2196: }
2197:
2198: $count = (int)$this->find('count', compact('conditions', 'recursive'));
2199:
2200: $Model->updateAll(
2201: array($field => $count),
2202: array($Model->escapeField() => $keys[$foreignKey])
2203: );
2204: }
2205: }
2206: }
2207:
2208: /**
2209: * Helper method for `Model::updateCounterCache()`. Checks the fields to be updated for
2210: *
2211: * @param array $data The fields of the record that will be updated
2212: * @return array Returns updated foreign key values, along with an 'old' key containing the old
2213: * values, or empty if no foreign keys are updated.
2214: */
2215: protected function _prepareUpdateFields($data) {
2216: $foreignKeys = array();
2217: foreach ($this->belongsTo as $assoc => $info) {
2218: if (isset($info['counterCache']) && $info['counterCache']) {
2219: $foreignKeys[$assoc] = $info['foreignKey'];
2220: }
2221: }
2222:
2223: $included = array_intersect($foreignKeys, array_keys($data));
2224:
2225: if (empty($included) || empty($this->id)) {
2226: return array();
2227: }
2228:
2229: $old = $this->find('first', array(
2230: 'conditions' => array($this->alias . '.' . $this->primaryKey => $this->id),
2231: 'fields' => array_values($included),
2232: 'recursive' => -1
2233: ));
2234:
2235: return array_merge($data, array('old' => $old[$this->alias]));
2236: }
2237:
2238: /**
2239: * Backwards compatible passthrough method for:
2240: * saveMany(), validateMany(), saveAssociated() and validateAssociated()
2241: *
2242: * Saves multiple individual records for a single model; Also works with a single record, as well as
2243: * all its associated records.
2244: *
2245: * #### Options
2246: *
2247: * - `validate`: Set to false to disable validation, true to validate each record before saving,
2248: * 'first' to validate *all* records before any are saved (default),
2249: * or 'only' to only validate the records, but not save them.
2250: * - `atomic`: If true (default), will attempt to save all records in a single transaction.
2251: * Should be set to false if database/table does not support transactions.
2252: * - `fieldList`: Equivalent to the $fieldList parameter in Model::save().
2253: * It should be an associate array with model name as key and array of fields as value. Eg.
2254: * ```
2255: * array(
2256: * 'SomeModel' => array('field'),
2257: * 'AssociatedModel' => array('field', 'otherfield')
2258: * )
2259: * ```
2260: * - `deep`: See saveMany/saveAssociated
2261: * - `callbacks`: See Model::save()
2262: * - `counterCache`: See Model::save()
2263: *
2264: * @param array $data Record data to save. This can be either a numerically-indexed array (for saving multiple
2265: * records of the same type), or an array indexed by association name.
2266: * @param array $options Options to use when saving record data, See $options above.
2267: * @return mixed If atomic: True on success, or false on failure.
2268: * Otherwise: array similar to the $data array passed, but values are set to true/false
2269: * depending on whether each record saved successfully.
2270: * @link https://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveassociated-array-data-null-array-options-array
2271: * @link https://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveall-array-data-null-array-options-array
2272: */
2273: public function saveAll($data = array(), $options = array()) {
2274: $options += array('validate' => 'first');
2275: if (Hash::numeric(array_keys($data))) {
2276: if ($options['validate'] === 'only') {
2277: return $this->validateMany($data, $options);
2278: }
2279:
2280: return $this->saveMany($data, $options);
2281: }
2282:
2283: if ($options['validate'] === 'only') {
2284: return $this->validateAssociated($data, $options);
2285: }
2286:
2287: return $this->saveAssociated($data, $options);
2288: }
2289:
2290: /**
2291: * Saves multiple individual records for a single model
2292: *
2293: * #### Options
2294: *
2295: * - `validate`: Set to false to disable validation, true to validate each record before saving,
2296: * 'first' to validate *all* records before any are saved (default),
2297: * - `atomic`: If true (default), will attempt to save all records in a single transaction.
2298: * Should be set to false if database/table does not support transactions.
2299: * - `fieldList`: Equivalent to the $fieldList parameter in Model::save()
2300: * - `deep`: If set to true, all associated data will be saved as well.
2301: * - `callbacks`: See Model::save()
2302: * - `counterCache`: See Model::save()
2303: *
2304: * @param array $data Record data to save. This should be a numerically-indexed array
2305: * @param array $options Options to use when saving record data, See $options above.
2306: * @return mixed If atomic: True on success, or false on failure.
2307: * Otherwise: array similar to the $data array passed, but values are set to true/false
2308: * depending on whether each record saved successfully.
2309: * @throws PDOException
2310: * @link https://book.cakephp.org/2.0/en/models/saving-your-data.html#model-savemany-array-data-null-array-options-array
2311: */
2312: public function saveMany($data = null, $options = array()) {
2313: if (empty($data)) {
2314: $data = $this->data;
2315: }
2316:
2317: $options += array('validate' => 'first', 'atomic' => true, 'deep' => false);
2318: $this->validationErrors = $validationErrors = array();
2319:
2320: if (empty($data) && $options['validate'] !== false) {
2321: $result = $this->save($data, $options);
2322: if (!$options['atomic']) {
2323: return array(!empty($result));
2324: }
2325:
2326: return !empty($result);
2327: }
2328:
2329: if ($options['validate'] === 'first') {
2330: $validates = $this->validateMany($data, $options);
2331: if ((!$validates && $options['atomic']) || (!$options['atomic'] && in_array(false, $validates, true))) {
2332: return $validates;
2333: }
2334: $options['validate'] = false;
2335: }
2336:
2337: $transactionBegun = false;
2338: if ($options['atomic']) {
2339: $db = $this->getDataSource();
2340: $transactionBegun = $db->begin();
2341: }
2342:
2343: try {
2344: $return = array();
2345: foreach ($data as $key => $record) {
2346: $validates = $this->create(null) !== null;
2347: $saved = false;
2348: if ($validates) {
2349: if ($options['deep']) {
2350: $saved = $this->saveAssociated($record, array('atomic' => false) + $options);
2351: } else {
2352: $saved = (bool)$this->save($record, array('atomic' => false) + $options);
2353: }
2354: }
2355:
2356: $validates = ($validates && ($saved === true || (is_array($saved) && !in_array(false, Hash::flatten($saved), true))));
2357: if (!$validates) {
2358: $validationErrors[$key] = $this->validationErrors;
2359: }
2360:
2361: if (!$options['atomic']) {
2362: $return[$key] = $validates;
2363: } elseif (!$validates) {
2364: break;
2365: }
2366: }
2367:
2368: $this->validationErrors = $validationErrors;
2369:
2370: if (!$options['atomic']) {
2371: return $return;
2372: }
2373:
2374: if ($validates) {
2375: if ($transactionBegun) {
2376: return $db->commit() !== false;
2377: }
2378: return true;
2379: }
2380:
2381: if ($transactionBegun) {
2382: $db->rollback();
2383: }
2384: return false;
2385: } catch (Exception $e) {
2386: if ($transactionBegun) {
2387: $db->rollback();
2388: }
2389: throw $e;
2390: }
2391: }
2392:
2393: /**
2394: * Validates multiple individual records for a single model
2395: *
2396: * #### Options
2397: *
2398: * - `atomic`: If true (default), returns boolean. If false returns array.
2399: * - `fieldList`: Equivalent to the $fieldList parameter in Model::save()
2400: * - `deep`: If set to true, all associated data will be validated as well.
2401: *
2402: * Warning: This method could potentially change the passed argument `$data`,
2403: * If you do not want this to happen, make a copy of `$data` before passing it
2404: * to this method
2405: *
2406: * @param array &$data Record data to validate. This should be a numerically-indexed array
2407: * @param array $options Options to use when validating record data (see above), See also $options of validates().
2408: * @return bool|array If atomic: True on success, or false on failure.
2409: * Otherwise: array similar to the $data array passed, but values are set to true/false
2410: * depending on whether each record validated successfully.
2411: */
2412: public function validateMany(&$data, $options = array()) {
2413: return $this->validator()->validateMany($data, $options);
2414: }
2415:
2416: /**
2417: * Saves a single record, as well as all its directly associated records.
2418: *
2419: * #### Options
2420: *
2421: * - `validate`: Set to `false` to disable validation, `true` to validate each record before saving,
2422: * 'first' to validate *all* records before any are saved(default),
2423: * - `atomic`: If true (default), will attempt to save all records in a single transaction.
2424: * Should be set to false if database/table does not support transactions.
2425: * - `fieldList`: Equivalent to the $fieldList parameter in Model::save().
2426: * It should be an associate array with model name as key and array of fields as value. Eg.
2427: * ```
2428: * array(
2429: * 'SomeModel' => array('field'),
2430: * 'AssociatedModel' => array('field', 'otherfield')
2431: * )
2432: * ```
2433: * - `deep`: If set to true, not only directly associated data is saved, but deeper nested associated data as well.
2434: * - `callbacks`: See Model::save()
2435: * - `counterCache`: See Model::save()
2436: *
2437: * @param array $data Record data to save. This should be an array indexed by association name.
2438: * @param array $options Options to use when saving record data, See $options above.
2439: * @return mixed If atomic: True on success, or false on failure.
2440: * Otherwise: array similar to the $data array passed, but values are set to true/false
2441: * depending on whether each record saved successfully.
2442: * @throws PDOException
2443: * @link https://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveassociated-array-data-null-array-options-array
2444: */
2445: public function saveAssociated($data = null, $options = array()) {
2446: if (empty($data)) {
2447: $data = $this->data;
2448: }
2449:
2450: $options += array('validate' => 'first', 'atomic' => true, 'deep' => false);
2451: $this->validationErrors = $validationErrors = array();
2452:
2453: if (empty($data) && $options['validate'] !== false) {
2454: $result = $this->save($data, $options);
2455: if (!$options['atomic']) {
2456: return array(!empty($result));
2457: }
2458:
2459: return !empty($result);
2460: }
2461:
2462: if ($options['validate'] === 'first') {
2463: $validates = $this->validateAssociated($data, $options);
2464: if ((!$validates && $options['atomic']) || (!$options['atomic'] && in_array(false, Hash::flatten($validates), true))) {
2465: return $validates;
2466: }
2467:
2468: $options['validate'] = false;
2469: }
2470:
2471: $transactionBegun = false;
2472: if ($options['atomic']) {
2473: $db = $this->getDataSource();
2474: $transactionBegun = $db->begin();
2475: }
2476:
2477: try {
2478: $associations = $this->getAssociated();
2479: $return = array();
2480: $validates = true;
2481: foreach ($data as $association => $values) {
2482: $isEmpty = empty($values) || (isset($values[$association]) && empty($values[$association]));
2483: if ($isEmpty || !isset($associations[$association]) || $associations[$association] !== 'belongsTo') {
2484: continue;
2485: }
2486:
2487: $Model = $this->{$association};
2488:
2489: $validates = $Model->create(null) !== null;
2490: $saved = false;
2491: if ($validates) {
2492: if ($options['deep']) {
2493: $saved = $Model->saveAssociated($values, array('atomic' => false) + $options);
2494: } else {
2495: $saved = (bool)$Model->save($values, array('atomic' => false) + $options);
2496: }
2497: $validates = ($saved === true || (is_array($saved) && !in_array(false, Hash::flatten($saved), true)));
2498: }
2499:
2500: if ($validates) {
2501: $key = $this->belongsTo[$association]['foreignKey'];
2502: if (isset($data[$this->alias])) {
2503: $data[$this->alias][$key] = $Model->id;
2504: } else {
2505: $data = array_merge(array($key => $Model->id), $data, array($key => $Model->id));
2506: }
2507: $options = $this->_addToWhiteList($key, $options);
2508: } else {
2509: $validationErrors[$association] = $Model->validationErrors;
2510: }
2511:
2512: $return[$association] = $validates;
2513: }
2514:
2515: if ($validates && !($this->create(null) !== null && $this->save($data, array('atomic' => false) + $options))) {
2516: $validationErrors[$this->alias] = $this->validationErrors;
2517: $validates = false;
2518: }
2519: $return[$this->alias] = $validates;
2520:
2521: foreach ($data as $association => $values) {
2522: if (!$validates) {
2523: break;
2524: }
2525:
2526: $isEmpty = empty($values) || (isset($values[$association]) && empty($values[$association]));
2527: if ($isEmpty || !isset($associations[$association])) {
2528: continue;
2529: }
2530:
2531: $Model = $this->{$association};
2532:
2533: $type = $associations[$association];
2534: $key = $this->{$type}[$association]['foreignKey'];
2535: switch ($type) {
2536: case 'hasOne':
2537: if (isset($values[$association])) {
2538: $values[$association][$key] = $this->id;
2539: } else {
2540: $values = array_merge(array($key => $this->id), $values, array($key => $this->id));
2541: }
2542:
2543: $validates = $Model->create(null) !== null;
2544: $saved = false;
2545:
2546: if ($validates) {
2547: $options = $Model->_addToWhiteList($key, $options);
2548: if ($options['deep']) {
2549: $saved = $Model->saveAssociated($values, array('atomic' => false) + $options);
2550: } else {
2551: $saved = (bool)$Model->save($values, $options);
2552: }
2553: }
2554:
2555: $validates = ($validates && ($saved === true || (is_array($saved) && !in_array(false, Hash::flatten($saved), true))));
2556: if (!$validates) {
2557: $validationErrors[$association] = $Model->validationErrors;
2558: }
2559:
2560: $return[$association] = $validates;
2561: break;
2562: case 'hasMany':
2563: foreach ($values as $i => $value) {
2564: if (isset($values[$i][$association])) {
2565: $values[$i][$association][$key] = $this->id;
2566: } else {
2567: $values[$i] = array_merge(array($key => $this->id), $value, array($key => $this->id));
2568: }
2569: }
2570:
2571: $options = $Model->_addToWhiteList($key, $options);
2572: $_return = $Model->saveMany($values, array('atomic' => false) + $options);
2573: if (in_array(false, $_return, true)) {
2574: $validationErrors[$association] = $Model->validationErrors;
2575: $validates = false;
2576: }
2577:
2578: $return[$association] = $_return;
2579: break;
2580: }
2581: }
2582: $this->validationErrors = $validationErrors;
2583:
2584: if (isset($validationErrors[$this->alias])) {
2585: $this->validationErrors = $validationErrors[$this->alias];
2586: unset($validationErrors[$this->alias]);
2587: $this->validationErrors = array_merge($this->validationErrors, $validationErrors);
2588: }
2589:
2590: if (!$options['atomic']) {
2591: return $return;
2592: }
2593: if ($validates) {
2594: if ($transactionBegun) {
2595: return $db->commit() !== false;
2596: }
2597:
2598: return true;
2599: }
2600:
2601: if ($transactionBegun) {
2602: $db->rollback();
2603: }
2604: return false;
2605: } catch (Exception $e) {
2606: if ($transactionBegun) {
2607: $db->rollback();
2608: }
2609: throw $e;
2610: }
2611: }
2612:
2613: /**
2614: * Helper method for saveAll() and friends, to add foreign key to fieldlist
2615: *
2616: * @param string $key fieldname to be added to list
2617: * @param array $options Options list
2618: * @return array options
2619: */
2620: protected function _addToWhiteList($key, $options) {
2621: if (empty($options['fieldList']) && $this->whitelist && !in_array($key, $this->whitelist)) {
2622: $options['fieldList'][$this->alias] = $this->whitelist;
2623: $options['fieldList'][$this->alias][] = $key;
2624: return $options;
2625: }
2626:
2627: if (!empty($options['fieldList'][$this->alias]) && is_array($options['fieldList'][$this->alias])) {
2628: $options['fieldList'][$this->alias][] = $key;
2629: return $options;
2630: }
2631:
2632: if (!empty($options['fieldList']) && is_array($options['fieldList']) && Hash::dimensions($options['fieldList']) < 2) {
2633: $options['fieldList'][] = $key;
2634: }
2635:
2636: return $options;
2637: }
2638:
2639: /**
2640: * Validates a single record, as well as all its directly associated records.
2641: *
2642: * #### Options
2643: *
2644: * - `atomic`: If true (default), returns boolean. If false returns array.
2645: * - `fieldList`: Equivalent to the $fieldList parameter in Model::save()
2646: * - `deep`: If set to true, not only directly associated data , but deeper nested associated data is validated as well.
2647: *
2648: * Warning: This method could potentially change the passed argument `$data`,
2649: * If you do not want this to happen, make a copy of `$data` before passing it
2650: * to this method
2651: *
2652: * @param array &$data Record data to validate. This should be an array indexed by association name.
2653: * @param array $options Options to use when validating record data (see above), See also $options of validates().
2654: * @return array|bool If atomic: True on success, or false on failure.
2655: * Otherwise: array similar to the $data array passed, but values are set to true/false
2656: * depending on whether each record validated successfully.
2657: */
2658: public function validateAssociated(&$data, $options = array()) {
2659: return $this->validator()->validateAssociated($data, $options);
2660: }
2661:
2662: /**
2663: * Updates multiple model records based on a set of conditions.
2664: *
2665: * @param array $fields Set of fields and values, indexed by fields.
2666: * Fields are treated as SQL snippets, to insert literal values manually escape your data.
2667: * @param mixed $conditions Conditions to match, true for all records
2668: * @return bool True on success, false on failure
2669: * @link https://book.cakephp.org/2.0/en/models/saving-your-data.html#model-updateall-array-fields-mixed-conditions
2670: */
2671: public function updateAll($fields, $conditions = true) {
2672: return $this->getDataSource()->update($this, $fields, null, $conditions);
2673: }
2674:
2675: /**
2676: * Removes record for given ID. If no ID is given, the current ID is used. Returns true on success.
2677: *
2678: * @param int|string $id ID of record to delete
2679: * @param bool $cascade Set to true to delete records that depend on this record
2680: * @return bool True on success
2681: * @triggers Model.beforeDelete $this, array($cascade)
2682: * @triggers Model.afterDelete $this
2683: * @link https://book.cakephp.org/2.0/en/models/deleting-data.html
2684: */
2685: public function delete($id = null, $cascade = true) {
2686: if (!empty($id)) {
2687: $this->id = $id;
2688: }
2689:
2690: $id = $this->id;
2691:
2692: $event = new CakeEvent('Model.beforeDelete', $this, array($cascade));
2693: list($event->break, $event->breakOn) = array(true, array(false, null));
2694: $this->getEventManager()->dispatch($event);
2695: if ($event->isStopped()) {
2696: return false;
2697: }
2698:
2699: if (!$this->exists($this->getID())) {
2700: return false;
2701: }
2702:
2703: $this->_deleteDependent($id, $cascade);
2704: $this->_deleteLinks($id);
2705: $this->id = $id;
2706:
2707: if (!empty($this->belongsTo)) {
2708: foreach ($this->belongsTo as $assoc) {
2709: if (empty($assoc['counterCache'])) {
2710: continue;
2711: }
2712:
2713: $keys = $this->find('first', array(
2714: 'fields' => $this->_collectForeignKeys(),
2715: 'conditions' => array($this->alias . '.' . $this->primaryKey => $id),
2716: 'recursive' => -1,
2717: 'callbacks' => false
2718: ));
2719: break;
2720: }
2721: }
2722:
2723: if (!$this->getDataSource()->delete($this, array($this->alias . '.' . $this->primaryKey => $id))) {
2724: return false;
2725: }
2726:
2727: if (!empty($keys[$this->alias])) {
2728: $this->updateCounterCache($keys[$this->alias]);
2729: }
2730:
2731: $this->getEventManager()->dispatch(new CakeEvent('Model.afterDelete', $this));
2732: $this->_clearCache();
2733: $this->id = false;
2734:
2735: return true;
2736: }
2737:
2738: /**
2739: * Cascades model deletes through associated hasMany and hasOne child records.
2740: *
2741: * @param string $id ID of record that was deleted
2742: * @param bool $cascade Set to true to delete records that depend on this record
2743: * @return void
2744: */
2745: protected function _deleteDependent($id, $cascade) {
2746: if ($cascade !== true) {
2747: return;
2748: }
2749:
2750: if (!empty($this->__backAssociation)) {
2751: $savedAssociations = $this->__backAssociation;
2752: $this->__backAssociation = array();
2753: }
2754:
2755: foreach (array_merge($this->hasMany, $this->hasOne) as $assoc => $data) {
2756: if ($data['dependent'] !== true) {
2757: continue;
2758: }
2759:
2760: $Model = $this->{$assoc};
2761:
2762: if ($data['foreignKey'] === false && $data['conditions'] && in_array($this->name, $Model->getAssociated('belongsTo'))) {
2763: $Model->recursive = 0;
2764: $conditions = array($this->escapeField(null, $this->name) => $id);
2765: } else {
2766: $Model->recursive = -1;
2767: $conditions = array($Model->escapeField($data['foreignKey']) => $id);
2768: if ($data['conditions']) {
2769: $conditions = array_merge((array)$data['conditions'], $conditions);
2770: }
2771: }
2772:
2773: if (isset($data['exclusive']) && $data['exclusive']) {
2774: $Model->deleteAll($conditions);
2775: } else {
2776: $records = $Model->find('all', array(
2777: 'conditions' => $conditions, 'fields' => $Model->primaryKey
2778: ));
2779:
2780: if (!empty($records)) {
2781: foreach ($records as $record) {
2782: $Model->delete($record[$Model->alias][$Model->primaryKey]);
2783: }
2784: }
2785: }
2786: }
2787:
2788: if (isset($savedAssociations)) {
2789: $this->__backAssociation = $savedAssociations;
2790: }
2791: }
2792:
2793: /**
2794: * Cascades model deletes through HABTM join keys.
2795: *
2796: * @param string $id ID of record that was deleted
2797: * @return void
2798: */
2799: protected function _deleteLinks($id) {
2800: foreach ($this->hasAndBelongsToMany as $data) {
2801: list(, $joinModel) = pluginSplit($data['with']);
2802: $Model = $this->{$joinModel};
2803: $records = $Model->find('all', array(
2804: 'conditions' => $this->_getConditionsForDeletingLinks($Model, $id, $data),
2805: 'fields' => $Model->primaryKey,
2806: 'recursive' => -1,
2807: 'callbacks' => false
2808: ));
2809:
2810: if (!empty($records)) {
2811: foreach ($records as $record) {
2812: $Model->delete($record[$Model->alias][$Model->primaryKey]);
2813: }
2814: }
2815: }
2816: }
2817:
2818: /**
2819: * Returns the conditions to be applied to Model::find() when determining which HABTM records should be deleted via
2820: * Model::_deleteLinks()
2821: *
2822: * @param Model $Model HABTM join model instance
2823: * @param mixed $id The ID of the primary model which is being deleted
2824: * @param array $relationshipConfig The relationship config defined on the primary model
2825: * @return array
2826: */
2827: protected function _getConditionsForDeletingLinks(Model $Model, $id, array $relationshipConfig) {
2828: return array($Model->escapeField($relationshipConfig['foreignKey']) => $id);
2829: }
2830:
2831: /**
2832: * Deletes multiple model records based on a set of conditions.
2833: *
2834: * @param mixed $conditions Conditions to match
2835: * @param bool $cascade Set to true to delete records that depend on this record
2836: * @param bool $callbacks Run callbacks
2837: * @return bool True on success, false on failure
2838: * @link https://book.cakephp.org/2.0/en/models/deleting-data.html#deleteall
2839: */
2840: public function deleteAll($conditions, $cascade = true, $callbacks = false) {
2841: if (empty($conditions)) {
2842: return false;
2843: }
2844:
2845: $db = $this->getDataSource();
2846:
2847: if (!$cascade && !$callbacks) {
2848: return $db->delete($this, $conditions);
2849: }
2850:
2851: $ids = $this->find('all', array_merge(array(
2852: 'fields' => "{$this->alias}.{$this->primaryKey}",
2853: 'order' => false,
2854: 'group' => "{$this->alias}.{$this->primaryKey}",
2855: 'recursive' => 0), compact('conditions'))
2856: );
2857:
2858: if ($ids === false || $ids === null) {
2859: return false;
2860: }
2861:
2862: $ids = Hash::extract($ids, "{n}.{$this->alias}.{$this->primaryKey}");
2863: if (empty($ids)) {
2864: return true;
2865: }
2866:
2867: if ($callbacks) {
2868: $_id = $this->id;
2869: $result = true;
2870: foreach ($ids as $id) {
2871: $result = $result && $this->delete($id, $cascade);
2872: }
2873:
2874: $this->id = $_id;
2875: return $result;
2876: }
2877:
2878: foreach ($ids as $id) {
2879: $this->_deleteLinks($id);
2880: if ($cascade) {
2881: $this->_deleteDependent($id, $cascade);
2882: }
2883: }
2884:
2885: return $db->delete($this, array($this->alias . '.' . $this->primaryKey => $ids));
2886: }
2887:
2888: /**
2889: * Collects foreign keys from associations.
2890: *
2891: * @param string $type Association type.
2892: * @return array
2893: */
2894: protected function _collectForeignKeys($type = 'belongsTo') {
2895: $result = array();
2896:
2897: foreach ($this->{$type} as $assoc => $data) {
2898: if (isset($data['foreignKey']) && is_string($data['foreignKey'])) {
2899: $result[$assoc] = $data['foreignKey'];
2900: }
2901: }
2902:
2903: return $result;
2904: }
2905:
2906: /**
2907: * Returns true if a record with particular ID exists.
2908: *
2909: * If $id is not passed it calls `Model::getID()` to obtain the current record ID,
2910: * and then performs a `Model::find('count')` on the currently configured datasource
2911: * to ascertain the existence of the record in persistent storage.
2912: *
2913: * @param int|string $id ID of record to check for existence
2914: * @return bool True if such a record exists
2915: */
2916: public function exists($id = null) {
2917: if ($id === null) {
2918: $id = $this->getID();
2919: }
2920:
2921: if ($id === false) {
2922: return false;
2923: }
2924:
2925: if ($this->useTable === false) {
2926: return false;
2927: }
2928:
2929: return (bool)$this->find('count', array(
2930: 'conditions' => array(
2931: $this->alias . '.' . $this->primaryKey => $id
2932: ),
2933: 'recursive' => -1,
2934: 'callbacks' => false
2935: ));
2936: }
2937:
2938: /**
2939: * Returns true if a record that meets given conditions exists.
2940: *
2941: * @param array $conditions SQL conditions array
2942: * @return bool True if such a record exists
2943: */
2944: public function hasAny($conditions = null) {
2945: return (bool)$this->find('count', array('conditions' => $conditions, 'recursive' => -1));
2946: }
2947:
2948: /**
2949: * Queries the datasource and returns a result set array.
2950: *
2951: * Used to perform find operations, where the first argument is type of find operation to perform
2952: * (all / first / count / neighbors / list / threaded),
2953: * second parameter options for finding (indexed array, including: 'conditions', 'limit',
2954: * 'recursive', 'page', 'fields', 'offset', 'order', 'callbacks')
2955: *
2956: * Eg:
2957: * ```
2958: * $model->find('all', array(
2959: * 'conditions' => array('name' => 'Thomas Anderson'),
2960: * 'fields' => array('name', 'email'),
2961: * 'order' => 'field3 DESC',
2962: * 'recursive' => 1,
2963: * 'group' => 'type',
2964: * 'callbacks' => false,
2965: * ));
2966: * ```
2967: *
2968: * In addition to the standard query keys above, you can provide Datasource, and behavior specific
2969: * keys. For example, when using a SQL based datasource you can use the joins key to specify additional
2970: * joins that should be part of the query.
2971: *
2972: * ```
2973: * $model->find('all', array(
2974: * 'conditions' => array('name' => 'Thomas Anderson'),
2975: * 'joins' => array(
2976: * array(
2977: * 'alias' => 'Thought',
2978: * 'table' => 'thoughts',
2979: * 'type' => 'LEFT',
2980: * 'conditions' => '`Thought`.`person_id` = `Person`.`id`'
2981: * )
2982: * )
2983: * ));
2984: * ```
2985: *
2986: * ### Disabling callbacks
2987: *
2988: * The `callbacks` key allows you to disable or specify the callbacks that should be run. To
2989: * disable beforeFind & afterFind callbacks set `'callbacks' => false` in your options. You can
2990: * also set the callbacks option to 'before' or 'after' to enable only the specified callback.
2991: *
2992: * ### Adding new find types
2993: *
2994: * Behaviors and find types can also define custom finder keys which are passed into find().
2995: * See the documentation for custom find types
2996: * (https://book.cakephp.org/2.0/en/models/retrieving-your-data.html#creating-custom-find-types)
2997: * for how to implement custom find types.
2998: *
2999: * Specifying 'fields' for notation 'list':
3000: *
3001: * - If no fields are specified, then 'id' is used for key and 'model->displayField' is used for value.
3002: * - If a single field is specified, 'id' is used for key and specified field is used for value.
3003: * - If three fields are specified, they are used (in order) for key, value and group.
3004: * - Otherwise, first and second fields are used for key and value.
3005: *
3006: * Note: find(list) + database views have issues with MySQL 5.0. Try upgrading to MySQL 5.1 if you
3007: * have issues with database views.
3008: *
3009: * Note: find(count) has its own return values.
3010: *
3011: * @param string $type Type of find operation (all / first / count / neighbors / list / threaded)
3012: * @param array $query Option fields (conditions / fields / joins / limit / offset / order / page / group / callbacks)
3013: * @return array|int|null Array of records, int if the type is count, or Null on failure.
3014: * @link https://book.cakephp.org/2.0/en/models/retrieving-your-data.html
3015: */
3016: public function find($type = 'first', $query = array()) {
3017: $this->findQueryType = $type;
3018: $this->id = $this->getID();
3019:
3020: $query = $this->buildQuery($type, $query);
3021: if ($query === null) {
3022: return null;
3023: }
3024:
3025: return $this->_readDataSource($type, $query);
3026: }
3027:
3028: /**
3029: * Read from the datasource
3030: *
3031: * Model::_readDataSource() is used by all find() calls to read from the data source and can be overloaded to allow
3032: * caching of datasource calls.
3033: *
3034: * ```
3035: * protected function _readDataSource($type, $query) {
3036: * $cacheName = md5(json_encode($query) . json_encode($this->hasOne) . json_encode($this->belongsTo));
3037: * $cache = Cache::read($cacheName, 'cache-config-name');
3038: * if ($cache !== false) {
3039: * return $cache;
3040: * }
3041: *
3042: * $results = parent::_readDataSource($type, $query);
3043: * Cache::write($cacheName, $results, 'cache-config-name');
3044: * return $results;
3045: * }
3046: * ```
3047: *
3048: * @param string $type Type of find operation (all / first / count / neighbors / list / threaded)
3049: * @param array $query Option fields (conditions / fields / joins / limit / offset / order / page / group / callbacks)
3050: * @return array
3051: */
3052: protected function _readDataSource($type, $query) {
3053: $results = $this->getDataSource()->read($this, $query);
3054: $this->resetAssociations();
3055:
3056: if ($query['callbacks'] === true || $query['callbacks'] === 'after') {
3057: $results = $this->_filterResults($results);
3058: }
3059:
3060: $this->findQueryType = null;
3061:
3062: if ($this->findMethods[$type] === true) {
3063: return $this->{'_find' . ucfirst($type)}('after', $query, $results);
3064: }
3065: }
3066:
3067: /**
3068: * Builds the query array that is used by the data source to generate the query to fetch the data.
3069: *
3070: * @param string $type Type of find operation (all / first / count / neighbors / list / threaded)
3071: * @param array $query Option fields (conditions / fields / joins / limit / offset / order / page / group / callbacks)
3072: * @return array|null Query array or null if it could not be build for some reasons
3073: * @triggers Model.beforeFind $this, array($query)
3074: * @see Model::find()
3075: */
3076: public function buildQuery($type = 'first', $query = array()) {
3077: $query = array_merge(
3078: array(
3079: 'conditions' => null, 'fields' => null, 'joins' => array(), 'limit' => null,
3080: 'offset' => null, 'order' => null, 'page' => 1, 'group' => null, 'callbacks' => true,
3081: ),
3082: (array)$query
3083: );
3084:
3085: if ($this->findMethods[$type] === true) {
3086: $query = $this->{'_find' . ucfirst($type)}('before', $query);
3087: }
3088:
3089: if (!is_numeric($query['page']) || (int)$query['page'] < 1) {
3090: $query['page'] = 1;
3091: }
3092:
3093: if ($query['page'] > 1 && !empty($query['limit'])) {
3094: $query['offset'] = ($query['page'] - 1) * $query['limit'];
3095: }
3096:
3097: if ($query['order'] === null && $this->order !== null) {
3098: $query['order'] = $this->order;
3099: }
3100:
3101: if (is_object($query['order'])) {
3102: $query['order'] = array($query['order']);
3103: } else {
3104: $query['order'] = (array)$query['order'];
3105: }
3106:
3107: if ($query['callbacks'] === true || $query['callbacks'] === 'before') {
3108: $event = new CakeEvent('Model.beforeFind', $this, array($query));
3109: list($event->break, $event->breakOn, $event->modParams) = array(true, array(false, null), 0);
3110: $this->getEventManager()->dispatch($event);
3111:
3112: if ($event->isStopped()) {
3113: return null;
3114: }
3115:
3116: $query = $event->result === true ? $event->data[0] : $event->result;
3117: }
3118:
3119: return $query;
3120: }
3121:
3122: /**
3123: * Handles the before/after filter logic for find('all') operations. Only called by Model::find().
3124: *
3125: * @param string $state Either "before" or "after"
3126: * @param array $query Query.
3127: * @param array $results Results.
3128: * @return array
3129: * @see Model::find()
3130: */
3131: protected function _findAll($state, $query, $results = array()) {
3132: if ($state === 'before') {
3133: return $query;
3134: }
3135:
3136: return $results;
3137: }
3138:
3139: /**
3140: * Handles the before/after filter logic for find('first') operations. Only called by Model::find().
3141: *
3142: * @param string $state Either "before" or "after"
3143: * @param array $query Query.
3144: * @param array $results Results.
3145: * @return array
3146: * @see Model::find()
3147: */
3148: protected function _findFirst($state, $query, $results = array()) {
3149: if ($state === 'before') {
3150: $query['limit'] = 1;
3151: return $query;
3152: }
3153:
3154: if (empty($results[0])) {
3155: return array();
3156: }
3157:
3158: return $results[0];
3159: }
3160:
3161: /**
3162: * Handles the before/after filter logic for find('count') operations. Only called by Model::find().
3163: *
3164: * @param string $state Either "before" or "after"
3165: * @param array $query Query.
3166: * @param array $results Results.
3167: * @return int|false The number of records found, or false
3168: * @see Model::find()
3169: */
3170: protected function _findCount($state, $query, $results = array()) {
3171: if ($state === 'before') {
3172: if (!empty($query['type']) && isset($this->findMethods[$query['type']]) && $query['type'] !== 'count') {
3173: $query['operation'] = 'count';
3174: $query = $this->{'_find' . ucfirst($query['type'])}('before', $query);
3175: }
3176:
3177: $db = $this->getDataSource();
3178: $query['order'] = false;
3179: if (!method_exists($db, 'calculate')) {
3180: return $query;
3181: }
3182:
3183: if (!empty($query['fields']) && is_array($query['fields'])) {
3184: if (!preg_match('/^count/i', current($query['fields']))) {
3185: unset($query['fields']);
3186: }
3187: }
3188:
3189: if (empty($query['fields'])) {
3190: $query['fields'] = $db->calculate($this, 'count');
3191: } elseif (method_exists($db, 'expression') && is_string($query['fields']) && !preg_match('/count/i', $query['fields'])) {
3192: $query['fields'] = $db->calculate($this, 'count', array(
3193: $db->expression($query['fields']), 'count'
3194: ));
3195: }
3196:
3197: return $query;
3198: }
3199:
3200: foreach (array(0, $this->alias) as $key) {
3201: if (isset($results[0][$key]['count'])) {
3202: if ($query['group']) {
3203: return count($results);
3204: }
3205:
3206: return (int)$results[0][$key]['count'];
3207: }
3208: }
3209:
3210: return false;
3211: }
3212:
3213: /**
3214: * Handles the before/after filter logic for find('list') operations. Only called by Model::find().
3215: *
3216: * @param string $state Either "before" or "after"
3217: * @param array $query Query.
3218: * @param array $results Results.
3219: * @return array Key/value pairs of primary keys/display field values of all records found
3220: * @see Model::find()
3221: */
3222: protected function _findList($state, $query, $results = array()) {
3223: if ($state === 'before') {
3224: if (empty($query['fields'])) {
3225: $query['fields'] = array("{$this->alias}.{$this->primaryKey}", "{$this->alias}.{$this->displayField}");
3226: $list = array("{n}.{$this->alias}.{$this->primaryKey}", "{n}.{$this->alias}.{$this->displayField}", null);
3227: } else {
3228: if (!is_array($query['fields'])) {
3229: $query['fields'] = CakeText::tokenize($query['fields']);
3230: }
3231:
3232: if (count($query['fields']) === 1) {
3233: if (strpos($query['fields'][0], '.') === false) {
3234: $query['fields'][0] = $this->alias . '.' . $query['fields'][0];
3235: }
3236:
3237: $list = array("{n}.{$this->alias}.{$this->primaryKey}", '{n}.' . $query['fields'][0], null);
3238: $query['fields'] = array("{$this->alias}.{$this->primaryKey}", $query['fields'][0]);
3239: } elseif (count($query['fields']) === 3) {
3240: for ($i = 0; $i < 3; $i++) {
3241: if (strpos($query['fields'][$i], '.') === false) {
3242: $query['fields'][$i] = $this->alias . '.' . $query['fields'][$i];
3243: }
3244: }
3245:
3246: $list = array('{n}.' . $query['fields'][0], '{n}.' . $query['fields'][1], '{n}.' . $query['fields'][2]);
3247: } else {
3248: for ($i = 0; $i < 2; $i++) {
3249: if (strpos($query['fields'][$i], '.') === false) {
3250: $query['fields'][$i] = $this->alias . '.' . $query['fields'][$i];
3251: }
3252: }
3253:
3254: $list = array('{n}.' . $query['fields'][0], '{n}.' . $query['fields'][1], null);
3255: }
3256: }
3257:
3258: if (!isset($query['recursive']) || $query['recursive'] === null) {
3259: $query['recursive'] = -1;
3260: }
3261: list($query['list']['keyPath'], $query['list']['valuePath'], $query['list']['groupPath']) = $list;
3262:
3263: return $query;
3264: }
3265:
3266: if (empty($results)) {
3267: return array();
3268: }
3269:
3270: return Hash::combine($results, $query['list']['keyPath'], $query['list']['valuePath'], $query['list']['groupPath']);
3271: }
3272:
3273: /**
3274: * Detects the previous field's value, then uses logic to find the 'wrapping'
3275: * rows and return them.
3276: *
3277: * @param string $state Either "before" or "after"
3278: * @param array $query Query.
3279: * @param array $results Results.
3280: * @return array
3281: */
3282: protected function _findNeighbors($state, $query, $results = array()) {
3283: extract($query);
3284:
3285: if ($state === 'before') {
3286: $conditions = (array)$conditions;
3287: if (isset($field) && isset($value)) {
3288: if (strpos($field, '.') === false) {
3289: $field = $this->alias . '.' . $field;
3290: }
3291: } else {
3292: $field = $this->alias . '.' . $this->primaryKey;
3293: $value = $this->id;
3294: }
3295:
3296: $query['conditions'] = array_merge($conditions, array($field . ' <' => $value));
3297: $query['order'] = $field . ' DESC';
3298: $query['limit'] = 1;
3299: $query['field'] = $field;
3300: $query['value'] = $value;
3301:
3302: return $query;
3303: }
3304:
3305: unset($query['conditions'][$field . ' <']);
3306: $return = array();
3307: if (isset($results[0])) {
3308: $prevVal = Hash::get($results[0], $field);
3309: $query['conditions'][$field . ' >='] = $prevVal;
3310: $query['conditions'][$field . ' !='] = $value;
3311: $query['limit'] = 2;
3312: } else {
3313: $return['prev'] = null;
3314: $query['conditions'][$field . ' >'] = $value;
3315: $query['limit'] = 1;
3316: }
3317:
3318: $query['order'] = $field . ' ASC';
3319: $neighbors = $this->find('all', $query);
3320: if (!array_key_exists('prev', $return)) {
3321: $return['prev'] = isset($neighbors[0]) ? $neighbors[0] : null;
3322: }
3323:
3324: if (count($neighbors) === 2) {
3325: $return['next'] = $neighbors[1];
3326: } elseif (count($neighbors) === 1 && !$return['prev']) {
3327: $return['next'] = $neighbors[0];
3328: } else {
3329: $return['next'] = null;
3330: }
3331:
3332: return $return;
3333: }
3334:
3335: /**
3336: * In the event of ambiguous results returned (multiple top level results, with different parent_ids)
3337: * top level results with different parent_ids to the first result will be dropped
3338: *
3339: * @param string $state Either "before" or "after".
3340: * @param array $query Query.
3341: * @param array $results Results.
3342: * @return array Threaded results
3343: */
3344: protected function _findThreaded($state, $query, $results = array()) {
3345: if ($state === 'before') {
3346: return $query;
3347: }
3348:
3349: $parent = 'parent_id';
3350: if (isset($query['parent'])) {
3351: $parent = $query['parent'];
3352: }
3353:
3354: return Hash::nest($results, array(
3355: 'idPath' => '{n}.' . $this->alias . '.' . $this->primaryKey,
3356: 'parentPath' => '{n}.' . $this->alias . '.' . $parent
3357: ));
3358: }
3359:
3360: /**
3361: * Passes query results through model and behavior afterFind() methods.
3362: *
3363: * @param array $results Results to filter
3364: * @param bool $primary If this is the primary model results (results from model where the find operation was performed)
3365: * @return array Set of filtered results
3366: * @triggers Model.afterFind $this, array($results, $primary)
3367: */
3368: protected function _filterResults($results, $primary = true) {
3369: $event = new CakeEvent('Model.afterFind', $this, array($results, $primary));
3370: $event->modParams = 0;
3371: $this->getEventManager()->dispatch($event);
3372: return $event->result;
3373: }
3374:
3375: /**
3376: * This resets the association arrays for the model back
3377: * to those originally defined in the model. Normally called at the end
3378: * of each call to Model::find()
3379: *
3380: * @return bool Success
3381: */
3382: public function resetAssociations() {
3383: if (!empty($this->__backAssociation)) {
3384: foreach ($this->_associations as $type) {
3385: if (isset($this->__backAssociation[$type])) {
3386: $this->{$type} = $this->__backAssociation[$type];
3387: }
3388: }
3389:
3390: $this->__backAssociation = array();
3391: }
3392:
3393: foreach ($this->_associations as $type) {
3394: foreach ($this->{$type} as $key => $name) {
3395: if (property_exists($this, $key) && !empty($this->{$key}->__backAssociation)) {
3396: $this->{$key}->resetAssociations();
3397: }
3398: }
3399: }
3400:
3401: $this->__backAssociation = array();
3402: return true;
3403: }
3404:
3405: /**
3406: * Returns false if any fields passed match any (by default, all if $or = false) of their matching values.
3407: *
3408: * Can be used as a validation method. When used as a validation method, the `$or` parameter
3409: * contains an array of fields to be validated.
3410: *
3411: * @param array $fields Field/value pairs to search (if no values specified, they are pulled from $this->data)
3412: * @param bool|array $or If false, all fields specified must match in order for a false return value
3413: * @return bool False if any records matching any fields are found
3414: */
3415: public function isUnique($fields, $or = true) {
3416: if (is_array($or)) {
3417: $isRule = (
3418: array_key_exists('rule', $or) &&
3419: array_key_exists('required', $or) &&
3420: array_key_exists('message', $or)
3421: );
3422: if (!$isRule) {
3423: $args = func_get_args();
3424: $fields = $args[1];
3425: $or = isset($args[2]) ? $args[2] : true;
3426: }
3427: }
3428: if (!is_array($fields)) {
3429: $fields = func_get_args();
3430: $fieldCount = count($fields) - 1;
3431: if (is_bool($fields[$fieldCount])) {
3432: $or = $fields[$fieldCount];
3433: unset($fields[$fieldCount]);
3434: }
3435: }
3436:
3437: foreach ($fields as $field => $value) {
3438: if (is_numeric($field)) {
3439: unset($fields[$field]);
3440:
3441: $field = $value;
3442: $value = null;
3443: if (isset($this->data[$this->alias][$field])) {
3444: $value = $this->data[$this->alias][$field];
3445: }
3446: }
3447:
3448: if (strpos($field, '.') === false) {
3449: unset($fields[$field]);
3450: $fields[$this->alias . '.' . $field] = $value;
3451: }
3452: }
3453:
3454: if ($or) {
3455: $fields = array('or' => $fields);
3456: }
3457:
3458: if (!empty($this->id)) {
3459: $fields[$this->alias . '.' . $this->primaryKey . ' !='] = $this->id;
3460: }
3461:
3462: return !$this->find('count', array('conditions' => $fields, 'recursive' => -1));
3463: }
3464:
3465: /**
3466: * Returns a resultset for a given SQL statement. Custom SQL queries should be performed with this method.
3467: *
3468: * The method can options 2nd and 3rd parameters.
3469: *
3470: * - 2nd param: Either a boolean to control query caching or an array of parameters
3471: * for use with prepared statement placeholders.
3472: * - 3rd param: If 2nd argument is provided, a boolean flag for enabling/disabled
3473: * query caching.
3474: *
3475: * If the query cache param as 2nd or 3rd argument is not given then the model's
3476: * default `$cacheQueries` value is used.
3477: *
3478: * @param string $sql SQL statement
3479: * @return mixed Resultset array or boolean indicating success / failure depending on the query executed
3480: * @link https://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-query
3481: */
3482: public function query($sql) {
3483: $params = func_get_args();
3484: // use $this->cacheQueries as default when argument not explicitly given already
3485: if (count($params) === 1 || count($params) === 2 && !is_bool($params[1])) {
3486: $params[] = $this->cacheQueries;
3487: }
3488: $db = $this->getDataSource();
3489: return call_user_func_array(array(&$db, 'query'), $params);
3490: }
3491:
3492: /**
3493: * Returns true if all fields pass validation. Will validate hasAndBelongsToMany associations
3494: * that use the 'with' key as well. Since _saveMulti is incapable of exiting a save operation.
3495: *
3496: * Will validate the currently set data. Use Model::set() or Model::create() to set the active data.
3497: *
3498: * @param array $options An optional array of custom options to be made available in the beforeValidate callback
3499: * @return bool True if there are no errors
3500: */
3501: public function validates($options = array()) {
3502: return $this->validator()->validates($options);
3503: }
3504:
3505: /**
3506: * Returns an array of fields that have failed the validation of the current model.
3507: *
3508: * Additionally it populates the validationErrors property of the model with the same array.
3509: *
3510: * @param array|string $options An optional array of custom options to be made available in the beforeValidate callback
3511: * @return array|bool Array of invalid fields and their error messages
3512: * @see Model::validates()
3513: */
3514: public function invalidFields($options = array()) {
3515: return $this->validator()->errors($options);
3516: }
3517:
3518: /**
3519: * Marks a field as invalid, optionally setting the name of validation
3520: * rule (in case of multiple validation for field) that was broken.
3521: *
3522: * @param string $field The name of the field to invalidate
3523: * @param mixed $value Name of validation rule that was not failed, or validation message to
3524: * be returned. If no validation key is provided, defaults to true.
3525: * @return void
3526: */
3527: public function invalidate($field, $value = true) {
3528: $this->validator()->invalidate($field, $value);
3529: }
3530:
3531: /**
3532: * Returns true if given field name is a foreign key in this model.
3533: *
3534: * @param string $field Returns true if the input string ends in "_id"
3535: * @return bool True if the field is a foreign key listed in the belongsTo array.
3536: */
3537: public function isForeignKey($field) {
3538: $foreignKeys = array();
3539: if (!empty($this->belongsTo)) {
3540: foreach ($this->belongsTo as $data) {
3541: $foreignKeys[] = $data['foreignKey'];
3542: }
3543: }
3544:
3545: return in_array($field, $foreignKeys);
3546: }
3547:
3548: /**
3549: * Escapes the field name and prepends the model name. Escaping is done according to the
3550: * current database driver's rules.
3551: *
3552: * @param string $field Field to escape (e.g: id)
3553: * @param string $alias Alias for the model (e.g: Post)
3554: * @return string The name of the escaped field for this Model (i.e. id becomes `Post`.`id`).
3555: */
3556: public function escapeField($field = null, $alias = null) {
3557: if (empty($alias)) {
3558: $alias = $this->alias;
3559: }
3560:
3561: if (empty($field)) {
3562: $field = $this->primaryKey;
3563: }
3564:
3565: $db = $this->getDataSource();
3566: if (strpos($field, $db->name($alias) . '.') === 0) {
3567: return $field;
3568: }
3569:
3570: return $db->name($alias . '.' . $field);
3571: }
3572:
3573: /**
3574: * Returns the current record's ID
3575: *
3576: * @param int $list Index on which the composed ID is located
3577: * @return mixed The ID of the current record, false if no ID
3578: */
3579: public function getID($list = 0) {
3580: if (empty($this->id) || (is_array($this->id) && isset($this->id[0]) && empty($this->id[0]))) {
3581: return false;
3582: }
3583:
3584: if (!is_array($this->id)) {
3585: return $this->id;
3586: }
3587:
3588: if (isset($this->id[$list]) && !empty($this->id[$list])) {
3589: return $this->id[$list];
3590: }
3591:
3592: if (isset($this->id[$list])) {
3593: return false;
3594: }
3595:
3596: return current($this->id);
3597: }
3598:
3599: /**
3600: * Returns the ID of the last record this model inserted.
3601: *
3602: * @return mixed Last inserted ID
3603: */
3604: public function getLastInsertID() {
3605: return $this->getInsertID();
3606: }
3607:
3608: /**
3609: * Returns the ID of the last record this model inserted.
3610: *
3611: * @return mixed Last inserted ID
3612: */
3613: public function getInsertID() {
3614: return $this->_insertID;
3615: }
3616:
3617: /**
3618: * Sets the ID of the last record this model inserted
3619: *
3620: * @param int|string $id Last inserted ID
3621: * @return void
3622: */
3623: public function setInsertID($id) {
3624: $this->_insertID = $id;
3625: }
3626:
3627: /**
3628: * Returns the number of rows returned from the last query.
3629: *
3630: * @return int Number of rows
3631: */
3632: public function getNumRows() {
3633: return $this->getDataSource()->lastNumRows();
3634: }
3635:
3636: /**
3637: * Returns the number of rows affected by the last query.
3638: *
3639: * @return int Number of rows
3640: */
3641: public function getAffectedRows() {
3642: return $this->getDataSource()->lastAffected();
3643: }
3644:
3645: /**
3646: * Sets the DataSource to which this model is bound.
3647: *
3648: * @param string $dataSource The name of the DataSource, as defined in app/Config/database.php
3649: * @return void
3650: * @throws MissingConnectionException
3651: */
3652: public function setDataSource($dataSource = null) {
3653: $oldConfig = $this->useDbConfig;
3654:
3655: if ($dataSource) {
3656: $this->useDbConfig = $dataSource;
3657: }
3658:
3659: $db = ConnectionManager::getDataSource($this->useDbConfig);
3660: if (!empty($oldConfig) && isset($db->config['prefix'])) {
3661: $oldDb = ConnectionManager::getDataSource($oldConfig);
3662:
3663: if (!isset($this->tablePrefix) || (!isset($oldDb->config['prefix']) || $this->tablePrefix === $oldDb->config['prefix'])) {
3664: $this->tablePrefix = $db->config['prefix'];
3665: }
3666: } elseif (isset($db->config['prefix'])) {
3667: $this->tablePrefix = $db->config['prefix'];
3668: }
3669:
3670: $schema = $db->getSchemaName();
3671: $defaultProperties = get_class_vars(get_class($this));
3672: if (isset($defaultProperties['schemaName'])) {
3673: $schema = $defaultProperties['schemaName'];
3674: }
3675: $this->schemaName = $schema;
3676: }
3677:
3678: /**
3679: * Gets the DataSource to which this model is bound.
3680: *
3681: * @return DataSource A DataSource object
3682: */
3683: public function getDataSource() {
3684: if (!$this->_sourceConfigured && $this->useTable !== false) {
3685: $this->_sourceConfigured = true;
3686: $this->setSource($this->useTable);
3687: }
3688:
3689: return ConnectionManager::getDataSource($this->useDbConfig);
3690: }
3691:
3692: /**
3693: * Get associations
3694: *
3695: * @return array
3696: */
3697: public function associations() {
3698: return $this->_associations;
3699: }
3700:
3701: /**
3702: * Gets all the models with which this model is associated.
3703: *
3704: * @param string $type Only result associations of this type
3705: * @return array|null Associations
3706: */
3707: public function getAssociated($type = null) {
3708: if (!$type) {
3709: $associated = array();
3710: foreach ($this->_associations as $assoc) {
3711: if (!empty($this->{$assoc})) {
3712: $models = array_keys($this->{$assoc});
3713: foreach ($models as $m) {
3714: $associated[$m] = $assoc;
3715: }
3716: }
3717: }
3718:
3719: return $associated;
3720: }
3721:
3722: if (in_array($type, $this->_associations)) {
3723: if (empty($this->{$type})) {
3724: return array();
3725: }
3726:
3727: return array_keys($this->{$type});
3728: }
3729:
3730: $assoc = array_merge(
3731: $this->hasOne,
3732: $this->hasMany,
3733: $this->belongsTo,
3734: $this->hasAndBelongsToMany
3735: );
3736:
3737: if (array_key_exists($type, $assoc)) {
3738: foreach ($this->_associations as $a) {
3739: if (isset($this->{$a}[$type])) {
3740: $assoc[$type]['association'] = $a;
3741: break;
3742: }
3743: }
3744:
3745: return $assoc[$type];
3746: }
3747:
3748: return null;
3749: }
3750:
3751: /**
3752: * Gets the name and fields to be used by a join model. This allows specifying join fields
3753: * in the association definition.
3754: *
3755: * @param string|array $assoc The model to be joined
3756: * @param array $keys Any join keys which must be merged with the keys queried
3757: * @return array
3758: */
3759: public function joinModel($assoc, $keys = array()) {
3760: if (is_string($assoc)) {
3761: list(, $assoc) = pluginSplit($assoc);
3762: return array($assoc, array_keys($this->{$assoc}->schema()));
3763: }
3764:
3765: if (is_array($assoc)) {
3766: $with = key($assoc);
3767: return array($with, array_unique(array_merge($assoc[$with], $keys)));
3768: }
3769:
3770: trigger_error(
3771: __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)),
3772: E_USER_WARNING
3773: );
3774: }
3775:
3776: /**
3777: * Called before each find operation. Return false if you want to halt the find
3778: * call, otherwise return the (modified) query data.
3779: *
3780: * @param array $query Data used to execute this query, i.e. conditions, order, etc.
3781: * @return mixed true if the operation should continue, false if it should abort; or, modified
3782: * $query to continue with new $query
3783: * @link https://book.cakephp.org/2.0/en/models/callback-methods.html#beforefind
3784: */
3785: public function beforeFind($query) {
3786: return true;
3787: }
3788:
3789: /**
3790: * Called after each find operation. Can be used to modify any results returned by find().
3791: * Return value should be the (modified) results.
3792: *
3793: * @param mixed $results The results of the find operation
3794: * @param bool $primary Whether this model is being queried directly (vs. being queried as an association)
3795: * @return mixed Result of the find operation
3796: * @link https://book.cakephp.org/2.0/en/models/callback-methods.html#afterfind
3797: */
3798: public function afterFind($results, $primary = false) {
3799: return $results;
3800: }
3801:
3802: /**
3803: * Called before each save operation, after validation. Return a non-true result
3804: * to halt the save.
3805: *
3806: * @param array $options Options passed from Model::save().
3807: * @return bool True if the operation should continue, false if it should abort
3808: * @link https://book.cakephp.org/2.0/en/models/callback-methods.html#beforesave
3809: * @see Model::save()
3810: */
3811: public function beforeSave($options = array()) {
3812: return true;
3813: }
3814:
3815: /**
3816: * Called after each successful save operation.
3817: *
3818: * @param bool $created True if this save created a new record
3819: * @param array $options Options passed from Model::save().
3820: * @return void
3821: * @link https://book.cakephp.org/2.0/en/models/callback-methods.html#aftersave
3822: * @see Model::save()
3823: */
3824: public function afterSave($created, $options = array()) {
3825: }
3826:
3827: /**
3828: * Called before every deletion operation.
3829: *
3830: * @param bool $cascade If true records that depend on this record will also be deleted
3831: * @return bool True if the operation should continue, false if it should abort
3832: * @link https://book.cakephp.org/2.0/en/models/callback-methods.html#beforedelete
3833: */
3834: public function beforeDelete($cascade = true) {
3835: return true;
3836: }
3837:
3838: /**
3839: * Called after every deletion operation.
3840: *
3841: * @return void
3842: * @link https://book.cakephp.org/2.0/en/models/callback-methods.html#afterdelete
3843: */
3844: public function afterDelete() {
3845: }
3846:
3847: /**
3848: * Called during validation operations, before validation. Please note that custom
3849: * validation rules can be defined in $validate.
3850: *
3851: * @param array $options Options passed from Model::save().
3852: * @return bool True if validate operation should continue, false to abort
3853: * @link https://book.cakephp.org/2.0/en/models/callback-methods.html#beforevalidate
3854: * @see Model::save()
3855: */
3856: public function beforeValidate($options = array()) {
3857: return true;
3858: }
3859:
3860: /**
3861: * Called after data has been checked for errors
3862: *
3863: * @return void
3864: */
3865: public function afterValidate() {
3866: }
3867:
3868: /**
3869: * Called when a DataSource-level error occurs.
3870: *
3871: * @return void
3872: * @link https://book.cakephp.org/2.0/en/models/callback-methods.html#onerror
3873: */
3874: public function onError() {
3875: }
3876:
3877: /**
3878: * Clears cache for this model.
3879: *
3880: * @param string $type If null this deletes cached views if Cache.check is true
3881: * Will be used to allow deleting query cache also
3882: * @return mixed True on delete, null otherwise
3883: */
3884: protected function _clearCache($type = null) {
3885: if ($type !== null || Configure::read('Cache.check') !== true) {
3886: return;
3887: }
3888: $pluralized = Inflector::pluralize($this->alias);
3889: $assoc = array(
3890: strtolower($pluralized),
3891: Inflector::underscore($pluralized)
3892: );
3893: foreach ($this->_associations as $association) {
3894: foreach ($this->{$association} as $className) {
3895: $pluralizedAssociation = Inflector::pluralize($className['className']);
3896: if (!in_array(strtolower($pluralizedAssociation), $assoc)) {
3897: $assoc = array_merge($assoc, array(
3898: strtolower($pluralizedAssociation),
3899: Inflector::underscore($pluralizedAssociation)
3900: ));
3901: }
3902: }
3903: }
3904: clearCache(array_unique($assoc));
3905: return true;
3906: }
3907:
3908: /**
3909: * Returns an instance of a model validator for this class
3910: *
3911: * @param ModelValidator $instance Model validator instance.
3912: * If null a new ModelValidator instance will be made using current model object
3913: * @return ModelValidator
3914: */
3915: public function validator(ModelValidator $instance = null) {
3916: if ($instance) {
3917: $this->_validator = $instance;
3918: } elseif (!$this->_validator) {
3919: $this->_validator = new ModelValidator($this);
3920: }
3921:
3922: return $this->_validator;
3923: }
3924:
3925: }
3926: