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