統計
| ブランチ: | リビジョン:

pictcode / lib / Cake / Model / Model.php @ 0b1b8047

履歴 | 表示 | アノテート | ダウンロード (114.428 KB)

1
<?php
2
/**
3
 * Object-relational mapper.
4
 *
5
 * DBO-backed object data model, for mapping database tables to CakePHP objects.
6
 *
7
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
8
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
9
 *
10
 * Licensed under The MIT License
11
 * For full copyright and license information, please see the LICENSE.txt
12
 * Redistributions of files must retain the above copyright notice.
13
 *
14
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
15
 * @link          http://cakephp.org CakePHP(tm) Project
16
 * @package       Cake.Model
17
 * @since         CakePHP(tm) v 0.10.0.0
18
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
19
 */
20

    
21
App::uses('ClassRegistry', 'Utility');
22
App::uses('Validation', 'Utility');
23
App::uses('CakeText', 'Utility');
24
App::uses('Hash', 'Utility');
25
App::uses('BehaviorCollection', 'Model');
26
App::uses('ModelBehavior', 'Model');
27
App::uses('ModelValidator', 'Model');
28
App::uses('ConnectionManager', 'Model');
29
App::uses('Xml', 'Utility');
30
App::uses('CakeEvent', 'Event');
31
App::uses('CakeEventListener', 'Event');
32
App::uses('CakeEventManager', 'Event');
33

    
34
/**
35
 * Object-relational mapper.
36
 *
37
 * DBO-backed object data model.
38
 * Automatically selects a database table name based on a pluralized lowercase object class name
39
 * (i.e. class 'User' => table 'users'; class 'Man' => table 'men')
40
 * The table is required to have at least 'id auto_increment' primary key.
41
 *
42
 * @package       Cake.Model
43
 * @link          http://book.cakephp.org/2.0/en/models.html
44
 */
45
class Model extends Object implements CakeEventListener {
46

    
47
/**
48
 * The name of the DataSource connection that this Model uses
49
 *
50
 * The value must be an attribute name that you defined in `app/Config/database.php`
51
 * or created using `ConnectionManager::create()`.
52
 *
53
 * @var string
54
 * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#usedbconfig
55
 */
56
        public $useDbConfig = 'default';
57

    
58
/**
59
 * Custom database table name, or null/false if no table association is desired.
60
 *
61
 * @var string
62
 * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#usetable
63
 */
64
        public $useTable = null;
65

    
66
/**
67
 * Custom display field name. Display fields are used by Scaffold, in SELECT boxes' OPTION elements.
68
 *
69
 * This field is also used in `find('list')` when called with no extra parameters in the fields list
70
 *
71
 * @var string
72
 * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#displayfield
73
 */
74
        public $displayField = null;
75

    
76
/**
77
 * Value of the primary key ID of the record that this model is currently pointing to.
78
 * Automatically set after database insertions.
79
 *
80
 * @var mixed
81
 */
82
        public $id = false;
83

    
84
/**
85
 * Container for the data that this model gets from persistent storage (usually, a database).
86
 *
87
 * @var array
88
 * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#data
89
 */
90
        public $data = array();
91

    
92
/**
93
 * Holds physical schema/database name for this model. Automatically set during Model creation.
94
 *
95
 * @var string
96
 */
97
        public $schemaName = null;
98

    
99
/**
100
 * Table name for this Model.
101
 *
102
 * @var string
103
 */
104
        public $table = false;
105

    
106
/**
107
 * The name of the primary key field for this model.
108
 *
109
 * @var string
110
 * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#primarykey
111
 */
112
        public $primaryKey = null;
113

    
114
/**
115
 * Field-by-field table metadata.
116
 *
117
 * @var array
118
 */
119
        protected $_schema = null;
120

    
121
/**
122
 * List of validation rules. It must be an array with the field name as key and using
123
 * as value one of the following possibilities
124
 *
125
 * ### Validating using regular expressions
126
 *
127
 * ```
128
 * public $validate = array(
129
 *     'name' => '/^[a-z].+$/i'
130
 * );
131
 * ```
132
 *
133
 * ### Validating using methods (no parameters)
134
 *
135
 * ```
136
 * public $validate = array(
137
 *     'name' => 'notBlank'
138
 * );
139
 * ```
140
 *
141
 * ### Validating using methods (with parameters)
142
 *
143
 * ```
144
 * public $validate = array(
145
 *     'length' => array(
146
 *         'rule' => array('lengthBetween', 5, 25)
147
 *     )
148
 * );
149
 * ```
150
 *
151
 * ### Validating using custom method
152
 *
153
 * ```
154
 * public $validate = array(
155
 *     'password' => array(
156
 *         'rule' => array('customValidation')
157
 *     )
158
 * );
159
 * public function customValidation($data) {
160
 *     // $data will contain array('password' => 'value')
161
 *     if (isset($this->data[$this->alias]['password2'])) {
162
 *         return $this->data[$this->alias]['password2'] === current($data);
163
 *     }
164
 *     return true;
165
 * }
166
 * ```
167
 *
168
 * ### Validations with messages
169
 *
170
 * The messages will be used in Model::$validationErrors and can be used in the FormHelper
171
 *
172
 * ```
173
 * public $validate = array(
174
 *     'length' => array(
175
 *         'rule' => array('lengthBetween', 5, 15),
176
 *         'message' => array('Between %d to %d characters')
177
 *     )
178
 * );
179
 * ```
180
 *
181
 * ### Multiple validations to the same field
182
 *
183
 * ```
184
 * public $validate = array(
185
 *     'login' => array(
186
 *         array(
187
 *             'rule' => 'alphaNumeric',
188
 *             'message' => 'Only alphabets and numbers allowed',
189
 *             'last' => true
190
 *         ),
191
 *         array(
192
 *             'rule' => array('minLength', 8),
193
 *             'message' => array('Minimum length of %d characters')
194
 *         )
195
 *     )
196
 * );
197
 * ```
198
 *
199
 * ### Valid keys in validations
200
 *
201
 * - `rule`: String with method name, regular expression (started by slash) or array with method and parameters
202
 * - `message`: String with the message or array if have multiple parameters. See http://php.net/sprintf
203
 * - `last`: Boolean value to indicate if continue validating the others rules if the current fail [Default: true]
204
 * - `required`: Boolean value to indicate if the field must be present on save
205
 * - `allowEmpty`: Boolean value to indicate if the field can be empty
206
 * - `on`: Possible values: `update`, `create`. Indicate to apply this rule only on update or create
207
 *
208
 * @var array
209
 * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#validate
210
 * @link http://book.cakephp.org/2.0/en/models/data-validation.html
211
 */
212
        public $validate = array();
213

    
214
/**
215
 * List of validation errors.
216
 *
217
 * @var array
218
 */
219
        public $validationErrors = array();
220

    
221
/**
222
 * Name of the validation string domain to use when translating validation errors.
223
 *
224
 * @var string
225
 */
226
        public $validationDomain = null;
227

    
228
/**
229
 * Database table prefix for tables in model.
230
 *
231
 * @var string
232
 * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#tableprefix
233
 */
234
        public $tablePrefix = null;
235

    
236
/**
237
 * Plugin model belongs to.
238
 *
239
 * @var string
240
 */
241
        public $plugin = null;
242

    
243
/**
244
 * Name of the model.
245
 *
246
 * @var string
247
 * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#name
248
 */
249
        public $name = null;
250

    
251
/**
252
 * Alias name for model.
253
 *
254
 * @var string
255
 */
256
        public $alias = null;
257

    
258
/**
259
 * List of table names included in the model description. Used for associations.
260
 *
261
 * @var array
262
 */
263
        public $tableToModel = array();
264

    
265
/**
266
 * Whether or not to cache queries for this model. This enables in-memory
267
 * caching only, the results are not stored beyond the current request.
268
 *
269
 * @var bool
270
 * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#cachequeries
271
 */
272
        public $cacheQueries = false;
273

    
274
/**
275
 * Detailed list of belongsTo associations.
276
 *
277
 * ### Basic usage
278
 *
279
 * `public $belongsTo = array('Group', 'Department');`
280
 *
281
 * ### Detailed configuration
282
 *
283
 * ```
284
 * public $belongsTo = array(
285
 *     'Group',
286
 *     'Department' => array(
287
 *         'className' => 'Department',
288
 *         'foreignKey' => 'department_id'
289
 *     )
290
 * );
291
 * ```
292
 *
293
 * ### Possible keys in association
294
 *
295
 * - `className`: the class name of the model being associated to the current model.
296
 *   If you're defining a 'Profile belongsTo User' relationship, the className key should equal 'User.'
297
 * - `foreignKey`: the name of the foreign key found in the current model. This is
298
 *   especially handy if you need to define multiple belongsTo relationships. The default
299
 *   value for this key is the underscored, singular name of the other model, suffixed with '_id'.
300
 * - `conditions`: An SQL fragment used to filter related model records. It's good
301
 *   practice to use model names in SQL fragments: 'User.active = 1' is always
302
 *   better than just 'active = 1.'
303
 * - `type`: the type of the join to use in the SQL query, default is LEFT which
304
 *   may not fit your needs in all situations, INNER may be helpful when you want
305
 *   everything from your main and associated models or nothing at all!(effective
306
 *   when used with some conditions of course). (NB: type value is in lower case - i.e. left, inner)
307
 * - `fields`: A list of fields to be retrieved when the associated model data is
308
 *   fetched. Returns all fields by default.
309
 * - `order`: An SQL fragment that defines the sorting order for the returned associated rows.
310
 * - `counterCache`: If set to true the associated Model will automatically increase or
311
 *   decrease the "[singular_model_name]_count" field in the foreign table whenever you do
312
 *   a save() or delete(). If its a string then its the field name to use. The value in the
313
 *   counter field represents the number of related rows.
314
 * - `counterScope`: Optional conditions array to use for updating counter cache field.
315
 *
316
 * @var array
317
 * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#belongsto
318
 */
319
        public $belongsTo = array();
320

    
321
/**
322
 * Detailed list of hasOne associations.
323
 *
324
 * ### Basic usage
325
 *
326
 * `public $hasOne = array('Profile', 'Address');`
327
 *
328
 * ### Detailed configuration
329
 *
330
 * ```
331
 * public $hasOne = array(
332
 *     'Profile',
333
 *     'Address' => array(
334
 *         'className' => 'Address',
335
 *         'foreignKey' => 'user_id'
336
 *     )
337
 * );
338
 * ```
339
 *
340
 * ### Possible keys in association
341
 *
342
 * - `className`: the class name of the model being associated to the current model.
343
 *   If you're defining a 'User hasOne Profile' relationship, the className key should equal 'Profile.'
344
 * - `foreignKey`: the name of the foreign key found in the other model. This is
345
 *   especially handy if you need to define multiple hasOne relationships.
346
 *   The default value for this key is the underscored, singular name of the
347
 *   current model, suffixed with '_id'. In the example above it would default to 'user_id'.
348
 * - `conditions`: An SQL fragment used to filter related model records. It's good
349
 *   practice to use model names in SQL fragments: "Profile.approved = 1" is
350
 *   always better than just "approved = 1."
351
 * - `fields`: A list of fields to be retrieved when the associated model data is
352
 *   fetched. Returns all fields by default.
353
 * - `order`: An SQL fragment that defines the sorting order for the returned associated rows.
354
 * - `dependent`: When the dependent key is set to true, and the model's delete()
355
 *   method is called with the cascade parameter set to true, associated model
356
 *   records are also deleted. In this case we set it true so that deleting a
357
 *   User will also delete her associated Profile.
358
 *
359
 * @var array
360
 * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasone
361
 */
362
        public $hasOne = array();
363

    
364
/**
365
 * Detailed list of hasMany associations.
366
 *
367
 * ### Basic usage
368
 *
369
 * `public $hasMany = array('Comment', 'Task');`
370
 *
371
 * ### Detailed configuration
372
 *
373
 * ```
374
 * public $hasMany = array(
375
 *     'Comment',
376
 *     'Task' => array(
377
 *         'className' => 'Task',
378
 *         'foreignKey' => 'user_id'
379
 *     )
380
 * );
381
 * ```
382
 *
383
 * ### Possible keys in association
384
 *
385
 * - `className`: the class name of the model being associated to the current model.
386
 *   If you're defining a 'User hasMany Comment' relationship, the className key should equal 'Comment.'
387
 * - `foreignKey`: the name of the foreign key found in the other model. This is
388
 *   especially handy if you need to define multiple hasMany relationships. The default
389
 *   value for this key is the underscored, singular name of the actual model, suffixed with '_id'.
390
 * - `conditions`: An SQL fragment used to filter related model records. It's good
391
 *   practice to use model names in SQL fragments: "Comment.status = 1" is always
392
 *   better than just "status = 1."
393
 * - `fields`: A list of fields to be retrieved when the associated model data is
394
 *   fetched. Returns all fields by default.
395
 * - `order`: An SQL fragment that defines the sorting order for the returned associated rows.
396
 * - `limit`: The maximum number of associated rows you want returned.
397
 * - `offset`: The number of associated rows to skip over (given the current
398
 *   conditions and order) before fetching and associating.
399
 * - `dependent`: When dependent is set to true, recursive model deletion is
400
 *   possible. In this example, Comment records will be deleted when their
401
 *   associated User record has been deleted.
402
 * - `exclusive`: When exclusive is set to true, recursive model deletion does
403
 *   the delete with a deleteAll() call, instead of deleting each entity separately.
404
 *   This greatly improves performance, but may not be ideal for all circumstances.
405
 * - `finderQuery`: A complete SQL query CakePHP can use to fetch associated model
406
 *   records. This should be used in situations that require very custom results.
407
 *
408
 * @var array
409
 * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasmany
410
 */
411
        public $hasMany = array();
412

    
413
/**
414
 * Detailed list of hasAndBelongsToMany associations.
415
 *
416
 * ### Basic usage
417
 *
418
 * `public $hasAndBelongsToMany = array('Role', 'Address');`
419
 *
420
 * ### Detailed configuration
421
 *
422
 * ```
423
 * public $hasAndBelongsToMany = array(
424
 *     'Role',
425
 *     'Address' => array(
426
 *         'className' => 'Address',
427
 *         'foreignKey' => 'user_id',
428
 *         'associationForeignKey' => 'address_id',
429
 *         'joinTable' => 'addresses_users'
430
 *     )
431
 * );
432
 * ```
433
 *
434
 * ### Possible keys in association
435
 *
436
 * - `className`: the class name of the model being associated to the current model.
437
 *   If you're defining a 'Recipe HABTM Tag' relationship, the className key should equal 'Tag.'
438
 * - `joinTable`: The name of the join table used in this association (if the
439
 *   current table doesn't adhere to the naming convention for HABTM join tables).
440
 * - `with`: Defines the name of the model for the join table. By default CakePHP
441
 *   will auto-create a model for you. Using the example above it would be called
442
 *   RecipesTag. By using this key you can override this default name. The join
443
 *   table model can be used just like any "regular" model to access the join table directly.
444
 * - `foreignKey`: the name of the foreign key found in the current model.
445
 *   This is especially handy if you need to define multiple HABTM relationships.
446
 *   The default value for this key is the underscored, singular name of the
447
 *   current model, suffixed with '_id'.
448
 * - `associationForeignKey`: the name of the foreign key found in the other model.
449
 *   This is especially handy if you need to define multiple HABTM relationships.
450
 *   The default value for this key is the underscored, singular name of the other
451
 *   model, suffixed with '_id'.
452
 * - `unique`: If true (default value) cake will first delete existing relationship
453
 *   records in the foreign keys table before inserting new ones, when updating a
454
 *   record. So existing associations need to be passed again when updating.
455
 *   To prevent deletion of existing relationship records, set this key to a string 'keepExisting'.
456
 * - `conditions`: An SQL fragment used to filter related model records. It's good
457
 *   practice to use model names in SQL fragments: "Comment.status = 1" is always
458
 *   better than just "status = 1."
459
 * - `fields`: A list of fields to be retrieved when the associated model data is
460
 *   fetched. Returns all fields by default.
461
 * - `order`: An SQL fragment that defines the sorting order for the returned associated rows.
462
 * - `limit`: The maximum number of associated rows you want returned.
463
 * - `offset`: The number of associated rows to skip over (given the current
464
 *   conditions and order) before fetching and associating.
465
 * - `finderQuery`, A complete SQL query CakePHP
466
 *   can use to fetch associated model records. This should
467
 *   be used in situations that require very custom results.
468
 *
469
 * @var array
470
 * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasandbelongstomany-habtm
471
 */
472
        public $hasAndBelongsToMany = array();
473

    
474
/**
475
 * List of behaviors to load when the model object is initialized. Settings can be
476
 * passed to behaviors by using the behavior name as index. Eg:
477
 *
478
 * public $actsAs = array('Translate', 'MyBehavior' => array('setting1' => 'value1'))
479
 *
480
 * @var array
481
 * @link http://book.cakephp.org/2.0/en/models/behaviors.html#using-behaviors
482
 */
483
        public $actsAs = null;
484

    
485
/**
486
 * Holds the Behavior objects currently bound to this model.
487
 *
488
 * @var BehaviorCollection
489
 */
490
        public $Behaviors = null;
491

    
492
/**
493
 * Whitelist of fields allowed to be saved.
494
 *
495
 * @var array
496
 */
497
        public $whitelist = array();
498

    
499
/**
500
 * Whether or not to cache sources for this model.
501
 *
502
 * @var bool
503
 */
504
        public $cacheSources = true;
505

    
506
/**
507
 * Type of find query currently executing.
508
 *
509
 * @var string
510
 */
511
        public $findQueryType = null;
512

    
513
/**
514
 * Number of associations to recurse through during find calls. Fetches only
515
 * the first level by default.
516
 *
517
 * @var int
518
 * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#recursive
519
 */
520
        public $recursive = 1;
521

    
522
/**
523
 * The column name(s) and direction(s) to order find results by default.
524
 *
525
 * public $order = "Post.created DESC";
526
 * public $order = array("Post.view_count DESC", "Post.rating DESC");
527
 *
528
 * @var string
529
 * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#order
530
 */
531
        public $order = null;
532

    
533
/**
534
 * Array of virtual fields this model has. Virtual fields are aliased
535
 * SQL expressions. Fields added to this property will be read as other fields in a model
536
 * but will not be saveable.
537
 *
538
 * `public $virtualFields = array('two' => '1 + 1');`
539
 *
540
 * Is a simplistic example of how to set virtualFields
541
 *
542
 * @var array
543
 * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#virtualfields
544
 */
545
        public $virtualFields = array();
546

    
547
/**
548
 * Default list of association keys.
549
 *
550
 * @var array
551
 */
552
        protected $_associationKeys = array(
553
                'belongsTo' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'counterCache'),
554
                'hasOne' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'dependent'),
