Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

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