Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

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