555
                'hasMany' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'dependent', 'exclusive', 'finderQuery', 'counterQuery'),
556
                'hasAndBelongsToMany' => array('className', 'joinTable', 'with', 'foreignKey', 'associationForeignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'unique', 'finderQuery')
557
        );
558

    
559
/**
560
 * Holds provided/generated association key names and other data for all associations.
561
 *
562
 * @var array
563
 */
564
        protected $_associations = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
565

    
566
// @codingStandardsIgnoreStart
567

    
568
/**
569
 * Holds model associations temporarily to allow for dynamic (un)binding.
570
 *
571
 * @var array
572
 */
573
        public $__backAssociation = array();
574

    
575
/**
576
 * Back inner association
577
 *
578
 * @var array
579
 */
580
        public $__backInnerAssociation = array();
581

    
582
/**
583
 * Back original association
584
 *
585
 * @var array
586
 */
587
        public $__backOriginalAssociation = array();
588

    
589
/**
590
 * Back containable association
591
 *
592
 * @var array
593
 */
594
        public $__backContainableAssociation = array();
595

    
596
/**
597
 * Safe update mode
598
 * If true, this prevents Model::save() from generating a query with WHERE 1 = 1 on race condition.
599
 *
600
 * @var bool
601
 */
602
        public $__safeUpdateMode = false;
603

    
604
// @codingStandardsIgnoreEnd
605

    
606
/**
607
 * If true, afterFind will be passed consistent formatted $results in case of $primary is false.
608
 * The format will be such as the following.
609
 *
610
 * ```
611
 * $results = array(
612
 *         0 => array(
613
 *                 'ModelName' => array(
614
 *                         'field1' => 'value1',
615
 *                         'field2' => 'value2'
616
 *                 )
617
 *         )
618
 * );
619
 * ```
620
 *
621
 * @var bool
622
 */
623
        public $useConsistentAfterFind = true;
624

    
625
/**
626
 * The ID of the model record that was last inserted.
627
 *
628
 * @var int
629
 */
630
        protected $_insertID = null;
631

    
632
/**
633
 * Has the datasource been configured.
634
 *
635
 * @var bool
636
 * @see Model::getDataSource
637
 */
638
        protected $_sourceConfigured = false;
639

    
640
/**
641
 * List of valid finder method options, supplied as the first parameter to find().
642
 *
643
 * @var array
644
 */
645
        public $findMethods = array(
646
                'all' => true, 'first' => true, 'count' => true,
647
                'neighbors' => true, 'list' => true, 'threaded' => true
648
        );
649

    
650
/**
651
 * Instance of the CakeEventManager this model is using
652
 * to dispatch inner events.
653
 *
654
 * @var CakeEventManager
655
 */
656
        protected $_eventManager = null;
657

    
658
/**
659
 * Instance of the ModelValidator
660
 *
661
 * @var ModelValidator
662
 */
663
        protected $_validator = null;
664

    
665
/**
666
 * Constructor. Binds the model's database table to the object.
667
 *
668
 * If `$id` is an array it can be used to pass several options into the model.
669
 *
670
 * - `id`: The id to start the model on.
671
 * - `table`: The table to use for this model.
672
 * - `ds`: The connection name this model is connected to.
673
 * - `name`: The name of the model eg. Post.
674
 * - `alias`: The alias of the model, this is used for registering the instance in the `ClassRegistry`.
675
 *   eg. `ParentThread`
676
 *
677
 * ### Overriding Model's __construct method.
678
 *
679
 * When overriding Model::__construct() be careful to include and pass in all 3 of the
680
 * arguments to `parent::__construct($id, $table, $ds);`
681
 *
682
 * ### Dynamically creating models
683
 *
684
 * You can dynamically create model instances using the $id array syntax.
685
 *
686
 * ```
687
 * $Post = new Model(array('table' => 'posts', 'name' => 'Post', 'ds' => 'connection2'));
688
 * ```
689
 *
690
 * Would create a model attached to the posts table on connection2. Dynamic model creation is useful
691
 * when you want a model object that contains no associations or attached behaviors.
692
 *
693
 * @param bool|int|string|array $id Set this ID for this model on startup,
694
 * can also be an array of options, see above.
695
 * @param string $table Name of database table to use.
696
 * @param string $ds DataSource connection name.
697
 */
698
        public function __construct($id = false, $table = null, $ds = null) {
699
                parent::__construct();
700

    
701
                if (is_array($id)) {
702
                        extract(array_merge(
703
                                array(
704
                                        'id' => $this->id, 'table' => $this->useTable, 'ds' => $this->useDbConfig,
705
                                        'name' => $this->name, 'alias' => $this->alias, 'plugin' => $this->plugin
706
                                ),
707
                                $id
708
                        ));
709
                }
710

    
711
                if ($this->plugin === null) {
712
                        $this->plugin = (isset($plugin) ? $plugin : $this->plugin);
713
                }
714

    
715
                if ($this->name === null) {
716
                        $this->name = (isset($name) ? $name : get_class($this));
717
                }
718

    
719
                if ($this->alias === null) {
720
                        $this->alias = (isset($alias) ? $alias : $this->name);
721
                }
722

    
723
                if ($this->primaryKey === null) {
724
                        $this->primaryKey = 'id';
725
                }
726

    
727
                ClassRegistry::addObject($this->alias, $this);
728

    
729
                $this->id = $id;
730
                unset($id);
731

    
732
                if ($table === false) {
733
                        $this->useTable = false;
734
                } elseif ($table) {
735
                        $this->useTable = $table;
736
                }
737

    
738
                if ($ds !== null) {
739
                        $this->useDbConfig = $ds;
740
                }
741

    
742
                if (is_subclass_of($this, 'AppModel')) {
743
                        $merge = array('actsAs', 'findMethods');
744
                        $parentClass = get_parent_class($this);
745
                        if ($parentClass !== 'AppModel') {
746
                                $this->_mergeVars($merge, $parentClass);
747
                        }
748
                        $this->_mergeVars($merge, 'AppModel');
749
                }
750
                $this->_mergeVars(array('findMethods'), 'Model');
751

    
752
                $this->Behaviors = new BehaviorCollection();
753

    
754
                if ($this->useTable !== false) {
755

    
756
                        if ($this->useTable === null) {
757
                                $this->useTable = Inflector::tableize($this->name);
758
                        }
759

    
760
                        if (!$this->displayField) {
761
                                unset($this->displayField);
762
                        }
763
                        $this->table = $this->useTable;
764
                        $this->tableToModel[$this->table] = $this->alias;
765
                } elseif ($this->table === false) {
766
                        $this->table = Inflector::tableize($this->name);
767
                }
768

    
769
                if ($this->tablePrefix === null) {
770
                        unset($this->tablePrefix);
771
                }
772

    
773
                $this->_createLinks();
774
                $this->Behaviors->init($this->alias, $this->actsAs);
775
        }
776

    
777
/**
778
 * Returns a list of all events that will fire in the model during it's lifecycle.
779
 * You can override this function to add your own listener callbacks
780
 *
781
 * @return array
782
 */
783
        public function implementedEvents() {
784
                return array(
785
                        'Model.beforeFind' => array('callable' => 'beforeFind', 'passParams' => true),
786
                        'Model.afterFind' => array('callable' => 'afterFind', 'passParams' => true),
787
                        'Model.beforeValidate' => array('callable' => 'beforeValidate', 'passParams' => true),
788
                        'Model.afterValidate' => array('callable' => 'afterValidate'),
789
                        'Model.beforeSave' => array('callable' => 'beforeSave', 'passParams' => true),
790
                        'Model.afterSave' => array('callable' => 'afterSave', 'passParams' => true),
791
                        'Model.beforeDelete' => array('callable' => 'beforeDelete', 'passParams' => true),
792
                        'Model.afterDelete' => array('callable' => 'afterDelete'),
793
                );
794
        }
795

    
796
/**
797
 * Returns the CakeEventManager manager instance that is handling any callbacks.
798
 * You can use this instance to register any new listeners or callbacks to the
799
 * model events, or create your own events and trigger them at will.
800
 *
801
 * @return CakeEventManager
802
 */
803
        public function getEventManager() {
804
                if (empty($this->_eventManager)) {
805
                        $this->_eventManager = new CakeEventManager();
806
                        $this->_eventManager->attach($this->Behaviors);
807
                        $this->_eventManager->attach($this);
808
                }
809

    
810
                return $this->_eventManager;
811
        }
812

    
813
/**
814
 * Handles custom method calls, like findBy<field> for DB models,
815
 * and custom RPC calls for remote data sources.
816
 *
817
 * @param string $method Name of method to call.
818
 * @param array $params Parameters for the method.
819
 * @return mixed Whatever is returned by called method
820
 */
821
        public function __call($method, $params) {
822
                $result = $this->Behaviors->dispatchMethod($this, $method, $params);
823
                if ($result !== array('unhandled')) {
824
                        return $result;
825
                }
826

    
827
                return $this->getDataSource()->query($method, $params, $this);
828
        }
829

    
830
/**
831
 * Handles the lazy loading of model associations by looking in the association arrays for the requested variable
832
 *
833
 * @param string $name variable tested for existence in class
834
 * @return bool true if the variable exists (if is a not loaded model association it will be created), false otherwise
835
 */
836
        public function __isset($name) {
837
                $className = false;
838

    
839
                foreach ($this->_associations as $type) {
840
                        if (isset($name, $this->{$type}[$name])) {
841
                                $className = empty($this->{$type}[$name]['className']) ? $name : $this->{$type}[$name]['className'];
842
                                break;
843
                        } elseif (isset($name, $this->__backAssociation[$type][$name])) {
844
                                $className = empty($this->__backAssociation[$type][$name]['className']) ?
845
                                        $name : $this->__backAssociation[$type][$name]['className'];
846
                                break;
847
                        } elseif ($type === 'hasAndBelongsToMany') {
848
                                foreach ($this->{$type} as $k => $relation) {
849
                                        if (empty($relation['with'])) {
850
                                                continue;
851
                                        }
852

    
853
                                        if (is_array($relation['with'])) {
854
                                                if (key($relation['with']) === $name) {
855
                                                        $className = $name;
856
                                                }
857
                                        } else {
858
                                                list($plugin, $class) = pluginSplit($relation['with']);
859
                                                if ($class === $name) {
860
                                                        $className = $relation['with'];
861
                                                }
862
                                        }
863

    
864
                                        if ($className) {
865
                                                $assocKey = $k;
866
                                                $dynamic = !empty($relation['dynamicWith']);
867
                                                break(2);
868
                                        }
869
                                }
870
                        }
871
                }
872

    
873
                if (!$className) {
874
                        return false;
875
                }
876

    
877
                list($plugin, $className) = pluginSplit($className);
878

    
879
                if (!ClassRegistry::isKeySet($className) && !empty($dynamic)) {
880
                        $this->{$className} = new AppModel(array(
881
                                'name' => $className,
882
                                'table' => $this->hasAndBelongsToMany[$assocKey]['joinTable'],
883
                                'ds' => $this->useDbConfig
884
                        ));
885
                } else {
886
                        $this->_constructLinkedModel($name, $className, $plugin);
887
                }
888

    
889
                if (!empty($assocKey)) {
890
                        $this->hasAndBelongsToMany[$assocKey]['joinTable'] = $this->{$name}->table;
891
                        if (count($this->{$name}->schema()) <= 2 && $this->{$name}->primaryKey !== false) {
892
                                $this->{$name}->primaryKey = $this->hasAndBelongsToMany[$assocKey]['foreignKey'];
893
                        }
894
                }
895

    
896
                return true;
897
        }
898

    
899
/**
900
 * Returns the value of the requested variable if it can be set by __isset()
901
 *
902
 * @param string $name variable requested for it's value or reference
903
 * @return mixed value of requested variable if it is set
904
 */
905
        public function __get($name) {
906
                if ($name === 'displayField') {
907
                        return $this->displayField = $this->hasField(array('title', 'name', $this->primaryKey));
908
                }
909

    
910
                if ($name === 'tablePrefix') {
911
                        $this->setDataSource();
912
                        if (property_exists($this, 'tablePrefix') && !empty($this->tablePrefix)) {
913
                                return $this->tablePrefix;
914
                        }
915

    
916
                        return $this->tablePrefix = null;
917
                }
918

    
919
                if (isset($this->{$name})) {
920
                        return $this->{$name};
921
                }
922
        }
923

    
924
/**
925
 * Bind model associations on the fly.
926
 *
927
 * If `$reset` is false, association will not be reset
928
 * to the originals defined in the model
929
 *
930
 * Example: Add a new hasOne binding to the Profile model not
931
 * defined in the model source code:
932
 *
933
 * `$this->User->bindModel(array('hasOne' => array('Profile')));`
934
 *
935
 * Bindings that are not made permanent will be reset by the next Model::find() call on this
936
 * model.
937
 *
938
 * @param array $params Set of bindings (indexed by binding type)
939
 * @param bool $reset Set to false to make the binding permanent
940
 * @return bool Success
941
 * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#creating-and-destroying-associations-on-the-fly
942
 */
943
        public function bindModel($params, $reset = true) {
944
                foreach ($params as $assoc => $model) {
945
                        if ($reset === true && !isset($this->__backAssociation[$assoc])) {
946
                                $this->__backAssociation[$assoc] = $this->{$assoc};
947
                        }
948

    
949
                        foreach ($model as $key => $value) {
950
                                $assocName = $key;
951

    
952
                                if (is_numeric($key)) {
953
                                        $assocName = $value;
954
                                        $value = array();
955
                                }
956

    
957
                                $this->{$assoc}[$assocName] = $value;
958

    
959
                                if (property_exists($this, $assocName)) {
960
                                        unset($this->{$assocName});
961
                                }
962

    
963
                                if ($reset === false && isset($this->__backAssociation[$assoc])) {
964
                                        $this->__backAssociation[$assoc][$assocName] = $value;
965
                                }
966
                        }
967
                }
968

    
969
                $this->_createLinks();
970
                return true;
971
        }
972

    
973
/**
974
 * Turn off associations on the fly.
975
 *
976
 * If $reset is false, association will not be reset
977
 * to the originals defined in the model
978
 *
979
 * Example: Turn off the associated Model Support request,
980
 * to temporarily lighten the User model:
981
 *
982
 * `$this->User->unbindModel(array('hasMany' => array('SupportRequest')));`
983
 * Or alternatively:
984
 * `$this->User->unbindModel(array('hasMany' => 'SupportRequest'));`
985
 *
986
 * Unbound models that are not made permanent will reset with the next call to Model::find()
987
 *
988
 * @param array $params Set of bindings to unbind (indexed by binding type)
989
 * @param bool $reset Set to false to make the unbinding permanent
990
 * @return bool Success
991
 * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#creating-and-destroying-associations-on-the-fly
992
 */
993
        public function unbindModel($params, $reset = true) {
994
                foreach ($params as $assoc => $models) {
995
                        if ($reset === true && !isset($this->__backAssociation[$assoc])) {
996
                                $this->__backAssociation[$assoc] = $this->{$assoc};
997
                        }
998
                        $models = Hash::normalize((array)$models, false);
999
                        foreach ($models as $model) {
1000
                                if ($reset === false && isset($this->__backAssociation[$assoc][$model])) {
1001
                                        unset($this->__backAssociation[$assoc][$model]);
1002
                                }
1003

    
1004
                                unset($this->{$assoc}[$model]);
1005
                        }
1006
                }
1007

    
1008
                return true;
1009
        }
1010

    
1011
/**
1012
 * Create a set of associations.
1013
 *
1014
 * @return void
1015
 */
1016
        protected function _createLinks() {
1017
                foreach ($this->_associations as $type) {
1018
                        $association =& $this->{$type};
1019

    
1020
                        if (!is_array($association)) {
1021
                                $association = explode(',', $association);
1022

    
1023
                                foreach ($association as $i => $className) {
1024
                                        $className = trim($className);
1025
                                        unset ($association[$i]);
1026
                                        $association[$className] = array();
1027
                                }
1028
                        }
1029

    
1030
                        if (!empty($association)) {
1031
                                foreach ($association as $assoc => $value) {
1032
                                        $plugin = null;
1033

    
1034
                                        if (is_numeric($assoc)) {
1035
                                                unset($association[$assoc]);
1036
                                                $assoc = $value;
1037
                                                $value = array();
1038

    
1039
                                                if (strpos($assoc, '.') !== false) {
1040
                                                        list($plugin, $assoc) = pluginSplit($assoc, true);
1041
                                                        $association[$assoc] = array('className' => $plugin . $assoc);
1042
                                                } else {
1043
                                                        $association[$assoc] = $value;
1044
                                                }
1045
                                        }
1046

    
1047
                                        $this->_generateAssociation($type, $assoc);
1048
                                }
1049
                        }
1050
                }
1051
        }
