CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Reporting Security Issues
    • Privacy Policy
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Get Involved
    • Issues (GitHub)
    • Bakery
    • Featured Resources
    • Training
    • Meetups
    • My CakePHP
    • CakeFest
    • Newsletter
    • Linkedin
    • YouTube
    • Facebook
    • Twitter
    • Mastodon
    • Help & Support
    • Forum
    • Stack Overflow
    • Slack
    • Paid Support
CakePHP

C CakePHP 2.0 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.0
      • 4.2
      • 4.1
      • 4.0
      • 3.9
      • 3.8
      • 3.7
      • 3.6
      • 3.5
      • 3.4
      • 3.3
      • 3.2
      • 3.1
      • 3.0
      • 2.10
      • 2.9
      • 2.8
      • 2.7
      • 2.6
      • 2.5
      • 2.4
      • 2.3
      • 2.2
      • 2.1
      • 2.0
      • 1.3
      • 1.2

Packages

  • Cake
    • Cache
      • Engine
    • Configure
    • Console
      • Command
        • Task
    • Controller
      • Component
        • Auth
    • Core
    • Error
    • I18n
    • Log
      • Engine
    • Model
      • Behavior
      • Datasource
        • Database
        • Session
    • Network
      • Email
      • Http
    • Routing
      • Route
    • TestSuite
      • Coverage
      • Fixture
      • Reporter
    • Utility
    • View
      • Helper

Classes

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

Generated using CakePHP API Docs