1052

    
1053
/**
1054
 * Protected helper method to create associated models of a given class.
1055
 *
1056
 * @param string $assoc Association name
1057
 * @param string $className Class name
1058
 * @param string $plugin name of the plugin where $className is located
1059
 *         examples: public $hasMany = array('Assoc' => array('className' => 'ModelName'));
1060
 *                                         usage: $this->Assoc->modelMethods();
1061
 *
1062
 *                                 public $hasMany = array('ModelName');
1063
 *                                         usage: $this->ModelName->modelMethods();
1064
 * @return void
1065
 */
1066
        protected function _constructLinkedModel($assoc, $className = null, $plugin = null) {
1067
                if (empty($className)) {
1068
                        $className = $assoc;
1069
                }
1070

    
1071
                if (!isset($this->{$assoc}) || $this->{$assoc}->name !== $className) {
1072
                        if ($plugin) {
1073
                                $plugin .= '.';
1074
                        }
1075

    
1076
                        $model = array('class' => $plugin . $className, 'alias' => $assoc);
1077
                        $this->{$assoc} = ClassRegistry::init($model);
1078

    
1079
                        if ($plugin) {
1080
                                ClassRegistry::addObject($plugin . $className, $this->{$assoc});
1081
                        }
1082

    
1083
                        if ($assoc) {
1084
                                $this->tableToModel[$this->{$assoc}->table] = $assoc;
1085
                        }
1086
                }
1087
        }
1088

    
1089
/**
1090
 * Build an array-based association from string.
1091
 *
1092
 * @param string $type 'belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany'
1093
 * @param string $assocKey Association key.
1094
 * @return void
1095
 */
1096
        protected function _generateAssociation($type, $assocKey) {
1097
                $class = $assocKey;
1098
                $dynamicWith = false;
1099
                $assoc =& $this->{$type}[$assocKey];
1100

    
1101
                foreach ($this->_associationKeys[$type] as $key) {
1102
                        if (!isset($assoc[$key]) || $assoc[$key] === null) {
1103
                                $data = '';
1104

    
1105
                                switch ($key) {
1106
                                        case 'fields':
1107
                                                $data = '';
1108
                                                break;
1109

    
1110
                                        case 'foreignKey':
1111
                                                $data = (($type === 'belongsTo') ? Inflector::underscore($assocKey) : Inflector::singularize($this->table)) . '_id';
1112
                                                break;
1113

    
1114
                                        case 'associationForeignKey':
1115
                                                $data = Inflector::singularize($this->{$class}->table) . '_id';
1116
                                                break;
1117

    
1118
                                        case 'with':
1119
                                                $data = Inflector::camelize(Inflector::singularize($assoc['joinTable']));
1120
                                                $dynamicWith = true;
1121
                                                break;
1122

    
1123
                                        case 'joinTable':
1124
                                                $tables = array($this->table, $this->{$class}->table);
1125
                                                sort($tables);
1126
                                                $data = $tables[0] . '_' . $tables[1];
1127
                                                break;
1128

    
1129
                                        case 'className':
1130
                                                $data = $class;
1131
                                                break;
1132

    
1133
                                        case 'unique':
1134
                                                $data = true;
1135
                                                break;
1136
                                }
1137

    
1138
                                $assoc[$key] = $data;
1139
                        }
1140

    
1141
                        if ($dynamicWith) {
1142
                                $assoc['dynamicWith'] = true;
1143
                        }
1144
                }
1145
        }
1146

    
1147
/**
1148
 * Sets a custom table for your model class. Used by your controller to select a database table.
1149
 *
1150
 * @param string $tableName Name of the custom table
1151
 * @throws MissingTableException when database table $tableName is not found on data source
1152
 * @return void
1153
 */
1154
        public function setSource($tableName) {
1155
                $this->setDataSource($this->useDbConfig);
1156
                $db = ConnectionManager::getDataSource($this->useDbConfig);
1157

    
1158
                if (method_exists($db, 'listSources')) {
1159
                        $restore = $db->cacheSources;
1160
                        $db->cacheSources = ($restore && $this->cacheSources);
1161
                        $sources = $db->listSources();
1162
                        $db->cacheSources = $restore;
1163

    
1164
                        if (is_array($sources) && !in_array(strtolower($this->tablePrefix . $tableName), array_map('strtolower', $sources))) {
1165
                                throw new MissingTableException(array(
1166
                                        'table' => $this->tablePrefix . $tableName,
1167
                                        'class' => $this->alias,
1168
                                        'ds' => $this->useDbConfig,
1169
                                ));
1170
                        }
1171

    
1172
                        if ($sources) {
1173
                                $this->_schema = null;
1174
                        }
1175
                }
1176

    
1177
                $this->table = $this->useTable = $tableName;
1178
                $this->tableToModel[$this->table] = $this->alias;
1179
        }
1180

    
1181
/**
1182
 * This function does two things:
1183
 *
1184
 * 1. it scans the array $one for the primary key,
1185
 * and if that's found, it sets the current id to the value of $one[id].
1186
 * For all other keys than 'id' the keys and values of $one are copied to the 'data' property of this object.
1187
 * 2. Returns an array with all of $one's keys and values.
1188
 * (Alternative indata: two strings, which are mangled to
1189
 * a one-item, two-dimensional array using $one for a key and $two as its value.)
1190
 *
1191
 * @param string|array|SimpleXmlElement|DomNode $one Array or string of data
1192
 * @param string $two Value string for the alternative indata method
1193
 * @return array|null Data with all of $one's keys and values, otherwise null.
1194
 * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html
1195
 */
1196
        public function set($one, $two = null) {
1197
                if (!$one) {
1198
                        return null;
1199
                }
1200

    
1201
                if (is_object($one)) {
1202
                        if ($one instanceof SimpleXMLElement || $one instanceof DOMNode) {
1203
                                $one = $this->_normalizeXmlData(Xml::toArray($one));
1204
                        } else {
1205
                                $one = Set::reverse($one);
1206
                        }
1207
                }
1208

    
1209
                if (is_array($one)) {
1210
                        $data = $one;
1211
                        if (empty($one[$this->alias])) {
1212
                                $data = $this->_setAliasData($one);
1213
                        }
1214
                } else {
1215
                        $data = array($this->alias => array($one => $two));
1216
                }
1217

    
1218
                foreach ($data as $modelName => $fieldSet) {
1219
                        if (!is_array($fieldSet)) {
1220
                                continue;
1221
                        }
1222

    
1223
                        if (!isset($this->data[$modelName])) {
1224
                                $this->data[$modelName] = array();
1225
                        }
1226

    
1227
                        foreach ($fieldSet as $fieldName => $fieldValue) {
1228
                                unset($this->validationErrors[$fieldName]);
1229

    
1230
                                if ($modelName === $this->alias && $fieldName === $this->primaryKey) {
1231
                                        $this->id = $fieldValue;
1232
                                }
1233

    
1234
                                if (is_array($fieldValue) || is_object($fieldValue)) {
1235
                                        $fieldValue = $this->deconstruct($fieldName, $fieldValue);
1236
                                }
1237

    
1238
                                $this->data[$modelName][$fieldName] = $fieldValue;
1239
                        }
1240
                }
1241

    
1242
                return $data;
1243
        }
1244

    
1245
/**
1246
 * Move values to alias
1247
 *
1248
 * @param array $data Data.
1249
 * @return array
1250
 */
1251
        protected function _setAliasData($data) {
1252
                $models = array_keys($this->getAssociated());
1253
                $schema = array_keys((array)$this->schema());
1254

    
1255
                foreach ($data as $field => $value) {
1256
                        if (in_array($field, $schema) || !in_array($field, $models)) {
1257
                                $data[$this->alias][$field] = $value;
1258
                                unset($data[$field]);
1259
                        }
1260
                }
1261

    
1262
                return $data;
1263
        }
1264

    
1265
/**
1266
 * Normalize `Xml::toArray()` to use in `Model::save()`
1267
 *
1268
 * @param array $xml XML as array
1269
 * @return array
1270
 */
1271
        protected function _normalizeXmlData(array $xml) {
1272
                $return = array();
1273
                foreach ($xml as $key => $value) {
1274
                        if (is_array($value)) {
1275
                                $return[Inflector::camelize($key)] = $this->_normalizeXmlData($value);
1276
                        } elseif ($key[0] === '@') {
1277
                                $return[substr($key, 1)] = $value;
1278
                        } else {
1279
                                $return[$key] = $value;
1280
                        }
1281
                }
1282

    
1283
                return $return;
1284
        }
1285

    
1286
/**
1287
 * Deconstructs a complex data type (array or object) into a single field value.
1288
 *
1289
 * @param string $field The name of the field to be deconstructed
1290
 * @param array|object $data An array or object to be deconstructed into a field
1291
 * @return mixed The resulting data that should be assigned to a field
1292
 */
1293
        public function deconstruct($field, $data) {
1294
                if (!is_array($data)) {
1295
                        return $data;
1296
                }
1297

    
1298
                $type = $this->getColumnType($field);
1299

    
1300
                if (!in_array($type, array('datetime', 'timestamp', 'date', 'time'))) {
1301
                        return $data;
1302
                }
1303

    
1304
                $useNewDate = (isset($data['year']) || isset($data['month']) ||
1305
                        isset($data['day']) || isset($data['hour']) || isset($data['minute']));
1306

    
1307
                $dateFields = array('Y' => 'year', 'm' => 'month', 'd' => 'day', 'H' => 'hour', 'i' => 'min', 's' => 'sec');
1308
                $timeFields = array('H' => 'hour', 'i' => 'min', 's' => 'sec');
1309
                $date = array();
1310

    
1311
                if (isset($data['meridian']) && empty($data['meridian'])) {
1312
                        return null;
1313
                }
1314

    
1315
                if (isset($data['hour']) &&
1316
                        isset($data['meridian']) &&
1317
                        !empty($data['hour']) &&
1318
                        $data['hour'] != 12 &&
1319
                        $data['meridian'] === 'pm'
1320
                ) {
1321
                        $data['hour'] = $data['hour'] + 12;
1322
                }
1323

    
1324
                if (isset($data['hour']) && isset($data['meridian']) && $data['hour'] == 12 && $data['meridian'] === 'am') {
1325
                        $data['hour'] = '00';
1326
                }
1327

    
1328
                if ($type === 'time') {
1329
                        foreach ($timeFields as $key => $val) {
1330
                                if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') {
1331
                                        $data[$val] = '00';
1332
                                } elseif ($data[$val] !== '') {
1333
                                        $data[$val] = sprintf('%02d', $data[$val]);
1334
                                }
1335

    
1336
                                if (!empty($data[$val])) {
1337
                                        $date[$key] = $data[$val];
1338
                                } else {
1339
                                        return null;
1340
                                }
1341
                        }
1342
                }
1343

    
1344
                if ($type === 'datetime' || $type === 'timestamp' || $type === 'date') {
1345
                        foreach ($dateFields as $key => $val) {
1346
                                if ($val === 'hour' || $val === 'min' || $val === 'sec') {
1347
                                        if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') {
1348
                                                $data[$val] = '00';
1349
                                        } else {
1350
                                                $data[$val] = sprintf('%02d', $data[$val]);
1351
                                        }
1352
                                }
1353

    
1354
                                if (!isset($data[$val]) || isset($data[$val]) && (empty($data[$val]) || $data[$val][0] === '-')) {
1355
                                        return null;
1356
                                }
1357

    
1358
                                if (isset($data[$val]) && !empty($data[$val])) {
1359
                                        $date[$key] = $data[$val];
1360
                                }
1361
                        }
1362
                }
1363

    
1364
                if ($useNewDate && !empty($date)) {
1365
                        $format = $this->getDataSource()->columns[$type]['format'];
1366
                        foreach (array('m', 'd', 'H', 'i', 's') as $index) {
1367
                                if (isset($date[$index])) {
1368
                                        $date[$index] = sprintf('%02d', $date[$index]);
1369
                                }
1370
                        }
1371

    
1372
                        return str_replace(array_keys($date), array_values($date), $format);
1373
                }
1374

    
1375
                return $data;
1376
        }
1377

    
1378
/**
1379
 * Returns an array of table metadata (column names and types) from the database.
1380
 * $field => keys(type, null, default, key, length, extra)
1381
 *
1382
 * @param bool|string $field Set to true to reload schema, or a string to return a specific field
1383
 * @return array|null Array of table metadata
1384
 */
1385
        public function schema($field = false) {
1386
                if ($this->useTable !== false && (!is_array($this->_schema) || $field === true)) {
1387
                        $db = $this->getDataSource();
1388
                        $db->cacheSources = ($this->cacheSources && $db->cacheSources);
1389
                        if (method_exists($db, 'describe')) {
1390
                                $this->_schema = $db->describe($this);
1391
                        }
1392
                }
1393

    
1394
                if (!is_string($field)) {
1395
                        return $this->_schema;
1396
                }
1397

    
1398
                if (isset($this->_schema[$field])) {
1399
                        return $this->_schema[$field];
1400
                }
1401

    
1402
                return null;
1403
        }
1404

    
1405
/**
1406
 * Returns an associative array of field names and column types.
1407
 *
1408
 * @return array Field types indexed by field name
1409
 */
1410
        public function getColumnTypes() {
1411
                $columns = $this->schema();
1412
                if (empty($columns)) {
1413
                        trigger_error(__d('cake_dev', '(Model::getColumnTypes) Unable to build model field data. If you are using a model without a database table, try implementing schema()'), E_USER_WARNING);
1414
                }
1415

    
1416
                $cols = array();
1417
                foreach ($columns as $field => $values) {
1418
                        $cols[$field] = $values['type'];
1419
                }
1420

    
1421
                return $cols;
1422
        }
1423

    
1424
/**
1425
 * Returns the column type of a column in the model.
1426
 *
1427
 * @param string $column The name of the model column
1428
 * @return string Column type
1429
 */
1430
        public function getColumnType($column) {
1431
                $cols = $this->schema();
1432
                if (isset($cols[$column]) && isset($cols[$column]['type'])) {
1433
                        return $cols[$column]['type'];
1434
                }
1435

    
1436
                $db = $this->getDataSource();
1437
                $model = null;
1438

    
1439
                $startQuote = isset($db->startQuote) ? $db->startQuote : null;
1440
                $endQuote = isset($db->endQuote) ? $db->endQuote : null;
1441
                $column = str_replace(array($startQuote, $endQuote), '', $column);
1442

    
1443
                if (strpos($column, '.')) {
1444
                        list($model, $column) = explode('.', $column);
1445
                }
1446

    
1447
                if (isset($model) && $model != $this->alias && isset($this->{$model})) {
1448
                        return $this->{$model}->getColumnType($column);
1449
                }
1450

    
1451
                if (isset($cols[$column]) && isset($cols[$column]['type'])) {
1452
                        return $cols[$column]['type'];
1453
                }
1454

    
1455
                return null;
1456
        }
1457

    
1458
/**
1459
 * Returns true if the supplied field exists in the model's database table.
1460
 *
1461
 * @param string|array $name Name of field to look for, or an array of names
1462
 * @param bool $checkVirtual checks if the field is declared as virtual
1463
 * @return mixed If $name is a string, returns a boolean indicating whether the field exists.
1464
 *               If $name is an array of field names, returns the first field that exists,
1465
 *               or false if none exist.
1466
 */
1467
        public function hasField($name, $checkVirtual = false) {
1468
                if (is_array($name)) {
1469
                        foreach ($name as $n) {
1470
                                if ($this->hasField($n, $checkVirtual)) {
1471
                                        return $n;
1472
                                }
1473
                        }
1474

    
1475
                        return false;
1476
                }
1477

    
1478
                if ($checkVirtual && !empty($this->virtualFields) && $this->isVirtualField($name)) {
1479
                        return true;
1480
                }
1481

    
1482
                if (empty($this->_schema)) {
1483
                        $this->schema();
1484
                }
1485

    
1486
                if ($this->_schema) {
1487
                        return isset($this->_schema[$name]);
1488
                }
1489

    
1490
                return false;
1491
        }
1492

    
1493
/**
1494
 * Check that a method is callable on a model. This will check both the model's own methods, its
1495
 * inherited methods and methods that could be callable through behaviors.
1496
 *
1497
 * @param string $method The method to be called.
1498
 * @return bool True on method being callable.
1499
 */
1500
        public function hasMethod($method) {
1501
                if (method_exists($this, $method)) {
1502
                        return true;
1503
                }
1504

    
1505
                return $this->Behaviors->hasMethod($method);
1506
        }
1507

    
1508
/**
1509
 * Returns true if the supplied field is a model Virtual Field
1510
 *
1511
 * @param string $field Name of field to look for
1512
 * @return bool indicating whether the field exists as a model virtual field.
1513
 */
1514
        public function isVirtualField($field) {
1515
                if (empty($this->virtualFields) || !is_string($field)) {
1516
                        return false;
1517
                }
1518

    
1519
                if (isset($this->virtualFields[$field])) {
1520
                        return true;
1521
                }
1522

    
1523
                if (strpos($field, '.') !== false) {
1524
                        list($model, $field) = explode('.', $field);
1525
                        if ($model === $this->alias && isset($this->virtualFields[$field])) {
1526
                                return true;
1527
                        }
1528
                }
1529

    
1530
                return false;
1531
        }
1532

    
1533
/**
1534
 * Returns the expression for a model virtual field
1535
 *
1536
 * @param string $field Name of field to look for
1537
 * @return mixed If $field is string expression bound to virtual field $field
1538
 *    If $field is null, returns an array of all model virtual fields
1539
 *    or false if none $field exist.
1540
 */
1541
        public function getVirtualField($field = null) {
1542
                if (!$field) {
1543
                        return empty($this->virtualFields) ? false : $this->virtualFields;
1544
                }
1545

    
1546
                if ($this->isVirtualField($field)) {
1547
                        if (strpos($field, '.') !== false) {
1548
                                list(, $field) = pluginSplit($field);
1549
                        }
1550

    
1551
                        return $this->virtualFields[$field];
1552
                }
1553

    
1554
                return false;
1555
        }
1556

    
1557
/**
1558
 * Initializes the model for writing a new record, loading the default values
1559
 * for those fields that are not defined in $data, and clearing previous validation errors.
1560
 * Especially helpful for saving data in loops.
1561
 *
1562
 * @param bool|array $data Optional data array to assign to the model after it is created. If null or false,
1563
 *   schema data defaults are not merged.
1564
 * @param bool $filterKey If true, overwrites any primary key input with an empty value
1565
 * @return array The current Model::data; after merging $data and/or defaults from database
1566
 * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-create-array-data-array
1567
 */
1568
        public function create($data = array(), $filterKey = false) {
1569
                $defaults = array();
1570
                $this->id = false;
1571
                $this->data = array();
1572
                $this->validationErrors = array();
1573

    
1574
                if ($data !== null && $data !== false) {
1575
                        $schema = (array)$this->schema();
1576
                        foreach ($schema as $field => $properties) {
1577
                                if ($this->primaryKey !== $field && isset($properties['default']) && $properties['default'] !== '') {
1578
                                        $defaults[$field] = $properties['default'];
1579
                                }
1580
                        }
1581

    
1582
                        $this->set($defaults);
1583
                        $this->set($data);
1584
                }
1585

    
1586
                if ($filterKey) {
1587
                        $this->set($this->primaryKey, false);
1588
                }
1589

    
1590
                return $this->data;
1591
        }
1592

    
1593
/**
1594
 * This function is a convenient wrapper class to create(false) and, as the name suggests, clears the id, data, and validation errors.
1595
 *
1596
 * @return bool Always true upon success
1597
 * @see Model::create()
1598
 */
1599
        public function clear() {
1600
                $this->create(false);
1601
                return true;
1602
        }
1603

    
1604
/**
1605
 * Returns a list of fields from the database, and sets the current model
1606
 * data (Model::$data) with the record found.
1607
 *
1608
 * @param string|array $fields String of single field name, or an array of field names.
1609
 * @param int|string $id The ID of the record to read
1610
 * @return array Array of database fields, or false if not found
1611
 * @link http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-read
1612
 */
1613
        public function read($fields = null, $id = null) {
1614
                $this->validationErrors = array();
1615

    
1616
                if ($id) {
1617
                        $this->id = $id;
1618
                }
1619

    
1620
                $id = $this->id;
1621

    
1622
                if (is_array($this->id)) {
1623
                        $id = $this->id[0];
1624
                }
1625

    
1626
                if ($id !== null && $id !== false) {
1627
                        $this->data = $this->find('first', array(
1628
                                'conditions' => array($this->alias . '.' . $this->primaryKey => $id),
1629
                                'fields' => $fields
1630
                        ));
1631

    
1632
                        return $this->data;
1633
                }
1634

    
1635
                return false;
1636
        }
1637

    
1638
/**
1639
 * Returns the content of a single field given the supplied conditions,
1640
 * of the first record in the supplied order.
1641
 *
1642
 * @param string $name The name of the field to get.
1643
 * @param array $conditions SQL conditions (defaults to NULL).
1644
 * @param string $order SQL ORDER BY fragment.
1645
 * @return string|false Field content, or false if not found.
1646
 * @link http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-field
1647
 */
1648
        public function field($name, $conditions = null, $order = null) {
1649
                if ($conditions === null && $this->id !== false) {
1650
                        $conditions = array($this->alias . '.' . $this->primaryKey => $this->id);
1651
                }
1652

    
1653
                $recursive = $this->recursive;
1654
                if ($this->recursive >= 1) {
1655
                        $recursive = -1;
1656
                }
1657

    
1658
                $fields = $name;
1659
                $data = $this->find('first', compact('conditions', 'fields', 'order', 'recursive'));
1660
                if (!$data) {
1661
                        return false;
1662
                }
1663

    
1664
                if (strpos($name, '.') === false) {
1665
                        if (isset($data[$this->alias][$name])) {
1666
                                return $data[$this->alias][$name];
1667
                        }
1668
                } else {
1669
                        $name = explode('.', $name);
1670
                        if (isset($data[$name[0]][$name[1]])) {
1671
                                return $data[$name[0]][$name[1]];
1672
                        }
1673
                }
1674

    
1675
                if (isset($data[0]) && count($data[0]) > 0) {
1676
                        return array_shift($data[0]);
1677
                }
1678
        }
1679

    
1680
/**
1681
 * Saves the value of a single field to the database, based on the current
1682
 * model ID.
1683
 *
1684
 * @param string $name Name of the table field
1685
 * @param mixed $value Value of the field
1686
 * @param bool|array $validate Either a boolean, or an array.
1687
 *   If a boolean, indicates whether or not to validate before saving.
1688
 *   If an array, allows control of 'validate', 'callbacks' and 'counterCache' options.
1689
 *   See Model::save() for details of each options.
1690
 * @return bool|array See Model::save() False on failure or an array of model data on success.
1691
 * @see Model::save()
1692
 * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-savefield-string-fieldname-string-fieldvalue-validate-false
1693
 */
1694
        public function saveField($name, $value, $validate = false) {
1695
                $id = $this->id;
1696
                $this->create(false);
1697

    
1698
                $options = array('validate' => $validate, 'fieldList' => array($name));
1699
                if (is_array($validate)) {
1700
                        $options = $validate + array('validate' => false, 'fieldList' => array($name));
1701
                }
1702

    
1703
                return $this->save(array($this->alias => array($this->primaryKey => $id, $name => $value)), $options);
1704
        }
1705

    
1706
/**
1707
 * Saves model data (based on white-list, if supplied) to the database. By
1708
 * default, validation occurs before save. Passthrough method to _doSave() with
1709
 * transaction handling.
1710
 *
1711
 * @param array $data Data to save.
1712
 * @param bool|array $validate Either a boolean, or an array.
1713
 *   If a boolean, indicates whether or not to validate before saving.
1714
 *   If an array, can have following keys:
1715
 *
1716
 *   - atomic: If true (default), will attempt to save the record in a single transaction.
1717
 *   - validate: Set to true/false to enable or disable validation.
1718
 *   - fieldList: An array of fields you want to allow for saving.
1719
 *   - callbacks: Set to false to disable callbacks. Using 'before' or 'after'
1720
 *     will enable only those callbacks.
1721
 *   - `counterCache`: Boolean to control updating of counter caches (if any)
1722
 *
1723
 * @param array $fieldList List of fields to allow to be saved
1724
 * @return mixed On success Model::$data if its not empty or true, false on failure
1725
 * @throws Exception
1726
 * @throws PDOException
1727
 * @triggers Model.beforeSave $this, array($options)
1728
 * @triggers Model.afterSave $this, array($created, $options)
1729
 * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html
1730
 */
1731
        public function save($data = null, $validate = true, $fieldList = array()) {
1732
                $defaults = array(
1733
                        'validate' => true, 'fieldList' => array(),
1734
                        'callbacks' => true, 'counterCache' => true,
1735
                        'atomic' => true
1736
                );
1737

    
1738
                if (!is_array($validate)) {
1739
                        $options = compact('validate', 'fieldList') + $defaults;
1740
                } else {
1741
                        $options = $validate + $defaults;
1742
                }
1743

    
1744
                if (!$options['atomic']) {
1745
                        return $this->_doSave($data, $options);
1746
                }
1747

    
1748
                $db = $this->getDataSource();
1749
                $transactionBegun = $db->begin();
1750
                try {
1751
                        $success = $this->_doSave($data, $options);
1752
                        if ($transactionBegun) {
1753
                                if ($success) {
1754
                                        $db->commit();
1755
                                } else {
1756
                                        $db->rollback();
1757
                                }
1758
                        }
1759
                        return $success;
1760
                } catch (Exception $e) {
1761
                        if ($transactionBegun) {
1762
                                $db->rollback();
1763
                        }
1764
                        throw $e;
1765
                }
1766
        }
1767

    
1768
/**
1769
 * Saves model data (based on white-list, if supplied) to the database. By
1770
 * default, validation occurs before save.
1771
 *
1772
 * @param array $data Data to save.
1773
 * @param array $options can have following keys:
1774
 *
1775
 *   - validate: Set to true/false to enable or disable validation.
1776
 *   - fieldList: An array of fields you want to allow for saving.
1777
 *   - callbacks: Set to false to disable callbacks. Using 'before' or 'after'
1778
 *      will enable only those callbacks.
1779
 *   - `counterCache`: Boolean to control updating of counter caches (if any)
1780
 *
1781
 * @return mixed On success Model::$data if its not empty or true, false on failure
1782
 * @throws PDOException
1783
 * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html
1784
 */
1785
        protected function _doSave($data = null, $options = array()) {
1786
                $_whitelist = $this->whitelist;
1787
                $fields = array();
1788

    
1789
                if (!empty($options['fieldList'])) {
1790
                        if (!empty($options['fieldList'][$this->alias]) && is_array($options['fieldList'][$this->alias])) {
1791
                                $this->whitelist = $options['fieldList'][$this->alias];
1792
                        } elseif (Hash::dimensions($options['fieldList']) < 2) {
1793
                                $this->whitelist = $options['fieldList'];
1794
                        }
1795
                } elseif ($options['fieldList'] === null) {
1796
                        $this->whitelist = array();
1797
                }
1798

    
1799
                $this->set($data);
1800

    
1801
                if (empty($this->data) && !$this->hasField(array('created', 'updated', 'modified'))) {
1802
                        $this->whitelist = $_whitelist;
1803
                        return false;
1804
                }
1805

    
1806
                foreach (array('created', 'updated', 'modified') as $field) {
1807
                        $keyPresentAndEmpty = (
1808
                                isset($this->data[$this->alias]) &&
1809
                                array_key_exists($field, $this->data[$this->alias]) &&
1810
                                $this->data[$this->alias][$field] === null
1811
                        );
1812

    
1813
                        if ($keyPresentAndEmpty) {
1814
                                unset($this->data[$this->alias][$field]);
1815
                        }
1816
                }
1817

    
1818
                $exists = $this->exists();
1819
                $dateFields = array('modified', 'updated');
1820

    
1821
                if (!$exists) {
1822
                        $dateFields[] = 'created';
1823
                }
1824

    
1825
                if (isset($this->data[$this->alias])) {
1826
                        $fields = array_keys($this->data[$this->alias]);
1827
                }
1828

    
1829
                if ($options['validate'] && !$this->validates($options)) {
1830
                        $this->whitelist = $_whitelist;
1831
                        return false;
1832
                }
1833

    
1834
                $db = $this->getDataSource();
1835
                $now = time();
1836

    
1837
                foreach ($dateFields as $updateCol) {
1838
                        $fieldHasValue = in_array($updateCol, $fields);
1839
                        $fieldInWhitelist = (
1840
                                count($this->whitelist) === 0 ||
1841
                                in_array($updateCol, $this->whitelist)
1842
                        );
1843
                        if (($fieldHasValue && $fieldInWhitelist) || !$this->hasField($updateCol)) {
1844
                                continue;
1845
                        }
1846

    
1847
                        $default = array('formatter' => 'date');
1848
                        $colType = array_merge($default, $db->columns[$this->getColumnType($updateCol)]);
1849

    
1850
                        $time = $now;
1851
                        if (array_key_exists('format', $colType)) {
1852
                                $time = call_user_func($colType['formatter'], $colType['format']);
1853
                        }
1854

    
1855
                        if (!empty($this->whitelist)) {
1856
                                $this->whitelist[] = $updateCol;
1857
                        }
1858
                        $this->set($updateCol, $time);
1859
                }
1860

    
1861
                if ($options['callbacks'] === true || $options['callbacks'] === 'before') {
1862
                        $event = new CakeEvent('Model.beforeSave', $this, array($options));
1863
                        list($event->break, $event->breakOn) = array(true, array(false, null));
1864
                        $this->getEventManager()->dispatch($event);
1865
                        if (!$event->result) {
1866
                                $this->whitelist = $_whitelist;
1867
                                return false;
1868
                        }
1869
                }
1870

    
1871
                if (empty($this->data[$this->alias][$this->primaryKey])) {
1872
                        unset($this->data[$this->alias][$this->primaryKey]);
1873
                }
1874
                $joined = $fields = $values = array();
1875

    
1876
                foreach ($this->data as $n => $v) {
1877
                        if (isset($this->hasAndBelongsToMany[$n])) {
1878
                                if (isset($v[$n])) {
1879
                                        $v = $v[$n];
1880
                                }
1881
                                $joined[$n] = $v;
1882
                        } elseif ($n === $this->alias) {
1883
                                foreach (array('created', 'updated', 'modified') as $field) {
1884
                                        if (array_key_exists($field, $v) && empty($v[$field])) {
1885
                                                unset($v[$field]);
1886
                                        }
1887
                                }
1888

    
1889
                                foreach ($v as $x => $y) {
1890
                                        if ($this->hasField($x) && (empty($this->whitelist) || in_array($x, $this->whitelist))) {
1891
                                                list($fields[], $values[]) = array($x, $y);
1892
                                        }
1893
                                }
1894
                        }
1895
                }
1896

    
1897
                if (empty($fields) && empty($joined)) {
1898
                        $this->whitelist = $_whitelist;
1899
                        return false;
1900
                }
1901

    
1902
                $count = count($fields);
1903

    
1904
                if (!$exists && $count > 0) {
1905
                        $this->id = false;
1906
                }
1907

    
1908
                $success = true;
1909
                $created = false;
1910

    
1911
                if ($count > 0) {
1912
                        $cache = $this->_prepareUpdateFields(array_combine($fields, $values));
1913

    
1914
                        if (!empty($this->id)) {
1915
                                $this->__safeUpdateMode = true;
1916
                                try {
1917
                                        $success = (bool)$db->update($this, $fields, $values);
1918
                                } catch (Exception $e) {
1919
                                        $this->__safeUpdateMode = false;
1920
                                        throw $e;
1921
                                }
1922
                                $this->__safeUpdateMode = false;
1923
                        } else {
1924
                                if (empty($this->data[$this->alias][$this->primaryKey]) && $this->_isUUIDField($this->primaryKey)) {
1925
                                        if (array_key_exists($this->primaryKey, $this->data[$this->alias])) {
1926
                                                $j = array_search($this->primaryKey, $fields);
1927
                                                $values[$j] = CakeText::uuid();
1928
                                        } else {
1929
                                                list($fields[], $values[]) = array($this->primaryKey, CakeText::uuid());
1930
                                        }
1931
                                }
1932

    
1933
                                if (!$db->create($this, $fields, $values)) {
1934
                                        $success = false;
1935
                                } else {
1936
                                        $created = true;
1937
                                }
1938
                        }
1939

    
1940
                        if ($success && $options['counterCache'] && !empty($this->belongsTo)) {
1941
                                $this->updateCounterCache($cache, $created);
1942
                        }
1943
                }
1944

    
1945
                if ($success && !empty($joined)) {
1946
                        $this->_saveMulti($joined, $this->id, $db);
1947
                }
1948

    
1949
                if (!$success) {
1950
                        $this->whitelist = $_whitelist;
1951
                        return $success;
1952
                }
1953

    
1954
                if ($count > 0) {
1955
                        if ($created) {
1956
                                $this->data[$this->alias][$this->primaryKey] = $this->id;
1957
                        }
1958

    
1959
                        if ($options['callbacks'] === true || $options['callbacks'] === 'after') {
1960
                                $event = new CakeEvent('Model.afterSave', $this, array($created, $options));
1961
                                $this->getEventManager()->dispatch($event);
1962
                        }
1963
                }
1964

    
1965
                if (!empty($this->data)) {
1966
                        $success = $this->data;
1967
                }
1968

    
1969
                $this->_clearCache();
1970
                $this->validationErrors = array();
1971
                $this->whitelist = $_whitelist;
1972
                $this->data = false;
1973

    
1974
                return $success;
1975
        }
1976

    
1977
/**
1978
 * Check if the passed in field is a UUID field
1979
 *
1980
 * @param string $field the field to check
1981
 * @return bool
1982
 */
1983
        protected function _isUUIDField($field) {
1984
                $field = $this->schema($field);
1985
                return $field['length'] == 36 && in_array($field['type'], array('string', 'binary'));
1986
        }
1987

    
1988
/**
1989
 * Saves model hasAndBelongsToMany data to the database.
1990
 *
1991
 * @param array $joined Data to save
1992
 * @param int|string $id ID of record in this model
1993
 * @param DataSource $db Datasource instance.
1994
 * @return void
1995
 */
1996
        protected function _saveMulti($joined, $id, $db) {
1997
                foreach ($joined as $assoc => $data) {
1998
                        if (!isset($this->hasAndBelongsToMany[$assoc])) {
1999
                                continue;
2000
                        }
2001

    
2002
                        $habtm = $this->hasAndBelongsToMany[$assoc];
2003

    
2004
                        list($join) = $this->joinModel($habtm['with']);
2005

    
2006
                        $Model = $this->{$join};
2007

    
2008
                        if (!empty($habtm['with'])) {
2009
                                $withModel = is_array($habtm['with']) ? key($habtm['with']) : $habtm['with'];
2010
                                list(, $withModel) = pluginSplit($withModel);
2011
                                $dbMulti = $this->{$withModel}->getDataSource();
2012
                        } else {
2013
                                $dbMulti = $db;
2014
                        }
2015

    
2016
                        $isUUID = !empty($Model->primaryKey) && $Model->_isUUIDField($Model->primaryKey);
2017

    
2018
                        $newData = $newValues = $newJoins = array();
2019
                        $primaryAdded = false;
2020

    
2021
                        $fields = array(
2022
                                $dbMulti->name($habtm['foreignKey']),
2023
                                $dbMulti->name($habtm['associationForeignKey'])
2024
                        );
2025

    
2026
                        $idField = $db->name($Model->primaryKey);
2027
                        if ($isUUID && !in_array($idField, $fields)) {
2028
                                $fields[] = $idField;
2029
                                $primaryAdded = true;
2030
                        }
2031

    
2032
                        foreach ((array)$data as $row) {
2033
                                if ((is_string($row) && (strlen($row) === 36 || strlen($row) === 16)) || is_numeric($row)) {
2034
                                        $newJoins[] = $row;
2035
                                        $values = array($id, $row);
2036

    
2037
                                        if ($isUUID && $primaryAdded) {
2038
                                                $values[] = CakeText::uuid();
2039
                                        }
2040

    
2041
                                        $newValues[$row] = $values;
2042
                                        unset($values);
2043
                                } elseif (isset($row[$habtm['associationForeignKey']])) {
2044
                                        if (!empty($row[$Model->primaryKey])) {
2045
                                                $newJoins[] = $row[$habtm['associationForeignKey']];
2046
                                        }
2047

    
2048
                                        $newData[] = $row;
2049
                                } elseif (isset($row[$join]) && isset($row[$join][$habtm['associationForeignKey']])) {
2050
                                        if (!empty($row[$join][$Model->primaryKey])) {
2051
                                                $newJoins[] = $row[$join][$habtm['associationForeignKey']];
2052
                                        }
2053

    
2054
                                        $newData[] = $row[$join];
2055
                                }
2056
                        }
2057

    
2058
                        $keepExisting = $habtm['unique'] === 'keepExisting';
2059
                        if ($habtm['unique']) {
2060
                                $conditions = array(
2061
                                        $join . '.' . $habtm['foreignKey'] => $id
2062
                                );
2063

    
2064
                                if (!empty($habtm['conditions'])) {
2065
                                        $conditions = array_merge($conditions, (array)$habtm['conditions']);
2066
                                }
2067

    
2068
                                $associationForeignKey = $Model->alias . '.' . $habtm['associationForeignKey'];
2069
                                $links = $Model->find('all', array(
2070
                                        'conditions' => $conditions,
2071
                                        'recursive' => empty($habtm['conditions']) ? -1 : 0,
2072
                                        'fields' => $associationForeignKey,
2073
                                ));
2074

    
2075
                                $oldLinks = Hash::extract($links, "{n}.{$associationForeignKey}");
2076
                                if (!empty($oldLinks)) {
2077
                                        if ($keepExisting && !empty($newJoins)) {
2078
                                                $conditions[$associationForeignKey] = array_diff($oldLinks, $newJoins);
2079
                                        } else {
2080
                                                $conditions[$associationForeignKey] = $oldLinks;
2081
                                        }
2082

    
2083
                                        $dbMulti->delete($Model, $conditions);
2084
                                }
2085
                        }
2086

    
2087
                        if (!empty($newData)) {
2088
                                foreach ($newData as $data) {
2089
                                        $data[$habtm['foreignKey']] = $id;
2090
                                        if (empty($data[$Model->primaryKey])) {
2091
                                                $Model->create();
2092
                                        }
2093

    
2094
                                        $Model->save($data, array('atomic' => false));
2095
                                }
2096
                        }
2097

    
2098
                        if (!empty($newValues)) {
2099
                                if ($keepExisting && !empty($links)) {
2100
                                        foreach ($links as $link) {
2101
                                                $oldJoin = $link[$join][$habtm['associationForeignKey']];
2102
                                                if (!in_array($oldJoin, $newJoins)) {
2103
                                                        $conditions[$associationForeignKey] = $oldJoin;
2104
                                                        $db->delete($Model, $conditions);
2105
                                                } else {
2106
                                                        unset($newValues[$oldJoin]);
2107
                                                }
2108
                                        }
2109

    
2110
                                        $newValues = array_values($newValues);
2111
                                }
2112

    
2113
                                if (!empty($newValues)) {
2114
                                        $dbMulti->insertMulti($Model, $fields, $newValues);
2115
                                }
2116
                        }
2117
                }
2118
        }
2119

    
2120
/**
2121
 * Updates the counter cache of belongsTo associations after a save or delete operation
2122
 *
2123
 * @param array $keys Optional foreign key data, defaults to the information $this->data
2124
 * @param bool $created True if a new record was created, otherwise only associations with
2125
 *   'counterScope' defined get updated
2126
 * @return void
2127
 */
2128
        public function updateCounterCache($keys = array(), $created = false) {
2129
                if (empty($keys) && isset($this->data[$this->alias])) {
2130
                        $keys = $this->data[$this->alias];
2131
                }
2132
                $keys['old'] = isset($keys['old']) ? $keys['old'] : array();
2133

    
2134
                foreach ($this->belongsTo as $parent => $assoc) {
2135
                        if (empty($assoc['counterCache'])) {
2136
                                continue;
2137
                        }
2138

    
2139
                        $Model = $this->{$parent};
2140

    
2141
                        if (!is_array($assoc['counterCache'])) {
2142
                                if (isset($assoc['counterScope'])) {
2143
                                        $assoc['counterCache'] = array($assoc['counterCache'] => $assoc['counterScope']);
2144
                                } else {
2145
                                        $assoc['counterCache'] = array($assoc['counterCache'] => array());
2146
                                }
2147
                        }
2148

    
2149
                        $foreignKey = $assoc['foreignKey'];
2150
                        $fkQuoted = $this->escapeField($assoc['foreignKey']);
2151

    
2152
                        foreach ($assoc['counterCache'] as $field => $conditions) {
2153
                                if (!is_string($field)) {
2154
                                        $field = Inflector::underscore($this->alias) . '_count';
2155
                                }
2156

    
2157
                                if (!$Model->hasField($field)) {
2158
                                        continue;
2159
                                }
2160

    
2161
                                if ($conditions === true) {
2162
                                        $conditions = array();
2163
                                } else {
2164
                                        $conditions = (array)$conditions;
2165
                                }
2166

    
2167
                                if (!array_key_exists($foreignKey, $keys)) {
2168
                                        $keys[$foreignKey] = $this->field($foreignKey);
2169
                                }
2170

    
2171
                                $recursive = (empty($conditions) ? -1 : 0);
2172

    
2173
                                if (isset($keys['old'][$foreignKey]) && $keys['old'][$foreignKey] != $keys[$foreignKey]) {
2174
                                        $conditions[$fkQuoted] = $keys['old'][$foreignKey];
2175
                                        $count = (int)$this->find('count', compact('conditions', 'recursive'));
2176

    
2177
                                        $Model->updateAll(
2178
                                                array($field => $count),
2179
                                                array($Model->escapeField() => $keys['old'][$foreignKey])
2180
                                        );
2181
                                }
2182

    
2183
                                $conditions[$fkQuoted] = $keys[$foreignKey];
2184

    
2185
                                if ($recursive === 0) {
2186
                                        $conditions = array_merge($conditions, (array)$conditions);
2187
                                }
2188

    
2189
                                $count = (int)$this->find('count', compact('conditions', 'recursive'));
2190

    
2191
                                $Model->updateAll(
2192
                                        array($field => $count),
2193
                                        array($Model->escapeField() => $keys[$foreignKey])
2194
                                );
2195
                        }
2196
                }
2197
        }
2198

    
2199
/**
2200
 * Helper method for `Model::updateCounterCache()`. Checks the fields to be updated for
2201
 *
2202
 * @param array $data The fields of the record that will be updated
2203
 * @return array Returns updated foreign key values, along with an 'old' key containing the old
2204
 *     values, or empty if no foreign keys are updated.
2205
 */
2206
        protected function _prepareUpdateFields($data) {
2207
                $foreignKeys = array();
2208
                foreach ($this->belongsTo as $assoc => $info) {
2209
                        if (isset($info['counterCache']) && $info['counterCache']) {
2210
                                $foreignKeys[$assoc] = $info['foreignKey'];
2211
                        }
2212
                }
2213

    
2214
                $included = array_intersect($foreignKeys, array_keys($data));
2215

    
2216
                if (empty($included) || empty($this->id)) {
2217
                        return array();
2218
                }
2219

    
2220
                $old = $this->find('first', array(
2221
                        'conditions' => array($this->alias . '.' . $this->primaryKey => $this->id),
2222
                        'fields' => array_values($included),
2223
                        'recursive' => -1
2224
                ));
2225

    
2226
                return array_merge($data, array('old' => $old[$this->alias]));
2227
        }
2228

    
2229
/**
2230
 * Backwards compatible passthrough method for:
2231
 * saveMany(), validateMany(), saveAssociated() and validateAssociated()
2232
 *
2233
 * Saves multiple individual records for a single model; Also works with a single record, as well as
2234
 * all its associated records.
2235
 *
2236
 * #### Options
2237
 *
2238
 * - `validate`: Set to false to disable validation, true to validate each record before saving,
2239
 *   'first' to validate *all* records before any are saved (default),
2240
 *   or 'only' to only validate the records, but not save them.
2241
 * - `atomic`: If true (default), will attempt to save all records in a single transaction.
2242
 *   Should be set to false if database/table does not support transactions.
2243
 * - `fieldList`: Equivalent to the $fieldList parameter in Model::save().
2244
 *   It should be an associate array with model name as key and array of fields as value. Eg.
2245
 *   ```
2246
 *   array(
2247
 *       'SomeModel' => array('field'),
2248
 *       'AssociatedModel' => array('field', 'otherfield')
2249
 *   )
2250
 *   ```
2251
 * - `deep`: See saveMany/saveAssociated
2252
 * - `callbacks`: See Model::save()
2253
 * - `counterCache`: See Model::save()
2254
 *
2255
 * @param array $data Record data to save. This can be either a numerically-indexed array (for saving multiple
2256
 *     records of the same type), or an array indexed by association name.
2257
 * @param array $options Options to use when saving record data, See $options above.
2258
 * @return mixed If atomic: True on success, or false on failure.
2259
 *    Otherwise: array similar to the $data array passed, but values are set to true/false
2260
 *    depending on whether each record saved successfully.
2261
 * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveassociated-array-data-null-array-options-array
2262
 * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveall-array-data-null-array-options-array
2263
 */
2264
        public function saveAll($data = array(), $options = array()) {
2265
                $options += array('validate' => 'first');
2266
                if (Hash::numeric(array_keys($data))) {
2267
                        if ($options['validate'] === 'only') {
2268
                                return $this->validateMany($data, $options);
2269
                        }
2270

    
2271
                        return $this->saveMany($data, $options);
2272
                }
2273

    
2274
                if ($options['validate'] === 'only') {
2275
                        return $this->validateAssociated($data, $options);
2276
                }
2277

    
2278
                return $this->saveAssociated($data, $options);
2279
        }
2280

    
2281
/**
2282
 * Saves multiple individual records for a single model
2283
 *
2284
 * #### Options
2285
 *
2286
 * - `validate`: Set to false to disable validation, true to validate each record before saving,
2287
 *   'first' to validate *all* records before any are saved (default),
2288
 * - `atomic`: If true (default), will attempt to save all records in a single transaction.
2289
 *   Should be set to false if database/table does not support transactions.
2290
 * - `fieldList`: Equivalent to the $fieldList parameter in Model::save()
2291
 * - `deep`: If set to true, all associated data will be saved as well.
2292
 * - `callbacks`: See Model::save()
2293
 * - `counterCache`: See Model::save()
2294
 *
2295
 * @param array $data Record data to save. This should be a numerically-indexed array
2296
 * @param array $options Options to use when saving record data, See $options above.
2297
 * @return mixed If atomic: True on success, or false on failure.
2298
 *    Otherwise: array similar to the $data array passed, but values are set to true/false
2299
 *    depending on whether each record saved successfully.
2300
 * @throws PDOException
2301
 * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-savemany-array-data-null-array-options-array
2302
 */
2303
        public function saveMany($data = null, $options = array()) {
2304
                if (empty($data)) {
2305
                        $data = $this->data;
2306
                }
2307

    
2308
                $options += array('validate' => 'first', 'atomic' => true, 'deep' => false);
2309
                $this->validationErrors = $validationErrors = array();
2310

    
2311
                if (empty($data) && $options['validate'] !== false) {
2312
                        $result = $this->save($data, $options);
2313
                        if (!$options['atomic']) {
2314
                                return array(!empty($result));
2315
                        }
2316

    
2317
                        return !empty($result);
2318
                }
2319

    
2320
                if ($options['validate'] === 'first') {
2321
                        $validates = $this->validateMany($data, $options);
2322
                        if ((!$validates && $options['atomic']) || (!$options['atomic'] && in_array(false, $validates, true))) {
2323
                                return $validates;
2324
                        }
2325
                        $options['validate'] = false;
2326
                }
2327

    
2328
                $transactionBegun = false;
2329
                if ($options['atomic']) {
2330
                        $db = $this->getDataSource();
2331
                        $transactionBegun = $db->begin();
2332
                }
2333

    
2334
                try {
2335
                        $return = array();
2336
                        foreach ($data as $key => $record) {
2337
                                $validates = $this->create(null) !== null;
2338
                                $saved = false;
2339
                                if ($validates) {
2340
                                        if ($options['deep']) {
2341
                                                $saved = $this->saveAssociated($record, array('atomic' => false) + $options);
2342
                                        } else {
2343
                                                $saved = (bool)$this->save($record, array('atomic' => false) + $options);
2344
                                        }
2345
                                }
2346

    
2347
                                $validates = ($validates && ($saved === true || (is_array($saved) && !in_array(false, Hash::flatten($saved), true))));
2348
                                if (!$validates) {
2349
                                        $validationErrors[$key] = $this->validationErrors;
2350
                                }
2351

    
2352
                                if (!$options['atomic']) {
2353
                                        $return[$key] = $validates;
2354
                                } elseif (!$validates) {
2355
                                        break;
2356
                                }
2357
                        }
2358

    
2359
                        $this->validationErrors = $validationErrors;
2360

    
2361
                        if (!$options['atomic']) {
2362
                                return $return;
2363
                        }
2364

    
2365
                        if ($validates) {
2366
                                if ($transactionBegun) {
2367
                                        return $db->commit() !== false;
2368
                                }
2369
                                return true;
2370
                        }
2371

    
2372
                        if ($transactionBegun) {
2373
                                $db->rollback();
2374
                        }
2375
                        return false;
2376
                } catch (Exception $e) {
2377
                        if ($transactionBegun) {
2378
                                $db->rollback();
2379
                        }
2380
                        throw $e;
2381
                }
2382
        }
2383

    
2384
/**
2385
 * Validates multiple individual records for a single model
2386
 *
2387
 * #### Options
2388
 *
2389
 * - `atomic`: If true (default), returns boolean. If false returns array.
2390
 * - `fieldList`: Equivalent to the $fieldList parameter in Model::save()
2391
 * - `deep`: If set to true, all associated data will be validated as well.
2392
 *
2393
 * Warning: This method could potentially change the passed argument `$data`,
2394
 * If you do not want this to happen, make a copy of `$data` before passing it
2395
 * to this method
2396
 *
2397
 * @param array &$data Record data to validate. This should be a numerically-indexed array
2398
 * @param array $options Options to use when validating record data (see above), See also $options of validates().
2399
 * @return bool|array If atomic: True on success, or false on failure.
2400
 *    Otherwise: array similar to the $data array passed, but values are set to true/false
2401
 *    depending on whether each record validated successfully.
2402
 */
2403
        public function validateMany(&$data, $options = array()) {
2404
                return $this->validator()->validateMany($data, $options);
2405
        }
2406

    
2407
/**
2408
 * Saves a single record, as well as all its directly associated records.
2409
 *
2410
 * #### Options
2411
 *
2412
 * - `validate`: Set to `false` to disable validation, `true` to validate each record before saving,
2413
 *   'first' to validate *all* records before any are saved(default),
2414
 * - `atomic`: If true (default), will attempt to save all records in a single transaction.
2415
 *   Should be set to false if database/table does not support transactions.
2416
 * - `fieldList`: Equivalent to the $fieldList parameter in Model::save().
2417
 *   It should be an associate array with model name as key and array of fields as value. Eg.
2418
 *   ```
2419
 *   array(
2420
 *       'SomeModel' => array('field'),
2421
 *       'AssociatedModel' => array('field', 'otherfield')
2422
 *   )
2423
 *   ```
2424
 * - `deep`: If set to true, not only directly associated data is saved, but deeper nested associated data as well.
2425
 * - `callbacks`: See Model::save()
2426
 * - `counterCache`: See Model::save()
2427
 *
2428
 * @param array $data Record data to save. This should be an array indexed by association name.
2429
 * @param array $options Options to use when saving record data, See $options above.
2430
 * @return mixed If atomic: True on success, or false on failure.
2431
 *    Otherwise: array similar to the $data array passed, but values are set to true/false
2432
 *    depending on whether each record saved successfully.
2433
 * @throws PDOException
2434
 * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveassociated-array-data-null-array-options-array
2435
 */
2436
        public function saveAssociated($data = null, $options = array()) {
2437
                if (empty($data)) {
2438
                        $data = $this->data;
2439
                }
2440

    
2441
                $options += array('validate' => 'first', 'atomic' => true, 'deep' => false);
2442
                $this->validationErrors = $validationErrors = array();
2443

    
2444
                if (empty($data) && $options['validate'] !== false) {
2445
                        $result = $this->save($data, $options);
2446
                        if (!$options['atomic']) {
2447
                                return array(!empty($result));
2448
                        }
2449

    
2450
                        return !empty($result);
2451
                }
2452

    
2453
                if ($options['validate'] === 'first') {
2454
                        $validates = $this->validateAssociated($data, $options);
2455
                        if ((!$validates && $options['atomic']) || (!$options['atomic'] && in_array(false, Hash::flatten($validates), true))) {
2456
                                return $validates;
2457
                        }
2458

    
2459
                        $options['validate'] = false;
2460
                }
2461

    
2462
                $transactionBegun = false;
2463
                if ($options['atomic']) {
2464
                        $db = $this->getDataSource();
2465
                        $transactionBegun = $db->begin();
2466
                }
2467

    
2468
                try {
2469
                        $associations = $this->getAssociated();
2470
                        $return = array();
2471
                        $validates = true;
2472
                        foreach ($data as $association => $values) {
2473
                                $isEmpty = empty($values) || (isset($values[$association]) && empty($values[$association]));
2474
                                if ($isEmpty || !isset($associations[$association]) || $associations[$association] !== 'belongsTo') {
2475
                                        continue;
2476
                                }
2477

    
2478
                                $Model = $this->{$association};
2479

    
2480
                                $validates = $Model->create(null) !== null;
2481
                                $saved = false;
2482
                                if ($validates) {
2483
                                        if ($options['deep']) {
2484
                                                $saved = $Model->saveAssociated($values, array('atomic' => false) + $options);
2485
                                        } else {
2486
                                                $saved = (bool)$Model->save($values, array('atomic' => false) + $options);
2487
                                        }
2488
                                        $validates = ($saved === true || (is_array($saved) && !in_array(false, Hash::flatten($saved), true)));
2489
                                }
2490

    
2491
                                if ($validates) {
2492
                                        $key = $this->belongsTo[$association]['foreignKey'];
2493
                                        if (isset($data[$this->alias])) {
2494
                                                $data[$this->alias][$key] = $Model->id;
2495
                                        } else {
2496
                                                $data = array_merge(array($key => $Model->id), $data, array($key => $Model->id));
2497
                                        }
2498
                                        $options = $this->_addToWhiteList($key, $options);
2499
                                } else {
2500
                                        $validationErrors[$association] = $Model->validationErrors;
2501
                                }
2502

    
2503
                                $return[$association] = $validates;
2504
                        }
2505

    
2506
                        if ($validates && !($this->create(null) !== null && $this->save($data, array('atomic' => false) + $options))) {
2507
                                $validationErrors[$this->alias] = $this->validationErrors;
2508
                                $validates = false;
2509
                        }
2510
                        $return[$this->alias] = $validates;
2511

    
2512
                        foreach ($data as $association => $values) {
2513
                                if (!$validates) {
2514
                                        break;
2515
                                }
2516

    
2517
                                $isEmpty = empty($values) || (isset($values[$association]) && empty($values[$association]));
2518
                                if ($isEmpty || !isset($associations[$association])) {
2519
                                        continue;
2520
                                }
2521

    
2522
                                $Model = $this->{$association};
2523

    
2524
                                $type = $associations[$association];
2525
                                $key = $this->{$type}[$association]['foreignKey'];
2526
                                switch ($type) {
2527
                                        case 'hasOne':
2528
                                                if (isset($values[$association])) {
2529
                                                        $values[$association][$key] = $this->id;
2530
                                                } else {
2531
                                                        $values = array_merge(array($key => $this->id), $values, array($key => $this->id));
2532
                                                }
2533

    
2534
                                                $validates = $Model->create(null) !== null;
2535
                                                $saved = false;
2536

    
2537
                                                if ($validates) {
2538
                                                        $options = $Model->_addToWhiteList($key, $options);
2539
                                                        if ($options['deep']) {
2540
                                                                $saved = $Model->saveAssociated($values, array('atomic' => false) + $options);
2541
                                                        } else {
2542
                                                                $saved = (bool)$Model->save($values, $options);
2543
                                                        }
2544
                                                }
2545

    
2546
                                                $validates = ($validates && ($saved === true || (is_array($saved) && !in_array(false, Hash::flatten($saved), true))));
2547
                                                if (!$validates) {
2548
                                                        $validationErrors[$association] = $Model->validationErrors;
2549
                                                }
2550

    
2551
                                                $return[$association] = $validates;
2552
                                                break;
2553
                                        case 'hasMany':
2554
                                                foreach ($values as $i => $value) {
2555
                                                        if (isset($values[$i][$association])) {
2556
                                                                $values[$i][$association][$key] = $this->id;
2557
                                                        } else {
2558
                                                                $values[$i] = array_merge(array($key => $this->id), $value, array($key => $this->id));
2559
                                                        }
2560
                                                }
2561

    
2562
                                                $options = $Model->_addToWhiteList($key, $options);
2563
                                                $_return = $Model->saveMany($values, array('atomic' => false) + $options);
2564
                                                if (in_array(false, $_return, true)) {
2565
                                                        $validationErrors[$association] = $Model->validationErrors;
2566
                                                        $validates = false;
2567
                                                }
2568

    
2569
                                                $return[$association] = $_return;
2570
                                                break;
2571
                                }
2572
                        }
2573
                        $this->validationErrors = $validationErrors;
2574

    
2575
                        if (isset($validationErrors[$this->alias])) {
2576
                                $this->validationErrors = $validationErrors[$this->alias];
2577
                                unset($validationErrors[$this->alias]);
2578
                                $this->validationErrors = array_merge($this->validationErrors, $validationErrors);
2579
                        }
2580

    
2581
                        if (!$options['atomic']) {
2582
                                return $return;
2583
                        }
2584
                        if ($validates) {
2585
                                if ($transactionBegun) {
2586
                                        return $db->commit() !== false;
2587
                                }
2588

    
2589
                                return true;
2590
                        }
2591

    
2592
                        if ($transactionBegun) {
2593
                                $db->rollback();
2594
                        }
2595
                        return false;
2596
                } catch (Exception $e) {
2597
                        if ($transactionBegun) {
2598
                                $db->rollback();
2599
                        }
2600
                        throw $e;
2601
                }
2602
        }
2603

    
2604
/**
2605
 * Helper method for saveAll() and friends, to add foreign key to fieldlist
2606
 *
2607
 * @param string $key fieldname to be added to list
2608
 * @param array $options Options list
2609
 * @return array options
2610
 */
2611
        protected function _addToWhiteList($key, $options) {
2612
                if (empty($options['fieldList']) && $this->whitelist && !in_array($key, $this->whitelist)) {
2613
                        $options['fieldList'][$this->alias] = $this->whitelist;
2614
                        $options['fieldList'][$this->alias][] = $key;
2615
                        return $options;
2616
                }
2617

    
2618
                if (!empty($options['fieldList'][$this->alias]) && is_array($options['fieldList'][$this->alias])) {
2619
                        $options['fieldList'][$this->alias][] = $key;
2620
                        return $options;
2621
                }
2622

    
2623
                if (!empty($options['fieldList']) && is_array($options['fieldList']) && Hash::dimensions($options['fieldList']) < 2) {
2624
                        $options['fieldList'][] = $key;
2625
                }
2626

    
2627
                return $options;
2628
        }
2629

    
2630
/**
2631
 * Validates a single record, as well as all its directly associated records.
2632
 *
2633
 * #### Options
2634
 *
2635
 * - `atomic`: If true (default), returns boolean. If false returns array.
2636
 * - `fieldList`: Equivalent to the $fieldList parameter in Model::save()
2637
 * - `deep`: If set to true, not only directly associated data , but deeper nested associated data is validated as well.
2638
 *
2639
 * Warning: This method could potentially change the passed argument `$data`,
2640
 * If you do not want this to happen, make a copy of `$data` before passing it
2641
 * to this method
2642
 *
2643
 * @param array &$data Record data to validate. This should be an array indexed by association name.
2644
 * @param array $options Options to use when validating record data (see above), See also $options of validates().
2645
 * @return array|bool If atomic: True on success, or false on failure.
2646
 *    Otherwise: array similar to the $data array passed, but values are set to true/false
2647
 *    depending on whether each record validated successfully.
2648
 */
2649
        public function validateAssociated(&$data, $options = array()) {
2650
                return $this->validator()->validateAssociated($data, $options);
2651
        }
2652

    
2653
/**
2654
 * Updates multiple model records based on a set of conditions.
2655
 *
2656
 * @param array $fields Set of fields and values, indexed by fields.
2657
 *    Fields are treated as SQL snippets, to insert literal values manually escape your data.
2658
 * @param mixed $conditions Conditions to match, true for all records
2659
 * @return bool True on success, false on failure
2660
 * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-updateall-array-fields-mixed-conditions
2661
 */
2662
        public function updateAll($fields, $conditions = true) {
2663
                return $this->getDataSource()->update($this, $fields, null, $conditions);
2664
        }
2665

    
2666
/**
2667
 * Removes record for given ID. If no ID is given, the current ID is used. Returns true on success.
2668
 *
2669
 * @param int|string $id ID of record to delete
2670
 * @param bool $cascade Set to true to delete records that depend on this record
2671
 * @return bool True on success
2672
 * @triggers Model.beforeDelete $this, array($cascade)
2673
 * @triggers Model.afterDelete $this
2674
 * @link http://book.cakephp.org/2.0/en/models/deleting-data.html
2675
 */
2676
        public function delete($id = null, $cascade = true) {
2677
                if (!empty($id)) {
2678
                        $this->id = $id;
2679
                }
2680

    
2681
                $id = $this->id;
2682

    
2683
                $event = new CakeEvent('Model.beforeDelete', $this, array($cascade));
2684
                list($event->break, $event->breakOn) = array(true, array(false, null));
2685
                $this->getEventManager()->dispatch($event);
2686
                if ($event->isStopped()) {
2687
                        return false;
2688
                }
2689

    
2690
                if (!$this->exists()) {
2691
                        return false;
2692
                }
2693

    
2694
                $this->_deleteDependent($id, $cascade);
2695
                $this->_deleteLinks($id);
2696
                $this->id = $id;
2697

    
2698
                if (!empty($this->belongsTo)) {
2699
                        foreach ($this->belongsTo as $assoc) {
2700
                                if (empty($assoc['counterCache'])) {
2701
                                        continue;
2702
                                }
2703

    
2704
                                $keys = $this->find('first', array(
2705
                                        'fields' => $this->_collectForeignKeys(),
2706
                                        'conditions' => array($this->alias . '.' . $this->primaryKey => $id),
2707
                                        'recursive' => -1,
2708
                                        'callbacks' => false
2709
                                ));
2710
                                break;
2711
                        }
2712
                }
2713

    
2714
                if (!$this->getDataSource()->delete($this, array($this->alias . '.' . $this->primaryKey => $id))) {
2715
                        return false;
2716
                }
2717

    
2718
                if (!empty($keys[$this->alias])) {
2719
                        $this->updateCounterCache($keys[$this->alias]);
2720
                }
2721

    
2722
                $this->getEventManager()->dispatch(new CakeEvent('Model.afterDelete', $this));
2723
                $this->_clearCache();
2724
                $this->id = false;
2725

    
2726
                return true;
2727
        }
2728

    
2729
/**
2730
 * Cascades model deletes through associated hasMany and hasOne child records.
2731
 *
2732
 * @param string $id ID of record that was deleted
2733
 * @param bool $cascade Set to true to delete records that depend on this record
2734
 * @return void
2735
 */
2736
        protected function _deleteDependent($id, $cascade) {
2737
                if ($cascade !== true) {
2738
                        return;
2739
                }
2740

    
2741
                if (!empty($this->__backAssociation)) {
2742
                        $savedAssociations = $this->__backAssociation;
2743
                        $this->__backAssociation = array();
2744
                }
2745

    
2746
                foreach (array_merge($this->hasMany, $this->hasOne) as $assoc => $data) {
2747
                        if ($data['dependent'] !== true) {
2748
                                continue;
2749
                        }
2750

    
2751
                        $Model = $this->{$assoc};
2752

    
2753
                        if ($data['foreignKey'] === false && $data['conditions'] && in_array($this->name, $Model->getAssociated('belongsTo'))) {
2754
                                $Model->recursive = 0;
2755
                                $conditions = array($this->escapeField(null, $this->name) => $id);
2756
                        } else {
2757
                                $Model->recursive = -1;
2758
                                $conditions = array($Model->escapeField($data['foreignKey']) => $id);
2759
                                if ($data['conditions']) {
2760
                                        $conditions = array_merge((array)$data['conditions'], $conditions);
2761
                                }
2762
                        }
2763

    
2764
                        if (isset($data['exclusive']) && $data['exclusive']) {
2765
                                $Model->deleteAll($conditions);
2766
                        } else {
2767
                                $records = $Model->find('all', array(
2768
                                        'conditions' => $conditions, 'fields' => $Model->primaryKey
2769
                                ));
2770

    
2771
                                if (!empty($records)) {
2772
                                        foreach ($records as $record) {
2773
                                                $Model->delete($record[$Model->alias][$Model->primaryKey]);
2774
                                        }
2775
                                }
2776
                        }
2777
                }
2778

    
2779
                if (isset($savedAssociations)) {
2780
                        $this->__backAssociation = $savedAssociations;
2781
                }
2782
        }
2783

    
2784
/**
2785
 * Cascades model deletes through HABTM join keys.
2786
 *
2787
 * @param string $id ID of record that was deleted
2788
 * @return void
2789
 */
2790
        protected function _deleteLinks($id) {
2791
                foreach ($this->hasAndBelongsToMany as $data) {
2792
                        list(, $joinModel) = pluginSplit($data['with']);
2793
                        $Model = $this->{$joinModel};
2794
                        $records = $Model->find('all', array(
2795
                                'conditions' => array($Model->escapeField($data['foreignKey']) => $id),
2796
                                'fields' => $Model->primaryKey,
2797
                                'recursive' => -1,
2798
                                'callbacks' => false
2799
                        ));
2800

    
2801
                        if (!empty($records)) {
2802
                                foreach ($records as $record) {
2803
                                        $Model->delete($record[$Model->alias][$Model->primaryKey]);
2804
                                }
2805
                        }
2806
                }
2807
        }
2808

    
2809
/**
2810
 * Deletes multiple model records based on a set of conditions.
2811
 *
2812
 * @param mixed $conditions Conditions to match
2813
 * @param bool $cascade Set to true to delete records that depend on this record
2814
 * @param bool $callbacks Run callbacks
2815
 * @return bool True on success, false on failure
2816
 * @link http://book.cakephp.org/2.0/en/models/deleting-data.html#deleteall
2817
 */
2818
        public function deleteAll($conditions, $cascade = true, $callbacks = false) {
2819
                if (empty($conditions)) {
2820
                        return false;
2821
                }
2822

    
2823
                $db = $this->getDataSource();
2824

    
2825
                if (!$cascade && !$callbacks) {
2826
                        return $db->delete($this, $conditions);
2827
                }
2828

    
2829
                $ids = $this->find('all', array_merge(array(
2830
                        'fields' => "{$this->alias}.{$this->primaryKey}",
2831
                        'order' => false,
2832
                        'group' => "{$this->alias}.{$this->primaryKey}",
2833
                        'recursive' => 0), compact('conditions'))
2834
                );
2835

    
2836
                if ($ids === false || $ids === null) {
2837
                        return false;
2838
                }
2839

    
2840
                $ids = Hash::extract($ids, "{n}.{$this->alias}.{$this->primaryKey}");
2841
                if (empty($ids)) {
2842
                        return true;
2843
                }
2844

    
2845
                if ($callbacks) {
2846
                        $_id = $this->id;
2847
                        $result = true;
2848
                        foreach ($ids as $id) {
2849
                                $result = $result && $this->delete($id, $cascade);
2850
                        }
2851

    
2852
                        $this->id = $_id;
2853
                        return $result;
2854
                }
2855

    
2856
                foreach ($ids as $id) {
2857
                        $this->_deleteLinks($id);
2858
                        if ($cascade) {
2859
                                $this->_deleteDependent($id, $cascade);
2860
                        }
2861
                }
2862

    
2863
                return $db->delete($this, array($this->alias . '.' . $this->primaryKey => $ids));
2864
        }
2865

    
2866
/**
2867
 * Collects foreign keys from associations.
2868
 *
2869
 * @param string $type Association type.
2870
 * @return array
2871
 */
2872
        protected function _collectForeignKeys($type = 'belongsTo') {
2873
                $result = array();
2874

    
2875
                foreach ($this->{$type} as $assoc => $data) {
2876
                        if (isset($data['foreignKey']) && is_string($data['foreignKey'])) {
2877
                                $result[$assoc] = $data['foreignKey'];
2878
                        }
2879
                }
2880

    
2881
                return $result;
2882
        }
2883

    
2884
/**
2885
 * Returns true if a record with particular ID exists.
2886
 *
2887
 * If $id is not passed it calls `Model::getID()` to obtain the current record ID,
2888
 * and then performs a `Model::find('count')` on the currently configured datasource
2889
 * to ascertain the existence of the record in persistent storage.
2890
 *
2891
 * @param int|string $id ID of record to check for existence
2892
 * @return bool True if such a record exists
2893
 */
2894
        public function exists($id = null) {
2895
                if ($id === null) {
2896
                        $id = $this->getID();
2897
                }
2898

    
2899
                if ($id === false) {
2900
                        return false;
2901
                }
2902

    
2903
                if ($this->useTable === false) {
2904
                        return false;
2905
                }
2906

    
2907
                return (bool)$this->find('count', array(
2908
                        'conditions' => array(
2909
                                $this->alias . '.' . $this->primaryKey => $id
2910
                        ),
2911
                        'recursive' => -1,
2912
                        'callbacks' => false
2913
                ));
2914
        }
2915

    
2916
/**
2917
 * Returns true if a record that meets given conditions exists.
2918
 *
2919
 * @param array $conditions SQL conditions array
2920
 * @return bool True if such a record exists
2921
 */
2922
        public function hasAny($conditions = null) {
2923
                return (bool)$this->find('count', array('conditions' => $conditions, 'recursive' => -1));
2924
        }
2925

    
2926
/**
2927
 * Queries the datasource and returns a result set array.
2928
 *
2929
 * Used to perform find operations, where the first argument is type of find operation to perform
2930
 * (all / first / count / neighbors / list / threaded),
2931
 * second parameter options for finding (indexed array, including: 'conditions', 'limit',
2932
 * 'recursive', 'page', 'fields', 'offset', 'order', 'callbacks')
2933
 *
2934
 * Eg:
2935
 * ```
2936
 * $model->find('all', array(
2937
 *   'conditions' => array('name' => 'Thomas Anderson'),
2938
 *   'fields' => array('name', 'email'),
2939
 *   'order' => 'field3 DESC',
2940
 *   'recursive' => 2,
2941
 *   'group' => 'type',
2942
 *   'callbacks' => false,
2943
 * ));
2944
 * ```
2945
 *
2946
 * In addition to the standard query keys above, you can provide Datasource, and behavior specific
2947
 * keys. For example, when using a SQL based datasource you can use the joins key to specify additional
2948
 * joins that should be part of the query.
2949
 *
2950
 * ```
2951
 * $model->find('all', array(
2952
 *   'conditions' => array('name' => 'Thomas Anderson'),
2953
 *   'joins' => array(
2954
 *     array(
2955
 *       'alias' => 'Thought',
2956
 *       'table' => 'thoughts',
2957
 *       'type' => 'LEFT',
2958
 *       'conditions' => '`Thought`.`person_id` = `Person`.`id`'
2959
 *     )
2960
 *   )
2961
 * ));
2962
 * ```
2963
 *
2964
 * ### Disabling callbacks
2965
 *
2966
 * The `callbacks` key allows you to disable or specify the callbacks that should be run. To
2967
 * disable beforeFind & afterFind callbacks set `'callbacks' => false` in your options. You can
2968
 * also set the callbacks option to 'before' or 'after' to enable only the specified callback.
2969
 *
2970
 * ### Adding new find types
2971
 *
2972
 * Behaviors and find types can also define custom finder keys which are passed into find().
2973
 * See the documentation for custom find types
2974
 * (http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#creating-custom-find-types)
2975
 * for how to implement custom find types.
2976
 *
2977
 * Specifying 'fields' for notation 'list':
2978
 *
2979
 * - If no fields are specified, then 'id' is used for key and 'model->displayField' is used for value.
2980
 * - If a single field is specified, 'id' is used for key and specified field is used for value.
2981
 * - If three fields are specified, they are used (in order) for key, value and group.
2982
 * - Otherwise, first and second fields are used for key and value.
2983
 *
2984
 * Note: find(list) + database views have issues with MySQL 5.0. Try upgrading to MySQL 5.1 if you
2985
 * have issues with database views.
2986
 *
2987
 * Note: find(count) has its own return values.
2988
 *
2989
 * @param string $type Type of find operation (all / first / count / neighbors / list / threaded)
2990
 * @param array $query Option fields (conditions / fields / joins / limit / offset / order / page / group / callbacks)
2991
 * @return array|null Array of records, or Null on failure.
2992
 * @link http://book.cakephp.org/2.0/en/models/retrieving-your-data.html
2993
 */
2994
        public function find($type = 'first', $query = array()) {
2995
                $this->findQueryType = $type;
2996
                $this->id = $this->getID();
2997

    
2998
                $query = $this->buildQuery($type, $query);
2999
                if ($query === null) {
3000
                        return null;
3001
                }
3002

    
3003
                return $this->_readDataSource($type, $query);
3004
        }
3005

    
3006
/**
3007
 * Read from the datasource
3008
 *
3009
 * Model::_readDataSource() is used by all find() calls to read from the data source and can be overloaded to allow
3010
 * caching of datasource calls.
3011
 *
3012
 * ```
3013
 * protected function _readDataSource($type, $query) {
3014
 *                 $cacheName = md5(json_encode($query));
3015
 *                 $cache = Cache::read($cacheName, 'cache-config-name');
3016
 *                 if ($cache !== false) {
3017
 *                         return $cache;
3018
 *                 }
3019
 *
3020
 *                 $results = parent::_readDataSource($type, $query);
3021
 *                 Cache::write($cacheName, $results, 'cache-config-name');
3022
 *                 return $results;
3023
 * }
3024
 * ```
3025
 *
3026
 * @param string $type Type of find operation (all / first / count / neighbors / list / threaded)
3027
 * @param array $query Option fields (conditions / fields / joins / limit / offset / order / page / group / callbacks)
3028
 * @return array
3029
 */
3030
        protected function _readDataSource($type, $query) {
3031
                $results = $this->getDataSource()->read($this, $query);
3032
                $this->resetAssociations();
3033

    
3034
                if ($query['callbacks'] === true || $query['callbacks'] === 'after') {
3035
                        $results = $this->_filterResults($results);
3036
                }
3037

    
3038
                $this->findQueryType = null;
3039

    
3040
                if ($this->findMethods[$type] === true) {
3041
                        return $this->{'_find' . ucfirst($type)}('after', $query, $results);
3042
                }
3043
        }
3044

    
3045
/**
3046
 * Builds the query array that is used by the data source to generate the query to fetch the data.
3047
 *
3048
 * @param string $type Type of find operation (all / first / count / neighbors / list / threaded)
3049
 * @param array $query Option fields (conditions / fields / joins / limit / offset / order / page / group / callbacks)
3050
 * @return array|null Query array or null if it could not be build for some reasons
3051
 * @triggers Model.beforeFind $this, array($query)
3052
 * @see Model::find()
3053
 */
3054
        public function buildQuery($type = 'first', $query = array()) {
3055
                $query = array_merge(
3056
                        array(
3057
                                'conditions' => null, 'fields' => null, 'joins' => array(), 'limit' => null,
3058
                                'offset' => null, 'order' => null, 'page' => 1, 'group' => null, 'callbacks' => true,
3059
                        ),
3060
                        (array)$query
3061
                );
3062

    
3063
                if ($this->findMethods[$type] === true) {
3064
                        $query = $this->{'_find' . ucfirst($type)}('before', $query);
3065
                }
3066

    
3067
                if (!is_numeric($query['page']) || (int)$query['page'] < 1) {
3068
                        $query['page'] = 1;
3069
                }
3070

    
3071
                if ($query['page'] > 1 && !empty($query['limit'])) {
3072
                        $query['offset'] = ($query['page'] - 1) * $query['limit'];
3073
                }
3074

    
3075
                if ($query['order'] === null && $this->order !== null) {
3076
                        $query['order'] = $this->order;
3077
                }
3078

    
3079
                $query['order'] = array($query['order']);
3080

    
3081
                if ($query['callbacks'] === true || $query['callbacks'] === 'before') {
3082
                        $event = new CakeEvent('Model.beforeFind', $this, array($query));
3083
                        list($event->break, $event->breakOn, $event->modParams) = array(true, array(false, null), 0);
3084
                        $this->getEventManager()->dispatch($event);
3085

    
3086
                        if ($event->isStopped()) {
3087
                                return null;
3088
                        }
3089

    
3090
                        $query = $event->result === true ? $event->data[0] : $event->result;
3091
                }
3092

    
3093
                return $query;
3094
        }
3095

    
3096
/**
3097
 * Handles the before/after filter logic for find('all') operations. Only called by Model::find().
3098
 *
3099
 * @param string $state Either "before" or "after"
3100
 * @param array $query Query.
3101
 * @param array $results Results.
3102
 * @return array
3103
 * @see Model::find()
3104
 */
3105
        protected function _findAll($state, $query, $results = array()) {
3106
                if ($state === 'before') {
3107
                        return $query;
3108
                }
3109

    
3110
                return $results;
3111
        }
3112

    
3113
/**
3114
 * Handles the before/after filter logic for find('first') operations. Only called by Model::find().
3115
 *
3116
 * @param string $state Either "before" or "after"
3117
 * @param array $query Query.
3118
 * @param array $results Results.
3119
 * @return array
3120
 * @see Model::find()
3121
 */
3122
        protected function _findFirst($state, $query, $results = array()) {
3123
                if ($state === 'before') {
3124
                        $query['limit'] = 1;
3125
                        return $query;
3126
                }
3127

    
3128
                if (empty($results[0])) {
3129
                        return array();
3130
                }
3131

    
3132
                return $results[0];
3133
        }
3134

    
3135
/**
3136
 * Handles the before/after filter logic for find('count') operations. Only called by Model::find().
3137
 *
3138
 * @param string $state Either "before" or "after"
3139
 * @param array $query Query.
3140
 * @param array $results Results.
3141
 * @return int The number of records found, or false
3142
 * @see Model::find()
3143
 */
3144
        protected function _findCount($state, $query, $results = array()) {
3145
                if ($state === 'before') {
3146
                        if (!empty($query['type']) && isset($this->findMethods[$query['type']]) && $query['type'] !== 'count') {
3147
                                $query['operation'] = 'count';
3148
                                $query = $this->{'_find' . ucfirst($query['type'])}('before', $query);
3149
                        }
3150

    
3151
                        $db = $this->getDataSource();
3152
                        $query['order'] = false;
3153
                        if (!method_exists($db, 'calculate')) {
3154
                                return $query;
3155
                        }
3156

    
3157
                        if (!empty($query['fields']) && is_array($query['fields'])) {
3158
                                if (!preg_match('/^count/i', current($query['fields']))) {
3159
                                        unset($query['fields']);
3160
                                }
3161
                        }
3162

    
3163
                        if (empty($query['fields'])) {
3164
                                $query['fields'] = $db->calculate($this, 'count');
3165
                        } elseif (method_exists($db, 'expression') && is_string($query['fields']) && !preg_match('/count/i', $query['fields'])) {
3166
                                $query['fields'] = $db->calculate($this, 'count', array(
3167
                                        $db->expression($query['fields']), 'count'
3168
                                ));
3169
                        }
3170

    
3171
                        return $query;
3172
                }
3173

    
3174
                foreach (array(0, $this->alias) as $key) {
3175
                        if (isset($results[0][$key]['count'])) {
3176
                                if ($query['group']) {
3177
                                        return count($results);
3178
                                }
3179

    
3180
                                return (int)$results[0][$key]['count'];
3181
                        }
3182
                }
3183

    
3184
                return false;
3185
        }
3186

    
3187
/**
3188
 * Handles the before/after filter logic for find('list') operations. Only called by Model::find().
3189
 *
3190
 * @param string $state Either "before" or "after"
3191
 * @param array $query Query.
3192
 * @param array $results Results.
3193
 * @return array Key/value pairs of primary keys/display field values of all records found
3194
 * @see Model::find()
3195
 */
3196
        protected function _findList($state, $query, $results = array()) {
3197
                if ($state === 'before') {
3198
                        if (empty($query['fields'])) {
3199
                                $query['fields'] = array("{$this->alias}.{$this->primaryKey}", "{$this->alias}.{$this->displayField}");
3200
                                $list = array("{n}.{$this->alias}.{$this->primaryKey}", "{n}.{$this->alias}.{$this->displayField}", null);
3201
                        } else {
3202
                                if (!is_array($query['fields'])) {
3203
                                        $query['fields'] = CakeText::tokenize($query['fields']);
3204
                                }
3205

    
3206
                                if (count($query['fields']) === 1) {
3207
                                        if (strpos($query['fields'][0], '.') === false) {
3208
                                                $query['fields'][0] = $this->alias . '.' . $query['fields'][0];
3209
                                        }
3210

    
3211
                                        $list = array("{n}.{$this->alias}.{$this->primaryKey}", '{n}.' . $query['fields'][0], null);
3212
                                        $query['fields'] = array("{$this->alias}.{$this->primaryKey}", $query['fields'][0]);
3213
                                } elseif (count($query['fields']) === 3) {
3214
                                        for ($i = 0; $i < 3; $i++) {
3215
                                                if (strpos($query['fields'][$i], '.') === false) {
3216
                                                        $query['fields'][$i] = $this->alias . '.' . $query['fields'][$i];
3217
                                                }
3218
                                        }
3219

    
3220
                                        $list = array('{n}.' . $query['fields'][0], '{n}.' . $query['fields'][1], '{n}.' . $query['fields'][2]);
3221
                                } else {
3222
                                        for ($i = 0; $i < 2; $i++) {
3223
                                                if (strpos($query['fields'][$i], '.') === false) {
3224
                                                        $query['fields'][$i] = $this->alias . '.' . $query['fields'][$i];
3225
                                                }
3226
                                        }
3227

    
3228
                                        $list = array('{n}.' . $query['fields'][0], '{n}.' . $query['fields'][1], null);
3229
                                }
3230
                        }
3231

    
3232
                        if (!isset($query['recursive']) || $query['recursive'] === null) {
3233
                                $query['recursive'] = -1;
3234
                        }
3235
                        list($query['list']['keyPath'], $query['list']['valuePath'], $query['list']['groupPath']) = $list;
3236

    
3237
                        return $query;
3238
                }
3239

    
3240
                if (empty($results)) {
3241
                        return array();
3242
                }
3243

    
3244
                return Hash::combine($results, $query['list']['keyPath'], $query['list']['valuePath'], $query['list']['groupPath']);
3245
        }
3246

    
3247
/**
3248
 * Detects the previous field's value, then uses logic to find the 'wrapping'
3249
 * rows and return them.
3250
 *
3251
 * @param string $state Either "before" or "after"
3252
 * @param array $query Query.
3253
 * @param array $results Results.
3254
 * @return array
3255
 */
3256
        protected function _findNeighbors($state, $query, $results = array()) {
3257
                extract($query);
3258

    
3259
                if ($state === 'before') {
3260
                        $conditions = (array)$conditions;
3261
                        if (isset($field) && isset($value)) {
3262
                                if (strpos($field, '.') === false) {
3263
                                        $field = $this->alias . '.' . $field;
3264
                                }
3265
                        } else {
3266
                                $field = $this->alias . '.' . $this->primaryKey;
3267
                                $value = $this->id;
3268
                        }
3269

    
3270
                        $query['conditions'] = array_merge($conditions, array($field . ' <' => $value));
3271
                        $query['order'] = $field . ' DESC';
3272
                        $query['limit'] = 1;
3273
                        $query['field'] = $field;
3274
                        $query['value'] = $value;
3275

    
3276
                        return $query;
3277
                }
3278

    
3279
                unset($query['conditions'][$field . ' <']);
3280
                $return = array();
3281
                if (isset($results[0])) {
3282
                        $prevVal = Hash::get($results[0], $field);
3283
                        $query['conditions'][$field . ' >='] = $prevVal;
3284
                        $query['conditions'][$field . ' !='] = $value;
3285
                        $query['limit'] = 2;
3286
                } else {
3287
                        $return['prev'] = null;
3288
                        $query['conditions'][$field . ' >'] = $value;
3289
                        $query['limit'] = 1;
3290
                }
3291

    
3292
                $query['order'] = $field . ' ASC';
3293
                $neighbors = $this->find('all', $query);
3294
                if (!array_key_exists('prev', $return)) {
3295
                        $return['prev'] = isset($neighbors[0]) ? $neighbors[0] : null;
3296
                }
3297

    
3298
                if (count($neighbors) === 2) {
3299
                        $return['next'] = $neighbors[1];
3300
                } elseif (count($neighbors) === 1 && !$return['prev']) {
3301
                        $return['next'] = $neighbors[0];
3302
                } else {
3303
                        $return['next'] = null;
3304
                }
3305

    
3306
                return $return;
3307
        }
3308

    
3309
/**
3310
 * In the event of ambiguous results returned (multiple top level results, with different parent_ids)
3311
 * top level results with different parent_ids to the first result will be dropped
3312
 *
3313
 * @param string $state Either "before" or "after".
3314
 * @param array $query Query.
3315
 * @param array $results Results.
3316
 * @return array Threaded results
3317
 */
3318
        protected function _findThreaded($state, $query, $results = array()) {
3319
                if ($state === 'before') {
3320
                        return $query;
3321
                }
3322

    
3323
                $parent = 'parent_id';
3324
                if (isset($query['parent'])) {
3325
                        $parent = $query['parent'];
3326
                }
3327

    
3328
                return Hash::nest($results, array(
3329
                        'idPath' => '{n}.' . $this->alias . '.' . $this->primaryKey,
3330
                        'parentPath' => '{n}.' . $this->alias . '.' . $parent
3331
                ));
3332
        }
3333

    
3334
/**
3335
 * Passes query results through model and behavior afterFind() methods.
3336
 *
3337
 * @param array $results Results to filter
3338
 * @param bool $primary If this is the primary model results (results from model where the find operation was performed)
3339
 * @return array Set of filtered results
3340
 * @triggers Model.afterFind $this, array($results, $primary)
3341
 */
3342
        protected function _filterResults($results, $primary = true) {
3343
                $event = new CakeEvent('Model.afterFind', $this, array($results, $primary));
3344
                $event->modParams = 0;
3345
                $this->getEventManager()->dispatch($event);
3346
                return $event->result;
3347
        }
3348

    
3349
/**
3350
 * This resets the association arrays for the model back
3351
 * to those originally defined in the model. Normally called at the end
3352
 * of each call to Model::find()
3353
 *
3354
 * @return bool Success
3355
 */
3356
        public function resetAssociations() {
3357
                if (!empty($this->__backAssociation)) {
3358
                        foreach ($this->_associations as $type) {
3359
                                if (isset($this->__backAssociation[$type])) {
3360
                                        $this->{$type} = $this->__backAssociation[$type];
3361
                                }
3362
                        }
3363

    
3364
                        $this->__backAssociation = array();
3365
                }
3366

    
3367
                foreach ($this->_associations as $type) {
3368
                        foreach ($this->{$type} as $key => $name) {
3369
                                if (property_exists($this, $key) && !empty($this->{$key}->__backAssociation)) {
3370
                                        $this->{$key}->resetAssociations();
3371
                                }
3372
                        }
3373
                }
3374

    
3375
                $this->__backAssociation = array();
3376
                return true;
3377
        }
3378

    
3379
/**
3380
 * Returns false if any fields passed match any (by default, all if $or = false) of their matching values.
3381
 *
3382
 * Can be used as a validation method. When used as a validation method, the `$or` parameter
3383
 * contains an array of fields to be validated.
3384
 *
3385
 * @param array $fields Field/value pairs to search (if no values specified, they are pulled from $this->data)
3386
 * @param bool|array $or If false, all fields specified must match in order for a false return value
3387
 * @return bool False if any records matching any fields are found
3388
 */
3389
        public function isUnique($fields, $or = true) {
3390
                if (is_array($or)) {
3391
                        $isRule = (
3392
                                array_key_exists('rule', $or) &&
3393
                                array_key_exists('required', $or) &&
3394
                                array_key_exists('message', $or)
3395
                        );
3396
                        if (!$isRule) {
3397
                                $args = func_get_args();
3398
                                $fields = $args[1];
3399
                                $or = isset($args[2]) ? $args[2] : true;
3400
                        }
3401
                }
3402
                if (!is_array($fields)) {
3403
                        $fields = func_get_args();
3404
                        $fieldCount = count($fields) - 1;
3405
                        if (is_bool($fields[$fieldCount])) {
3406
                                $or = $fields[$fieldCount];
3407
                                unset($fields[$fieldCount]);
3408
                        }
3409
                }
3410

    
3411
                foreach ($fields as $field => $value) {
3412
                        if (is_numeric($field)) {
3413
                                unset($fields[$field]);
3414

    
3415
                                $field = $value;
3416
                                $value = null;
3417
                                if (isset($this->data[$this->alias][$field])) {
3418
                                        $value = $this->data[$this->alias][$field];
3419
                                }
3420
                        }
3421

    
3422
                        if (strpos($field, '.') === false) {
3423
                                unset($fields[$field]);
3424
                                $fields[$this->alias . '.' . $field] = $value;
3425
                        }
3426
                }
3427

    
3428
                if ($or) {
3429
                        $fields = array('or' => $fields);
3430
                }
3431

    
3432
                if (!empty($this->id)) {
3433
                        $fields[$this->alias . '.' . $this->primaryKey . ' !='] = $this->id;
3434
                }
3435

    
3436
                return !$this->find('count', array('conditions' => $fields, 'recursive' => -1));
3437
        }
3438

    
3439
/**
3440
 * Returns a resultset for a given SQL statement. Custom SQL queries should be performed with this method.
3441
 *
3442
 * The method can options 2nd and 3rd parameters.
3443
 *
3444
 * - 2nd param: Either a boolean to control query caching or an array of parameters
3445
 *    for use with prepared statement placeholders.
3446
 * - 3rd param: If 2nd argument is provided, a boolean flag for enabling/disabled
3447
 *   query caching.
3448
 *
3449
 * @param string $sql SQL statement
3450
 * @return mixed Resultset array or boolean indicating success / failure depending on the query executed
3451
 * @link http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-query
3452
 */
3453
        public function query($sql) {
3454
                $params = func_get_args();
3455
                $db = $this->getDataSource();
3456
                return call_user_func_array(array(&$db, 'query'), $params);
3457
        }
3458

    
3459
/**
3460
 * Returns true if all fields pass validation. Will validate hasAndBelongsToMany associations
3461
 * that use the 'with' key as well. Since _saveMulti is incapable of exiting a save operation.
3462
 *
3463
 * Will validate the currently set data. Use Model::set() or Model::create() to set the active data.
3464
 *
3465
 * @param array $options An optional array of custom options to be made available in the beforeValidate callback
3466
 * @return bool True if there are no errors
3467
 */
3468
        public function validates($options = array()) {
3469
                return $this->validator()->validates($options);
3470
        }
3471

    
3472
/**
3473
 * Returns an array of fields that have failed the validation of the current model.
3474
 *
3475
 * Additionally it populates the validationErrors property of the model with the same array.
3476
 *
3477
 * @param array|string $options An optional array of custom options to be made available in the beforeValidate callback
3478
 * @return array Array of invalid fields and their error messages
3479
 * @see Model::validates()
3480
 */
3481
        public function invalidFields($options = array()) {
3482
                return $this->validator()->errors($options);
3483
        }
3484

    
3485
/**
3486
 * Marks a field as invalid, optionally setting the name of validation
3487
 * rule (in case of multiple validation for field) that was broken.
3488
 *
3489
 * @param string $field The name of the field to invalidate
3490
 * @param mixed $value Name of validation rule that was not failed, or validation message to
3491
 *    be returned. If no validation key is provided, defaults to true.
3492
 * @return void
3493
 */
3494
        public function invalidate($field, $value = true) {
3495
                $this->validator()->invalidate($field, $value);
3496
        }
3497

    
3498
/**
3499
 * Returns true if given field name is a foreign key in this model.
3500
 *
3501
 * @param string $field Returns true if the input string ends in "_id"
3502
 * @return bool True if the field is a foreign key listed in the belongsTo array.
3503
 */
3504
        public function isForeignKey($field) {
3505
                $foreignKeys = array();
3506
                if (!empty($this->belongsTo)) {
3507
                        foreach ($this->belongsTo as $data) {
3508
                                $foreignKeys[] = $data['foreignKey'];
3509
                        }
3510
                }
3511

    
3512
                return in_array($field, $foreignKeys);
3513
        }
3514

    
3515
/**
3516
 * Escapes the field name and prepends the model name. Escaping is done according to the
3517
 * current database driver's rules.
3518
 *
3519
 * @param string $field Field to escape (e.g: id)
3520
 * @param string $alias Alias for the model (e.g: Post)
3521
 * @return string The name of the escaped field for this Model (i.e. id becomes `Post`.`id`).
3522
 */
3523
        public function escapeField($field = null, $alias = null) {
3524
                if (empty($alias)) {
3525
                        $alias = $this->alias;
3526
                }
3527

    
3528
                if (empty($field)) {
3529
                        $field = $this->primaryKey;
3530
                }
3531

    
3532
                $db = $this->getDataSource();
3533
                if (strpos($field, $db->name($alias) . '.') === 0) {
3534
                        return $field;
3535
                }
3536

    
3537
                return $db->name($alias . '.' . $field);
3538
        }
3539

    
3540
/**
3541
 * Returns the current record's ID
3542
 *
3543
 * @param int $list Index on which the composed ID is located
3544
 * @return mixed The ID of the current record, false if no ID
3545
 */
3546
        public function getID($list = 0) {
3547
                if (empty($this->id) || (is_array($this->id) && isset($this->id[0]) && empty($this->id[0]))) {
3548
                        return false;
3549
                }
3550

    
3551
                if (!is_array($this->id)) {
3552
                        return $this->id;
3553
                }
3554

    
3555
                if (isset($this->id[$list]) && !empty($this->id[$list])) {
3556
                        return $this->id[$list];
3557
                }
3558

    
3559
                if (isset($this->id[$list])) {
3560
                        return false;
3561
                }
3562

    
3563
                return current($this->id);
3564
        }
3565

    
3566
/**
3567
 * Returns the ID of the last record this model inserted.
3568
 *
3569
 * @return mixed Last inserted ID
3570
 */
3571
        public function getLastInsertID() {
3572
                return $this->getInsertID();
3573
        }
3574

    
3575
/**
3576
 * Returns the ID of the last record this model inserted.
3577
 *
3578
 * @return mixed Last inserted ID
3579
 */
3580
        public function getInsertID() {
3581
                return $this->_insertID;
3582
        }
3583

    
3584
/**
3585
 * Sets the ID of the last record this model inserted
3586
 *
3587
 * @param int|string $id Last inserted ID
3588
 * @return void
3589
 */
3590
        public function setInsertID($id) {
3591
                $this->_insertID = $id;
3592
        }
3593

    
3594
/**
3595
 * Returns the number of rows returned from the last query.
3596
 *
3597
 * @return int Number of rows
3598
 */
3599
        public function getNumRows() {
3600
                return $this->getDataSource()->lastNumRows();
3601
        }
3602

    
3603
/**
3604
 * Returns the number of rows affected by the last query.
3605
 *
3606
 * @return int Number of rows
3607
 */
3608
        public function getAffectedRows() {
3609
                return $this->getDataSource()->lastAffected();
3610
        }
3611

    
3612
/**
3613
 * Sets the DataSource to which this model is bound.
3614
 *
3615
 * @param string $dataSource The name of the DataSource, as defined in app/Config/database.php
3616
 * @return void
3617
 * @throws MissingConnectionException
3618
 */
3619
        public function setDataSource($dataSource = null) {
3620
                $oldConfig = $this->useDbConfig;
3621

    
3622
                if ($dataSource) {
3623
                        $this->useDbConfig = $dataSource;
3624
                }
3625

    
3626
                $db = ConnectionManager::getDataSource($this->useDbConfig);
3627
                if (!empty($oldConfig) && isset($db->config['prefix'])) {
3628
                        $oldDb = ConnectionManager::getDataSource($oldConfig);
3629

    
3630
                        if (!isset($this->tablePrefix) || (!isset($oldDb->config['prefix']) || $this->tablePrefix === $oldDb->config['prefix'])) {
3631
                                $this->tablePrefix = $db->config['prefix'];
3632
                        }
3633
                } elseif (isset($db->config['prefix'])) {
3634
                        $this->tablePrefix = $db->config['prefix'];
3635
                }
3636

    
3637
                $schema = $db->getSchemaName();
3638
                $defaultProperties = get_class_vars(get_class($this));
3639
                if (isset($defaultProperties['schemaName'])) {
3640
                        $schema = $defaultProperties['schemaName'];
3641
                }
3642
                $this->schemaName = $schema;
3643
        }
3644

    
3645
/**
3646
 * Gets the DataSource to which this model is bound.
3647
 *
3648
 * @return DataSource A DataSource object
3649
 */
3650
        public function getDataSource() {
3651
                if (!$this->_sourceConfigured && $this->useTable !== false) {
3652
                        $this->_sourceConfigured = true;
3653
                        $this->setSource($this->useTable);
3654
                }
3655

    
3656
                return ConnectionManager::getDataSource($this->useDbConfig);
3657
        }
3658

    
3659
/**
3660
 * Get associations
3661
 *
3662
 * @return array
3663
 */
3664
        public function associations() {
3665
                return $this->_associations;
3666
        }
3667

    
3668
/**
3669
 * Gets all the models with which this model is associated.
3670
 *
3671
 * @param string $type Only result associations of this type
3672
 * @return array|null Associations
3673
 */
3674
        public function getAssociated($type = null) {
3675
                if (!$type) {
3676
                        $associated = array();
3677
                        foreach ($this->_associations as $assoc) {
3678
                                if (!empty($this->{$assoc})) {
3679
                                        $models = array_keys($this->{$assoc});
3680
                                        foreach ($models as $m) {
3681
                                                $associated[$m] = $assoc;
3682
                                        }
3683
                                }
3684
                        }
3685

    
3686
                        return $associated;
3687
                }
3688

    
3689
                if (in_array($type, $this->_associations)) {
3690
                        if (empty($this->{$type})) {
3691
                                return array();
3692
                        }
3693

    
3694
                        return array_keys($this->{$type});
3695
                }
3696

    
3697
                $assoc = array_merge(
3698
                        $this->hasOne,
3699
                        $this->hasMany,
3700
                        $this->belongsTo,
3701
                        $this->hasAndBelongsToMany
3702
                );
3703

    
3704
                if (array_key_exists($type, $assoc)) {
3705
                        foreach ($this->_associations as $a) {
3706
                                if (isset($this->{$a}[$type])) {
3707
                                        $assoc[$type]['association'] = $a;
3708
                                        break;
3709
                                }
3710
                        }
3711

    
3712
                        return $assoc[$type];
3713
                }
3714

    
3715
                return null;
3716
        }
3717

    
3718
/**
3719
 * Gets the name and fields to be used by a join model. This allows specifying join fields
3720
 * in the association definition.
3721
 *
3722
 * @param string|array $assoc The model to be joined
3723
 * @param array $keys Any join keys which must be merged with the keys queried
3724
 * @return array
3725
 */
3726
        public function joinModel($assoc, $keys = array()) {
3727
                if (is_string($assoc)) {
3728
                        list(, $assoc) = pluginSplit($assoc);
3729
                        return array($assoc, array_keys($this->{$assoc}->schema()));
3730
                }
3731

    
3732
                if (is_array($assoc)) {
3733
                        $with = key($assoc);
3734
                        return array($with, array_unique(array_merge($assoc[$with], $keys)));
3735
                }
3736

    
3737
                trigger_error(
3738
                        __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)),
3739
                        E_USER_WARNING
3740
                );
3741
        }
3742

    
3743
/**
3744
 * Called before each find operation. Return false if you want to halt the find
3745
 * call, otherwise return the (modified) query data.
3746
 *
3747
 * @param array $query Data used to execute this query, i.e. conditions, order, etc.
3748
 * @return mixed true if the operation should continue, false if it should abort; or, modified
3749
 *  $query to continue with new $query
3750
 * @link http://book.cakephp.org/2.0/en/models/callback-methods.html#beforefind
3751
 */
3752
        public function beforeFind($query) {
3753
                return true;
3754
        }
3755

    
3756
/**
3757
 * Called after each find operation. Can be used to modify any results returned by find().
3758
 * Return value should be the (modified) results.
3759
 *
3760
 * @param mixed $results The results of the find operation
3761
 * @param bool $primary Whether this model is being queried directly (vs. being queried as an association)
3762
 * @return mixed Result of the find operation
3763
 * @link http://book.cakephp.org/2.0/en/models/callback-methods.html#afterfind
3764
 */
3765
        public function afterFind($results, $primary = false) {
3766
                return $results;
3767
        }
3768

    
3769
/**
3770
 * Called before each save operation, after validation. Return a non-true result
3771
 * to halt the save.
3772
 *
3773
 * @param array $options Options passed from Model::save().
3774
 * @return bool True if the operation should continue, false if it should abort
3775
 * @link http://book.cakephp.org/2.0/en/models/callback-methods.html#beforesave
3776
 * @see Model::save()
3777
 */
3778
        public function beforeSave($options = array()) {
3779
                return true;
3780
        }
3781

    
3782
/**
3783
 * Called after each successful save operation.
3784
 *
3785
 * @param bool $created True if this save created a new record
3786
 * @param array $options Options passed from Model::save().
3787
 * @return void
3788
 * @link http://book.cakephp.org/2.0/en/models/callback-methods.html#aftersave
3789
 * @see Model::save()
3790
 */
3791
        public function afterSave($created, $options = array()) {
3792
        }
3793

    
3794
/**
3795
 * Called before every deletion operation.
3796
 *
3797
 * @param bool $cascade If true records that depend on this record will also be deleted
3798
 * @return bool True if the operation should continue, false if it should abort
3799
 * @link http://book.cakephp.org/2.0/en/models/callback-methods.html#beforedelete
3800
 */
3801
        public function beforeDelete($cascade = true) {
3802
                return true;
3803
        }
3804

    
3805
/**
3806
 * Called after every deletion operation.
3807
 *
3808
 * @return void
3809
 * @link http://book.cakephp.org/2.0/en/models/callback-methods.html#afterdelete
3810
 */
3811
        public function afterDelete() {
3812
        }
3813

    
3814
/**
3815
 * Called during validation operations, before validation. Please note that custom
3816
 * validation rules can be defined in $validate.
3817
 *
3818
 * @param array $options Options passed from Model::save().
3819
 * @return bool True if validate operation should continue, false to abort
3820
 * @link http://book.cakephp.org/2.0/en/models/callback-methods.html#beforevalidate
3821
 * @see Model::save()
3822
 */
3823
        public function beforeValidate($options = array()) {
3824
                return true;
3825
        }
3826

    
3827
/**
3828
 * Called after data has been checked for errors
3829
 *
3830
 * @return void
3831
 */
3832
        public function afterValidate() {
3833
        }
3834

    
3835
/**
3836
 * Called when a DataSource-level error occurs.
3837
 *
3838
 * @return void
3839
 * @link http://book.cakephp.org/2.0/en/models/callback-methods.html#onerror
3840
 */
3841
        public function onError() {
3842
        }
3843

    
3844
/**
3845
 * Clears cache for this model.
3846
 *
3847
 * @param string $type If null this deletes cached views if Cache.check is true
3848
 *     Will be used to allow deleting query cache also
3849
 * @return mixed True on delete, null otherwise
3850
 */
3851
        protected function _clearCache($type = null) {
3852
                if ($type !== null || Configure::read('Cache.check') !== true) {
3853
                        return;
3854
                }
3855
                $pluralized = Inflector::pluralize($this->alias);
3856
                $assoc = array(
3857
                        strtolower($pluralized),
3858
                        Inflector::underscore($pluralized)
3859
                );
3860
                foreach ($this->_associations as $association) {
3861
                        foreach ($this->{$association} as $className) {
3862
                                $pluralizedAssociation = Inflector::pluralize($className['className']);
3863
                                if (!in_array(strtolower($pluralizedAssociation), $assoc)) {
3864
                                        $assoc = array_merge($assoc, array(
3865
                                                strtolower($pluralizedAssociation),
3866
                                                Inflector::underscore($pluralizedAssociation)
3867
                                        ));
3868
                                }
3869
                        }
3870
                }
3871
                clearCache(array_unique($assoc));
3872
                return true;
3873
        }
3874

    
3875
/**
3876
 * Returns an instance of a model validator for this class
3877
 *
3878
 * @param ModelValidator $instance Model validator instance.
3879
 *  If null a new ModelValidator instance will be made using current model object
3880
 * @return ModelValidator
3881
 */
3882
        public function validator(ModelValidator $instance = null) {
3883
                if ($instance) {
3884
                        $this->_validator = $instance;
3885
                } elseif (!$this->_validator) {
3886
                        $this->_validator = new ModelValidator($this);
3887
                }
3888

    
3889
                return $this->_validator;
3890
        }
3891

    
3892
}