mirror of
https://github.com/brmlab/brmbiolab_sklad.git
synced 2025-10-29 14:34:00 +01:00
Initial commit
This commit is contained in:
commit
3b93da31de
1004 changed files with 265840 additions and 0 deletions
185
lib/Cake/Model/AclNode.php
Normal file
185
lib/Cake/Model/AclNode.php
Normal file
|
|
@ -0,0 +1,185 @@
|
|||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @package Cake.Model
|
||||
* @since CakePHP(tm) v 0.2.9
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
App::uses('Model', 'Model');
|
||||
|
||||
/**
|
||||
* ACL Node
|
||||
*
|
||||
* @package Cake.Model
|
||||
*/
|
||||
class AclNode extends Model {
|
||||
|
||||
/**
|
||||
* Explicitly disable in-memory query caching for ACL models
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
public $cacheQueries = false;
|
||||
|
||||
/**
|
||||
* ACL models use the Tree behavior
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $actsAs = array('Tree' => array('type' => 'nested'));
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
*/
|
||||
public function __construct() {
|
||||
$config = Configure::read('Acl.database');
|
||||
if (isset($config)) {
|
||||
$this->useDbConfig = $config;
|
||||
}
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the Aro/Aco node for this model
|
||||
*
|
||||
* @param string|array|Model $ref Array with 'model' and 'foreign_key', model object, or string value
|
||||
* @return array Node found in database
|
||||
* @throws CakeException when binding to a model that doesn't exist.
|
||||
*/
|
||||
public function node($ref = null) {
|
||||
$db = $this->getDataSource();
|
||||
$type = $this->alias;
|
||||
$result = null;
|
||||
|
||||
if (!empty($this->useTable)) {
|
||||
$table = $this->useTable;
|
||||
} else {
|
||||
$table = Inflector::pluralize(Inflector::underscore($type));
|
||||
}
|
||||
|
||||
if (empty($ref)) {
|
||||
return null;
|
||||
} elseif (is_string($ref)) {
|
||||
$path = explode('/', $ref);
|
||||
$start = $path[0];
|
||||
unset($path[0]);
|
||||
|
||||
$queryData = array(
|
||||
'conditions' => array(
|
||||
$db->name("{$type}.lft") . ' <= ' . $db->name("{$type}0.lft"),
|
||||
$db->name("{$type}.rght") . ' >= ' . $db->name("{$type}0.rght")),
|
||||
'fields' => array('id', 'parent_id', 'model', 'foreign_key', 'alias'),
|
||||
'joins' => array(array(
|
||||
'table' => $table,
|
||||
'alias' => "{$type}0",
|
||||
'type' => 'INNER',
|
||||
'conditions' => array("{$type}0.alias" => $start)
|
||||
)),
|
||||
'order' => $db->name("{$type}.lft") . ' DESC'
|
||||
);
|
||||
|
||||
$conditionsAfterJoin = array();
|
||||
|
||||
foreach ($path as $i => $alias) {
|
||||
$j = $i - 1;
|
||||
|
||||
$queryData['joins'][] = array(
|
||||
'table' => $table,
|
||||
'alias' => "{$type}{$i}",
|
||||
'type' => 'INNER',
|
||||
'conditions' => array(
|
||||
$db->name("{$type}{$i}.alias") . ' = ' . $db->value($alias, 'string')
|
||||
)
|
||||
);
|
||||
|
||||
// it will be better if this conditions will performs after join operation
|
||||
$conditionsAfterJoin[] = $db->name("{$type}{$j}.id") . ' = ' . $db->name("{$type}{$i}.parent_id");
|
||||
$conditionsAfterJoin[] = $db->name("{$type}{$i}.rght") . ' < ' . $db->name("{$type}{$j}.rght");
|
||||
$conditionsAfterJoin[] = $db->name("{$type}{$i}.lft") . ' > ' . $db->name("{$type}{$j}.lft");
|
||||
|
||||
$queryData['conditions'] = array('or' => array(
|
||||
$db->name("{$type}.lft") . ' <= ' . $db->name("{$type}0.lft") . ' AND ' . $db->name("{$type}.rght") . ' >= ' . $db->name("{$type}0.rght"),
|
||||
$db->name("{$type}.lft") . ' <= ' . $db->name("{$type}{$i}.lft") . ' AND ' . $db->name("{$type}.rght") . ' >= ' . $db->name("{$type}{$i}.rght"))
|
||||
);
|
||||
}
|
||||
$queryData['conditions'] = array_merge($queryData['conditions'], $conditionsAfterJoin);
|
||||
$result = $db->read($this, $queryData, -1);
|
||||
$path = array_values($path);
|
||||
|
||||
if (
|
||||
!isset($result[0][$type]) ||
|
||||
(!empty($path) && $result[0][$type]['alias'] != $path[count($path) - 1]) ||
|
||||
(empty($path) && $result[0][$type]['alias'] != $start)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
} elseif (is_object($ref) && $ref instanceof Model) {
|
||||
$ref = array('model' => $ref->name, 'foreign_key' => $ref->id);
|
||||
} elseif (is_array($ref) && !(isset($ref['model']) && isset($ref['foreign_key']))) {
|
||||
$name = key($ref);
|
||||
list(, $alias) = pluginSplit($name);
|
||||
|
||||
$model = ClassRegistry::init(array('class' => $name, 'alias' => $alias));
|
||||
|
||||
if (empty($model)) {
|
||||
throw new CakeException('cake_dev', "Model class '%s' not found in AclNode::node() when trying to bind %s object", $type, $this->alias);
|
||||
}
|
||||
|
||||
$tmpRef = null;
|
||||
if (method_exists($model, 'bindNode')) {
|
||||
$tmpRef = $model->bindNode($ref);
|
||||
}
|
||||
if (empty($tmpRef)) {
|
||||
$ref = array('model' => $alias, 'foreign_key' => $ref[$name][$model->primaryKey]);
|
||||
} else {
|
||||
if (is_string($tmpRef)) {
|
||||
return $this->node($tmpRef);
|
||||
}
|
||||
$ref = $tmpRef;
|
||||
}
|
||||
}
|
||||
if (is_array($ref)) {
|
||||
if (is_array(current($ref)) && is_string(key($ref))) {
|
||||
$name = key($ref);
|
||||
$ref = current($ref);
|
||||
}
|
||||
foreach ($ref as $key => $val) {
|
||||
if (strpos($key, $type) !== 0 && strpos($key, '.') === false) {
|
||||
unset($ref[$key]);
|
||||
$ref["{$type}0.{$key}"] = $val;
|
||||
}
|
||||
}
|
||||
$queryData = array(
|
||||
'conditions' => $ref,
|
||||
'fields' => array('id', 'parent_id', 'model', 'foreign_key', 'alias'),
|
||||
'joins' => array(array(
|
||||
'table' => $table,
|
||||
'alias' => "{$type}0",
|
||||
'type' => 'INNER',
|
||||
'conditions' => array(
|
||||
$db->name("{$type}.lft") . ' <= ' . $db->name("{$type}0.lft"),
|
||||
$db->name("{$type}.rght") . ' >= ' . $db->name("{$type}0.rght")
|
||||
)
|
||||
)),
|
||||
'order' => $db->name("{$type}.lft") . ' DESC'
|
||||
);
|
||||
$result = $db->read($this, $queryData, -1);
|
||||
|
||||
if (!$result) {
|
||||
throw new CakeException(__d('cake_dev', "AclNode::node() - Couldn't find %s node identified by \"%s\"", $type, print_r($ref, true)));
|
||||
}
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
}
|
||||
39
lib/Cake/Model/Aco.php
Normal file
39
lib/Cake/Model/Aco.php
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @package Cake.Model
|
||||
* @since CakePHP(tm) v 0.2.9
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
App::uses('AclNode', 'Model');
|
||||
|
||||
/**
|
||||
* Access Control Object
|
||||
*
|
||||
* @package Cake.Model
|
||||
*/
|
||||
class Aco extends AclNode {
|
||||
|
||||
/**
|
||||
* Model name
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $name = 'Aco';
|
||||
|
||||
/**
|
||||
* Binds to ARO nodes through permissions settings
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $hasAndBelongsToMany = array('Aro' => array('with' => 'Permission'));
|
||||
}
|
||||
39
lib/Cake/Model/AcoAction.php
Normal file
39
lib/Cake/Model/AcoAction.php
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @package Cake.Model
|
||||
* @since CakePHP(tm) v 0.2.9
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
App::uses('AppModel', 'Model');
|
||||
|
||||
/**
|
||||
* Action for Access Control Object
|
||||
*
|
||||
* @package Cake.Model
|
||||
*/
|
||||
class AcoAction extends AppModel {
|
||||
|
||||
/**
|
||||
* Model name
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $name = 'AcoAction';
|
||||
|
||||
/**
|
||||
* ACO Actions belong to ACOs
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $belongsTo = array('Aco');
|
||||
}
|
||||
39
lib/Cake/Model/Aro.php
Normal file
39
lib/Cake/Model/Aro.php
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @package Cake.Model
|
||||
* @since CakePHP(tm) v 0.2.9
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
App::uses('AclNode', 'Model');
|
||||
|
||||
/**
|
||||
* Access Request Object
|
||||
*
|
||||
* @package Cake.Model
|
||||
*/
|
||||
class Aro extends AclNode {
|
||||
|
||||
/**
|
||||
* Model name
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $name = 'Aro';
|
||||
|
||||
/**
|
||||
* AROs are linked to ACOs by means of Permission
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $hasAndBelongsToMany = array('Aco' => array('with' => 'Permission'));
|
||||
}
|
||||
144
lib/Cake/Model/Behavior/AclBehavior.php
Normal file
144
lib/Cake/Model/Behavior/AclBehavior.php
Normal file
|
|
@ -0,0 +1,144 @@
|
|||
<?php
|
||||
/**
|
||||
* ACL behavior class.
|
||||
*
|
||||
* Enables objects to easily tie into an ACL system
|
||||
*
|
||||
* CakePHP : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP Project
|
||||
* @package Cake.Model.Behavior
|
||||
* @since CakePHP v 1.2.0.4487
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
App::uses('ModelBehavior', 'Model');
|
||||
App::uses('AclNode', 'Model');
|
||||
App::uses('Hash', 'Utility');
|
||||
|
||||
/**
|
||||
* ACL behavior
|
||||
*
|
||||
* Enables objects to easily tie into an ACL system
|
||||
*
|
||||
* @package Cake.Model.Behavior
|
||||
* @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/acl.html
|
||||
*/
|
||||
class AclBehavior extends ModelBehavior {
|
||||
|
||||
/**
|
||||
* Maps ACL type options to ACL models
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_typeMaps = array('requester' => 'Aro', 'controlled' => 'Aco', 'both' => array('Aro', 'Aco'));
|
||||
|
||||
/**
|
||||
* Sets up the configuration for the model, and loads ACL models if they haven't been already
|
||||
*
|
||||
* @param Model $model Model using this behavior.
|
||||
* @param array $config Configuration options.
|
||||
* @return void
|
||||
*/
|
||||
public function setup(Model $model, $config = array()) {
|
||||
if (isset($config[0])) {
|
||||
$config['type'] = $config[0];
|
||||
unset($config[0]);
|
||||
}
|
||||
$this->settings[$model->name] = array_merge(array('type' => 'controlled'), $config);
|
||||
$this->settings[$model->name]['type'] = strtolower($this->settings[$model->name]['type']);
|
||||
|
||||
$types = $this->_typeMaps[$this->settings[$model->name]['type']];
|
||||
|
||||
if (!is_array($types)) {
|
||||
$types = array($types);
|
||||
}
|
||||
foreach ($types as $type) {
|
||||
$model->{$type} = ClassRegistry::init($type);
|
||||
}
|
||||
if (!method_exists($model, 'parentNode')) {
|
||||
trigger_error(__d('cake_dev', 'Callback %s not defined in %s', 'parentNode()', $model->alias), E_USER_WARNING);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the Aro/Aco node for this model
|
||||
*
|
||||
* @param Model $model Model using this behavior.
|
||||
* @param string|array|Model $ref Array with 'model' and 'foreign_key', model object, or string value
|
||||
* @param string $type Only needed when Acl is set up as 'both', specify 'Aro' or 'Aco' to get the correct node
|
||||
* @return array
|
||||
* @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/acl.html#node
|
||||
*/
|
||||
public function node(Model $model, $ref = null, $type = null) {
|
||||
if (empty($type)) {
|
||||
$type = $this->_typeMaps[$this->settings[$model->name]['type']];
|
||||
if (is_array($type)) {
|
||||
trigger_error(__d('cake_dev', 'AclBehavior is setup with more then one type, please specify type parameter for node()'), E_USER_WARNING);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (empty($ref)) {
|
||||
$ref = array('model' => $model->name, 'foreign_key' => $model->id);
|
||||
}
|
||||
return $model->{$type}->node($ref);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new ARO/ACO node bound to this record
|
||||
*
|
||||
* @param Model $model Model using this behavior.
|
||||
* @param bool $created True if this is a new record
|
||||
* @param array $options Options passed from Model::save().
|
||||
* @return void
|
||||
*/
|
||||
public function afterSave(Model $model, $created, $options = array()) {
|
||||
$types = $this->_typeMaps[$this->settings[$model->name]['type']];
|
||||
if (!is_array($types)) {
|
||||
$types = array($types);
|
||||
}
|
||||
foreach ($types as $type) {
|
||||
$parent = $model->parentNode();
|
||||
if (!empty($parent)) {
|
||||
$parent = $this->node($model, $parent, $type);
|
||||
}
|
||||
$data = array(
|
||||
'parent_id' => isset($parent[0][$type]['id']) ? $parent[0][$type]['id'] : null,
|
||||
'model' => $model->name,
|
||||
'foreign_key' => $model->id
|
||||
);
|
||||
if (!$created) {
|
||||
$node = $this->node($model, null, $type);
|
||||
$data['id'] = isset($node[0][$type]['id']) ? $node[0][$type]['id'] : null;
|
||||
}
|
||||
$model->{$type}->create();
|
||||
$model->{$type}->save($data);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroys the ARO/ACO node bound to the deleted record
|
||||
*
|
||||
* @param Model $model Model using this behavior.
|
||||
* @return void
|
||||
*/
|
||||
public function afterDelete(Model $model) {
|
||||
$types = $this->_typeMaps[$this->settings[$model->name]['type']];
|
||||
if (!is_array($types)) {
|
||||
$types = array($types);
|
||||
}
|
||||
foreach ($types as $type) {
|
||||
$node = Hash::extract($this->node($model, null, $type), "0.{$type}.id");
|
||||
if (!empty($node)) {
|
||||
$model->{$type}->delete($node);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
431
lib/Cake/Model/Behavior/ContainableBehavior.php
Normal file
431
lib/Cake/Model/Behavior/ContainableBehavior.php
Normal file
|
|
@ -0,0 +1,431 @@
|
|||
<?php
|
||||
/**
|
||||
* Behavior for binding management.
|
||||
*
|
||||
* Behavior to simplify manipulating a model's bindings when doing a find operation
|
||||
*
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @package Cake.Model.Behavior
|
||||
* @since CakePHP(tm) v 1.2.0.5669
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
App::uses('ModelBehavior', 'Model');
|
||||
|
||||
/**
|
||||
* Behavior to allow for dynamic and atomic manipulation of a Model's associations
|
||||
* used for a find call. Most useful for limiting the amount of associations and
|
||||
* data returned.
|
||||
*
|
||||
* @package Cake.Model.Behavior
|
||||
* @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html
|
||||
*/
|
||||
class ContainableBehavior extends ModelBehavior {
|
||||
|
||||
/**
|
||||
* Types of relationships available for models
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $types = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
|
||||
|
||||
/**
|
||||
* Runtime configuration for this behavior
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $runtime = array();
|
||||
|
||||
/**
|
||||
* Initiate behavior for the model using specified settings.
|
||||
*
|
||||
* Available settings:
|
||||
*
|
||||
* - recursive: (boolean, optional) set to true to allow containable to automatically
|
||||
* determine the recursiveness level needed to fetch specified models,
|
||||
* and set the model recursiveness to this level. setting it to false
|
||||
* disables this feature. DEFAULTS TO: true
|
||||
* - notices: (boolean, optional) issues E_NOTICES for bindings referenced in a
|
||||
* containable call that are not valid. DEFAULTS TO: true
|
||||
* - autoFields: (boolean, optional) auto-add needed fields to fetch requested
|
||||
* bindings. DEFAULTS TO: true
|
||||
*
|
||||
* @param Model $Model Model using the behavior
|
||||
* @param array $settings Settings to override for model.
|
||||
* @return void
|
||||
*/
|
||||
public function setup(Model $Model, $settings = array()) {
|
||||
if (!isset($this->settings[$Model->alias])) {
|
||||
$this->settings[$Model->alias] = array('recursive' => true, 'notices' => true, 'autoFields' => true);
|
||||
}
|
||||
$this->settings[$Model->alias] = array_merge($this->settings[$Model->alias], $settings);
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs before a find() operation. Used to allow 'contain' setting
|
||||
* as part of the find call, like this:
|
||||
*
|
||||
* `Model->find('all', array('contain' => array('Model1', 'Model2')));`
|
||||
*
|
||||
* {{{
|
||||
* Model->find('all', array('contain' => array(
|
||||
* 'Model1' => array('Model11', 'Model12'),
|
||||
* 'Model2',
|
||||
* 'Model3' => array(
|
||||
* 'Model31' => 'Model311',
|
||||
* 'Model32',
|
||||
* 'Model33' => array('Model331', 'Model332')
|
||||
* )));
|
||||
* }}}
|
||||
*
|
||||
* @param Model $Model Model using the behavior
|
||||
* @param array $query Query parameters as set by cake
|
||||
* @return array
|
||||
*/
|
||||
public function beforeFind(Model $Model, $query) {
|
||||
$reset = (isset($query['reset']) ? $query['reset'] : true);
|
||||
$noContain = false;
|
||||
$contain = array();
|
||||
|
||||
if (isset($this->runtime[$Model->alias]['contain'])) {
|
||||
$noContain = empty($this->runtime[$Model->alias]['contain']);
|
||||
$contain = $this->runtime[$Model->alias]['contain'];
|
||||
unset($this->runtime[$Model->alias]['contain']);
|
||||
}
|
||||
|
||||
if (isset($query['contain'])) {
|
||||
$noContain = $noContain || empty($query['contain']);
|
||||
if ($query['contain'] !== false) {
|
||||
$contain = array_merge($contain, (array)$query['contain']);
|
||||
}
|
||||
}
|
||||
$noContain = $noContain && empty($contain);
|
||||
|
||||
if ($noContain || empty($contain)) {
|
||||
if ($noContain) {
|
||||
$query['recursive'] = -1;
|
||||
}
|
||||
return $query;
|
||||
}
|
||||
if ((isset($contain[0]) && is_bool($contain[0])) || is_bool(end($contain))) {
|
||||
$reset = is_bool(end($contain))
|
||||
? array_pop($contain)
|
||||
: array_shift($contain);
|
||||
}
|
||||
$containments = $this->containments($Model, $contain);
|
||||
$map = $this->containmentsMap($containments);
|
||||
|
||||
$mandatory = array();
|
||||
foreach ($containments['models'] as $model) {
|
||||
$instance = $model['instance'];
|
||||
$needed = $this->fieldDependencies($instance, $map, false);
|
||||
if (!empty($needed)) {
|
||||
$mandatory = array_merge($mandatory, $needed);
|
||||
}
|
||||
if ($contain) {
|
||||
$backupBindings = array();
|
||||
foreach ($this->types as $relation) {
|
||||
if (!empty($instance->__backAssociation[$relation])) {
|
||||
$backupBindings[$relation] = $instance->__backAssociation[$relation];
|
||||
} else {
|
||||
$backupBindings[$relation] = $instance->{$relation};
|
||||
}
|
||||
}
|
||||
foreach ($this->types as $type) {
|
||||
$unbind = array();
|
||||
foreach ($instance->{$type} as $assoc => $options) {
|
||||
if (!isset($model['keep'][$assoc])) {
|
||||
$unbind[] = $assoc;
|
||||
}
|
||||
}
|
||||
if (!empty($unbind)) {
|
||||
if (!$reset && empty($instance->__backOriginalAssociation)) {
|
||||
$instance->__backOriginalAssociation = $backupBindings;
|
||||
}
|
||||
$instance->unbindModel(array($type => $unbind), $reset);
|
||||
}
|
||||
foreach ($instance->{$type} as $assoc => $options) {
|
||||
if (isset($model['keep'][$assoc]) && !empty($model['keep'][$assoc])) {
|
||||
if (isset($model['keep'][$assoc]['fields'])) {
|
||||
$model['keep'][$assoc]['fields'] = $this->fieldDependencies($containments['models'][$assoc]['instance'], $map, $model['keep'][$assoc]['fields']);
|
||||
}
|
||||
if (!$reset && empty($instance->__backOriginalAssociation)) {
|
||||
$instance->__backOriginalAssociation = $backupBindings;
|
||||
} elseif ($reset) {
|
||||
$instance->__backAssociation[$type] = $backupBindings[$type];
|
||||
}
|
||||
$instance->{$type}[$assoc] = array_merge($instance->{$type}[$assoc], $model['keep'][$assoc]);
|
||||
}
|
||||
if (!$reset) {
|
||||
$instance->__backInnerAssociation[] = $assoc;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($this->settings[$Model->alias]['recursive']) {
|
||||
$query['recursive'] = (isset($query['recursive'])) ? max($query['recursive'], $containments['depth']) : $containments['depth'];
|
||||
}
|
||||
|
||||
$autoFields = ($this->settings[$Model->alias]['autoFields']
|
||||
&& !in_array($Model->findQueryType, array('list', 'count'))
|
||||
&& !empty($query['fields']));
|
||||
|
||||
if (!$autoFields) {
|
||||
return $query;
|
||||
}
|
||||
|
||||
$query['fields'] = (array)$query['fields'];
|
||||
foreach (array('hasOne', 'belongsTo') as $type) {
|
||||
if (!empty($Model->{$type})) {
|
||||
foreach ($Model->{$type} as $assoc => $data) {
|
||||
if ($Model->useDbConfig === $Model->{$assoc}->useDbConfig && !empty($data['fields'])) {
|
||||
foreach ((array)$data['fields'] as $field) {
|
||||
$query['fields'][] = (strpos($field, '.') === false ? $assoc . '.' : '') . $field;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($mandatory[$Model->alias])) {
|
||||
foreach ($mandatory[$Model->alias] as $field) {
|
||||
if ($field === '--primaryKey--') {
|
||||
$field = $Model->primaryKey;
|
||||
} elseif (preg_match('/^.+\.\-\-[^-]+\-\-$/', $field)) {
|
||||
list($modelName, $field) = explode('.', $field);
|
||||
if ($Model->useDbConfig === $Model->{$modelName}->useDbConfig) {
|
||||
$field = $modelName . '.' . (
|
||||
($field === '--primaryKey--') ? $Model->$modelName->primaryKey : $field
|
||||
);
|
||||
} else {
|
||||
$field = null;
|
||||
}
|
||||
}
|
||||
if ($field !== null) {
|
||||
$query['fields'][] = $field;
|
||||
}
|
||||
}
|
||||
}
|
||||
$query['fields'] = array_unique($query['fields']);
|
||||
return $query;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unbinds all relations from a model except the specified ones. Calling this function without
|
||||
* parameters unbinds all related models.
|
||||
*
|
||||
* @param Model $Model Model on which binding restriction is being applied
|
||||
* @return void
|
||||
* @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html#using-containable
|
||||
*/
|
||||
public function contain(Model $Model) {
|
||||
$args = func_get_args();
|
||||
$contain = call_user_func_array('am', array_slice($args, 1));
|
||||
$this->runtime[$Model->alias]['contain'] = $contain;
|
||||
}
|
||||
|
||||
/**
|
||||
* Permanently restore the original binding settings of given model, useful
|
||||
* for restoring the bindings after using 'reset' => false as part of the
|
||||
* contain call.
|
||||
*
|
||||
* @param Model $Model Model on which to reset bindings
|
||||
* @return void
|
||||
*/
|
||||
public function resetBindings(Model $Model) {
|
||||
if (!empty($Model->__backOriginalAssociation)) {
|
||||
$Model->__backAssociation = $Model->__backOriginalAssociation;
|
||||
unset($Model->__backOriginalAssociation);
|
||||
}
|
||||
$Model->resetAssociations();
|
||||
if (!empty($Model->__backInnerAssociation)) {
|
||||
$assocs = $Model->__backInnerAssociation;
|
||||
$Model->__backInnerAssociation = array();
|
||||
foreach ($assocs as $currentModel) {
|
||||
$this->resetBindings($Model->$currentModel);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process containments for model.
|
||||
*
|
||||
* @param Model $Model Model on which binding restriction is being applied
|
||||
* @param array $contain Parameters to use for restricting this model
|
||||
* @param array $containments Current set of containments
|
||||
* @param bool $throwErrors Whether non-existent bindings show throw errors
|
||||
* @return array Containments
|
||||
*/
|
||||
public function containments(Model $Model, $contain, $containments = array(), $throwErrors = null) {
|
||||
$options = array('className', 'joinTable', 'with', 'foreignKey', 'associationForeignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'unique', 'finderQuery');
|
||||
$keep = array();
|
||||
if ($throwErrors === null) {
|
||||
$throwErrors = (empty($this->settings[$Model->alias]) ? true : $this->settings[$Model->alias]['notices']);
|
||||
}
|
||||
foreach ((array)$contain as $name => $children) {
|
||||
if (is_numeric($name)) {
|
||||
$name = $children;
|
||||
$children = array();
|
||||
}
|
||||
if (preg_match('/(?<!\.)\(/', $name)) {
|
||||
$name = str_replace('(', '.(', $name);
|
||||
}
|
||||
if (strpos($name, '.') !== false) {
|
||||
$chain = explode('.', $name);
|
||||
$name = array_shift($chain);
|
||||
$children = array(implode('.', $chain) => $children);
|
||||
}
|
||||
|
||||
$children = (array)$children;
|
||||
foreach ($children as $key => $val) {
|
||||
if (is_string($key) && is_string($val) && !in_array($key, $options, true)) {
|
||||
$children[$key] = (array)$val;
|
||||
}
|
||||
}
|
||||
|
||||
$keys = array_keys($children);
|
||||
if ($keys && isset($children[0])) {
|
||||
$keys = array_merge(array_values($children), $keys);
|
||||
}
|
||||
|
||||
foreach ($keys as $i => $key) {
|
||||
if (is_array($key)) {
|
||||
continue;
|
||||
}
|
||||
$optionKey = in_array($key, $options, true);
|
||||
if (!$optionKey && is_string($key) && preg_match('/^[a-z(]/', $key) && (!isset($Model->{$key}) || !is_object($Model->{$key}))) {
|
||||
$option = 'fields';
|
||||
$val = array($key);
|
||||
if ($key{0} === '(') {
|
||||
$val = preg_split('/\s*,\s*/', substr($key, 1, -1));
|
||||
} elseif (preg_match('/ASC|DESC$/', $key)) {
|
||||
$option = 'order';
|
||||
$val = $Model->{$name}->alias . '.' . $key;
|
||||
} elseif (preg_match('/[ =!]/', $key)) {
|
||||
$option = 'conditions';
|
||||
$val = $Model->{$name}->alias . '.' . $key;
|
||||
}
|
||||
$children[$option] = is_array($val) ? $val : array($val);
|
||||
$newChildren = null;
|
||||
if (!empty($name) && !empty($children[$key])) {
|
||||
$newChildren = $children[$key];
|
||||
}
|
||||
unset($children[$key], $children[$i]);
|
||||
$key = $option;
|
||||
$optionKey = true;
|
||||
if (!empty($newChildren)) {
|
||||
$children = Hash::merge($children, $newChildren);
|
||||
}
|
||||
}
|
||||
if ($optionKey && isset($children[$key])) {
|
||||
if (!empty($keep[$name][$key]) && is_array($keep[$name][$key])) {
|
||||
$keep[$name][$key] = array_merge((isset($keep[$name][$key]) ? $keep[$name][$key] : array()), (array)$children[$key]);
|
||||
} else {
|
||||
$keep[$name][$key] = $children[$key];
|
||||
}
|
||||
unset($children[$key]);
|
||||
}
|
||||
}
|
||||
|
||||
if (!isset($Model->{$name}) || !is_object($Model->{$name})) {
|
||||
if ($throwErrors) {
|
||||
trigger_error(__d('cake_dev', 'Model "%s" is not associated with model "%s"', $Model->alias, $name), E_USER_WARNING);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
$containments = $this->containments($Model->{$name}, $children, $containments);
|
||||
$depths[] = $containments['depth'] + 1;
|
||||
if (!isset($keep[$name])) {
|
||||
$keep[$name] = array();
|
||||
}
|
||||
}
|
||||
|
||||
if (!isset($containments['models'][$Model->alias])) {
|
||||
$containments['models'][$Model->alias] = array('keep' => array(), 'instance' => &$Model);
|
||||
}
|
||||
|
||||
$containments['models'][$Model->alias]['keep'] = array_merge($containments['models'][$Model->alias]['keep'], $keep);
|
||||
$containments['depth'] = empty($depths) ? 0 : max($depths);
|
||||
return $containments;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate needed fields to fetch the required bindings for the given model.
|
||||
*
|
||||
* @param Model $Model Model
|
||||
* @param array $map Map of relations for given model
|
||||
* @param array|bool $fields If array, fields to initially load, if false use $Model as primary model
|
||||
* @return array Fields
|
||||
*/
|
||||
public function fieldDependencies(Model $Model, $map, $fields = array()) {
|
||||
if ($fields === false) {
|
||||
foreach ($map as $parent => $children) {
|
||||
foreach ($children as $type => $bindings) {
|
||||
foreach ($bindings as $dependency) {
|
||||
if ($type === 'hasAndBelongsToMany') {
|
||||
$fields[$parent][] = '--primaryKey--';
|
||||
} elseif ($type === 'belongsTo') {
|
||||
$fields[$parent][] = $dependency . '.--primaryKey--';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return $fields;
|
||||
}
|
||||
if (empty($map[$Model->alias])) {
|
||||
return $fields;
|
||||
}
|
||||
foreach ($map[$Model->alias] as $type => $bindings) {
|
||||
foreach ($bindings as $dependency) {
|
||||
$innerFields = array();
|
||||
switch ($type) {
|
||||
case 'belongsTo':
|
||||
$fields[] = $Model->{$type}[$dependency]['foreignKey'];
|
||||
break;
|
||||
case 'hasOne':
|
||||
case 'hasMany':
|
||||
$innerFields[] = $Model->$dependency->primaryKey;
|
||||
$fields[] = $Model->primaryKey;
|
||||
break;
|
||||
}
|
||||
if (!empty($innerFields) && !empty($Model->{$type}[$dependency]['fields'])) {
|
||||
$Model->{$type}[$dependency]['fields'] = array_unique(array_merge($Model->{$type}[$dependency]['fields'], $innerFields));
|
||||
}
|
||||
}
|
||||
}
|
||||
return array_unique($fields);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the map of containments
|
||||
*
|
||||
* @param array $containments Containments
|
||||
* @return array Built containments
|
||||
*/
|
||||
public function containmentsMap($containments) {
|
||||
$map = array();
|
||||
foreach ($containments['models'] as $name => $model) {
|
||||
$instance = $model['instance'];
|
||||
foreach ($this->types as $type) {
|
||||
foreach ($instance->{$type} as $assoc => $options) {
|
||||
if (isset($model['keep'][$assoc])) {
|
||||
$map[$name][$type] = isset($map[$name][$type]) ? array_merge($map[$name][$type], (array)$assoc) : (array)$assoc;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return $map;
|
||||
}
|
||||
|
||||
}
|
||||
707
lib/Cake/Model/Behavior/TranslateBehavior.php
Normal file
707
lib/Cake/Model/Behavior/TranslateBehavior.php
Normal file
|
|
@ -0,0 +1,707 @@
|
|||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @package Cake.Model.Behavior
|
||||
* @since CakePHP(tm) v 1.2.0.4525
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
App::uses('ModelBehavior', 'Model');
|
||||
App::uses('I18n', 'I18n');
|
||||
App::uses('I18nModel', 'Model');
|
||||
|
||||
/**
|
||||
* Translate behavior
|
||||
*
|
||||
* @package Cake.Model.Behavior
|
||||
* @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/translate.html
|
||||
*/
|
||||
class TranslateBehavior extends ModelBehavior {
|
||||
|
||||
/**
|
||||
* Used for runtime configuration of model
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $runtime = array();
|
||||
|
||||
/**
|
||||
* Stores the joinTable object for generating joins.
|
||||
*
|
||||
* @var object
|
||||
*/
|
||||
protected $_joinTable;
|
||||
|
||||
/**
|
||||
* Stores the runtime model for generating joins.
|
||||
*
|
||||
* @var Model
|
||||
*/
|
||||
protected $_runtimeModel;
|
||||
|
||||
/**
|
||||
* Callback
|
||||
*
|
||||
* $config for TranslateBehavior should be
|
||||
* array('fields' => array('field_one',
|
||||
* 'field_two' => 'FieldAssoc', 'field_three'))
|
||||
*
|
||||
* With above example only one permanent hasMany will be joined (for field_two
|
||||
* as FieldAssoc)
|
||||
*
|
||||
* $config could be empty - and translations configured dynamically by
|
||||
* bindTranslation() method
|
||||
*
|
||||
* @param Model $Model Model the behavior is being attached to.
|
||||
* @param array $config Array of configuration information.
|
||||
* @return mixed
|
||||
*/
|
||||
public function setup(Model $Model, $config = array()) {
|
||||
$db = ConnectionManager::getDataSource($Model->useDbConfig);
|
||||
if (!$db->connected) {
|
||||
trigger_error(
|
||||
__d('cake_dev', 'Datasource %s for TranslateBehavior of model %s is not connected', $Model->useDbConfig, $Model->alias),
|
||||
E_USER_ERROR
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->settings[$Model->alias] = array();
|
||||
$this->runtime[$Model->alias] = array('fields' => array());
|
||||
$this->translateModel($Model);
|
||||
return $this->bindTranslation($Model, $config, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleanup Callback unbinds bound translations and deletes setting information.
|
||||
*
|
||||
* @param Model $Model Model being detached.
|
||||
* @return void
|
||||
*/
|
||||
public function cleanup(Model $Model) {
|
||||
$this->unbindTranslation($Model);
|
||||
unset($this->settings[$Model->alias]);
|
||||
unset($this->runtime[$Model->alias]);
|
||||
}
|
||||
|
||||
/**
|
||||
* beforeFind Callback
|
||||
*
|
||||
* @param Model $Model Model find is being run on.
|
||||
* @param array $query Array of Query parameters.
|
||||
* @return array Modified query
|
||||
*/
|
||||
public function beforeFind(Model $Model, $query) {
|
||||
$this->runtime[$Model->alias]['virtualFields'] = $Model->virtualFields;
|
||||
$locale = $this->_getLocale($Model);
|
||||
if (empty($locale)) {
|
||||
return $query;
|
||||
}
|
||||
$db = $Model->getDataSource();
|
||||
$RuntimeModel = $this->translateModel($Model);
|
||||
|
||||
if (!empty($RuntimeModel->tablePrefix)) {
|
||||
$tablePrefix = $RuntimeModel->tablePrefix;
|
||||
} else {
|
||||
$tablePrefix = $db->config['prefix'];
|
||||
}
|
||||
$joinTable = new StdClass();
|
||||
$joinTable->tablePrefix = $tablePrefix;
|
||||
$joinTable->table = $RuntimeModel->table;
|
||||
$joinTable->schemaName = $RuntimeModel->getDataSource()->getSchemaName();
|
||||
|
||||
$this->_joinTable = $joinTable;
|
||||
$this->_runtimeModel = $RuntimeModel;
|
||||
|
||||
if (is_string($query['fields']) && $query['fields'] === "COUNT(*) AS {$db->name('count')}") {
|
||||
$query['fields'] = "COUNT(DISTINCT({$db->name($Model->escapeField())})) {$db->alias}count";
|
||||
$query['joins'][] = array(
|
||||
'type' => 'INNER',
|
||||
'alias' => $RuntimeModel->alias,
|
||||
'table' => $joinTable,
|
||||
'conditions' => array(
|
||||
$Model->escapeField() => $db->identifier($RuntimeModel->escapeField('foreign_key')),
|
||||
$RuntimeModel->escapeField('model') => $Model->name,
|
||||
$RuntimeModel->escapeField('locale') => $locale
|
||||
)
|
||||
);
|
||||
$conditionFields = $this->_checkConditions($Model, $query);
|
||||
foreach ($conditionFields as $field) {
|
||||
$query = $this->_addJoin($Model, $query, $field, $field, $locale);
|
||||
}
|
||||
unset($this->_joinTable, $this->_runtimeModel);
|
||||
return $query;
|
||||
} elseif (is_string($query['fields'])) {
|
||||
$query['fields'] = String::tokenize($query['fields']);
|
||||
}
|
||||
|
||||
$fields = array_merge(
|
||||
$this->settings[$Model->alias],
|
||||
$this->runtime[$Model->alias]['fields']
|
||||
);
|
||||
$addFields = array();
|
||||
if (empty($query['fields'])) {
|
||||
$addFields = $fields;
|
||||
} elseif (is_array($query['fields'])) {
|
||||
$isAllFields = (
|
||||
in_array($Model->alias . '.' . '*', $query['fields']) ||
|
||||
in_array($Model->escapeField('*'), $query['fields'])
|
||||
);
|
||||
foreach ($fields as $key => $value) {
|
||||
$field = (is_numeric($key)) ? $value : $key;
|
||||
if (
|
||||
$isAllFields ||
|
||||
in_array($Model->alias . '.' . $field, $query['fields']) ||
|
||||
in_array($field, $query['fields'])
|
||||
) {
|
||||
$addFields[] = $field;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$this->runtime[$Model->alias]['virtualFields'] = $Model->virtualFields;
|
||||
if ($addFields) {
|
||||
foreach ($addFields as $_f => $field) {
|
||||
$aliasField = is_numeric($_f) ? $field : $_f;
|
||||
|
||||
foreach (array($aliasField, $Model->alias . '.' . $aliasField) as $_field) {
|
||||
$key = array_search($_field, (array)$query['fields']);
|
||||
|
||||
if ($key !== false) {
|
||||
unset($query['fields'][$key]);
|
||||
}
|
||||
}
|
||||
$query = $this->_addJoin($Model, $query, $field, $aliasField, $locale);
|
||||
}
|
||||
}
|
||||
$this->runtime[$Model->alias]['beforeFind'] = $addFields;
|
||||
unset($this->_joinTable, $this->_runtimeModel);
|
||||
return $query;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check a query's conditions for translated fields.
|
||||
* Return an array of translated fields found in the conditions.
|
||||
*
|
||||
* @param Model $Model The model being read.
|
||||
* @param array $query The query array.
|
||||
* @return array The list of translated fields that are in the conditions.
|
||||
*/
|
||||
protected function _checkConditions(Model $Model, $query) {
|
||||
$conditionFields = array();
|
||||
if (empty($query['conditions']) || (!empty($query['conditions']) && !is_array($query['conditions']))) {
|
||||
return $conditionFields;
|
||||
}
|
||||
foreach ($query['conditions'] as $col => $val) {
|
||||
foreach ($this->settings[$Model->alias] as $field => $assoc) {
|
||||
if (is_numeric($field)) {
|
||||
$field = $assoc;
|
||||
}
|
||||
if (strpos($col, $field) !== false) {
|
||||
$conditionFields[] = $field;
|
||||
}
|
||||
}
|
||||
}
|
||||
return $conditionFields;
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends a join for translated fields.
|
||||
*
|
||||
* @param Model $Model The model being worked on.
|
||||
* @param array $query The query array to append a join to.
|
||||
* @param string $field The field name being joined.
|
||||
* @param string $aliasField The aliased field name being joined.
|
||||
* @param string|array $locale The locale(s) having joins added.
|
||||
* @return array The modified query
|
||||
*/
|
||||
protected function _addJoin(Model $Model, $query, $field, $aliasField, $locale) {
|
||||
$db = ConnectionManager::getDataSource($Model->useDbConfig);
|
||||
$RuntimeModel = $this->_runtimeModel;
|
||||
$joinTable = $this->_joinTable;
|
||||
$aliasVirtual = "i18n_{$field}";
|
||||
$alias = "I18n__{$field}";
|
||||
if (is_array($locale)) {
|
||||
foreach ($locale as $_locale) {
|
||||
$aliasVirtualLocale = "{$aliasVirtual}_{$_locale}";
|
||||
$aliasLocale = "{$alias}__{$_locale}";
|
||||
$Model->virtualFields[$aliasVirtualLocale] = "{$aliasLocale}.content";
|
||||
if (!empty($query['fields']) && is_array($query['fields'])) {
|
||||
$query['fields'][] = $aliasVirtualLocale;
|
||||
}
|
||||
$query['joins'][] = array(
|
||||
'type' => 'LEFT',
|
||||
'alias' => $aliasLocale,
|
||||
'table' => $joinTable,
|
||||
'conditions' => array(
|
||||
$Model->escapeField() => $db->identifier("{$aliasLocale}.foreign_key"),
|
||||
"{$aliasLocale}.model" => $Model->name,
|
||||
"{$aliasLocale}.{$RuntimeModel->displayField}" => $aliasField,
|
||||
"{$aliasLocale}.locale" => $_locale
|
||||
)
|
||||
);
|
||||
}
|
||||
} else {
|
||||
$Model->virtualFields[$aliasVirtual] = "{$alias}.content";
|
||||
if (!empty($query['fields']) && is_array($query['fields'])) {
|
||||
$query['fields'][] = $aliasVirtual;
|
||||
}
|
||||
$query['joins'][] = array(
|
||||
'type' => 'INNER',
|
||||
'alias' => $alias,
|
||||
'table' => $joinTable,
|
||||
'conditions' => array(
|
||||
"{$Model->alias}.{$Model->primaryKey}" => $db->identifier("{$alias}.foreign_key"),
|
||||
"{$alias}.model" => $Model->name,
|
||||
"{$alias}.{$RuntimeModel->displayField}" => $aliasField,
|
||||
"{$alias}.locale" => $locale
|
||||
)
|
||||
);
|
||||
}
|
||||
return $query;
|
||||
}
|
||||
|
||||
/**
|
||||
* afterFind Callback
|
||||
*
|
||||
* @param Model $Model Model find was run on
|
||||
* @param array $results Array of model results.
|
||||
* @param bool $primary Did the find originate on $model.
|
||||
* @return array Modified results
|
||||
*/
|
||||
public function afterFind(Model $Model, $results, $primary = false) {
|
||||
$Model->virtualFields = $this->runtime[$Model->alias]['virtualFields'];
|
||||
|
||||
$this->runtime[$Model->alias]['virtualFields'] = $this->runtime[$Model->alias]['fields'] = array();
|
||||
if (!empty($this->runtime[$Model->alias]['restoreFields'])) {
|
||||
$this->runtime[$Model->alias]['fields'] = $this->runtime[$Model->alias]['restoreFields'];
|
||||
unset($this->runtime[$Model->alias]['restoreFields']);
|
||||
}
|
||||
|
||||
$locale = $this->_getLocale($Model);
|
||||
|
||||
if (empty($locale) || empty($results) || empty($this->runtime[$Model->alias]['beforeFind'])) {
|
||||
return $results;
|
||||
}
|
||||
$beforeFind = $this->runtime[$Model->alias]['beforeFind'];
|
||||
|
||||
foreach ($results as $key => &$row) {
|
||||
$results[$key][$Model->alias]['locale'] = (is_array($locale)) ? current($locale) : $locale;
|
||||
foreach ($beforeFind as $_f => $field) {
|
||||
$aliasField = is_numeric($_f) ? $field : $_f;
|
||||
$aliasVirtual = "i18n_{$field}";
|
||||
if (is_array($locale)) {
|
||||
foreach ($locale as $_locale) {
|
||||
$aliasVirtualLocale = "{$aliasVirtual}_{$_locale}";
|
||||
if (!isset($row[$Model->alias][$aliasField]) && !empty($row[$Model->alias][$aliasVirtualLocale])) {
|
||||
$row[$Model->alias][$aliasField] = $row[$Model->alias][$aliasVirtualLocale];
|
||||
$row[$Model->alias]['locale'] = $_locale;
|
||||
}
|
||||
unset($row[$Model->alias][$aliasVirtualLocale]);
|
||||
}
|
||||
|
||||
if (!isset($row[$Model->alias][$aliasField])) {
|
||||
$row[$Model->alias][$aliasField] = '';
|
||||
}
|
||||
} else {
|
||||
$value = '';
|
||||
if (isset($row[$Model->alias][$aliasVirtual])) {
|
||||
$value = $row[$Model->alias][$aliasVirtual];
|
||||
}
|
||||
$row[$Model->alias][$aliasField] = $value;
|
||||
unset($row[$Model->alias][$aliasVirtual]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return $results;
|
||||
}
|
||||
|
||||
/**
|
||||
* beforeValidate Callback
|
||||
*
|
||||
* @param Model $Model Model invalidFields was called on.
|
||||
* @param array $options Options passed from Model::save().
|
||||
* @return bool
|
||||
* @see Model::save()
|
||||
*/
|
||||
public function beforeValidate(Model $Model, $options = array()) {
|
||||
unset($this->runtime[$Model->alias]['beforeSave']);
|
||||
$this->_setRuntimeData($Model);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* beforeSave callback.
|
||||
*
|
||||
* Copies data into the runtime property when `$options['validate']` is
|
||||
* disabled. Or the runtime data hasn't been set yet.
|
||||
*
|
||||
* @param Model $Model Model save was called on.
|
||||
* @param array $options Options passed from Model::save().
|
||||
* @return bool true.
|
||||
* @see Model::save()
|
||||
*/
|
||||
public function beforeSave(Model $Model, $options = array()) {
|
||||
if (isset($options['validate']) && !$options['validate']) {
|
||||
unset($this->runtime[$Model->alias]['beforeSave']);
|
||||
}
|
||||
if (isset($this->runtime[$Model->alias]['beforeSave'])) {
|
||||
return true;
|
||||
}
|
||||
$this->_setRuntimeData($Model);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the runtime data.
|
||||
*
|
||||
* Used from beforeValidate() and beforeSave() for compatibility issues,
|
||||
* and to allow translations to be persisted even when validation
|
||||
* is disabled.
|
||||
*
|
||||
* @param Model $Model Model using this behavior.
|
||||
* @return void
|
||||
*/
|
||||
protected function _setRuntimeData(Model $Model) {
|
||||
$locale = $this->_getLocale($Model);
|
||||
if (empty($locale)) {
|
||||
return true;
|
||||
}
|
||||
$fields = array_merge($this->settings[$Model->alias], $this->runtime[$Model->alias]['fields']);
|
||||
$tempData = array();
|
||||
|
||||
foreach ($fields as $key => $value) {
|
||||
$field = (is_numeric($key)) ? $value : $key;
|
||||
|
||||
if (isset($Model->data[$Model->alias][$field])) {
|
||||
$tempData[$field] = $Model->data[$Model->alias][$field];
|
||||
if (is_array($Model->data[$Model->alias][$field])) {
|
||||
if (is_string($locale) && !empty($Model->data[$Model->alias][$field][$locale])) {
|
||||
$Model->data[$Model->alias][$field] = $Model->data[$Model->alias][$field][$locale];
|
||||
} else {
|
||||
$values = array_values($Model->data[$Model->alias][$field]);
|
||||
$Model->data[$Model->alias][$field] = $values[0];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
$this->runtime[$Model->alias]['beforeSave'] = $tempData;
|
||||
}
|
||||
|
||||
/**
|
||||
* Restores model data to the original data.
|
||||
* This solves issues with saveAssociated and validate = first.
|
||||
*
|
||||
* @param Model $Model Model using this behavior.
|
||||
* @return void
|
||||
*/
|
||||
public function afterValidate(Model $Model) {
|
||||
$Model->data[$Model->alias] = array_merge(
|
||||
$Model->data[$Model->alias],
|
||||
$this->runtime[$Model->alias]['beforeSave']
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* afterSave Callback
|
||||
*
|
||||
* @param Model $Model Model the callback is called on
|
||||
* @param bool $created Whether or not the save created a record.
|
||||
* @param array $options Options passed from Model::save().
|
||||
* @return void
|
||||
*/
|
||||
public function afterSave(Model $Model, $created, $options = array()) {
|
||||
if (!isset($this->runtime[$Model->alias]['beforeValidate']) && !isset($this->runtime[$Model->alias]['beforeSave'])) {
|
||||
return true;
|
||||
}
|
||||
if (isset($this->runtime[$Model->alias]['beforeValidate'])) {
|
||||
$tempData = $this->runtime[$Model->alias]['beforeValidate'];
|
||||
} else {
|
||||
$tempData = $this->runtime[$Model->alias]['beforeSave'];
|
||||
}
|
||||
|
||||
unset($this->runtime[$Model->alias]['beforeValidate'], $this->runtime[$Model->alias]['beforeSave']);
|
||||
$conditions = array('model' => $Model->name, 'foreign_key' => $Model->id);
|
||||
$RuntimeModel = $this->translateModel($Model);
|
||||
|
||||
if ($created) {
|
||||
$tempData = $this->_prepareTranslations($Model, $tempData);
|
||||
}
|
||||
$locale = $this->_getLocale($Model);
|
||||
|
||||
foreach ($tempData as $field => $value) {
|
||||
unset($conditions['content']);
|
||||
$conditions['field'] = $field;
|
||||
if (is_array($value)) {
|
||||
$conditions['locale'] = array_keys($value);
|
||||
} else {
|
||||
$conditions['locale'] = $locale;
|
||||
if (is_array($locale)) {
|
||||
$value = array($locale[0] => $value);
|
||||
} else {
|
||||
$value = array($locale => $value);
|
||||
}
|
||||
}
|
||||
$translations = $RuntimeModel->find('list', array(
|
||||
'conditions' => $conditions,
|
||||
'fields' => array(
|
||||
$RuntimeModel->alias . '.locale',
|
||||
$RuntimeModel->alias . '.id'
|
||||
)
|
||||
));
|
||||
foreach ($value as $_locale => $_value) {
|
||||
$RuntimeModel->create();
|
||||
$conditions['locale'] = $_locale;
|
||||
$conditions['content'] = $_value;
|
||||
if (array_key_exists($_locale, $translations)) {
|
||||
$RuntimeModel->save(array(
|
||||
$RuntimeModel->alias => array_merge(
|
||||
$conditions, array('id' => $translations[$_locale])
|
||||
)
|
||||
));
|
||||
} else {
|
||||
$RuntimeModel->save(array($RuntimeModel->alias => $conditions));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares the data to be saved for translated records.
|
||||
* Add blank fields, and populates data for multi-locale saves.
|
||||
*
|
||||
* @param Model $Model Model using this behavior
|
||||
* @param array $data The sparse data that was provided.
|
||||
* @return array The fully populated data to save.
|
||||
*/
|
||||
protected function _prepareTranslations(Model $Model, $data) {
|
||||
$fields = array_merge($this->settings[$Model->alias], $this->runtime[$Model->alias]['fields']);
|
||||
$locales = array();
|
||||
foreach ($data as $key => $value) {
|
||||
if (is_array($value)) {
|
||||
$locales = array_merge($locales, array_keys($value));
|
||||
}
|
||||
}
|
||||
$locales = array_unique($locales);
|
||||
$hasLocales = count($locales) > 0;
|
||||
|
||||
foreach ($fields as $key => $field) {
|
||||
if (!is_numeric($key)) {
|
||||
$field = $key;
|
||||
}
|
||||
if ($hasLocales && !isset($data[$field])) {
|
||||
$data[$field] = array_fill_keys($locales, '');
|
||||
} elseif (!isset($data[$field])) {
|
||||
$data[$field] = '';
|
||||
}
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* afterDelete Callback
|
||||
*
|
||||
* @param Model $Model Model the callback was run on.
|
||||
* @return void
|
||||
*/
|
||||
public function afterDelete(Model $Model) {
|
||||
$RuntimeModel = $this->translateModel($Model);
|
||||
$conditions = array('model' => $Model->name, 'foreign_key' => $Model->id);
|
||||
$RuntimeModel->deleteAll($conditions);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get selected locale for model
|
||||
*
|
||||
* @param Model $Model Model the locale needs to be set/get on.
|
||||
* @return mixed string or false
|
||||
*/
|
||||
protected function _getLocale(Model $Model) {
|
||||
if (!isset($Model->locale) || $Model->locale === null) {
|
||||
$I18n = I18n::getInstance();
|
||||
$I18n->l10n->get(Configure::read('Config.language'));
|
||||
$Model->locale = $I18n->l10n->locale;
|
||||
}
|
||||
|
||||
return $Model->locale;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get instance of model for translations.
|
||||
*
|
||||
* If the model has a translateModel property set, this will be used as the class
|
||||
* name to find/use. If no translateModel property is found 'I18nModel' will be used.
|
||||
*
|
||||
* @param Model $Model Model to get a translatemodel for.
|
||||
* @return Model
|
||||
*/
|
||||
public function translateModel(Model $Model) {
|
||||
if (!isset($this->runtime[$Model->alias]['model'])) {
|
||||
if (!isset($Model->translateModel) || empty($Model->translateModel)) {
|
||||
$className = 'I18nModel';
|
||||
} else {
|
||||
$className = $Model->translateModel;
|
||||
}
|
||||
|
||||
$this->runtime[$Model->alias]['model'] = ClassRegistry::init($className);
|
||||
}
|
||||
if (!empty($Model->translateTable) && $Model->translateTable !== $this->runtime[$Model->alias]['model']->useTable) {
|
||||
$this->runtime[$Model->alias]['model']->setSource($Model->translateTable);
|
||||
} elseif (empty($Model->translateTable) && empty($Model->translateModel)) {
|
||||
$this->runtime[$Model->alias]['model']->setSource('i18n');
|
||||
}
|
||||
return $this->runtime[$Model->alias]['model'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind translation for fields, optionally with hasMany association for
|
||||
* fake field.
|
||||
*
|
||||
* *Note* You should avoid binding translations that overlap existing model properties.
|
||||
* This can cause un-expected and un-desirable behavior.
|
||||
*
|
||||
* @param Model $Model using this behavior of model
|
||||
* @param string|array $fields string with field or array(field1, field2=>AssocName, field3)
|
||||
* @param bool $reset Leave true to have the fields only modified for the next operation.
|
||||
* if false the field will be added for all future queries.
|
||||
* @return bool
|
||||
* @throws CakeException when attempting to bind a translating called name. This is not allowed
|
||||
* as it shadows Model::$name.
|
||||
*/
|
||||
public function bindTranslation(Model $Model, $fields, $reset = true) {
|
||||
if (is_string($fields)) {
|
||||
$fields = array($fields);
|
||||
}
|
||||
$associations = array();
|
||||
$RuntimeModel = $this->translateModel($Model);
|
||||
$default = array(
|
||||
'className' => $RuntimeModel->alias,
|
||||
'foreignKey' => 'foreign_key'
|
||||
);
|
||||
|
||||
foreach ($fields as $key => $value) {
|
||||
if (is_numeric($key)) {
|
||||
$field = $value;
|
||||
$association = null;
|
||||
} else {
|
||||
$field = $key;
|
||||
$association = $value;
|
||||
}
|
||||
if ($association === 'name') {
|
||||
throw new CakeException(
|
||||
__d('cake_dev', 'You cannot bind a translation named "name".')
|
||||
);
|
||||
}
|
||||
$this->_removeField($Model, $field);
|
||||
|
||||
if ($association === null) {
|
||||
if ($reset) {
|
||||
$this->runtime[$Model->alias]['fields'][] = $field;
|
||||
} else {
|
||||
$this->settings[$Model->alias][] = $field;
|
||||
}
|
||||
} else {
|
||||
if ($reset) {
|
||||
$this->runtime[$Model->alias]['fields'][$field] = $association;
|
||||
$this->runtime[$Model->alias]['restoreFields'][] = $field;
|
||||
} else {
|
||||
$this->settings[$Model->alias][$field] = $association;
|
||||
}
|
||||
|
||||
foreach (array('hasOne', 'hasMany', 'belongsTo', 'hasAndBelongsToMany') as $type) {
|
||||
if (isset($Model->{$type}[$association]) || isset($Model->__backAssociation[$type][$association])) {
|
||||
trigger_error(
|
||||
__d('cake_dev', 'Association %s is already bound to model %s', $association, $Model->alias),
|
||||
E_USER_ERROR
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
$associations[$association] = array_merge($default, array('conditions' => array(
|
||||
'model' => $Model->name,
|
||||
$RuntimeModel->displayField => $field
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($associations)) {
|
||||
$Model->bindModel(array('hasMany' => $associations), $reset);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update runtime setting for a given field.
|
||||
*
|
||||
* @param Model $Model Model using this behavior
|
||||
* @param string $field The field to update.
|
||||
* @return void
|
||||
*/
|
||||
protected function _removeField(Model $Model, $field) {
|
||||
if (array_key_exists($field, $this->settings[$Model->alias])) {
|
||||
unset($this->settings[$Model->alias][$field]);
|
||||
} elseif (in_array($field, $this->settings[$Model->alias])) {
|
||||
$this->settings[$Model->alias] = array_merge(array_diff($this->settings[$Model->alias], array($field)));
|
||||
}
|
||||
|
||||
if (array_key_exists($field, $this->runtime[$Model->alias]['fields'])) {
|
||||
unset($this->runtime[$Model->alias]['fields'][$field]);
|
||||
} elseif (in_array($field, $this->runtime[$Model->alias]['fields'])) {
|
||||
$this->runtime[$Model->alias]['fields'] = array_merge(array_diff($this->runtime[$Model->alias]['fields'], array($field)));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Unbind translation for fields, optionally unbinds hasMany association for
|
||||
* fake field
|
||||
*
|
||||
* @param Model $Model using this behavior of model
|
||||
* @param string|array $fields string with field, or array(field1, field2=>AssocName, field3), or null for
|
||||
* unbind all original translations
|
||||
* @return bool
|
||||
*/
|
||||
public function unbindTranslation(Model $Model, $fields = null) {
|
||||
if (empty($fields) && empty($this->settings[$Model->alias])) {
|
||||
return false;
|
||||
}
|
||||
if (empty($fields)) {
|
||||
return $this->unbindTranslation($Model, $this->settings[$Model->alias]);
|
||||
}
|
||||
|
||||
if (is_string($fields)) {
|
||||
$fields = array($fields);
|
||||
}
|
||||
$associations = array();
|
||||
|
||||
foreach ($fields as $key => $value) {
|
||||
if (is_numeric($key)) {
|
||||
$field = $value;
|
||||
$association = null;
|
||||
} else {
|
||||
$field = $key;
|
||||
$association = $value;
|
||||
}
|
||||
|
||||
$this->_removeField($Model, $field);
|
||||
|
||||
if ($association !== null && (isset($Model->hasMany[$association]) || isset($Model->__backAssociation['hasMany'][$association]))) {
|
||||
$associations[] = $association;
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($associations)) {
|
||||
$Model->unbindModel(array('hasMany' => $associations), false);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
1073
lib/Cake/Model/Behavior/TreeBehavior.php
Normal file
1073
lib/Cake/Model/Behavior/TreeBehavior.php
Normal file
File diff suppressed because it is too large
Load diff
296
lib/Cake/Model/BehaviorCollection.php
Normal file
296
lib/Cake/Model/BehaviorCollection.php
Normal file
|
|
@ -0,0 +1,296 @@
|
|||
<?php
|
||||
/**
|
||||
* BehaviorCollection
|
||||
*
|
||||
* Provides management and interface for interacting with collections of behaviors.
|
||||
*
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @package Cake.Model
|
||||
* @since CakePHP(tm) v 1.2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
App::uses('ObjectCollection', 'Utility');
|
||||
App::uses('CakeEventListener', 'Event');
|
||||
|
||||
/**
|
||||
* Model behavior collection class.
|
||||
*
|
||||
* Defines the Behavior interface, and contains common model interaction functionality.
|
||||
*
|
||||
* @package Cake.Model
|
||||
*/
|
||||
class BehaviorCollection extends ObjectCollection implements CakeEventListener {
|
||||
|
||||
/**
|
||||
* Stores a reference to the attached name
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $modelName = null;
|
||||
|
||||
/**
|
||||
* Keeps a list of all methods of attached behaviors
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_methods = array();
|
||||
|
||||
/**
|
||||
* Keeps a list of all methods which have been mapped with regular expressions
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_mappedMethods = array();
|
||||
|
||||
/**
|
||||
* Attaches a model object and loads a list of behaviors
|
||||
*
|
||||
* @param string $modelName Model name.
|
||||
* @param array $behaviors Behaviors list.
|
||||
* @return void
|
||||
*/
|
||||
public function init($modelName, $behaviors = array()) {
|
||||
$this->modelName = $modelName;
|
||||
|
||||
if (!empty($behaviors)) {
|
||||
foreach (BehaviorCollection::normalizeObjectArray($behaviors) as $config) {
|
||||
$this->load($config['class'], $config['settings']);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Backwards compatible alias for load()
|
||||
*
|
||||
* @param string $behavior Behavior name.
|
||||
* @param array $config Configuration options.
|
||||
* @return void
|
||||
* @deprecated Will be removed in 3.0. Replaced with load().
|
||||
*/
|
||||
public function attach($behavior, $config = array()) {
|
||||
return $this->load($behavior, $config);
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a behavior into the collection. You can use use `$config['enabled'] = false`
|
||||
* to load a behavior with callbacks disabled. By default callbacks are enabled. Disable behaviors
|
||||
* can still be used as normal.
|
||||
*
|
||||
* You can alias your behavior as an existing behavior by setting the 'className' key, i.e.,
|
||||
* {{{
|
||||
* public $actsAs = array(
|
||||
* 'Tree' => array(
|
||||
* 'className' => 'AliasedTree'
|
||||
* );
|
||||
* );
|
||||
* }}}
|
||||
* All calls to the `Tree` behavior would use `AliasedTree` instead.
|
||||
*
|
||||
* @param string $behavior CamelCased name of the behavior to load
|
||||
* @param array $config Behavior configuration parameters
|
||||
* @return bool True on success, false on failure
|
||||
* @throws MissingBehaviorException when a behavior could not be found.
|
||||
*/
|
||||
public function load($behavior, $config = array()) {
|
||||
if (isset($config['className'])) {
|
||||
$alias = $behavior;
|
||||
$behavior = $config['className'];
|
||||
}
|
||||
$configDisabled = isset($config['enabled']) && $config['enabled'] === false;
|
||||
$priority = isset($config['priority']) ? $config['priority'] : $this->defaultPriority;
|
||||
unset($config['enabled'], $config['className'], $config['priority']);
|
||||
|
||||
list($plugin, $name) = pluginSplit($behavior, true);
|
||||
if (!isset($alias)) {
|
||||
$alias = $name;
|
||||
}
|
||||
|
||||
$class = $name . 'Behavior';
|
||||
|
||||
App::uses($class, $plugin . 'Model/Behavior');
|
||||
if (!class_exists($class)) {
|
||||
throw new MissingBehaviorException(array(
|
||||
'class' => $class,
|
||||
'plugin' => substr($plugin, 0, -1)
|
||||
));
|
||||
}
|
||||
|
||||
if (!isset($this->{$alias})) {
|
||||
if (ClassRegistry::isKeySet($class)) {
|
||||
$this->_loaded[$alias] = ClassRegistry::getObject($class);
|
||||
} else {
|
||||
$this->_loaded[$alias] = new $class();
|
||||
ClassRegistry::addObject($class, $this->_loaded[$alias]);
|
||||
}
|
||||
} elseif (isset($this->_loaded[$alias]->settings) && isset($this->_loaded[$alias]->settings[$this->modelName])) {
|
||||
if ($config !== null && $config !== false) {
|
||||
$config = array_merge($this->_loaded[$alias]->settings[$this->modelName], $config);
|
||||
} else {
|
||||
$config = array();
|
||||
}
|
||||
}
|
||||
if (empty($config)) {
|
||||
$config = array();
|
||||
}
|
||||
$this->_loaded[$alias]->settings['priority'] = $priority;
|
||||
$this->_loaded[$alias]->setup(ClassRegistry::getObject($this->modelName), $config);
|
||||
|
||||
foreach ($this->_loaded[$alias]->mapMethods as $method => $methodAlias) {
|
||||
$this->_mappedMethods[$method] = array($alias, $methodAlias);
|
||||
}
|
||||
$methods = get_class_methods($this->_loaded[$alias]);
|
||||
$parentMethods = array_flip(get_class_methods('ModelBehavior'));
|
||||
$callbacks = array(
|
||||
'setup', 'cleanup', 'beforeFind', 'afterFind', 'beforeSave', 'afterSave',
|
||||
'beforeDelete', 'afterDelete', 'onError'
|
||||
);
|
||||
|
||||
foreach ($methods as $m) {
|
||||
if (!isset($parentMethods[$m])) {
|
||||
$methodAllowed = (
|
||||
$m[0] !== '_' && !array_key_exists($m, $this->_methods) &&
|
||||
!in_array($m, $callbacks)
|
||||
);
|
||||
if ($methodAllowed) {
|
||||
$this->_methods[$m] = array($alias, $m);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($configDisabled) {
|
||||
$this->disable($alias);
|
||||
} elseif (!$this->enabled($alias)) {
|
||||
$this->enable($alias);
|
||||
} else {
|
||||
$this->setPriority($alias, $priority);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Detaches a behavior from a model
|
||||
*
|
||||
* @param string $name CamelCased name of the behavior to unload
|
||||
* @return void
|
||||
*/
|
||||
public function unload($name) {
|
||||
list(, $name) = pluginSplit($name);
|
||||
if (isset($this->_loaded[$name])) {
|
||||
$this->_loaded[$name]->cleanup(ClassRegistry::getObject($this->modelName));
|
||||
parent::unload($name);
|
||||
}
|
||||
foreach ($this->_methods as $m => $callback) {
|
||||
if (is_array($callback) && $callback[0] === $name) {
|
||||
unset($this->_methods[$m]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Backwards compatible alias for unload()
|
||||
*
|
||||
* @param string $name Name of behavior
|
||||
* @return void
|
||||
* @deprecated Will be removed in 3.0. Use unload instead.
|
||||
*/
|
||||
public function detach($name) {
|
||||
return $this->unload($name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispatches a behavior method. Will call either normal methods or mapped methods.
|
||||
*
|
||||
* If a method is not handled by the BehaviorCollection, and $strict is false, a
|
||||
* special return of `array('unhandled')` will be returned to signal the method was not found.
|
||||
*
|
||||
* @param Model $model The model the method was originally called on.
|
||||
* @param string $method The method called.
|
||||
* @param array $params Parameters for the called method.
|
||||
* @param bool $strict If methods are not found, trigger an error.
|
||||
* @return array All methods for all behaviors attached to this object
|
||||
*/
|
||||
public function dispatchMethod($model, $method, $params = array(), $strict = false) {
|
||||
$method = $this->hasMethod($method, true);
|
||||
|
||||
if ($strict && empty($method)) {
|
||||
trigger_error(__d('cake_dev', '%s - Method %s not found in any attached behavior', 'BehaviorCollection::dispatchMethod()', $method), E_USER_WARNING);
|
||||
return null;
|
||||
}
|
||||
if (empty($method)) {
|
||||
return array('unhandled');
|
||||
}
|
||||
if (count($method) === 3) {
|
||||
array_unshift($params, $method[2]);
|
||||
unset($method[2]);
|
||||
}
|
||||
return call_user_func_array(
|
||||
array($this->_loaded[$method[0]], $method[1]),
|
||||
array_merge(array(&$model), $params)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the method list for attached behaviors, i.e. all public, non-callback methods.
|
||||
* This does not include mappedMethods.
|
||||
*
|
||||
* @return array All public methods for all behaviors attached to this collection
|
||||
*/
|
||||
public function methods() {
|
||||
return $this->_methods;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check to see if a behavior in this collection implements the provided method. Will
|
||||
* also check mappedMethods.
|
||||
*
|
||||
* @param string $method The method to find.
|
||||
* @param bool $callback Return the callback for the method.
|
||||
* @return mixed If $callback is false, a boolean will be returned, if its true, an array
|
||||
* containing callback information will be returned. For mapped methods the array will have 3 elements.
|
||||
*/
|
||||
public function hasMethod($method, $callback = false) {
|
||||
if (isset($this->_methods[$method])) {
|
||||
return $callback ? $this->_methods[$method] : true;
|
||||
}
|
||||
foreach ($this->_mappedMethods as $pattern => $target) {
|
||||
if (preg_match($pattern . 'i', $method)) {
|
||||
if ($callback) {
|
||||
$target[] = $method;
|
||||
return $target;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the implemented events that will get routed to the trigger function
|
||||
* in order to dispatch them separately on each behavior
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function implementedEvents() {
|
||||
return array(
|
||||
'Model.beforeFind' => 'trigger',
|
||||
'Model.afterFind' => 'trigger',
|
||||
'Model.beforeValidate' => 'trigger',
|
||||
'Model.afterValidate' => 'trigger',
|
||||
'Model.beforeSave' => 'trigger',
|
||||
'Model.afterSave' => 'trigger',
|
||||
'Model.beforeDelete' => 'trigger',
|
||||
'Model.afterDelete' => 'trigger'
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
719
lib/Cake/Model/CakeSchema.php
Normal file
719
lib/Cake/Model/CakeSchema.php
Normal file
|
|
@ -0,0 +1,719 @@
|
|||
<?php
|
||||
/**
|
||||
* Schema database management for CakePHP.
|
||||
*
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @package Cake.Model
|
||||
* @since CakePHP(tm) v 1.2.0.5550
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
App::uses('Model', 'Model');
|
||||
App::uses('AppModel', 'Model');
|
||||
App::uses('ConnectionManager', 'Model');
|
||||
App::uses('File', 'Utility');
|
||||
|
||||
/**
|
||||
* Base Class for Schema management
|
||||
*
|
||||
* @package Cake.Model
|
||||
*/
|
||||
class CakeSchema extends Object {
|
||||
|
||||
/**
|
||||
* Name of the schema
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $name = null;
|
||||
|
||||
/**
|
||||
* Path to write location
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $path = null;
|
||||
|
||||
/**
|
||||
* File to write
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $file = 'schema.php';
|
||||
|
||||
/**
|
||||
* Connection used for read
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $connection = 'default';
|
||||
|
||||
/**
|
||||
* plugin name.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $plugin = null;
|
||||
|
||||
/**
|
||||
* Set of tables
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $tables = array();
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param array $options optional load object properties
|
||||
*/
|
||||
public function __construct($options = array()) {
|
||||
parent::__construct();
|
||||
|
||||
if (empty($options['name'])) {
|
||||
$this->name = preg_replace('/schema$/i', '', get_class($this));
|
||||
}
|
||||
if (!empty($options['plugin'])) {
|
||||
$this->plugin = $options['plugin'];
|
||||
}
|
||||
|
||||
if (strtolower($this->name) === 'cake') {
|
||||
$this->name = Inflector::camelize(Inflector::slug(Configure::read('App.dir')));
|
||||
}
|
||||
|
||||
if (empty($options['path'])) {
|
||||
$this->path = APP . 'Config' . DS . 'Schema';
|
||||
}
|
||||
|
||||
$options = array_merge(get_object_vars($this), $options);
|
||||
$this->build($options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds schema object properties
|
||||
*
|
||||
* @param array $data loaded object properties
|
||||
* @return void
|
||||
*/
|
||||
public function build($data) {
|
||||
$file = null;
|
||||
foreach ($data as $key => $val) {
|
||||
if (!empty($val)) {
|
||||
if (!in_array($key, array('plugin', 'name', 'path', 'file', 'connection', 'tables', '_log'))) {
|
||||
if ($key[0] === '_') {
|
||||
continue;
|
||||
}
|
||||
$this->tables[$key] = $val;
|
||||
unset($this->{$key});
|
||||
} elseif ($key !== 'tables') {
|
||||
if ($key === 'name' && $val !== $this->name && !isset($data['file'])) {
|
||||
$file = Inflector::underscore($val) . '.php';
|
||||
}
|
||||
$this->{$key} = $val;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (file_exists($this->path . DS . $file) && is_file($this->path . DS . $file)) {
|
||||
$this->file = $file;
|
||||
} elseif (!empty($this->plugin)) {
|
||||
$this->path = CakePlugin::path($this->plugin) . 'Config' . DS . 'Schema';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Before callback to be implemented in subclasses
|
||||
*
|
||||
* @param array $event schema object properties
|
||||
* @return bool Should process continue
|
||||
*/
|
||||
public function before($event = array()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* After callback to be implemented in subclasses
|
||||
*
|
||||
* @param array $event schema object properties
|
||||
* @return void
|
||||
*/
|
||||
public function after($event = array()) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads database and creates schema tables
|
||||
*
|
||||
* @param array $options schema object properties
|
||||
* @return array Set of name and tables
|
||||
*/
|
||||
public function load($options = array()) {
|
||||
if (is_string($options)) {
|
||||
$options = array('path' => $options);
|
||||
}
|
||||
|
||||
$this->build($options);
|
||||
extract(get_object_vars($this));
|
||||
|
||||
$class = $name . 'Schema';
|
||||
|
||||
if (!class_exists($class)) {
|
||||
if (file_exists($path . DS . $file) && is_file($path . DS . $file)) {
|
||||
require_once $path . DS . $file;
|
||||
} elseif (file_exists($path . DS . 'schema.php') && is_file($path . DS . 'schema.php')) {
|
||||
require_once $path . DS . 'schema.php';
|
||||
}
|
||||
}
|
||||
|
||||
if (class_exists($class)) {
|
||||
$Schema = new $class($options);
|
||||
return $Schema;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads database and creates schema tables
|
||||
*
|
||||
* Options
|
||||
*
|
||||
* - 'connection' - the db connection to use
|
||||
* - 'name' - name of the schema
|
||||
* - 'models' - a list of models to use, or false to ignore models
|
||||
*
|
||||
* @param array $options schema object properties
|
||||
* @return array Array indexed by name and tables
|
||||
*/
|
||||
public function read($options = array()) {
|
||||
extract(array_merge(
|
||||
array(
|
||||
'connection' => $this->connection,
|
||||
'name' => $this->name,
|
||||
'models' => true,
|
||||
),
|
||||
$options
|
||||
));
|
||||
$db = ConnectionManager::getDataSource($connection);
|
||||
|
||||
if (isset($this->plugin)) {
|
||||
App::uses($this->plugin . 'AppModel', $this->plugin . '.Model');
|
||||
}
|
||||
|
||||
$tables = array();
|
||||
$currentTables = (array)$db->listSources();
|
||||
|
||||
$prefix = null;
|
||||
if (isset($db->config['prefix'])) {
|
||||
$prefix = $db->config['prefix'];
|
||||
}
|
||||
|
||||
if (!is_array($models) && $models !== false) {
|
||||
if (isset($this->plugin)) {
|
||||
$models = App::objects($this->plugin . '.Model', null, false);
|
||||
} else {
|
||||
$models = App::objects('Model');
|
||||
}
|
||||
}
|
||||
|
||||
if (is_array($models)) {
|
||||
foreach ($models as $model) {
|
||||
$importModel = $model;
|
||||
$plugin = null;
|
||||
if ($model === 'AppModel') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isset($this->plugin)) {
|
||||
if ($model === $this->plugin . 'AppModel') {
|
||||
continue;
|
||||
}
|
||||
$importModel = $model;
|
||||
$plugin = $this->plugin . '.';
|
||||
}
|
||||
|
||||
App::uses($importModel, $plugin . 'Model');
|
||||
if (!class_exists($importModel)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$vars = get_class_vars($model);
|
||||
if (empty($vars['useDbConfig']) || $vars['useDbConfig'] != $connection) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
$Object = ClassRegistry::init(array('class' => $model, 'ds' => $connection));
|
||||
} catch (CakeException $e) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!is_object($Object) || $Object->useTable === false) {
|
||||
continue;
|
||||
}
|
||||
$db = $Object->getDataSource();
|
||||
|
||||
$fulltable = $table = $db->fullTableName($Object, false, false);
|
||||
if ($prefix && strpos($table, $prefix) !== 0) {
|
||||
continue;
|
||||
}
|
||||
if (!in_array($fulltable, $currentTables)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$table = $this->_noPrefixTable($prefix, $table);
|
||||
|
||||
$key = array_search($fulltable, $currentTables);
|
||||
if (empty($tables[$table])) {
|
||||
$tables[$table] = $this->_columns($Object);
|
||||
$tables[$table]['indexes'] = $db->index($Object);
|
||||
$tables[$table]['tableParameters'] = $db->readTableParameters($fulltable);
|
||||
unset($currentTables[$key]);
|
||||
}
|
||||
if (empty($Object->hasAndBelongsToMany)) {
|
||||
continue;
|
||||
}
|
||||
foreach ($Object->hasAndBelongsToMany as $assocData) {
|
||||
if (isset($assocData['with'])) {
|
||||
$class = $assocData['with'];
|
||||
}
|
||||
if (!is_object($Object->$class)) {
|
||||
continue;
|
||||
}
|
||||
$withTable = $db->fullTableName($Object->$class, false, false);
|
||||
if ($prefix && strpos($withTable, $prefix) !== 0) {
|
||||
continue;
|
||||
}
|
||||
if (in_array($withTable, $currentTables)) {
|
||||
$key = array_search($withTable, $currentTables);
|
||||
$noPrefixWith = $this->_noPrefixTable($prefix, $withTable);
|
||||
|
||||
$tables[$noPrefixWith] = $this->_columns($Object->$class);
|
||||
$tables[$noPrefixWith]['indexes'] = $db->index($Object->$class);
|
||||
$tables[$noPrefixWith]['tableParameters'] = $db->readTableParameters($withTable);
|
||||
unset($currentTables[$key]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($currentTables)) {
|
||||
foreach ($currentTables as $table) {
|
||||
if ($prefix) {
|
||||
if (strpos($table, $prefix) !== 0) {
|
||||
continue;
|
||||
}
|
||||
$table = $this->_noPrefixTable($prefix, $table);
|
||||
}
|
||||
$Object = new AppModel(array(
|
||||
'name' => Inflector::classify($table), 'table' => $table, 'ds' => $connection
|
||||
));
|
||||
|
||||
$systemTables = array(
|
||||
'aros', 'acos', 'aros_acos', Configure::read('Session.table'), 'i18n'
|
||||
);
|
||||
|
||||
$fulltable = $db->fullTableName($Object, false, false);
|
||||
|
||||
if (in_array($table, $systemTables)) {
|
||||
$tables[$Object->table] = $this->_columns($Object);
|
||||
$tables[$Object->table]['indexes'] = $db->index($Object);
|
||||
$tables[$Object->table]['tableParameters'] = $db->readTableParameters($fulltable);
|
||||
} elseif ($models === false) {
|
||||
$tables[$table] = $this->_columns($Object);
|
||||
$tables[$table]['indexes'] = $db->index($Object);
|
||||
$tables[$table]['tableParameters'] = $db->readTableParameters($fulltable);
|
||||
} else {
|
||||
$tables['missing'][$table] = $this->_columns($Object);
|
||||
$tables['missing'][$table]['indexes'] = $db->index($Object);
|
||||
$tables['missing'][$table]['tableParameters'] = $db->readTableParameters($fulltable);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ksort($tables);
|
||||
return compact('name', 'tables');
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes schema file from object or options
|
||||
*
|
||||
* @param array|object $object schema object or options array
|
||||
* @param array $options schema object properties to override object
|
||||
* @return mixed false or string written to file
|
||||
*/
|
||||
public function write($object, $options = array()) {
|
||||
if (is_object($object)) {
|
||||
$object = get_object_vars($object);
|
||||
$this->build($object);
|
||||
}
|
||||
|
||||
if (is_array($object)) {
|
||||
$options = $object;
|
||||
unset($object);
|
||||
}
|
||||
|
||||
extract(array_merge(
|
||||
get_object_vars($this), $options
|
||||
));
|
||||
|
||||
$out = "class {$name}Schema extends CakeSchema {\n\n";
|
||||
|
||||
if ($path !== $this->path) {
|
||||
$out .= "\tpublic \$path = '{$path}';\n\n";
|
||||
}
|
||||
|
||||
if ($file !== $this->file) {
|
||||
$out .= "\tpublic \$file = '{$file}';\n\n";
|
||||
}
|
||||
|
||||
if ($connection !== 'default') {
|
||||
$out .= "\tpublic \$connection = '{$connection}';\n\n";
|
||||
}
|
||||
|
||||
$out .= "\tpublic function before(\$event = array()) {\n\t\treturn true;\n\t}\n\n\tpublic function after(\$event = array()) {\n\t}\n\n";
|
||||
|
||||
if (empty($tables)) {
|
||||
$this->read();
|
||||
}
|
||||
|
||||
foreach ($tables as $table => $fields) {
|
||||
if (!is_numeric($table) && $table !== 'missing') {
|
||||
$out .= $this->generateTable($table, $fields);
|
||||
}
|
||||
}
|
||||
$out .= "}\n";
|
||||
|
||||
$file = new File($path . DS . $file, true);
|
||||
$content = "<?php \n{$out}";
|
||||
if ($file->write($content)) {
|
||||
return $content;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate the code for a table. Takes a table name and $fields array
|
||||
* Returns a completed variable declaration to be used in schema classes
|
||||
*
|
||||
* @param string $table Table name you want returned.
|
||||
* @param array $fields Array of field information to generate the table with.
|
||||
* @return string Variable declaration for a schema class
|
||||
*/
|
||||
public function generateTable($table, $fields) {
|
||||
$out = "\tpublic \${$table} = array(\n";
|
||||
if (is_array($fields)) {
|
||||
$cols = array();
|
||||
foreach ($fields as $field => $value) {
|
||||
if ($field !== 'indexes' && $field !== 'tableParameters') {
|
||||
if (is_string($value)) {
|
||||
$type = $value;
|
||||
$value = array('type' => $type);
|
||||
}
|
||||
$col = "\t\t'{$field}' => array('type' => '" . $value['type'] . "', ";
|
||||
unset($value['type']);
|
||||
$col .= implode(', ', $this->_values($value));
|
||||
} elseif ($field === 'indexes') {
|
||||
$col = "\t\t'indexes' => array(\n\t\t\t";
|
||||
$props = array();
|
||||
foreach ((array)$value as $key => $index) {
|
||||
$props[] = "'{$key}' => array(" . implode(', ', $this->_values($index)) . ")";
|
||||
}
|
||||
$col .= implode(",\n\t\t\t", $props) . "\n\t\t";
|
||||
} elseif ($field === 'tableParameters') {
|
||||
$col = "\t\t'tableParameters' => array(";
|
||||
$props = array();
|
||||
foreach ((array)$value as $key => $param) {
|
||||
$props[] = "'{$key}' => '$param'";
|
||||
}
|
||||
$col .= implode(', ', $props);
|
||||
}
|
||||
$col .= ")";
|
||||
$cols[] = $col;
|
||||
}
|
||||
$out .= implode(",\n", $cols);
|
||||
}
|
||||
$out .= "\n\t);\n\n";
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compares two sets of schemas
|
||||
*
|
||||
* @param array|object $old Schema object or array
|
||||
* @param array|object $new Schema object or array
|
||||
* @return array Tables (that are added, dropped, or changed)
|
||||
*/
|
||||
public function compare($old, $new = null) {
|
||||
if (empty($new)) {
|
||||
$new = $this;
|
||||
}
|
||||
if (is_array($new)) {
|
||||
if (isset($new['tables'])) {
|
||||
$new = $new['tables'];
|
||||
}
|
||||
} else {
|
||||
$new = $new->tables;
|
||||
}
|
||||
|
||||
if (is_array($old)) {
|
||||
if (isset($old['tables'])) {
|
||||
$old = $old['tables'];
|
||||
}
|
||||
} else {
|
||||
$old = $old->tables;
|
||||
}
|
||||
$tables = array();
|
||||
foreach ($new as $table => $fields) {
|
||||
if ($table === 'missing') {
|
||||
continue;
|
||||
}
|
||||
if (!array_key_exists($table, $old)) {
|
||||
$tables[$table]['create'] = $fields;
|
||||
} else {
|
||||
$diff = $this->_arrayDiffAssoc($fields, $old[$table]);
|
||||
if (!empty($diff)) {
|
||||
$tables[$table]['add'] = $diff;
|
||||
}
|
||||
$diff = $this->_arrayDiffAssoc($old[$table], $fields);
|
||||
if (!empty($diff)) {
|
||||
$tables[$table]['drop'] = $diff;
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($fields as $field => $value) {
|
||||
if (!empty($old[$table][$field])) {
|
||||
$diff = $this->_arrayDiffAssoc($value, $old[$table][$field]);
|
||||
if (!empty($diff) && $field !== 'indexes' && $field !== 'tableParameters') {
|
||||
$tables[$table]['change'][$field] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($tables[$table]['add'][$field]) && $field !== 'indexes' && $field !== 'tableParameters') {
|
||||
$wrapper = array_keys($fields);
|
||||
if ($column = array_search($field, $wrapper)) {
|
||||
if (isset($wrapper[$column - 1])) {
|
||||
$tables[$table]['add'][$field]['after'] = $wrapper[$column - 1];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($old[$table]['indexes']) && isset($new[$table]['indexes'])) {
|
||||
$diff = $this->_compareIndexes($new[$table]['indexes'], $old[$table]['indexes']);
|
||||
if ($diff) {
|
||||
if (!isset($tables[$table])) {
|
||||
$tables[$table] = array();
|
||||
}
|
||||
if (isset($diff['drop'])) {
|
||||
$tables[$table]['drop']['indexes'] = $diff['drop'];
|
||||
}
|
||||
if ($diff && isset($diff['add'])) {
|
||||
$tables[$table]['add']['indexes'] = $diff['add'];
|
||||
}
|
||||
}
|
||||
}
|
||||
if (isset($old[$table]['tableParameters']) && isset($new[$table]['tableParameters'])) {
|
||||
$diff = $this->_compareTableParameters($new[$table]['tableParameters'], $old[$table]['tableParameters']);
|
||||
if ($diff) {
|
||||
$tables[$table]['change']['tableParameters'] = $diff;
|
||||
}
|
||||
}
|
||||
}
|
||||
return $tables;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extended array_diff_assoc noticing change from/to NULL values
|
||||
*
|
||||
* It behaves almost the same way as array_diff_assoc except for NULL values: if
|
||||
* one of the values is not NULL - change is detected. It is useful in situation
|
||||
* where one value is strval('') ant other is strval(null) - in string comparing
|
||||
* methods this results as EQUAL, while it is not.
|
||||
*
|
||||
* @param array $array1 Base array
|
||||
* @param array $array2 Corresponding array checked for equality
|
||||
* @return array Difference as array with array(keys => values) from input array
|
||||
* where match was not found.
|
||||
*/
|
||||
protected function _arrayDiffAssoc($array1, $array2) {
|
||||
$difference = array();
|
||||
foreach ($array1 as $key => $value) {
|
||||
if (!array_key_exists($key, $array2)) {
|
||||
$difference[$key] = $value;
|
||||
continue;
|
||||
}
|
||||
$correspondingValue = $array2[$key];
|
||||
if (($value === null) !== ($correspondingValue === null)) {
|
||||
$difference[$key] = $value;
|
||||
continue;
|
||||
}
|
||||
if (is_bool($value) !== is_bool($correspondingValue)) {
|
||||
$difference[$key] = $value;
|
||||
continue;
|
||||
}
|
||||
if (is_array($value) && is_array($correspondingValue)) {
|
||||
continue;
|
||||
}
|
||||
if ($value === $correspondingValue) {
|
||||
continue;
|
||||
}
|
||||
$difference[$key] = $value;
|
||||
}
|
||||
return $difference;
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats Schema columns from Model Object
|
||||
*
|
||||
* @param array $values options keys(type, null, default, key, length, extra)
|
||||
* @return array Formatted values
|
||||
*/
|
||||
protected function _values($values) {
|
||||
$vals = array();
|
||||
if (is_array($values)) {
|
||||
foreach ($values as $key => $val) {
|
||||
if (is_array($val)) {
|
||||
$vals[] = "'{$key}' => array(" . implode(", ", $this->_values($val)) . ")";
|
||||
} else {
|
||||
$val = var_export($val, true);
|
||||
if ($val === 'NULL') {
|
||||
$val = 'null';
|
||||
}
|
||||
if (!is_numeric($key)) {
|
||||
$vals[] = "'{$key}' => {$val}";
|
||||
} else {
|
||||
$vals[] = "{$val}";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return $vals;
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats Schema columns from Model Object
|
||||
*
|
||||
* @param array &$Obj model object
|
||||
* @return array Formatted columns
|
||||
*/
|
||||
protected function _columns(&$Obj) {
|
||||
$db = $Obj->getDataSource();
|
||||
$fields = $Obj->schema(true);
|
||||
|
||||
$columns = array();
|
||||
foreach ($fields as $name => $value) {
|
||||
if ($Obj->primaryKey === $name) {
|
||||
$value['key'] = 'primary';
|
||||
}
|
||||
if (!isset($db->columns[$value['type']])) {
|
||||
trigger_error(__d('cake_dev', 'Schema generation error: invalid column type %s for %s.%s does not exist in DBO', $value['type'], $Obj->name, $name), E_USER_NOTICE);
|
||||
continue;
|
||||
} else {
|
||||
$defaultCol = $db->columns[$value['type']];
|
||||
if (isset($defaultCol['limit']) && $defaultCol['limit'] == $value['length']) {
|
||||
unset($value['length']);
|
||||
} elseif (isset($defaultCol['length']) && $defaultCol['length'] == $value['length']) {
|
||||
unset($value['length']);
|
||||
}
|
||||
unset($value['limit']);
|
||||
}
|
||||
|
||||
if (isset($value['default']) && ($value['default'] === '' || ($value['default'] === false && $value['type'] !== 'boolean'))) {
|
||||
unset($value['default']);
|
||||
}
|
||||
if (empty($value['length'])) {
|
||||
unset($value['length']);
|
||||
}
|
||||
if (empty($value['key'])) {
|
||||
unset($value['key']);
|
||||
}
|
||||
$columns[$name] = $value;
|
||||
}
|
||||
|
||||
return $columns;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare two schema files table Parameters
|
||||
*
|
||||
* @param array $new New indexes
|
||||
* @param array $old Old indexes
|
||||
* @return mixed False on failure, or an array of parameters to add & drop.
|
||||
*/
|
||||
protected function _compareTableParameters($new, $old) {
|
||||
if (!is_array($new) || !is_array($old)) {
|
||||
return false;
|
||||
}
|
||||
$change = $this->_arrayDiffAssoc($new, $old);
|
||||
return $change;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare two schema indexes
|
||||
*
|
||||
* @param array $new New indexes
|
||||
* @param array $old Old indexes
|
||||
* @return mixed false on failure or array of indexes to add and drop
|
||||
*/
|
||||
protected function _compareIndexes($new, $old) {
|
||||
if (!is_array($new) || !is_array($old)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$add = $drop = array();
|
||||
|
||||
$diff = $this->_arrayDiffAssoc($new, $old);
|
||||
if (!empty($diff)) {
|
||||
$add = $diff;
|
||||
}
|
||||
|
||||
$diff = $this->_arrayDiffAssoc($old, $new);
|
||||
if (!empty($diff)) {
|
||||
$drop = $diff;
|
||||
}
|
||||
|
||||
foreach ($new as $name => $value) {
|
||||
if (isset($old[$name])) {
|
||||
$newUnique = isset($value['unique']) ? $value['unique'] : 0;
|
||||
$oldUnique = isset($old[$name]['unique']) ? $old[$name]['unique'] : 0;
|
||||
$newColumn = $value['column'];
|
||||
$oldColumn = $old[$name]['column'];
|
||||
|
||||
$diff = false;
|
||||
|
||||
if ($newUnique != $oldUnique) {
|
||||
$diff = true;
|
||||
} elseif (is_array($newColumn) && is_array($oldColumn)) {
|
||||
$diff = ($newColumn !== $oldColumn);
|
||||
} elseif (is_string($newColumn) && is_string($oldColumn)) {
|
||||
$diff = ($newColumn != $oldColumn);
|
||||
} else {
|
||||
$diff = true;
|
||||
}
|
||||
if ($diff) {
|
||||
$drop[$name] = null;
|
||||
$add[$name] = $value;
|
||||
}
|
||||
}
|
||||
}
|
||||
return array_filter(compact('add', 'drop'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Trim the table prefix from the full table name, and return the prefix-less table
|
||||
*
|
||||
* @param string $prefix Table prefix
|
||||
* @param string $table Full table name
|
||||
* @return string Prefix-less table name
|
||||
*/
|
||||
protected function _noPrefixTable($prefix, $table) {
|
||||
return preg_replace('/^' . preg_quote($prefix) . '/', '', $table);
|
||||
}
|
||||
|
||||
}
|
||||
270
lib/Cake/Model/ConnectionManager.php
Normal file
270
lib/Cake/Model/ConnectionManager.php
Normal file
|
|
@ -0,0 +1,270 @@
|
|||
<?php
|
||||
/**
|
||||
* Datasource connection manager
|
||||
*
|
||||
* Provides an interface for loading and enumerating connections defined in app/Config/database.php
|
||||
*
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @package Cake.Model
|
||||
* @since CakePHP(tm) v 0.10.x.1402
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
App::uses('DataSource', 'Model/Datasource');
|
||||
|
||||
/**
|
||||
* Manages loaded instances of DataSource objects
|
||||
*
|
||||
* Provides an interface for loading and enumerating connections defined in
|
||||
* app/Config/database.php
|
||||
*
|
||||
* @package Cake.Model
|
||||
*/
|
||||
class ConnectionManager {
|
||||
|
||||
/**
|
||||
* Holds a loaded instance of the Connections object
|
||||
*
|
||||
* @var DATABASE_CONFIG
|
||||
*/
|
||||
public static $config = null;
|
||||
|
||||
/**
|
||||
* Holds instances DataSource objects
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected static $_dataSources = array();
|
||||
|
||||
/**
|
||||
* Contains a list of all file and class names used in Connection settings
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected static $_connectionsEnum = array();
|
||||
|
||||
/**
|
||||
* Indicates if the init code for this class has already been executed
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected static $_init = false;
|
||||
|
||||
/**
|
||||
* Loads connections configuration.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected static function _init() {
|
||||
include_once APP . 'Config' . DS . 'database.php';
|
||||
if (class_exists('DATABASE_CONFIG')) {
|
||||
self::$config = new DATABASE_CONFIG();
|
||||
}
|
||||
self::$_init = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a reference to a DataSource object
|
||||
*
|
||||
* @param string $name The name of the DataSource, as defined in app/Config/database.php
|
||||
* @return DataSource Instance
|
||||
* @throws MissingDatasourceException
|
||||
*/
|
||||
public static function getDataSource($name) {
|
||||
if (empty(self::$_init)) {
|
||||
self::_init();
|
||||
}
|
||||
|
||||
if (!empty(self::$_dataSources[$name])) {
|
||||
return self::$_dataSources[$name];
|
||||
}
|
||||
|
||||
if (empty(self::$_connectionsEnum[$name])) {
|
||||
self::_getConnectionObject($name);
|
||||
}
|
||||
|
||||
self::loadDataSource($name);
|
||||
$conn = self::$_connectionsEnum[$name];
|
||||
$class = $conn['classname'];
|
||||
|
||||
if (strpos(App::location($class), 'Datasource') === false) {
|
||||
throw new MissingDatasourceException(array(
|
||||
'class' => $class,
|
||||
'plugin' => null,
|
||||
'message' => 'Datasource is not found in Model/Datasource package.'
|
||||
));
|
||||
}
|
||||
self::$_dataSources[$name] = new $class(self::$config->{$name});
|
||||
self::$_dataSources[$name]->configKeyName = $name;
|
||||
|
||||
return self::$_dataSources[$name];
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the list of available DataSource connections
|
||||
* This will only return the datasources instantiated by this manager
|
||||
* It differs from enumConnectionObjects, since the latter will return all configured connections
|
||||
*
|
||||
* @return array List of available connections
|
||||
*/
|
||||
public static function sourceList() {
|
||||
if (empty(self::$_init)) {
|
||||
self::_init();
|
||||
}
|
||||
return array_keys(self::$_dataSources);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a DataSource name from an object reference.
|
||||
*
|
||||
* @param DataSource $source DataSource object
|
||||
* @return string Datasource name, or null if source is not present
|
||||
* in the ConnectionManager.
|
||||
*/
|
||||
public static function getSourceName($source) {
|
||||
if (empty(self::$_init)) {
|
||||
self::_init();
|
||||
}
|
||||
foreach (self::$_dataSources as $name => $ds) {
|
||||
if ($ds === $source) {
|
||||
return $name;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the DataSource class for the given connection name
|
||||
*
|
||||
* @param string|array $connName A string name of the connection, as defined in app/Config/database.php,
|
||||
* or an array containing the filename (without extension) and class name of the object,
|
||||
* to be found in app/Model/Datasource/ or lib/Cake/Model/Datasource/.
|
||||
* @return bool True on success, null on failure or false if the class is already loaded
|
||||
* @throws MissingDatasourceException
|
||||
*/
|
||||
public static function loadDataSource($connName) {
|
||||
if (empty(self::$_init)) {
|
||||
self::_init();
|
||||
}
|
||||
|
||||
if (is_array($connName)) {
|
||||
$conn = $connName;
|
||||
} else {
|
||||
$conn = self::$_connectionsEnum[$connName];
|
||||
}
|
||||
|
||||
if (class_exists($conn['classname'], false)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$plugin = $package = null;
|
||||
if (!empty($conn['plugin'])) {
|
||||
$plugin = $conn['plugin'] . '.';
|
||||
}
|
||||
if (!empty($conn['package'])) {
|
||||
$package = '/' . $conn['package'];
|
||||
}
|
||||
|
||||
App::uses($conn['classname'], $plugin . 'Model/Datasource' . $package);
|
||||
if (!class_exists($conn['classname'])) {
|
||||
throw new MissingDatasourceException(array(
|
||||
'class' => $conn['classname'],
|
||||
'plugin' => substr($plugin, 0, -1)
|
||||
));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a list of connections
|
||||
*
|
||||
* @return array An associative array of elements where the key is the connection name
|
||||
* (as defined in Connections), and the value is an array with keys 'filename' and 'classname'.
|
||||
*/
|
||||
public static function enumConnectionObjects() {
|
||||
if (empty(self::$_init)) {
|
||||
self::_init();
|
||||
}
|
||||
return (array)self::$config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Dynamically creates a DataSource object at runtime, with the given name and settings
|
||||
*
|
||||
* @param string $name The DataSource name
|
||||
* @param array $config The DataSource configuration settings
|
||||
* @return DataSource A reference to the DataSource object, or null if creation failed
|
||||
*/
|
||||
public static function create($name = '', $config = array()) {
|
||||
if (empty(self::$_init)) {
|
||||
self::_init();
|
||||
}
|
||||
|
||||
if (empty($name) || empty($config) || array_key_exists($name, self::$_connectionsEnum)) {
|
||||
return null;
|
||||
}
|
||||
self::$config->{$name} = $config;
|
||||
self::$_connectionsEnum[$name] = self::_connectionData($config);
|
||||
$return = self::getDataSource($name);
|
||||
return $return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a connection configuration at runtime given its name
|
||||
*
|
||||
* @param string $name the connection name as it was created
|
||||
* @return bool success if connection was removed, false if it does not exist
|
||||
*/
|
||||
public static function drop($name) {
|
||||
if (empty(self::$_init)) {
|
||||
self::_init();
|
||||
}
|
||||
|
||||
if (!isset(self::$config->{$name})) {
|
||||
return false;
|
||||
}
|
||||
unset(self::$_connectionsEnum[$name], self::$_dataSources[$name], self::$config->{$name});
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a list of class and file names associated with the user-defined DataSource connections
|
||||
*
|
||||
* @param string $name Connection name
|
||||
* @return void
|
||||
* @throws MissingDatasourceConfigException
|
||||
*/
|
||||
protected static function _getConnectionObject($name) {
|
||||
if (!empty(self::$config->{$name})) {
|
||||
self::$_connectionsEnum[$name] = self::_connectionData(self::$config->{$name});
|
||||
} else {
|
||||
throw new MissingDatasourceConfigException(array('config' => $name));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the file, class name, and parent for the given driver.
|
||||
*
|
||||
* @param array $config Array with connection configuration. Key 'datasource' is required
|
||||
* @return array An indexed array with: filename, classname, plugin and parent
|
||||
*/
|
||||
protected static function _connectionData($config) {
|
||||
$package = $classname = $plugin = null;
|
||||
|
||||
list($plugin, $classname) = pluginSplit($config['datasource']);
|
||||
if (strpos($classname, '/') !== false) {
|
||||
$package = dirname($classname);
|
||||
$classname = basename($classname);
|
||||
}
|
||||
return compact('package', 'classname', 'plugin');
|
||||
}
|
||||
|
||||
}
|
||||
741
lib/Cake/Model/Datasource/CakeSession.php
Normal file
741
lib/Cake/Model/Datasource/CakeSession.php
Normal file
|
|
@ -0,0 +1,741 @@
|
|||
<?php
|
||||
/**
|
||||
* Session class for CakePHP.
|
||||
*
|
||||
* CakePHP abstracts the handling of sessions.
|
||||
* There are several convenient methods to access session information.
|
||||
* This class is the implementation of those methods.
|
||||
* They are mostly used by the Session Component.
|
||||
*
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @package Cake.Model.Datasource
|
||||
* @since CakePHP(tm) v .0.10.0.1222
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
App::uses('Hash', 'Utility');
|
||||
App::uses('Security', 'Utility');
|
||||
|
||||
/**
|
||||
* Session class for CakePHP.
|
||||
*
|
||||
* CakePHP abstracts the handling of sessions. There are several convenient methods to access session information.
|
||||
* This class is the implementation of those methods. They are mostly used by the Session Component.
|
||||
*
|
||||
* @package Cake.Model.Datasource
|
||||
*/
|
||||
class CakeSession {
|
||||
|
||||
/**
|
||||
* True if the Session is still valid
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
public static $valid = false;
|
||||
|
||||
/**
|
||||
* Error messages for this session
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $error = false;
|
||||
|
||||
/**
|
||||
* User agent string
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected static $_userAgent = '';
|
||||
|
||||
/**
|
||||
* Path to where the session is active.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public static $path = '/';
|
||||
|
||||
/**
|
||||
* Error number of last occurred error
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
public static $lastError = null;
|
||||
|
||||
/**
|
||||
* Start time for this session.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
public static $time = false;
|
||||
|
||||
/**
|
||||
* Cookie lifetime
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
public static $cookieLifeTime;
|
||||
|
||||
/**
|
||||
* Time when this session becomes invalid.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
public static $sessionTime = false;
|
||||
|
||||
/**
|
||||
* Current Session id
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public static $id = null;
|
||||
|
||||
/**
|
||||
* Hostname
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public static $host = null;
|
||||
|
||||
/**
|
||||
* Session timeout multiplier factor
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
public static $timeout = null;
|
||||
|
||||
/**
|
||||
* Number of requests that can occur during a session time without the session being renewed.
|
||||
* This feature is only used when config value `Session.autoRegenerate` is set to true.
|
||||
*
|
||||
* @var int
|
||||
* @see CakeSession::_checkValid()
|
||||
*/
|
||||
public static $requestCountdown = 10;
|
||||
|
||||
/**
|
||||
* Whether or not the init function in this class was already called
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected static $_initialized = false;
|
||||
|
||||
/**
|
||||
* Session cookie name
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected static $_cookieName = null;
|
||||
|
||||
/**
|
||||
* Pseudo constructor.
|
||||
*
|
||||
* @param string $base The base path for the Session
|
||||
* @return void
|
||||
*/
|
||||
public static function init($base = null) {
|
||||
self::$time = time();
|
||||
|
||||
if (env('HTTP_USER_AGENT')) {
|
||||
self::$_userAgent = md5(env('HTTP_USER_AGENT') . Configure::read('Security.salt'));
|
||||
}
|
||||
|
||||
self::_setPath($base);
|
||||
self::_setHost(env('HTTP_HOST'));
|
||||
|
||||
if (!self::$_initialized) {
|
||||
register_shutdown_function('session_write_close');
|
||||
}
|
||||
|
||||
self::$_initialized = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup the Path variable
|
||||
*
|
||||
* @param string $base base path
|
||||
* @return void
|
||||
*/
|
||||
protected static function _setPath($base = null) {
|
||||
if (empty($base)) {
|
||||
self::$path = '/';
|
||||
return;
|
||||
}
|
||||
if (strpos($base, 'index.php') !== false) {
|
||||
$base = str_replace('index.php', '', $base);
|
||||
}
|
||||
if (strpos($base, '?') !== false) {
|
||||
$base = str_replace('?', '', $base);
|
||||
}
|
||||
self::$path = $base;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the host name
|
||||
*
|
||||
* @param string $host Hostname
|
||||
* @return void
|
||||
*/
|
||||
protected static function _setHost($host) {
|
||||
self::$host = $host;
|
||||
if (strpos(self::$host, ':') !== false) {
|
||||
self::$host = substr(self::$host, 0, strpos(self::$host, ':'));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the Session.
|
||||
*
|
||||
* @return bool True if session was started
|
||||
*/
|
||||
public static function start() {
|
||||
if (self::started()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$id = self::id();
|
||||
self::_startSession();
|
||||
|
||||
if (!$id && self::started()) {
|
||||
self::_checkValid();
|
||||
}
|
||||
|
||||
self::$error = false;
|
||||
self::$valid = true;
|
||||
return self::started();
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if Session has been started.
|
||||
*
|
||||
* @return bool True if session has been started.
|
||||
*/
|
||||
public static function started() {
|
||||
return isset($_SESSION) && session_id();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if given variable is set in session.
|
||||
*
|
||||
* @param string $name Variable name to check for
|
||||
* @return bool True if variable is there
|
||||
*/
|
||||
public static function check($name = null) {
|
||||
if (empty($name) || !self::_hasSession() || !self::start()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return Hash::get($_SESSION, $name) !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the session id.
|
||||
* Calling this method will not auto start the session. You might have to manually
|
||||
* assert a started session.
|
||||
*
|
||||
* Passing an id into it, you can also replace the session id if the session
|
||||
* has not already been started.
|
||||
* Note that depending on the session handler, not all characters are allowed
|
||||
* within the session id. For example, the file session handler only allows
|
||||
* characters in the range a-z A-Z 0-9 , (comma) and - (minus).
|
||||
*
|
||||
* @param string $id Id to replace the current session id
|
||||
* @return string Session id
|
||||
*/
|
||||
public static function id($id = null) {
|
||||
if ($id) {
|
||||
self::$id = $id;
|
||||
session_id(self::$id);
|
||||
}
|
||||
if (self::started()) {
|
||||
return session_id();
|
||||
}
|
||||
return self::$id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a variable from session.
|
||||
*
|
||||
* @param string $name Session variable to remove
|
||||
* @return bool Success
|
||||
*/
|
||||
public static function delete($name) {
|
||||
if (self::check($name)) {
|
||||
self::_overwrite($_SESSION, Hash::remove($_SESSION, $name));
|
||||
return !self::check($name);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Used to write new data to _SESSION, since PHP doesn't like us setting the _SESSION var itself.
|
||||
*
|
||||
* @param array &$old Set of old variables => values
|
||||
* @param array $new New set of variable => value
|
||||
* @return void
|
||||
*/
|
||||
protected static function _overwrite(&$old, $new) {
|
||||
if (!empty($old)) {
|
||||
foreach ($old as $key => $var) {
|
||||
if (!isset($new[$key])) {
|
||||
unset($old[$key]);
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach ($new as $key => $var) {
|
||||
$old[$key] = $var;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return error description for given error number.
|
||||
*
|
||||
* @param int $errorNumber Error to set
|
||||
* @return string Error as string
|
||||
*/
|
||||
protected static function _error($errorNumber) {
|
||||
if (!is_array(self::$error) || !array_key_exists($errorNumber, self::$error)) {
|
||||
return false;
|
||||
}
|
||||
return self::$error[$errorNumber];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns last occurred error as a string, if any.
|
||||
*
|
||||
* @return mixed Error description as a string, or false.
|
||||
*/
|
||||
public static function error() {
|
||||
if (self::$lastError) {
|
||||
return self::_error(self::$lastError);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if session is valid.
|
||||
*
|
||||
* @return bool Success
|
||||
*/
|
||||
public static function valid() {
|
||||
if (self::start() && self::read('Config')) {
|
||||
if (self::_validAgentAndTime() && self::$error === false) {
|
||||
self::$valid = true;
|
||||
} else {
|
||||
self::$valid = false;
|
||||
self::_setError(1, 'Session Highjacking Attempted !!!');
|
||||
}
|
||||
}
|
||||
return self::$valid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that the user agent is valid and that the session hasn't 'timed out'.
|
||||
* Since timeouts are implemented in CakeSession it checks the current self::$time
|
||||
* against the time the session is set to expire. The User agent is only checked
|
||||
* if Session.checkAgent == true.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected static function _validAgentAndTime() {
|
||||
$config = self::read('Config');
|
||||
$validAgent = (
|
||||
Configure::read('Session.checkAgent') === false ||
|
||||
self::$_userAgent == $config['userAgent']
|
||||
);
|
||||
return ($validAgent && self::$time <= $config['time']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get / Set the user agent
|
||||
*
|
||||
* @param string $userAgent Set the user agent
|
||||
* @return string Current user agent
|
||||
*/
|
||||
public static function userAgent($userAgent = null) {
|
||||
if ($userAgent) {
|
||||
self::$_userAgent = $userAgent;
|
||||
}
|
||||
if (empty(self::$_userAgent)) {
|
||||
CakeSession::init(self::$path);
|
||||
}
|
||||
return self::$_userAgent;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns given session variable, or all of them, if no parameters given.
|
||||
*
|
||||
* @param string|array $name The name of the session variable (or a path as sent to Set.extract)
|
||||
* @return mixed The value of the session variable, null if session not available,
|
||||
* session not started, or provided name not found in the session.
|
||||
*/
|
||||
public static function read($name = null) {
|
||||
if (empty($name) && $name !== null) {
|
||||
return false;
|
||||
}
|
||||
if (!self::_hasSession() || !self::start()) {
|
||||
return null;
|
||||
}
|
||||
if ($name === null) {
|
||||
return self::_returnSessionVars();
|
||||
}
|
||||
$result = Hash::get($_SESSION, $name);
|
||||
|
||||
if (isset($result)) {
|
||||
return $result;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all session variables.
|
||||
*
|
||||
* @return mixed Full $_SESSION array, or false on error.
|
||||
*/
|
||||
protected static function _returnSessionVars() {
|
||||
if (!empty($_SESSION)) {
|
||||
return $_SESSION;
|
||||
}
|
||||
self::_setError(2, 'No Session vars set');
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes value to given session variable name.
|
||||
*
|
||||
* @param string|array $name Name of variable
|
||||
* @param string $value Value to write
|
||||
* @return bool True if the write was successful, false if the write failed
|
||||
*/
|
||||
public static function write($name, $value = null) {
|
||||
if (empty($name) || !self::start()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$write = $name;
|
||||
if (!is_array($name)) {
|
||||
$write = array($name => $value);
|
||||
}
|
||||
foreach ($write as $key => $val) {
|
||||
self::_overwrite($_SESSION, Hash::insert($_SESSION, $key, $val));
|
||||
if (Hash::get($_SESSION, $key) !== $val) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to destroy invalid sessions.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function destroy() {
|
||||
if (!self::started()) {
|
||||
self::_startSession();
|
||||
}
|
||||
|
||||
session_destroy();
|
||||
|
||||
$_SESSION = null;
|
||||
self::$id = null;
|
||||
self::$_cookieName = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears the session, the session id, and renews the session.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function clear() {
|
||||
$_SESSION = null;
|
||||
self::$id = null;
|
||||
self::renew();
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to initialize a session, based on CakePHP core settings.
|
||||
*
|
||||
* Sessions can be configured with a few shortcut names as well as have any number of ini settings declared.
|
||||
*
|
||||
* @return void
|
||||
* @throws CakeSessionException Throws exceptions when ini_set() fails.
|
||||
*/
|
||||
protected static function _configureSession() {
|
||||
$sessionConfig = Configure::read('Session');
|
||||
|
||||
if (isset($sessionConfig['defaults'])) {
|
||||
$defaults = self::_defaultConfig($sessionConfig['defaults']);
|
||||
if ($defaults) {
|
||||
$sessionConfig = Hash::merge($defaults, $sessionConfig);
|
||||
}
|
||||
}
|
||||
if (!isset($sessionConfig['ini']['session.cookie_secure']) && env('HTTPS')) {
|
||||
$sessionConfig['ini']['session.cookie_secure'] = 1;
|
||||
}
|
||||
if (isset($sessionConfig['timeout']) && !isset($sessionConfig['cookieTimeout'])) {
|
||||
$sessionConfig['cookieTimeout'] = $sessionConfig['timeout'];
|
||||
}
|
||||
if (!isset($sessionConfig['ini']['session.cookie_lifetime'])) {
|
||||
$sessionConfig['ini']['session.cookie_lifetime'] = $sessionConfig['cookieTimeout'] * 60;
|
||||
}
|
||||
|
||||
if (!isset($sessionConfig['ini']['session.name'])) {
|
||||
$sessionConfig['ini']['session.name'] = $sessionConfig['cookie'];
|
||||
}
|
||||
self::$_cookieName = $sessionConfig['ini']['session.name'];
|
||||
|
||||
if (!empty($sessionConfig['handler'])) {
|
||||
$sessionConfig['ini']['session.save_handler'] = 'user';
|
||||
}
|
||||
if (!isset($sessionConfig['ini']['session.gc_maxlifetime'])) {
|
||||
$sessionConfig['ini']['session.gc_maxlifetime'] = $sessionConfig['timeout'] * 60;
|
||||
}
|
||||
if (!isset($sessionConfig['ini']['session.cookie_httponly'])) {
|
||||
$sessionConfig['ini']['session.cookie_httponly'] = 1;
|
||||
}
|
||||
|
||||
if (empty($_SESSION)) {
|
||||
if (!empty($sessionConfig['ini']) && is_array($sessionConfig['ini'])) {
|
||||
foreach ($sessionConfig['ini'] as $setting => $value) {
|
||||
if (ini_set($setting, $value) === false) {
|
||||
throw new CakeSessionException(__d('cake_dev', 'Unable to configure the session, setting %s failed.', $setting));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!empty($sessionConfig['handler']) && !isset($sessionConfig['handler']['engine'])) {
|
||||
call_user_func_array('session_set_save_handler', $sessionConfig['handler']);
|
||||
}
|
||||
if (!empty($sessionConfig['handler']['engine'])) {
|
||||
$handler = self::_getHandler($sessionConfig['handler']['engine']);
|
||||
session_set_save_handler(
|
||||
array($handler, 'open'),
|
||||
array($handler, 'close'),
|
||||
array($handler, 'read'),
|
||||
array($handler, 'write'),
|
||||
array($handler, 'destroy'),
|
||||
array($handler, 'gc')
|
||||
);
|
||||
}
|
||||
Configure::write('Session', $sessionConfig);
|
||||
self::$sessionTime = self::$time + ($sessionConfig['timeout'] * 60);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get session cookie name.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected static function _cookieName() {
|
||||
if (self::$_cookieName !== null) {
|
||||
return self::$_cookieName;
|
||||
}
|
||||
|
||||
self::init();
|
||||
self::_configureSession();
|
||||
|
||||
return self::$_cookieName = session_name();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether a session exists
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected static function _hasSession() {
|
||||
return self::started() || isset($_COOKIE[self::_cookieName()]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the handler class and make sure it implements the correct interface.
|
||||
*
|
||||
* @param string $handler Handler name.
|
||||
* @return void
|
||||
* @throws CakeSessionException
|
||||
*/
|
||||
protected static function _getHandler($handler) {
|
||||
list($plugin, $class) = pluginSplit($handler, true);
|
||||
App::uses($class, $plugin . 'Model/Datasource/Session');
|
||||
if (!class_exists($class)) {
|
||||
throw new CakeSessionException(__d('cake_dev', 'Could not load %s to handle the session.', $class));
|
||||
}
|
||||
$handler = new $class();
|
||||
if ($handler instanceof CakeSessionHandlerInterface) {
|
||||
return $handler;
|
||||
}
|
||||
throw new CakeSessionException(__d('cake_dev', 'Chosen SessionHandler does not implement CakeSessionHandlerInterface it cannot be used with an engine key.'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get one of the prebaked default session configurations.
|
||||
*
|
||||
* @param string $name Config name.
|
||||
* @return bool|array
|
||||
*/
|
||||
protected static function _defaultConfig($name) {
|
||||
$defaults = array(
|
||||
'php' => array(
|
||||
'cookie' => 'CAKEPHP',
|
||||
'timeout' => 240,
|
||||
'ini' => array(
|
||||
'session.use_trans_sid' => 0,
|
||||
'session.cookie_path' => self::$path
|
||||
)
|
||||
),
|
||||
'cake' => array(
|
||||
'cookie' => 'CAKEPHP',
|
||||
'timeout' => 240,
|
||||
'ini' => array(
|
||||
'session.use_trans_sid' => 0,
|
||||
'url_rewriter.tags' => '',
|
||||
'session.serialize_handler' => 'php',
|
||||
'session.use_cookies' => 1,
|
||||
'session.cookie_path' => self::$path,
|
||||
'session.save_path' => TMP . 'sessions',
|
||||
'session.save_handler' => 'files'
|
||||
)
|
||||
),
|
||||
'cache' => array(
|
||||
'cookie' => 'CAKEPHP',
|
||||
'timeout' => 240,
|
||||
'ini' => array(
|
||||
'session.use_trans_sid' => 0,
|
||||
'url_rewriter.tags' => '',
|
||||
'session.use_cookies' => 1,
|
||||
'session.cookie_path' => self::$path,
|
||||
'session.save_handler' => 'user',
|
||||
),
|
||||
'handler' => array(
|
||||
'engine' => 'CacheSession',
|
||||
'config' => 'default'
|
||||
)
|
||||
),
|
||||
'database' => array(
|
||||
'cookie' => 'CAKEPHP',
|
||||
'timeout' => 240,
|
||||
'ini' => array(
|
||||
'session.use_trans_sid' => 0,
|
||||
'url_rewriter.tags' => '',
|
||||
'session.use_cookies' => 1,
|
||||
'session.cookie_path' => self::$path,
|
||||
'session.save_handler' => 'user',
|
||||
'session.serialize_handler' => 'php',
|
||||
),
|
||||
'handler' => array(
|
||||
'engine' => 'DatabaseSession',
|
||||
'model' => 'Session'
|
||||
)
|
||||
)
|
||||
);
|
||||
if (isset($defaults[$name])) {
|
||||
return $defaults[$name];
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to start a session
|
||||
*
|
||||
* @return bool Success
|
||||
*/
|
||||
protected static function _startSession() {
|
||||
self::init();
|
||||
session_write_close();
|
||||
self::_configureSession();
|
||||
|
||||
if (headers_sent()) {
|
||||
if (empty($_SESSION)) {
|
||||
$_SESSION = array();
|
||||
}
|
||||
} else {
|
||||
// For IE<=8
|
||||
session_cache_limiter("must-revalidate");
|
||||
session_start();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to create a new session.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected static function _checkValid() {
|
||||
$config = self::read('Config');
|
||||
if ($config) {
|
||||
$sessionConfig = Configure::read('Session');
|
||||
|
||||
if (self::valid()) {
|
||||
self::write('Config.time', self::$sessionTime);
|
||||
if (isset($sessionConfig['autoRegenerate']) && $sessionConfig['autoRegenerate'] === true) {
|
||||
$check = $config['countdown'];
|
||||
$check -= 1;
|
||||
self::write('Config.countdown', $check);
|
||||
|
||||
if ($check < 1) {
|
||||
self::renew();
|
||||
self::write('Config.countdown', self::$requestCountdown);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
$_SESSION = array();
|
||||
self::destroy();
|
||||
self::_setError(1, 'Session Highjacking Attempted !!!');
|
||||
self::_startSession();
|
||||
self::_writeConfig();
|
||||
}
|
||||
} else {
|
||||
self::_writeConfig();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes configuration variables to the session
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected static function _writeConfig() {
|
||||
self::write('Config.userAgent', self::$_userAgent);
|
||||
self::write('Config.time', self::$sessionTime);
|
||||
self::write('Config.countdown', self::$requestCountdown);
|
||||
}
|
||||
|
||||
/**
|
||||
* Restarts this session.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function renew() {
|
||||
if (!session_id()) {
|
||||
return;
|
||||
}
|
||||
if (isset($_COOKIE[session_name()])) {
|
||||
setcookie(Configure::read('Session.cookie'), '', time() - 42000, self::$path);
|
||||
}
|
||||
session_regenerate_id(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to set an internal error message.
|
||||
*
|
||||
* @param int $errorNumber Number of the error
|
||||
* @param string $errorMessage Description of the error
|
||||
* @return void
|
||||
*/
|
||||
protected static function _setError($errorNumber, $errorMessage) {
|
||||
if (self::$error === false) {
|
||||
self::$error = array();
|
||||
}
|
||||
self::$error[$errorNumber] = $errorMessage;
|
||||
self::$lastError = $errorNumber;
|
||||
}
|
||||
|
||||
}
|
||||
437
lib/Cake/Model/Datasource/DataSource.php
Normal file
437
lib/Cake/Model/Datasource/DataSource.php
Normal file
|
|
@ -0,0 +1,437 @@
|
|||
<?php
|
||||
/**
|
||||
* DataSource base class
|
||||
*
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @package Cake.Model.Datasource
|
||||
* @since CakePHP(tm) v 0.10.5.1790
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
/**
|
||||
* DataSource base class
|
||||
*
|
||||
* DataSources are the link between models and the source of data that models represent.
|
||||
*
|
||||
* @link http://book.cakephp.org/2.0/en/models/datasources.html#basic-api-for-datasources
|
||||
* @package Cake.Model.Datasource
|
||||
*/
|
||||
class DataSource extends Object {
|
||||
|
||||
/**
|
||||
* Are we connected to the DataSource?
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
public $connected = false;
|
||||
|
||||
/**
|
||||
* The default configuration of a specific DataSource
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_baseConfig = array();
|
||||
|
||||
/**
|
||||
* Holds references to descriptions loaded by the DataSource
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_descriptions = array();
|
||||
|
||||
/**
|
||||
* Holds a list of sources (tables) contained in the DataSource
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_sources = null;
|
||||
|
||||
/**
|
||||
* The DataSource configuration
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $config = array();
|
||||
|
||||
/**
|
||||
* Whether or not this DataSource is in the middle of a transaction
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected $_transactionStarted = false;
|
||||
|
||||
/**
|
||||
* Whether or not source data like available tables and schema descriptions
|
||||
* should be cached
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
public $cacheSources = true;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param array $config Array of configuration information for the datasource.
|
||||
*/
|
||||
public function __construct($config = array()) {
|
||||
parent::__construct();
|
||||
$this->setConfig($config);
|
||||
}
|
||||
|
||||
/**
|
||||
* Caches/returns cached results for child instances
|
||||
*
|
||||
* @param mixed $data Unused in this class.
|
||||
* @return array Array of sources available in this datasource.
|
||||
*/
|
||||
public function listSources($data = null) {
|
||||
if ($this->cacheSources === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($this->_sources !== null) {
|
||||
return $this->_sources;
|
||||
}
|
||||
|
||||
$key = ConnectionManager::getSourceName($this) . '_' . $this->config['database'] . '_list';
|
||||
$key = preg_replace('/[^A-Za-z0-9_\-.+]/', '_', $key);
|
||||
$sources = Cache::read($key, '_cake_model_');
|
||||
|
||||
if (empty($sources)) {
|
||||
$sources = $data;
|
||||
Cache::write($key, $data, '_cake_model_');
|
||||
}
|
||||
|
||||
return $this->_sources = $sources;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a Model description (metadata) or null if none found.
|
||||
*
|
||||
* @param Model|string $model The model to describe.
|
||||
* @return array Array of Metadata for the $model
|
||||
*/
|
||||
public function describe($model) {
|
||||
if ($this->cacheSources === false) {
|
||||
return null;
|
||||
}
|
||||
if (is_string($model)) {
|
||||
$table = $model;
|
||||
} else {
|
||||
$table = $model->tablePrefix . $model->table;
|
||||
}
|
||||
|
||||
if (isset($this->_descriptions[$table])) {
|
||||
return $this->_descriptions[$table];
|
||||
}
|
||||
$cache = $this->_cacheDescription($table);
|
||||
|
||||
if ($cache !== null) {
|
||||
$this->_descriptions[$table] =& $cache;
|
||||
return $cache;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Begin a transaction
|
||||
*
|
||||
* @return bool Returns true if a transaction is not in progress
|
||||
*/
|
||||
public function begin() {
|
||||
return !$this->_transactionStarted;
|
||||
}
|
||||
|
||||
/**
|
||||
* Commit a transaction
|
||||
*
|
||||
* @return bool Returns true if a transaction is in progress
|
||||
*/
|
||||
public function commit() {
|
||||
return $this->_transactionStarted;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rollback a transaction
|
||||
*
|
||||
* @return bool Returns true if a transaction is in progress
|
||||
*/
|
||||
public function rollback() {
|
||||
return $this->_transactionStarted;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts column types to basic types
|
||||
*
|
||||
* @param string $real Real column type (i.e. "varchar(255)")
|
||||
* @return string Abstract column type (i.e. "string")
|
||||
*/
|
||||
public function column($real) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Used to create new records. The "C" CRUD.
|
||||
*
|
||||
* To-be-overridden in subclasses.
|
||||
*
|
||||
* @param Model $Model The Model to be created.
|
||||
* @param array $fields An Array of fields to be saved.
|
||||
* @param array $values An Array of values to save.
|
||||
* @return bool success
|
||||
*/
|
||||
public function create(Model $Model, $fields = null, $values = null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Used to read records from the Datasource. The "R" in CRUD
|
||||
*
|
||||
* To-be-overridden in subclasses.
|
||||
*
|
||||
* @param Model $Model The model being read.
|
||||
* @param array $queryData An array of query data used to find the data you want
|
||||
* @param int $recursive Number of levels of association
|
||||
* @return mixed
|
||||
*/
|
||||
public function read(Model $Model, $queryData = array(), $recursive = null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a record(s) in the datasource.
|
||||
*
|
||||
* To-be-overridden in subclasses.
|
||||
*
|
||||
* @param Model $Model Instance of the model class being updated
|
||||
* @param array $fields Array of fields to be updated
|
||||
* @param array $values Array of values to be update $fields to.
|
||||
* @param mixed $conditions The array of conditions to use.
|
||||
* @return bool Success
|
||||
*/
|
||||
public function update(Model $Model, $fields = null, $values = null, $conditions = null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a record(s) in the datasource.
|
||||
*
|
||||
* To-be-overridden in subclasses.
|
||||
*
|
||||
* @param Model $Model The model class having record(s) deleted
|
||||
* @param mixed $conditions The conditions to use for deleting.
|
||||
* @return bool Success
|
||||
*/
|
||||
public function delete(Model $Model, $conditions = null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the ID generated from the previous INSERT operation.
|
||||
*
|
||||
* @param mixed $source The source name.
|
||||
* @return mixed Last ID key generated in previous INSERT
|
||||
*/
|
||||
public function lastInsertId($source = null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of rows returned by last operation.
|
||||
*
|
||||
* @param mixed $source The source name.
|
||||
* @return int Number of rows returned by last operation
|
||||
*/
|
||||
public function lastNumRows($source = null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of rows affected by last query.
|
||||
*
|
||||
* @param mixed $source The source name.
|
||||
* @return int Number of rows affected by last query.
|
||||
*/
|
||||
public function lastAffected($source = null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether the conditions for the Datasource being available
|
||||
* are satisfied. Often used from connect() to check for support
|
||||
* before establishing a connection.
|
||||
*
|
||||
* @return bool Whether or not the Datasources conditions for use are met.
|
||||
*/
|
||||
public function enabled() {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the configuration for the DataSource.
|
||||
* Merges the $config information with the _baseConfig and the existing $config property.
|
||||
*
|
||||
* @param array $config The configuration array
|
||||
* @return void
|
||||
*/
|
||||
public function setConfig($config = array()) {
|
||||
$this->config = array_merge($this->_baseConfig, $this->config, $config);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cache the DataSource description
|
||||
*
|
||||
* @param string $object The name of the object (model) to cache
|
||||
* @param mixed $data The description of the model, usually a string or array
|
||||
* @return mixed
|
||||
*/
|
||||
protected function _cacheDescription($object, $data = null) {
|
||||
if ($this->cacheSources === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($data !== null) {
|
||||
$this->_descriptions[$object] =& $data;
|
||||
}
|
||||
|
||||
$key = ConnectionManager::getSourceName($this) . '_' . $object;
|
||||
$cache = Cache::read($key, '_cake_model_');
|
||||
|
||||
if (empty($cache)) {
|
||||
$cache = $data;
|
||||
Cache::write($key, $cache, '_cake_model_');
|
||||
}
|
||||
|
||||
return $cache;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces `{$__cakeID__$}` and `{$__cakeForeignKey__$}` placeholders in query data.
|
||||
*
|
||||
* @param string $query Query string needing replacements done.
|
||||
* @param array $data Array of data with values that will be inserted in placeholders.
|
||||
* @param string $association Name of association model being replaced.
|
||||
* @param Model $Model Model instance.
|
||||
* @param array $stack The context stack.
|
||||
* @return mixed String of query data with placeholders replaced, or false on failure.
|
||||
*/
|
||||
public function insertQueryData($query, $data, $association, Model $Model, $stack) {
|
||||
$keys = array('{$__cakeID__$}', '{$__cakeForeignKey__$}');
|
||||
|
||||
$modelAlias = $Model->alias;
|
||||
|
||||
foreach ($keys as $key) {
|
||||
if (strpos($query, $key) === false) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$insertKey = $InsertModel = null;
|
||||
switch ($key) {
|
||||
case '{$__cakeID__$}':
|
||||
$InsertModel = $Model;
|
||||
$insertKey = $Model->primaryKey;
|
||||
|
||||
break;
|
||||
case '{$__cakeForeignKey__$}':
|
||||
foreach ($Model->associations() as $type) {
|
||||
foreach ($Model->{$type} as $assoc => $assocData) {
|
||||
if ($assoc !== $association) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isset($assocData['foreignKey'])) {
|
||||
$InsertModel = $Model->{$assoc};
|
||||
$insertKey = $assocData['foreignKey'];
|
||||
}
|
||||
|
||||
break 3;
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
$val = $dataType = null;
|
||||
if (!empty($insertKey) && !empty($InsertModel)) {
|
||||
if (isset($data[$modelAlias][$insertKey])) {
|
||||
$val = $data[$modelAlias][$insertKey];
|
||||
} elseif (isset($data[$association][$insertKey])) {
|
||||
$val = $data[$association][$insertKey];
|
||||
} else {
|
||||
$found = false;
|
||||
foreach (array_reverse($stack) as $assocData) {
|
||||
if (isset($data[$assocData]) && isset($data[$assocData][$insertKey])) {
|
||||
$val = $data[$assocData][$insertKey];
|
||||
$found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!$found) {
|
||||
$val = '';
|
||||
}
|
||||
}
|
||||
|
||||
$dataType = $InsertModel->getColumnType($InsertModel->primaryKey);
|
||||
}
|
||||
|
||||
if (empty($val) && $val !== '0') {
|
||||
return false;
|
||||
}
|
||||
|
||||
$query = str_replace($key, $this->value($val, $dataType), $query);
|
||||
}
|
||||
|
||||
return $query;
|
||||
}
|
||||
|
||||
/**
|
||||
* To-be-overridden in subclasses.
|
||||
*
|
||||
* @param Model $Model Model instance
|
||||
* @param string $key Key name to make
|
||||
* @return string Key name for model.
|
||||
*/
|
||||
public function resolveKey(Model $Model, $key) {
|
||||
return $Model->alias . $key;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the schema name. Override this in subclasses.
|
||||
*
|
||||
* @return string schema name
|
||||
*/
|
||||
public function getSchemaName() {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes a connection. Override in subclasses
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function close() {
|
||||
return $this->connected = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the current datasource.
|
||||
*/
|
||||
public function __destruct() {
|
||||
if ($this->_transactionStarted) {
|
||||
$this->rollback();
|
||||
}
|
||||
if ($this->connected) {
|
||||
$this->close();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
815
lib/Cake/Model/Datasource/Database/Mysql.php
Normal file
815
lib/Cake/Model/Datasource/Database/Mysql.php
Normal file
|
|
@ -0,0 +1,815 @@
|
|||
<?php
|
||||
/**
|
||||
* MySQL layer for DBO
|
||||
*
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @package Cake.Model.Datasource.Database
|
||||
* @since CakePHP(tm) v 0.10.5.1790
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
App::uses('DboSource', 'Model/Datasource');
|
||||
|
||||
/**
|
||||
* MySQL DBO driver object
|
||||
*
|
||||
* Provides connection and SQL generation for MySQL RDMS
|
||||
*
|
||||
* @package Cake.Model.Datasource.Database
|
||||
*/
|
||||
class Mysql extends DboSource {
|
||||
|
||||
/**
|
||||
* Datasource description
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $description = "MySQL DBO Driver";
|
||||
|
||||
/**
|
||||
* Base configuration settings for MySQL driver
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_baseConfig = array(
|
||||
'persistent' => true,
|
||||
'host' => 'localhost',
|
||||
'login' => 'root',
|
||||
'password' => '',
|
||||
'database' => 'cake',
|
||||
'port' => '3306',
|
||||
'flags' => array()
|
||||
);
|
||||
|
||||
/**
|
||||
* Reference to the PDO object connection
|
||||
*
|
||||
* @var PDO
|
||||
*/
|
||||
protected $_connection = null;
|
||||
|
||||
/**
|
||||
* Start quote
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $startQuote = "`";
|
||||
|
||||
/**
|
||||
* End quote
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $endQuote = "`";
|
||||
|
||||
/**
|
||||
* use alias for update and delete. Set to true if version >= 4.1
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected $_useAlias = true;
|
||||
|
||||
/**
|
||||
* List of engine specific additional field parameters used on table creating
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $fieldParameters = array(
|
||||
'charset' => array('value' => 'CHARACTER SET', 'quote' => false, 'join' => ' ', 'column' => false, 'position' => 'beforeDefault'),
|
||||
'collate' => array('value' => 'COLLATE', 'quote' => false, 'join' => ' ', 'column' => 'Collation', 'position' => 'beforeDefault'),
|
||||
'comment' => array('value' => 'COMMENT', 'quote' => true, 'join' => ' ', 'column' => 'Comment', 'position' => 'afterDefault'),
|
||||
'unsigned' => array(
|
||||
'value' => 'UNSIGNED', 'quote' => false, 'join' => ' ', 'column' => false, 'position' => 'beforeDefault',
|
||||
'noVal' => true,
|
||||
'options' => array(true),
|
||||
'types' => array('integer', 'float', 'decimal', 'biginteger')
|
||||
)
|
||||
);
|
||||
|
||||
/**
|
||||
* List of table engine specific parameters used on table creating
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $tableParameters = array(
|
||||
'charset' => array('value' => 'DEFAULT CHARSET', 'quote' => false, 'join' => '=', 'column' => 'charset'),
|
||||
'collate' => array('value' => 'COLLATE', 'quote' => false, 'join' => '=', 'column' => 'Collation'),
|
||||
'engine' => array('value' => 'ENGINE', 'quote' => false, 'join' => '=', 'column' => 'Engine')
|
||||
);
|
||||
|
||||
/**
|
||||
* MySQL column definition
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $columns = array(
|
||||
'primary_key' => array('name' => 'NOT NULL AUTO_INCREMENT'),
|
||||
'string' => array('name' => 'varchar', 'limit' => '255'),
|
||||
'text' => array('name' => 'text'),
|
||||
'biginteger' => array('name' => 'bigint', 'limit' => '20'),
|
||||
'integer' => array('name' => 'int', 'limit' => '11', 'formatter' => 'intval'),
|
||||
'float' => array('name' => 'float', 'formatter' => 'floatval'),
|
||||
'decimal' => array('name' => 'decimal', 'formatter' => 'floatval'),
|
||||
'datetime' => array('name' => 'datetime', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
|
||||
'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
|
||||
'time' => array('name' => 'time', 'format' => 'H:i:s', 'formatter' => 'date'),
|
||||
'date' => array('name' => 'date', 'format' => 'Y-m-d', 'formatter' => 'date'),
|
||||
'binary' => array('name' => 'blob'),
|
||||
'boolean' => array('name' => 'tinyint', 'limit' => '1')
|
||||
);
|
||||
|
||||
/**
|
||||
* Mapping of collation names to character set names
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_charsets = array();
|
||||
|
||||
/**
|
||||
* Connects to the database using options in the given configuration array.
|
||||
*
|
||||
* MySQL supports a few additional options that other drivers do not:
|
||||
*
|
||||
* - `unix_socket` Set to the path of the MySQL sock file. Can be used in place
|
||||
* of host + port.
|
||||
* - `ssl_key` SSL key file for connecting via SSL. Must be combined with `ssl_cert`.
|
||||
* - `ssl_cert` The SSL certificate to use when connecting via SSL. Must be
|
||||
* combined with `ssl_key`.
|
||||
* - `ssl_ca` The certificate authority for SSL connections.
|
||||
*
|
||||
* @return bool True if the database could be connected, else false
|
||||
* @throws MissingConnectionException
|
||||
*/
|
||||
public function connect() {
|
||||
$config = $this->config;
|
||||
$this->connected = false;
|
||||
|
||||
$flags = $config['flags'] + array(
|
||||
PDO::ATTR_PERSISTENT => $config['persistent'],
|
||||
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
|
||||
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
|
||||
);
|
||||
|
||||
if (!empty($config['encoding'])) {
|
||||
$flags[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES ' . $config['encoding'];
|
||||
}
|
||||
if (!empty($config['ssl_key']) && !empty($config['ssl_cert'])) {
|
||||
$flags[PDO::MYSQL_ATTR_SSL_KEY] = $config['ssl_key'];
|
||||
$flags[PDO::MYSQL_ATTR_SSL_CERT] = $config['ssl_cert'];
|
||||
}
|
||||
if (!empty($config['ssl_ca'])) {
|
||||
$flags[PDO::MYSQL_ATTR_SSL_CA] = $config['ssl_ca'];
|
||||
}
|
||||
if (empty($config['unix_socket'])) {
|
||||
$dsn = "mysql:host={$config['host']};port={$config['port']};dbname={$config['database']}";
|
||||
} else {
|
||||
$dsn = "mysql:unix_socket={$config['unix_socket']};dbname={$config['database']}";
|
||||
}
|
||||
|
||||
try {
|
||||
$this->_connection = new PDO(
|
||||
$dsn,
|
||||
$config['login'],
|
||||
$config['password'],
|
||||
$flags
|
||||
);
|
||||
$this->connected = true;
|
||||
if (!empty($config['settings'])) {
|
||||
foreach ($config['settings'] as $key => $value) {
|
||||
$this->_execute("SET $key=$value");
|
||||
}
|
||||
}
|
||||
} catch (PDOException $e) {
|
||||
throw new MissingConnectionException(array(
|
||||
'class' => get_class($this),
|
||||
'message' => $e->getMessage()
|
||||
));
|
||||
}
|
||||
|
||||
$this->_charsets = array();
|
||||
$this->_useAlias = (bool)version_compare($this->getVersion(), "4.1", ">=");
|
||||
|
||||
return $this->connected;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether the MySQL extension is installed/loaded
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function enabled() {
|
||||
return in_array('mysql', PDO::getAvailableDrivers());
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array of sources (tables) in the database.
|
||||
*
|
||||
* @param mixed $data List of tables.
|
||||
* @return array Array of table names in the database
|
||||
*/
|
||||
public function listSources($data = null) {
|
||||
$cache = parent::listSources();
|
||||
if ($cache) {
|
||||
return $cache;
|
||||
}
|
||||
$result = $this->_execute('SHOW TABLES FROM ' . $this->name($this->config['database']));
|
||||
|
||||
if (!$result) {
|
||||
$result->closeCursor();
|
||||
return array();
|
||||
}
|
||||
$tables = array();
|
||||
|
||||
while ($line = $result->fetch(PDO::FETCH_NUM)) {
|
||||
$tables[] = $line[0];
|
||||
}
|
||||
|
||||
$result->closeCursor();
|
||||
parent::listSources($tables);
|
||||
return $tables;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a map of the columns contained in a result
|
||||
*
|
||||
* @param PDOStatement $results The results to format.
|
||||
* @return void
|
||||
*/
|
||||
public function resultSet($results) {
|
||||
$this->map = array();
|
||||
$numFields = $results->columnCount();
|
||||
$index = 0;
|
||||
|
||||
while ($numFields-- > 0) {
|
||||
$column = $results->getColumnMeta($index);
|
||||
if ($column['len'] === 1 && (empty($column['native_type']) || $column['native_type'] === 'TINY')) {
|
||||
$type = 'boolean';
|
||||
} else {
|
||||
$type = empty($column['native_type']) ? 'string' : $column['native_type'];
|
||||
}
|
||||
if (!empty($column['table']) && strpos($column['name'], $this->virtualFieldSeparator) === false) {
|
||||
$this->map[$index++] = array($column['table'], $column['name'], $type);
|
||||
} else {
|
||||
$this->map[$index++] = array(0, $column['name'], $type);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the next row from the current result set
|
||||
*
|
||||
* @return mixed array with results fetched and mapped to column names or false if there is no results left to fetch
|
||||
*/
|
||||
public function fetchResult() {
|
||||
if ($row = $this->_result->fetch(PDO::FETCH_NUM)) {
|
||||
$resultRow = array();
|
||||
foreach ($this->map as $col => $meta) {
|
||||
list($table, $column, $type) = $meta;
|
||||
$resultRow[$table][$column] = $row[$col];
|
||||
if ($type === 'boolean' && $row[$col] !== null) {
|
||||
$resultRow[$table][$column] = $this->boolean($resultRow[$table][$column]);
|
||||
}
|
||||
}
|
||||
return $resultRow;
|
||||
}
|
||||
$this->_result->closeCursor();
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the database encoding
|
||||
*
|
||||
* @return string The database encoding
|
||||
*/
|
||||
public function getEncoding() {
|
||||
return $this->_execute('SHOW VARIABLES LIKE ?', array('character_set_client'))->fetchObject()->Value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Query charset by collation
|
||||
*
|
||||
* @param string $name Collation name
|
||||
* @return string Character set name
|
||||
*/
|
||||
public function getCharsetName($name) {
|
||||
if ((bool)version_compare($this->getVersion(), "5", "<")) {
|
||||
return false;
|
||||
}
|
||||
if (isset($this->_charsets[$name])) {
|
||||
return $this->_charsets[$name];
|
||||
}
|
||||
$r = $this->_execute(
|
||||
'SELECT CHARACTER_SET_NAME FROM INFORMATION_SCHEMA.COLLATIONS WHERE COLLATION_NAME = ?',
|
||||
array($name)
|
||||
);
|
||||
$cols = $r->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
if (isset($cols['CHARACTER_SET_NAME'])) {
|
||||
$this->_charsets[$name] = $cols['CHARACTER_SET_NAME'];
|
||||
} else {
|
||||
$this->_charsets[$name] = false;
|
||||
}
|
||||
return $this->_charsets[$name];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array of the fields in given table name.
|
||||
*
|
||||
* @param Model|string $model Name of database table to inspect or model instance
|
||||
* @return array Fields in table. Keys are name and type
|
||||
* @throws CakeException
|
||||
*/
|
||||
public function describe($model) {
|
||||
$key = $this->fullTableName($model, false);
|
||||
$cache = parent::describe($key);
|
||||
if ($cache) {
|
||||
return $cache;
|
||||
}
|
||||
$table = $this->fullTableName($model);
|
||||
|
||||
$fields = false;
|
||||
$cols = $this->_execute('SHOW FULL COLUMNS FROM ' . $table);
|
||||
if (!$cols) {
|
||||
throw new CakeException(__d('cake_dev', 'Could not describe table for %s', $table));
|
||||
}
|
||||
|
||||
while ($column = $cols->fetch(PDO::FETCH_OBJ)) {
|
||||
$fields[$column->Field] = array(
|
||||
'type' => $this->column($column->Type),
|
||||
'null' => ($column->Null === 'YES' ? true : false),
|
||||
'default' => $column->Default,
|
||||
'length' => $this->length($column->Type)
|
||||
);
|
||||
if (in_array($fields[$column->Field]['type'], $this->fieldParameters['unsigned']['types'], true)) {
|
||||
$fields[$column->Field]['unsigned'] = $this->_unsigned($column->Type);
|
||||
}
|
||||
if (!empty($column->Key) && isset($this->index[$column->Key])) {
|
||||
$fields[$column->Field]['key'] = $this->index[$column->Key];
|
||||
}
|
||||
foreach ($this->fieldParameters as $name => $value) {
|
||||
if (!empty($column->{$value['column']})) {
|
||||
$fields[$column->Field][$name] = $column->{$value['column']};
|
||||
}
|
||||
}
|
||||
if (isset($fields[$column->Field]['collate'])) {
|
||||
$charset = $this->getCharsetName($fields[$column->Field]['collate']);
|
||||
if ($charset) {
|
||||
$fields[$column->Field]['charset'] = $charset;
|
||||
}
|
||||
}
|
||||
}
|
||||
$this->_cacheDescription($key, $fields);
|
||||
$cols->closeCursor();
|
||||
return $fields;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates and executes an SQL UPDATE statement for given model, fields, and values.
|
||||
*
|
||||
* @param Model $model The model to update.
|
||||
* @param array $fields The fields to update.
|
||||
* @param array $values The values to set.
|
||||
* @param mixed $conditions The conditions to use.
|
||||
* @return array
|
||||
*/
|
||||
public function update(Model $model, $fields = array(), $values = null, $conditions = null) {
|
||||
if (!$this->_useAlias) {
|
||||
return parent::update($model, $fields, $values, $conditions);
|
||||
}
|
||||
|
||||
if (!$values) {
|
||||
$combined = $fields;
|
||||
} else {
|
||||
$combined = array_combine($fields, $values);
|
||||
}
|
||||
|
||||
$alias = $joins = false;
|
||||
$fields = $this->_prepareUpdateFields($model, $combined, empty($conditions), !empty($conditions));
|
||||
$fields = implode(', ', $fields);
|
||||
$table = $this->fullTableName($model);
|
||||
|
||||
if (!empty($conditions)) {
|
||||
$alias = $this->name($model->alias);
|
||||
if ($model->name === $model->alias) {
|
||||
$joins = implode(' ', $this->_getJoins($model));
|
||||
}
|
||||
}
|
||||
$conditions = $this->conditions($this->defaultConditions($model, $conditions, $alias), true, true, $model);
|
||||
|
||||
if ($conditions === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!$this->execute($this->renderStatement('update', compact('table', 'alias', 'joins', 'fields', 'conditions')))) {
|
||||
$model->onError();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates and executes an SQL DELETE statement for given id/conditions on given model.
|
||||
*
|
||||
* @param Model $model The model to delete from.
|
||||
* @param mixed $conditions The conditions to use.
|
||||
* @return bool Success
|
||||
*/
|
||||
public function delete(Model $model, $conditions = null) {
|
||||
if (!$this->_useAlias) {
|
||||
return parent::delete($model, $conditions);
|
||||
}
|
||||
$alias = $this->name($model->alias);
|
||||
$table = $this->fullTableName($model);
|
||||
$joins = implode(' ', $this->_getJoins($model));
|
||||
|
||||
if (empty($conditions)) {
|
||||
$alias = $joins = false;
|
||||
}
|
||||
$complexConditions = false;
|
||||
foreach ((array)$conditions as $key => $value) {
|
||||
if (strpos($key, $model->alias) === false) {
|
||||
$complexConditions = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!$complexConditions) {
|
||||
$joins = false;
|
||||
}
|
||||
|
||||
$conditions = $this->conditions($this->defaultConditions($model, $conditions, $alias), true, true, $model);
|
||||
if ($conditions === false) {
|
||||
return false;
|
||||
}
|
||||
if ($this->execute($this->renderStatement('delete', compact('alias', 'table', 'joins', 'conditions'))) === false) {
|
||||
$model->onError();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the database encoding
|
||||
*
|
||||
* @param string $enc Database encoding
|
||||
* @return bool
|
||||
*/
|
||||
public function setEncoding($enc) {
|
||||
return $this->_execute('SET NAMES ' . $enc) !== false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array of the indexes in given datasource name.
|
||||
*
|
||||
* @param string $model Name of model to inspect
|
||||
* @return array Fields in table. Keys are column and unique
|
||||
*/
|
||||
public function index($model) {
|
||||
$index = array();
|
||||
$table = $this->fullTableName($model);
|
||||
$old = version_compare($this->getVersion(), '4.1', '<=');
|
||||
if ($table) {
|
||||
$indexes = $this->_execute('SHOW INDEX FROM ' . $table);
|
||||
// @codingStandardsIgnoreStart
|
||||
// MySQL columns don't match the cakephp conventions.
|
||||
while ($idx = $indexes->fetch(PDO::FETCH_OBJ)) {
|
||||
if ($old) {
|
||||
$idx = (object)current((array)$idx);
|
||||
}
|
||||
if (!isset($index[$idx->Key_name]['column'])) {
|
||||
$col = array();
|
||||
$index[$idx->Key_name]['column'] = $idx->Column_name;
|
||||
|
||||
if ($idx->Index_type === 'FULLTEXT') {
|
||||
$index[$idx->Key_name]['type'] = strtolower($idx->Index_type);
|
||||
} else {
|
||||
$index[$idx->Key_name]['unique'] = intval($idx->Non_unique == 0);
|
||||
}
|
||||
} else {
|
||||
if (!empty($index[$idx->Key_name]['column']) && !is_array($index[$idx->Key_name]['column'])) {
|
||||
$col[] = $index[$idx->Key_name]['column'];
|
||||
}
|
||||
$col[] = $idx->Column_name;
|
||||
$index[$idx->Key_name]['column'] = $col;
|
||||
}
|
||||
if (!empty($idx->Sub_part)) {
|
||||
if (!isset($index[$idx->Key_name]['length'])) {
|
||||
$index[$idx->Key_name]['length'] = array();
|
||||
}
|
||||
$index[$idx->Key_name]['length'][$idx->Column_name] = $idx->Sub_part;
|
||||
}
|
||||
}
|
||||
// @codingStandardsIgnoreEnd
|
||||
$indexes->closeCursor();
|
||||
}
|
||||
return $index;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a MySQL Alter Table syntax for the given Schema comparison
|
||||
*
|
||||
* @param array $compare Result of a CakeSchema::compare()
|
||||
* @param string $table The table name.
|
||||
* @return array Array of alter statements to make.
|
||||
*/
|
||||
public function alterSchema($compare, $table = null) {
|
||||
if (!is_array($compare)) {
|
||||
return false;
|
||||
}
|
||||
$out = '';
|
||||
$colList = array();
|
||||
foreach ($compare as $curTable => $types) {
|
||||
$indexes = $tableParameters = $colList = array();
|
||||
if (!$table || $table === $curTable) {
|
||||
$out .= 'ALTER TABLE ' . $this->fullTableName($curTable) . " \n";
|
||||
foreach ($types as $type => $column) {
|
||||
if (isset($column['indexes'])) {
|
||||
$indexes[$type] = $column['indexes'];
|
||||
unset($column['indexes']);
|
||||
}
|
||||
if (isset($column['tableParameters'])) {
|
||||
$tableParameters[$type] = $column['tableParameters'];
|
||||
unset($column['tableParameters']);
|
||||
}
|
||||
switch ($type) {
|
||||
case 'add':
|
||||
foreach ($column as $field => $col) {
|
||||
$col['name'] = $field;
|
||||
$alter = 'ADD ' . $this->buildColumn($col);
|
||||
if (isset($col['after'])) {
|
||||
$alter .= ' AFTER ' . $this->name($col['after']);
|
||||
}
|
||||
$colList[] = $alter;
|
||||
}
|
||||
break;
|
||||
case 'drop':
|
||||
foreach ($column as $field => $col) {
|
||||
$col['name'] = $field;
|
||||
$colList[] = 'DROP ' . $this->name($field);
|
||||
}
|
||||
break;
|
||||
case 'change':
|
||||
foreach ($column as $field => $col) {
|
||||
if (!isset($col['name'])) {
|
||||
$col['name'] = $field;
|
||||
}
|
||||
$colList[] = 'CHANGE ' . $this->name($field) . ' ' . $this->buildColumn($col);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
$colList = array_merge($colList, $this->_alterIndexes($curTable, $indexes));
|
||||
$colList = array_merge($colList, $this->_alterTableParameters($curTable, $tableParameters));
|
||||
$out .= "\t" . implode(",\n\t", $colList) . ";\n\n";
|
||||
}
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a "drop table" statement for the given table
|
||||
*
|
||||
* @param type $table Name of the table to drop
|
||||
* @return string Drop table SQL statement
|
||||
*/
|
||||
protected function _dropTable($table) {
|
||||
return 'DROP TABLE IF EXISTS ' . $this->fullTableName($table) . ";";
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate MySQL table parameter alteration statements for a table.
|
||||
*
|
||||
* @param string $table Table to alter parameters for.
|
||||
* @param array $parameters Parameters to add & drop.
|
||||
* @return array Array of table property alteration statements.
|
||||
*/
|
||||
protected function _alterTableParameters($table, $parameters) {
|
||||
if (isset($parameters['change'])) {
|
||||
return $this->buildTableParameters($parameters['change']);
|
||||
}
|
||||
return array();
|
||||
}
|
||||
|
||||
/**
|
||||
* Format indexes for create table
|
||||
*
|
||||
* @param array $indexes An array of indexes to generate SQL from
|
||||
* @param string $table Optional table name, not used
|
||||
* @return array An array of SQL statements for indexes
|
||||
* @see DboSource::buildIndex()
|
||||
*/
|
||||
public function buildIndex($indexes, $table = null) {
|
||||
$join = array();
|
||||
foreach ($indexes as $name => $value) {
|
||||
$out = '';
|
||||
if ($name === 'PRIMARY') {
|
||||
$out .= 'PRIMARY ';
|
||||
$name = null;
|
||||
} else {
|
||||
if (!empty($value['unique'])) {
|
||||
$out .= 'UNIQUE ';
|
||||
}
|
||||
$name = $this->startQuote . $name . $this->endQuote;
|
||||
}
|
||||
if (isset($value['type']) && strtolower($value['type']) === 'fulltext') {
|
||||
$out .= 'FULLTEXT ';
|
||||
}
|
||||
$out .= 'KEY ' . $name . ' (';
|
||||
|
||||
if (is_array($value['column'])) {
|
||||
if (isset($value['length'])) {
|
||||
$vals = array();
|
||||
foreach ($value['column'] as $column) {
|
||||
$name = $this->name($column);
|
||||
if (isset($value['length'])) {
|
||||
$name .= $this->_buildIndexSubPart($value['length'], $column);
|
||||
}
|
||||
$vals[] = $name;
|
||||
}
|
||||
$out .= implode(', ', $vals);
|
||||
} else {
|
||||
$out .= implode(', ', array_map(array(&$this, 'name'), $value['column']));
|
||||
}
|
||||
} else {
|
||||
$out .= $this->name($value['column']);
|
||||
if (isset($value['length'])) {
|
||||
$out .= $this->_buildIndexSubPart($value['length'], $value['column']);
|
||||
}
|
||||
}
|
||||
$out .= ')';
|
||||
$join[] = $out;
|
||||
}
|
||||
return $join;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate MySQL index alteration statements for a table.
|
||||
*
|
||||
* @param string $table Table to alter indexes for
|
||||
* @param array $indexes Indexes to add and drop
|
||||
* @return array Index alteration statements
|
||||
*/
|
||||
protected function _alterIndexes($table, $indexes) {
|
||||
$alter = array();
|
||||
if (isset($indexes['drop'])) {
|
||||
foreach ($indexes['drop'] as $name => $value) {
|
||||
$out = 'DROP ';
|
||||
if ($name === 'PRIMARY') {
|
||||
$out .= 'PRIMARY KEY';
|
||||
} else {
|
||||
$out .= 'KEY ' . $this->startQuote . $name . $this->endQuote;
|
||||
}
|
||||
$alter[] = $out;
|
||||
}
|
||||
}
|
||||
if (isset($indexes['add'])) {
|
||||
$add = $this->buildIndex($indexes['add']);
|
||||
foreach ($add as $index) {
|
||||
$alter[] = 'ADD ' . $index;
|
||||
}
|
||||
}
|
||||
return $alter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format length for text indexes
|
||||
*
|
||||
* @param array $lengths An array of lengths for a single index
|
||||
* @param string $column The column for which to generate the index length
|
||||
* @return string Formatted length part of an index field
|
||||
*/
|
||||
protected function _buildIndexSubPart($lengths, $column) {
|
||||
if ($lengths === null) {
|
||||
return '';
|
||||
}
|
||||
if (!isset($lengths[$column])) {
|
||||
return '';
|
||||
}
|
||||
return '(' . $lengths[$column] . ')';
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an detailed array of sources (tables) in the database.
|
||||
*
|
||||
* @param string $name Table name to get parameters
|
||||
* @return array Array of table names in the database
|
||||
*/
|
||||
public function listDetailedSources($name = null) {
|
||||
$condition = '';
|
||||
if (is_string($name)) {
|
||||
$condition = ' WHERE name = ' . $this->value($name);
|
||||
}
|
||||
$result = $this->_connection->query('SHOW TABLE STATUS ' . $condition, PDO::FETCH_ASSOC);
|
||||
|
||||
if (!$result) {
|
||||
$result->closeCursor();
|
||||
return array();
|
||||
}
|
||||
$tables = array();
|
||||
foreach ($result as $row) {
|
||||
$tables[$row['Name']] = (array)$row;
|
||||
unset($tables[$row['Name']]['queryString']);
|
||||
if (!empty($row['Collation'])) {
|
||||
$charset = $this->getCharsetName($row['Collation']);
|
||||
if ($charset) {
|
||||
$tables[$row['Name']]['charset'] = $charset;
|
||||
}
|
||||
}
|
||||
}
|
||||
$result->closeCursor();
|
||||
if (is_string($name) && isset($tables[$name])) {
|
||||
return $tables[$name];
|
||||
}
|
||||
return $tables;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts database-layer column types to basic types
|
||||
*
|
||||
* @param string $real Real database-layer column type (i.e. "varchar(255)")
|
||||
* @return string Abstract column type (i.e. "string")
|
||||
*/
|
||||
public function column($real) {
|
||||
if (is_array($real)) {
|
||||
$col = $real['name'];
|
||||
if (isset($real['limit'])) {
|
||||
$col .= '(' . $real['limit'] . ')';
|
||||
}
|
||||
return $col;
|
||||
}
|
||||
|
||||
$col = str_replace(')', '', $real);
|
||||
$limit = $this->length($real);
|
||||
if (strpos($col, '(') !== false) {
|
||||
list($col, $vals) = explode('(', $col);
|
||||
}
|
||||
|
||||
if (in_array($col, array('date', 'time', 'datetime', 'timestamp'))) {
|
||||
return $col;
|
||||
}
|
||||
if (($col === 'tinyint' && $limit === 1) || $col === 'boolean') {
|
||||
return 'boolean';
|
||||
}
|
||||
if (strpos($col, 'bigint') !== false || $col === 'bigint') {
|
||||
return 'biginteger';
|
||||
}
|
||||
if (strpos($col, 'int') !== false) {
|
||||
return 'integer';
|
||||
}
|
||||
if (strpos($col, 'char') !== false || $col === 'tinytext') {
|
||||
return 'string';
|
||||
}
|
||||
if (strpos($col, 'text') !== false) {
|
||||
return 'text';
|
||||
}
|
||||
if (strpos($col, 'blob') !== false || $col === 'binary') {
|
||||
return 'binary';
|
||||
}
|
||||
if (strpos($col, 'float') !== false || strpos($col, 'double') !== false) {
|
||||
return 'float';
|
||||
}
|
||||
if (strpos($col, 'decimal') !== false || strpos($col, 'numeric') !== false) {
|
||||
return 'decimal';
|
||||
}
|
||||
if (strpos($col, 'enum') !== false) {
|
||||
return "enum($vals)";
|
||||
}
|
||||
return 'text';
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the schema name
|
||||
*
|
||||
* @return string The schema name
|
||||
*/
|
||||
public function getSchemaName() {
|
||||
return $this->config['database'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the server support nested transactions
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function nestedTransactionSupported() {
|
||||
return $this->useNestedTransactions && version_compare($this->getVersion(), '4.1', '>=');
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if column type is unsigned
|
||||
*
|
||||
* @param string $real Real database-layer column type (i.e. "varchar(255)")
|
||||
* @return bool True if column is unsigned, false otherwise
|
||||
*/
|
||||
protected function _unsigned($real) {
|
||||
return strpos(strtolower($real), 'unsigned') !== false;
|
||||
}
|
||||
|
||||
}
|
||||
971
lib/Cake/Model/Datasource/Database/Postgres.php
Normal file
971
lib/Cake/Model/Datasource/Database/Postgres.php
Normal file
|
|
@ -0,0 +1,971 @@
|
|||
<?php
|
||||
/**
|
||||
* PostgreSQL layer for DBO.
|
||||
*
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @package Cake.Model.Datasource.Database
|
||||
* @since CakePHP(tm) v 0.9.1.114
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
App::uses('DboSource', 'Model/Datasource');
|
||||
|
||||
/**
|
||||
* PostgreSQL layer for DBO.
|
||||
*
|
||||
* @package Cake.Model.Datasource.Database
|
||||
*/
|
||||
class Postgres extends DboSource {
|
||||
|
||||
/**
|
||||
* Driver description
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $description = "PostgreSQL DBO Driver";
|
||||
|
||||
/**
|
||||
* Base driver configuration settings. Merged with user settings.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_baseConfig = array(
|
||||
'persistent' => true,
|
||||
'host' => 'localhost',
|
||||
'login' => 'root',
|
||||
'password' => '',
|
||||
'database' => 'cake',
|
||||
'schema' => 'public',
|
||||
'port' => 5432,
|
||||
'encoding' => '',
|
||||
'flags' => array()
|
||||
);
|
||||
|
||||
/**
|
||||
* Columns
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $columns = array(
|
||||
'primary_key' => array('name' => 'serial NOT NULL'),
|
||||
'string' => array('name' => 'varchar', 'limit' => '255'),
|
||||
'text' => array('name' => 'text'),
|
||||
'integer' => array('name' => 'integer', 'formatter' => 'intval'),
|
||||
'biginteger' => array('name' => 'bigint', 'limit' => '20'),
|
||||
'float' => array('name' => 'float', 'formatter' => 'floatval'),
|
||||
'decimal' => array('name' => 'decimal', 'formatter' => 'floatval'),
|
||||
'datetime' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
|
||||
'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
|
||||
'time' => array('name' => 'time', 'format' => 'H:i:s', 'formatter' => 'date'),
|
||||
'date' => array('name' => 'date', 'format' => 'Y-m-d', 'formatter' => 'date'),
|
||||
'binary' => array('name' => 'bytea'),
|
||||
'boolean' => array('name' => 'boolean'),
|
||||
'number' => array('name' => 'numeric'),
|
||||
'inet' => array('name' => 'inet')
|
||||
);
|
||||
|
||||
/**
|
||||
* Starting Quote
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $startQuote = '"';
|
||||
|
||||
/**
|
||||
* Ending Quote
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $endQuote = '"';
|
||||
|
||||
/**
|
||||
* Contains mappings of custom auto-increment sequences, if a table uses a sequence name
|
||||
* other than what is dictated by convention.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_sequenceMap = array();
|
||||
|
||||
/**
|
||||
* The set of valid SQL operations usable in a WHERE statement
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_sqlOps = array('like', 'ilike', 'or', 'not', 'in', 'between', '~', '~*', '!~', '!~*', 'similar to');
|
||||
|
||||
/**
|
||||
* Connects to the database using options in the given configuration array.
|
||||
*
|
||||
* @return bool True if successfully connected.
|
||||
* @throws MissingConnectionException
|
||||
*/
|
||||
public function connect() {
|
||||
$config = $this->config;
|
||||
$this->connected = false;
|
||||
|
||||
$flags = $config['flags'] + array(
|
||||
PDO::ATTR_PERSISTENT => $config['persistent'],
|
||||
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
|
||||
);
|
||||
|
||||
try {
|
||||
$this->_connection = new PDO(
|
||||
"pgsql:host={$config['host']};port={$config['port']};dbname={$config['database']}",
|
||||
$config['login'],
|
||||
$config['password'],
|
||||
$flags
|
||||
);
|
||||
|
||||
$this->connected = true;
|
||||
if (!empty($config['encoding'])) {
|
||||
$this->setEncoding($config['encoding']);
|
||||
}
|
||||
if (!empty($config['schema'])) {
|
||||
$this->_execute('SET search_path TO "' . $config['schema'] . '"');
|
||||
}
|
||||
if (!empty($config['settings'])) {
|
||||
foreach ($config['settings'] as $key => $value) {
|
||||
$this->_execute("SET $key TO $value");
|
||||
}
|
||||
}
|
||||
} catch (PDOException $e) {
|
||||
throw new MissingConnectionException(array(
|
||||
'class' => get_class($this),
|
||||
'message' => $e->getMessage()
|
||||
));
|
||||
}
|
||||
|
||||
return $this->connected;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if PostgreSQL is enabled/loaded
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function enabled() {
|
||||
return in_array('pgsql', PDO::getAvailableDrivers());
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array of tables in the database. If there are no tables, an error is raised and the application exits.
|
||||
*
|
||||
* @param mixed $data The sources to list.
|
||||
* @return array Array of table names in the database
|
||||
*/
|
||||
public function listSources($data = null) {
|
||||
$cache = parent::listSources();
|
||||
|
||||
if ($cache) {
|
||||
return $cache;
|
||||
}
|
||||
|
||||
$schema = $this->config['schema'];
|
||||
$sql = "SELECT table_name as name FROM INFORMATION_SCHEMA.tables WHERE table_schema = ?";
|
||||
$result = $this->_execute($sql, array($schema));
|
||||
|
||||
if (!$result) {
|
||||
return array();
|
||||
}
|
||||
|
||||
$tables = array();
|
||||
|
||||
foreach ($result as $item) {
|
||||
$tables[] = $item->name;
|
||||
}
|
||||
|
||||
$result->closeCursor();
|
||||
parent::listSources($tables);
|
||||
return $tables;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array of the fields in given table name.
|
||||
*
|
||||
* @param Model|string $model Name of database table to inspect
|
||||
* @return array Fields in table. Keys are name and type
|
||||
*/
|
||||
public function describe($model) {
|
||||
$table = $this->fullTableName($model, false, false);
|
||||
$fields = parent::describe($table);
|
||||
$this->_sequenceMap[$table] = array();
|
||||
$cols = null;
|
||||
|
||||
if ($fields === null) {
|
||||
$cols = $this->_execute(
|
||||
"SELECT DISTINCT table_schema AS schema, column_name AS name, data_type AS type, is_nullable AS null,
|
||||
column_default AS default, ordinal_position AS position, character_maximum_length AS char_length,
|
||||
character_octet_length AS oct_length FROM information_schema.columns
|
||||
WHERE table_name = ? AND table_schema = ? ORDER BY position",
|
||||
array($table, $this->config['schema'])
|
||||
);
|
||||
|
||||
// @codingStandardsIgnoreStart
|
||||
// Postgres columns don't match the coding standards.
|
||||
foreach ($cols as $c) {
|
||||
$type = $c->type;
|
||||
if (!empty($c->oct_length) && $c->char_length === null) {
|
||||
if ($c->type === 'character varying') {
|
||||
$length = null;
|
||||
$type = 'text';
|
||||
} elseif ($c->type === 'uuid') {
|
||||
$length = 36;
|
||||
} else {
|
||||
$length = intval($c->oct_length);
|
||||
}
|
||||
} elseif (!empty($c->char_length)) {
|
||||
$length = intval($c->char_length);
|
||||
} else {
|
||||
$length = $this->length($c->type);
|
||||
}
|
||||
if (empty($length)) {
|
||||
$length = null;
|
||||
}
|
||||
$fields[$c->name] = array(
|
||||
'type' => $this->column($type),
|
||||
'null' => ($c->null === 'NO' ? false : true),
|
||||
'default' => preg_replace(
|
||||
"/^'(.*)'$/",
|
||||
"$1",
|
||||
preg_replace('/::.*/', '', $c->default)
|
||||
),
|
||||
'length' => $length
|
||||
);
|
||||
if ($model instanceof Model) {
|
||||
if ($c->name === $model->primaryKey) {
|
||||
$fields[$c->name]['key'] = 'primary';
|
||||
if ($fields[$c->name]['type'] !== 'string') {
|
||||
$fields[$c->name]['length'] = 11;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (
|
||||
$fields[$c->name]['default'] === 'NULL' ||
|
||||
preg_match('/nextval\([\'"]?([\w.]+)/', $c->default, $seq)
|
||||
) {
|
||||
$fields[$c->name]['default'] = null;
|
||||
if (!empty($seq) && isset($seq[1])) {
|
||||
if (strpos($seq[1], '.') === false) {
|
||||
$sequenceName = $c->schema . '.' . $seq[1];
|
||||
} else {
|
||||
$sequenceName = $seq[1];
|
||||
}
|
||||
$this->_sequenceMap[$table][$c->name] = $sequenceName;
|
||||
}
|
||||
}
|
||||
if ($fields[$c->name]['type'] === 'timestamp' && $fields[$c->name]['default'] === '') {
|
||||
$fields[$c->name]['default'] = null;
|
||||
}
|
||||
if ($fields[$c->name]['type'] === 'boolean' && !empty($fields[$c->name]['default'])) {
|
||||
$fields[$c->name]['default'] = constant($fields[$c->name]['default']);
|
||||
}
|
||||
}
|
||||
$this->_cacheDescription($table, $fields);
|
||||
}
|
||||
// @codingStandardsIgnoreEnd
|
||||
|
||||
if (isset($model->sequence)) {
|
||||
$this->_sequenceMap[$table][$model->primaryKey] = $model->sequence;
|
||||
}
|
||||
|
||||
if ($cols) {
|
||||
$cols->closeCursor();
|
||||
}
|
||||
return $fields;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the ID generated from the previous INSERT operation.
|
||||
*
|
||||
* @param string $source Name of the database table
|
||||
* @param string $field Name of the ID database field. Defaults to "id"
|
||||
* @return int
|
||||
*/
|
||||
public function lastInsertId($source = null, $field = 'id') {
|
||||
$seq = $this->getSequence($source, $field);
|
||||
return $this->_connection->lastInsertId($seq);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the associated sequence for the given table/field
|
||||
*
|
||||
* @param string|Model $table Either a full table name (with prefix) as a string, or a model object
|
||||
* @param string $field Name of the ID database field. Defaults to "id"
|
||||
* @return string The associated sequence name from the sequence map, defaults to "{$table}_{$field}_seq"
|
||||
*/
|
||||
public function getSequence($table, $field = 'id') {
|
||||
if (is_object($table)) {
|
||||
$table = $this->fullTableName($table, false, false);
|
||||
}
|
||||
if (!isset($this->_sequenceMap[$table])) {
|
||||
$this->describe($table);
|
||||
}
|
||||
if (isset($this->_sequenceMap[$table][$field])) {
|
||||
return $this->_sequenceMap[$table][$field];
|
||||
}
|
||||
return "{$table}_{$field}_seq";
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset a sequence based on the MAX() value of $column. Useful
|
||||
* for resetting sequences after using insertMulti().
|
||||
*
|
||||
* @param string $table The name of the table to update.
|
||||
* @param string $column The column to use when resetting the sequence value,
|
||||
* the sequence name will be fetched using Postgres::getSequence();
|
||||
* @return bool success.
|
||||
*/
|
||||
public function resetSequence($table, $column) {
|
||||
$tableName = $this->fullTableName($table, false, false);
|
||||
$fullTable = $this->fullTableName($table);
|
||||
|
||||
$sequence = $this->value($this->getSequence($tableName, $column));
|
||||
$column = $this->name($column);
|
||||
$this->execute("SELECT setval($sequence, (SELECT MAX($column) FROM $fullTable))");
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes all the records in a table and drops all associated auto-increment sequences
|
||||
*
|
||||
* @param string|Model $table A string or model class representing the table to be truncated
|
||||
* @param bool $reset true for resetting the sequence, false to leave it as is.
|
||||
* and if 1, sequences are not modified
|
||||
* @return bool SQL TRUNCATE TABLE statement, false if not applicable.
|
||||
*/
|
||||
public function truncate($table, $reset = false) {
|
||||
$table = $this->fullTableName($table, false, false);
|
||||
if (!isset($this->_sequenceMap[$table])) {
|
||||
$cache = $this->cacheSources;
|
||||
$this->cacheSources = false;
|
||||
$this->describe($table);
|
||||
$this->cacheSources = $cache;
|
||||
}
|
||||
if ($this->execute('DELETE FROM ' . $this->fullTableName($table))) {
|
||||
if (isset($this->_sequenceMap[$table]) && $reset != true) {
|
||||
foreach ($this->_sequenceMap[$table] as $sequence) {
|
||||
list($schema, $sequence) = explode('.', $sequence);
|
||||
$this->_execute("ALTER SEQUENCE \"{$schema}\".\"{$sequence}\" RESTART WITH 1");
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares field names to be quoted by parent
|
||||
*
|
||||
* @param string $data The name to format.
|
||||
* @return string SQL field
|
||||
*/
|
||||
public function name($data) {
|
||||
if (is_string($data)) {
|
||||
$data = str_replace('"__"', '__', $data);
|
||||
}
|
||||
return parent::name($data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates the fields list of an SQL query.
|
||||
*
|
||||
* @param Model $model The model to get fields for.
|
||||
* @param string $alias Alias table name.
|
||||
* @param mixed $fields The list of fields to get.
|
||||
* @param bool $quote Whether or not to quote identifiers.
|
||||
* @return array
|
||||
*/
|
||||
public function fields(Model $model, $alias = null, $fields = array(), $quote = true) {
|
||||
if (empty($alias)) {
|
||||
$alias = $model->alias;
|
||||
}
|
||||
$fields = parent::fields($model, $alias, $fields, false);
|
||||
|
||||
if (!$quote) {
|
||||
return $fields;
|
||||
}
|
||||
$count = count($fields);
|
||||
|
||||
if ($count >= 1 && !preg_match('/^\s*COUNT\(\*/', $fields[0])) {
|
||||
$result = array();
|
||||
for ($i = 0; $i < $count; $i++) {
|
||||
if (!preg_match('/^.+\\(.*\\)/', $fields[$i]) && !preg_match('/\s+AS\s+/', $fields[$i])) {
|
||||
if (substr($fields[$i], -1) === '*') {
|
||||
if (strpos($fields[$i], '.') !== false && $fields[$i] != $alias . '.*') {
|
||||
$build = explode('.', $fields[$i]);
|
||||
$AssociatedModel = $model->{$build[0]};
|
||||
} else {
|
||||
$AssociatedModel = $model;
|
||||
}
|
||||
|
||||
$_fields = $this->fields($AssociatedModel, $AssociatedModel->alias, array_keys($AssociatedModel->schema()));
|
||||
$result = array_merge($result, $_fields);
|
||||
continue;
|
||||
}
|
||||
|
||||
$prepend = '';
|
||||
if (strpos($fields[$i], 'DISTINCT') !== false) {
|
||||
$prepend = 'DISTINCT ';
|
||||
$fields[$i] = trim(str_replace('DISTINCT', '', $fields[$i]));
|
||||
}
|
||||
|
||||
if (strrpos($fields[$i], '.') === false) {
|
||||
$fields[$i] = $prepend . $this->name($alias) . '.' . $this->name($fields[$i]) . ' AS ' . $this->name($alias . '__' . $fields[$i]);
|
||||
} else {
|
||||
$build = explode('.', $fields[$i]);
|
||||
$fields[$i] = $prepend . $this->name($build[0]) . '.' . $this->name($build[1]) . ' AS ' . $this->name($build[0] . '__' . $build[1]);
|
||||
}
|
||||
} else {
|
||||
$fields[$i] = preg_replace_callback('/\(([\s\.\w]+)\)/', array(&$this, '_quoteFunctionField'), $fields[$i]);
|
||||
}
|
||||
$result[] = $fields[$i];
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
return $fields;
|
||||
}
|
||||
|
||||
/**
|
||||
* Auxiliary function to quote matched `(Model.fields)` from a preg_replace_callback call
|
||||
* Quotes the fields in a function call.
|
||||
*
|
||||
* @param string $match matched string
|
||||
* @return string quoted string
|
||||
*/
|
||||
protected function _quoteFunctionField($match) {
|
||||
$prepend = '';
|
||||
if (strpos($match[1], 'DISTINCT') !== false) {
|
||||
$prepend = 'DISTINCT ';
|
||||
$match[1] = trim(str_replace('DISTINCT', '', $match[1]));
|
||||
}
|
||||
$constant = preg_match('/^\d+|NULL|FALSE|TRUE$/i', $match[1]);
|
||||
|
||||
if (!$constant && strpos($match[1], '.') === false) {
|
||||
$match[1] = $this->name($match[1]);
|
||||
} elseif (!$constant) {
|
||||
$parts = explode('.', $match[1]);
|
||||
if (!Hash::numeric($parts)) {
|
||||
$match[1] = $this->name($match[1]);
|
||||
}
|
||||
}
|
||||
return '(' . $prepend . $match[1] . ')';
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array of the indexes in given datasource name.
|
||||
*
|
||||
* @param string $model Name of model to inspect
|
||||
* @return array Fields in table. Keys are column and unique
|
||||
*/
|
||||
public function index($model) {
|
||||
$index = array();
|
||||
$table = $this->fullTableName($model, false, false);
|
||||
if ($table) {
|
||||
$indexes = $this->query("SELECT c2.relname, i.indisprimary, i.indisunique, i.indisclustered, i.indisvalid, pg_catalog.pg_get_indexdef(i.indexrelid, 0, true) as statement, c2.reltablespace
|
||||
FROM pg_catalog.pg_class c, pg_catalog.pg_class c2, pg_catalog.pg_index i
|
||||
WHERE c.oid = (
|
||||
SELECT c.oid
|
||||
FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
|
||||
WHERE c.relname ~ '^(" . $table . ")$'
|
||||
AND pg_catalog.pg_table_is_visible(c.oid)
|
||||
AND n.nspname ~ '^(" . $this->config['schema'] . ")$'
|
||||
)
|
||||
AND c.oid = i.indrelid AND i.indexrelid = c2.oid
|
||||
ORDER BY i.indisprimary DESC, i.indisunique DESC, c2.relname", false);
|
||||
foreach ($indexes as $info) {
|
||||
$key = array_pop($info);
|
||||
if ($key['indisprimary']) {
|
||||
$key['relname'] = 'PRIMARY';
|
||||
}
|
||||
preg_match('/\(([^\)]+)\)/', $key['statement'], $indexColumns);
|
||||
$parsedColumn = $indexColumns[1];
|
||||
if (strpos($indexColumns[1], ',') !== false) {
|
||||
$parsedColumn = explode(', ', $indexColumns[1]);
|
||||
}
|
||||
$index[$key['relname']]['unique'] = $key['indisunique'];
|
||||
$index[$key['relname']]['column'] = $parsedColumn;
|
||||
}
|
||||
}
|
||||
return $index;
|
||||
}
|
||||
|
||||
/**
|
||||
* Alter the Schema of a table.
|
||||
*
|
||||
* @param array $compare Results of CakeSchema::compare()
|
||||
* @param string $table name of the table
|
||||
* @return array
|
||||
*/
|
||||
public function alterSchema($compare, $table = null) {
|
||||
if (!is_array($compare)) {
|
||||
return false;
|
||||
}
|
||||
$out = '';
|
||||
$colList = array();
|
||||
foreach ($compare as $curTable => $types) {
|
||||
$indexes = $colList = array();
|
||||
if (!$table || $table === $curTable) {
|
||||
$out .= 'ALTER TABLE ' . $this->fullTableName($curTable) . " \n";
|
||||
foreach ($types as $type => $column) {
|
||||
if (isset($column['indexes'])) {
|
||||
$indexes[$type] = $column['indexes'];
|
||||
unset($column['indexes']);
|
||||
}
|
||||
switch ($type) {
|
||||
case 'add':
|
||||
foreach ($column as $field => $col) {
|
||||
$col['name'] = $field;
|
||||
$colList[] = 'ADD COLUMN ' . $this->buildColumn($col);
|
||||
}
|
||||
break;
|
||||
case 'drop':
|
||||
foreach ($column as $field => $col) {
|
||||
$col['name'] = $field;
|
||||
$colList[] = 'DROP COLUMN ' . $this->name($field);
|
||||
}
|
||||
break;
|
||||
case 'change':
|
||||
$schema = $this->describe($curTable);
|
||||
foreach ($column as $field => $col) {
|
||||
if (!isset($col['name'])) {
|
||||
$col['name'] = $field;
|
||||
}
|
||||
$original = $schema[$field];
|
||||
$fieldName = $this->name($field);
|
||||
|
||||
$default = isset($col['default']) ? $col['default'] : null;
|
||||
$nullable = isset($col['null']) ? $col['null'] : null;
|
||||
$boolToInt = $original['type'] === 'boolean' && $col['type'] === 'integer';
|
||||
unset($col['default'], $col['null']);
|
||||
if ($field !== $col['name']) {
|
||||
$newName = $this->name($col['name']);
|
||||
$out .= "\tRENAME {$fieldName} TO {$newName};\n";
|
||||
$out .= 'ALTER TABLE ' . $this->fullTableName($curTable) . " \n";
|
||||
$fieldName = $newName;
|
||||
}
|
||||
|
||||
if ($boolToInt) {
|
||||
$colList[] = 'ALTER COLUMN ' . $fieldName . ' SET DEFAULT NULL';
|
||||
$colList[] = 'ALTER COLUMN ' . $fieldName . ' TYPE ' . str_replace(array($fieldName, 'NOT NULL'), '', $this->buildColumn($col)) . ' USING CASE WHEN TRUE THEN 1 ELSE 0 END';
|
||||
} else {
|
||||
$colList[] = 'ALTER COLUMN ' . $fieldName . ' TYPE ' . str_replace(array($fieldName, 'NOT NULL'), '', $this->buildColumn($col));
|
||||
}
|
||||
|
||||
if (isset($nullable)) {
|
||||
$nullable = ($nullable) ? 'DROP NOT NULL' : 'SET NOT NULL';
|
||||
$colList[] = 'ALTER COLUMN ' . $fieldName . ' ' . $nullable;
|
||||
}
|
||||
|
||||
if (isset($default)) {
|
||||
if (!$boolToInt) {
|
||||
$colList[] = 'ALTER COLUMN ' . $fieldName . ' SET DEFAULT ' . $this->value($default, $col['type']);
|
||||
}
|
||||
} else {
|
||||
$colList[] = 'ALTER COLUMN ' . $fieldName . ' DROP DEFAULT';
|
||||
}
|
||||
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (isset($indexes['drop']['PRIMARY'])) {
|
||||
$colList[] = 'DROP CONSTRAINT ' . $curTable . '_pkey';
|
||||
}
|
||||
if (isset($indexes['add']['PRIMARY'])) {
|
||||
$cols = $indexes['add']['PRIMARY']['column'];
|
||||
if (is_array($cols)) {
|
||||
$cols = implode(', ', $cols);
|
||||
}
|
||||
$colList[] = 'ADD PRIMARY KEY (' . $cols . ')';
|
||||
}
|
||||
|
||||
if (!empty($colList)) {
|
||||
$out .= "\t" . implode(",\n\t", $colList) . ";\n\n";
|
||||
} else {
|
||||
$out = '';
|
||||
}
|
||||
$out .= implode(";\n\t", $this->_alterIndexes($curTable, $indexes));
|
||||
}
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate PostgreSQL index alteration statements for a table.
|
||||
*
|
||||
* @param string $table Table to alter indexes for
|
||||
* @param array $indexes Indexes to add and drop
|
||||
* @return array Index alteration statements
|
||||
*/
|
||||
protected function _alterIndexes($table, $indexes) {
|
||||
$alter = array();
|
||||
if (isset($indexes['drop'])) {
|
||||
foreach ($indexes['drop'] as $name => $value) {
|
||||
$out = 'DROP ';
|
||||
if ($name === 'PRIMARY') {
|
||||
continue;
|
||||
} else {
|
||||
$out .= 'INDEX ' . $name;
|
||||
}
|
||||
$alter[] = $out;
|
||||
}
|
||||
}
|
||||
if (isset($indexes['add'])) {
|
||||
foreach ($indexes['add'] as $name => $value) {
|
||||
$out = 'CREATE ';
|
||||
if ($name === 'PRIMARY') {
|
||||
continue;
|
||||
} else {
|
||||
if (!empty($value['unique'])) {
|
||||
$out .= 'UNIQUE ';
|
||||
}
|
||||
$out .= 'INDEX ';
|
||||
}
|
||||
if (is_array($value['column'])) {
|
||||
$out .= $name . ' ON ' . $table . ' (' . implode(', ', array_map(array(&$this, 'name'), $value['column'])) . ')';
|
||||
} else {
|
||||
$out .= $name . ' ON ' . $table . ' (' . $this->name($value['column']) . ')';
|
||||
}
|
||||
$alter[] = $out;
|
||||
}
|
||||
}
|
||||
return $alter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a limit statement in the correct format for the particular database.
|
||||
*
|
||||
* @param int $limit Limit of results returned
|
||||
* @param int $offset Offset from which to start results
|
||||
* @return string SQL limit/offset statement
|
||||
*/
|
||||
public function limit($limit, $offset = null) {
|
||||
if ($limit) {
|
||||
$rt = sprintf(' LIMIT %u', $limit);
|
||||
if ($offset) {
|
||||
$rt .= sprintf(' OFFSET %u', $offset);
|
||||
}
|
||||
return $rt;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts database-layer column types to basic types
|
||||
*
|
||||
* @param string $real Real database-layer column type (i.e. "varchar(255)")
|
||||
* @return string Abstract column type (i.e. "string")
|
||||
*/
|
||||
public function column($real) {
|
||||
if (is_array($real)) {
|
||||
$col = $real['name'];
|
||||
if (isset($real['limit'])) {
|
||||
$col .= '(' . $real['limit'] . ')';
|
||||
}
|
||||
return $col;
|
||||
}
|
||||
|
||||
$col = str_replace(')', '', $real);
|
||||
|
||||
if (strpos($col, '(') !== false) {
|
||||
list($col, $limit) = explode('(', $col);
|
||||
}
|
||||
|
||||
$floats = array(
|
||||
'float', 'float4', 'float8', 'double', 'double precision', 'real'
|
||||
);
|
||||
|
||||
switch (true) {
|
||||
case (in_array($col, array('date', 'time', 'inet', 'boolean'))):
|
||||
return $col;
|
||||
case (strpos($col, 'timestamp') !== false):
|
||||
return 'datetime';
|
||||
case (strpos($col, 'time') === 0):
|
||||
return 'time';
|
||||
case ($col === 'bigint'):
|
||||
return 'biginteger';
|
||||
case (strpos($col, 'int') !== false && $col !== 'interval'):
|
||||
return 'integer';
|
||||
case (strpos($col, 'char') !== false || $col === 'uuid'):
|
||||
return 'string';
|
||||
case (strpos($col, 'text') !== false):
|
||||
return 'text';
|
||||
case (strpos($col, 'bytea') !== false):
|
||||
return 'binary';
|
||||
case ($col === 'decimal' || $col === 'numeric'):
|
||||
return 'decimal';
|
||||
case (in_array($col, $floats)):
|
||||
return 'float';
|
||||
default:
|
||||
return 'text';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the length of a database-native column description, or null if no length
|
||||
*
|
||||
* @param string $real Real database-layer column type (i.e. "varchar(255)")
|
||||
* @return int An integer representing the length of the column
|
||||
*/
|
||||
public function length($real) {
|
||||
$col = str_replace(array(')', 'unsigned'), '', $real);
|
||||
$limit = null;
|
||||
|
||||
if (strpos($col, '(') !== false) {
|
||||
list($col, $limit) = explode('(', $col);
|
||||
}
|
||||
if ($col === 'uuid') {
|
||||
return 36;
|
||||
}
|
||||
if ($limit) {
|
||||
return intval($limit);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* resultSet method
|
||||
*
|
||||
* @param array &$results The results
|
||||
* @return void
|
||||
*/
|
||||
public function resultSet(&$results) {
|
||||
$this->map = array();
|
||||
$numFields = $results->columnCount();
|
||||
$index = 0;
|
||||
$j = 0;
|
||||
|
||||
while ($j < $numFields) {
|
||||
$column = $results->getColumnMeta($j);
|
||||
if (strpos($column['name'], '__')) {
|
||||
list($table, $name) = explode('__', $column['name']);
|
||||
$this->map[$index++] = array($table, $name, $column['native_type']);
|
||||
} else {
|
||||
$this->map[$index++] = array(0, $column['name'], $column['native_type']);
|
||||
}
|
||||
$j++;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the next row from the current result set
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function fetchResult() {
|
||||
if ($row = $this->_result->fetch(PDO::FETCH_NUM)) {
|
||||
$resultRow = array();
|
||||
|
||||
foreach ($this->map as $index => $meta) {
|
||||
list($table, $column, $type) = $meta;
|
||||
|
||||
switch ($type) {
|
||||
case 'bool':
|
||||
$resultRow[$table][$column] = $row[$index] === null ? null : $this->boolean($row[$index]);
|
||||
break;
|
||||
case 'binary':
|
||||
case 'bytea':
|
||||
$resultRow[$table][$column] = $row[$index] === null ? null : stream_get_contents($row[$index]);
|
||||
break;
|
||||
default:
|
||||
$resultRow[$table][$column] = $row[$index];
|
||||
}
|
||||
}
|
||||
return $resultRow;
|
||||
}
|
||||
$this->_result->closeCursor();
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Translates between PHP boolean values and PostgreSQL boolean values
|
||||
*
|
||||
* @param mixed $data Value to be translated
|
||||
* @param bool $quote true to quote a boolean to be used in a query, false to return the boolean value
|
||||
* @return bool Converted boolean value
|
||||
*/
|
||||
public function boolean($data, $quote = false) {
|
||||
switch (true) {
|
||||
case ($data === true || $data === false):
|
||||
$result = $data;
|
||||
break;
|
||||
case ($data === 't' || $data === 'f'):
|
||||
$result = ($data === 't');
|
||||
break;
|
||||
case ($data === 'true' || $data === 'false'):
|
||||
$result = ($data === 'true');
|
||||
break;
|
||||
case ($data === 'TRUE' || $data === 'FALSE'):
|
||||
$result = ($data === 'TRUE');
|
||||
break;
|
||||
default:
|
||||
$result = (bool)$data;
|
||||
}
|
||||
|
||||
if ($quote) {
|
||||
return ($result) ? 'TRUE' : 'FALSE';
|
||||
}
|
||||
return (bool)$result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the database encoding
|
||||
*
|
||||
* @param mixed $enc Database encoding
|
||||
* @return bool True on success, false on failure
|
||||
*/
|
||||
public function setEncoding($enc) {
|
||||
return $this->_execute('SET NAMES ' . $this->value($enc)) !== false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the database encoding
|
||||
*
|
||||
* @return string The database encoding
|
||||
*/
|
||||
public function getEncoding() {
|
||||
$result = $this->_execute('SHOW client_encoding')->fetch();
|
||||
if ($result === false) {
|
||||
return false;
|
||||
}
|
||||
return (isset($result['client_encoding'])) ? $result['client_encoding'] : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a Postgres-native column schema string
|
||||
*
|
||||
* @param array $column An array structured like the following:
|
||||
* array('name'=>'value', 'type'=>'value'[, options]),
|
||||
* where options can be 'default', 'length', or 'key'.
|
||||
* @return string
|
||||
*/
|
||||
public function buildColumn($column) {
|
||||
$col = $this->columns[$column['type']];
|
||||
if (!isset($col['length']) && !isset($col['limit'])) {
|
||||
unset($column['length']);
|
||||
}
|
||||
$out = parent::buildColumn($column);
|
||||
|
||||
$out = preg_replace(
|
||||
'/integer\([0-9]+\)/',
|
||||
'integer',
|
||||
$out
|
||||
);
|
||||
$out = preg_replace(
|
||||
'/bigint\([0-9]+\)/',
|
||||
'bigint',
|
||||
$out
|
||||
);
|
||||
|
||||
$out = str_replace('integer serial', 'serial', $out);
|
||||
$out = str_replace('bigint serial', 'bigserial', $out);
|
||||
if (strpos($out, 'timestamp DEFAULT')) {
|
||||
if (isset($column['null']) && $column['null']) {
|
||||
$out = str_replace('DEFAULT NULL', '', $out);
|
||||
} else {
|
||||
$out = str_replace('DEFAULT NOT NULL', '', $out);
|
||||
}
|
||||
}
|
||||
if (strpos($out, 'DEFAULT DEFAULT')) {
|
||||
if (isset($column['null']) && $column['null']) {
|
||||
$out = str_replace('DEFAULT DEFAULT', 'DEFAULT NULL', $out);
|
||||
} elseif (in_array($column['type'], array('integer', 'float'))) {
|
||||
$out = str_replace('DEFAULT DEFAULT', 'DEFAULT 0', $out);
|
||||
} elseif ($column['type'] === 'boolean') {
|
||||
$out = str_replace('DEFAULT DEFAULT', 'DEFAULT FALSE', $out);
|
||||
}
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format indexes for create table
|
||||
*
|
||||
* @param array $indexes The index to build
|
||||
* @param string $table The table name.
|
||||
* @return string
|
||||
*/
|
||||
public function buildIndex($indexes, $table = null) {
|
||||
$join = array();
|
||||
if (!is_array($indexes)) {
|
||||
return array();
|
||||
}
|
||||
foreach ($indexes as $name => $value) {
|
||||
if ($name === 'PRIMARY') {
|
||||
$out = 'PRIMARY KEY (' . $this->name($value['column']) . ')';
|
||||
} else {
|
||||
$out = 'CREATE ';
|
||||
if (!empty($value['unique'])) {
|
||||
$out .= 'UNIQUE ';
|
||||
}
|
||||
if (is_array($value['column'])) {
|
||||
$value['column'] = implode(', ', array_map(array(&$this, 'name'), $value['column']));
|
||||
} else {
|
||||
$value['column'] = $this->name($value['column']);
|
||||
}
|
||||
$out .= "INDEX {$name} ON {$table}({$value['column']});";
|
||||
}
|
||||
$join[] = $out;
|
||||
}
|
||||
return $join;
|
||||
}
|
||||
|
||||
/**
|
||||
* Overrides DboSource::renderStatement to handle schema generation with Postgres-style indexes
|
||||
*
|
||||
* @param string $type The query type.
|
||||
* @param array $data The array of data to render.
|
||||
* @return string
|
||||
*/
|
||||
public function renderStatement($type, $data) {
|
||||
switch (strtolower($type)) {
|
||||
case 'schema':
|
||||
extract($data);
|
||||
|
||||
foreach ($indexes as $i => $index) {
|
||||
if (preg_match('/PRIMARY KEY/', $index)) {
|
||||
unset($indexes[$i]);
|
||||
$columns[] = $index;
|
||||
break;
|
||||
}
|
||||
}
|
||||
$join = array('columns' => ",\n\t", 'indexes' => "\n");
|
||||
|
||||
foreach (array('columns', 'indexes') as $var) {
|
||||
if (is_array(${$var})) {
|
||||
${$var} = implode($join[$var], array_filter(${$var}));
|
||||
}
|
||||
}
|
||||
return "CREATE TABLE {$table} (\n\t{$columns}\n);\n{$indexes}";
|
||||
default:
|
||||
return parent::renderStatement($type, $data);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the schema name
|
||||
*
|
||||
* @return string The schema name
|
||||
*/
|
||||
public function getSchemaName() {
|
||||
return $this->config['schema'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the server support nested transactions
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function nestedTransactionSupported() {
|
||||
return $this->useNestedTransactions && version_compare($this->getVersion(), '8.0', '>=');
|
||||
}
|
||||
|
||||
}
|
||||
586
lib/Cake/Model/Datasource/Database/Sqlite.php
Normal file
586
lib/Cake/Model/Datasource/Database/Sqlite.php
Normal file
|
|
@ -0,0 +1,586 @@
|
|||
<?php
|
||||
/**
|
||||
* SQLite layer for DBO
|
||||
*
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @package Cake.Model.Datasource.Database
|
||||
* @since CakePHP(tm) v 0.9.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
App::uses('DboSource', 'Model/Datasource');
|
||||
App::uses('String', 'Utility');
|
||||
|
||||
/**
|
||||
* DBO implementation for the SQLite3 DBMS.
|
||||
*
|
||||
* A DboSource adapter for SQLite 3 using PDO
|
||||
*
|
||||
* @package Cake.Model.Datasource.Database
|
||||
*/
|
||||
class Sqlite extends DboSource {
|
||||
|
||||
/**
|
||||
* Datasource Description
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $description = "SQLite DBO Driver";
|
||||
|
||||
/**
|
||||
* Quote Start
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $startQuote = '"';
|
||||
|
||||
/**
|
||||
* Quote End
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $endQuote = '"';
|
||||
|
||||
/**
|
||||
* Base configuration settings for SQLite3 driver
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_baseConfig = array(
|
||||
'persistent' => false,
|
||||
'database' => null,
|
||||
'flags' => array()
|
||||
);
|
||||
|
||||
/**
|
||||
* SQLite3 column definition
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $columns = array(
|
||||
'primary_key' => array('name' => 'integer primary key autoincrement'),
|
||||
'string' => array('name' => 'varchar', 'limit' => '255'),
|
||||
'text' => array('name' => 'text'),
|
||||
'integer' => array('name' => 'integer', 'limit' => null, 'formatter' => 'intval'),
|
||||
'biginteger' => array('name' => 'bigint', 'limit' => 20),
|
||||
'float' => array('name' => 'float', 'formatter' => 'floatval'),
|
||||
'decimal' => array('name' => 'decimal', 'formatter' => 'floatval'),
|
||||
'datetime' => array('name' => 'datetime', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
|
||||
'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
|
||||
'time' => array('name' => 'time', 'format' => 'H:i:s', 'formatter' => 'date'),
|
||||
'date' => array('name' => 'date', 'format' => 'Y-m-d', 'formatter' => 'date'),
|
||||
'binary' => array('name' => 'blob'),
|
||||
'boolean' => array('name' => 'boolean')
|
||||
);
|
||||
|
||||
/**
|
||||
* List of engine specific additional field parameters used on table creating
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $fieldParameters = array(
|
||||
'collate' => array(
|
||||
'value' => 'COLLATE',
|
||||
'quote' => false,
|
||||
'join' => ' ',
|
||||
'column' => 'Collate',
|
||||
'position' => 'afterDefault',
|
||||
'options' => array(
|
||||
'BINARY', 'NOCASE', 'RTRIM'
|
||||
)
|
||||
),
|
||||
);
|
||||
|
||||
/**
|
||||
* Connects to the database using config['database'] as a filename.
|
||||
*
|
||||
* @return bool
|
||||
* @throws MissingConnectionException
|
||||
*/
|
||||
public function connect() {
|
||||
$config = $this->config;
|
||||
$flags = $config['flags'] + array(
|
||||
PDO::ATTR_PERSISTENT => $config['persistent'],
|
||||
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
|
||||
);
|
||||
try {
|
||||
$this->_connection = new PDO('sqlite:' . $config['database'], null, null, $flags);
|
||||
$this->connected = true;
|
||||
} catch(PDOException $e) {
|
||||
throw new MissingConnectionException(array(
|
||||
'class' => get_class($this),
|
||||
'message' => $e->getMessage()
|
||||
));
|
||||
}
|
||||
return $this->connected;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether the SQLite extension is installed/loaded
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function enabled() {
|
||||
return in_array('sqlite', PDO::getAvailableDrivers());
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array of tables in the database. If there are no tables, an error is raised and the application exits.
|
||||
*
|
||||
* @param mixed $data Unused.
|
||||
* @return array Array of table names in the database
|
||||
*/
|
||||
public function listSources($data = null) {
|
||||
$cache = parent::listSources();
|
||||
if ($cache) {
|
||||
return $cache;
|
||||
}
|
||||
|
||||
$result = $this->fetchAll("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;", false);
|
||||
|
||||
if (!$result || empty($result)) {
|
||||
return array();
|
||||
}
|
||||
|
||||
$tables = array();
|
||||
foreach ($result as $table) {
|
||||
$tables[] = $table[0]['name'];
|
||||
}
|
||||
parent::listSources($tables);
|
||||
return $tables;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array of the fields in given table name.
|
||||
*
|
||||
* @param Model|string $model Either the model or table name you want described.
|
||||
* @return array Fields in table. Keys are name and type
|
||||
*/
|
||||
public function describe($model) {
|
||||
$table = $this->fullTableName($model, false, false);
|
||||
$cache = parent::describe($table);
|
||||
if ($cache) {
|
||||
return $cache;
|
||||
}
|
||||
$fields = array();
|
||||
$result = $this->_execute(
|
||||
'PRAGMA table_info(' . $this->value($table, 'string') . ')'
|
||||
);
|
||||
|
||||
foreach ($result as $column) {
|
||||
$column = (array)$column;
|
||||
$default = ($column['dflt_value'] === 'NULL') ? null : trim($column['dflt_value'], "'");
|
||||
|
||||
$fields[$column['name']] = array(
|
||||
'type' => $this->column($column['type']),
|
||||
'null' => !$column['notnull'],
|
||||
'default' => $default,
|
||||
'length' => $this->length($column['type'])
|
||||
);
|
||||
if ($column['pk'] == 1) {
|
||||
$fields[$column['name']]['key'] = $this->index['PRI'];
|
||||
$fields[$column['name']]['null'] = false;
|
||||
if (empty($fields[$column['name']]['length'])) {
|
||||
$fields[$column['name']]['length'] = 11;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$result->closeCursor();
|
||||
$this->_cacheDescription($table, $fields);
|
||||
return $fields;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates and executes an SQL UPDATE statement for given model, fields, and values.
|
||||
*
|
||||
* @param Model $model The model instance to update.
|
||||
* @param array $fields The fields to update.
|
||||
* @param array $values The values to set columns to.
|
||||
* @param mixed $conditions array of conditions to use.
|
||||
* @return array
|
||||
*/
|
||||
public function update(Model $model, $fields = array(), $values = null, $conditions = null) {
|
||||
if (empty($values) && !empty($fields)) {
|
||||
foreach ($fields as $field => $value) {
|
||||
if (strpos($field, $model->alias . '.') !== false) {
|
||||
unset($fields[$field]);
|
||||
$field = str_replace($model->alias . '.', "", $field);
|
||||
$field = str_replace($model->alias . '.', "", $field);
|
||||
$fields[$field] = $value;
|
||||
}
|
||||
}
|
||||
}
|
||||
return parent::update($model, $fields, $values, $conditions);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes all the records in a table and resets the count of the auto-incrementing
|
||||
* primary key, where applicable.
|
||||
*
|
||||
* @param string|Model $table A string or model class representing the table to be truncated
|
||||
* @return bool SQL TRUNCATE TABLE statement, false if not applicable.
|
||||
*/
|
||||
public function truncate($table) {
|
||||
if (in_array('sqlite_sequence', $this->listSources())) {
|
||||
$this->_execute('DELETE FROM sqlite_sequence where name=' . $this->startQuote . $this->fullTableName($table, false, false) . $this->endQuote);
|
||||
}
|
||||
return $this->execute('DELETE FROM ' . $this->fullTableName($table));
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts database-layer column types to basic types
|
||||
*
|
||||
* @param string $real Real database-layer column type (i.e. "varchar(255)")
|
||||
* @return string Abstract column type (i.e. "string")
|
||||
*/
|
||||
public function column($real) {
|
||||
if (is_array($real)) {
|
||||
$col = $real['name'];
|
||||
if (isset($real['limit'])) {
|
||||
$col .= '(' . $real['limit'] . ')';
|
||||
}
|
||||
return $col;
|
||||
}
|
||||
|
||||
$col = strtolower(str_replace(')', '', $real));
|
||||
if (strpos($col, '(') !== false) {
|
||||
list($col) = explode('(', $col);
|
||||
}
|
||||
|
||||
$standard = array(
|
||||
'text',
|
||||
'integer',
|
||||
'float',
|
||||
'boolean',
|
||||
'timestamp',
|
||||
'date',
|
||||
'datetime',
|
||||
'time'
|
||||
);
|
||||
if (in_array($col, $standard)) {
|
||||
return $col;
|
||||
}
|
||||
if ($col === 'bigint') {
|
||||
return 'biginteger';
|
||||
}
|
||||
if (strpos($col, 'char') !== false) {
|
||||
return 'string';
|
||||
}
|
||||
if (in_array($col, array('blob', 'clob'))) {
|
||||
return 'binary';
|
||||
}
|
||||
if (strpos($col, 'numeric') !== false || strpos($col, 'decimal') !== false) {
|
||||
return 'decimal';
|
||||
}
|
||||
return 'text';
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate ResultSet
|
||||
*
|
||||
* @param mixed $results The results to modify.
|
||||
* @return void
|
||||
*/
|
||||
public function resultSet($results) {
|
||||
$this->results = $results;
|
||||
$this->map = array();
|
||||
$numFields = $results->columnCount();
|
||||
$index = 0;
|
||||
$j = 0;
|
||||
|
||||
// PDO::getColumnMeta is experimental and does not work with sqlite3,
|
||||
// so try to figure it out based on the querystring
|
||||
$querystring = $results->queryString;
|
||||
if (stripos($querystring, 'SELECT') === 0) {
|
||||
$last = strripos($querystring, 'FROM');
|
||||
if ($last !== false) {
|
||||
$selectpart = substr($querystring, 7, $last - 8);
|
||||
$selects = String::tokenize($selectpart, ',', '(', ')');
|
||||
}
|
||||
} elseif (strpos($querystring, 'PRAGMA table_info') === 0) {
|
||||
$selects = array('cid', 'name', 'type', 'notnull', 'dflt_value', 'pk');
|
||||
} elseif (strpos($querystring, 'PRAGMA index_list') === 0) {
|
||||
$selects = array('seq', 'name', 'unique');
|
||||
} elseif (strpos($querystring, 'PRAGMA index_info') === 0) {
|
||||
$selects = array('seqno', 'cid', 'name');
|
||||
}
|
||||
while ($j < $numFields) {
|
||||
if (!isset($selects[$j])) {
|
||||
$j++;
|
||||
continue;
|
||||
}
|
||||
if (preg_match('/\bAS\s+(.*)/i', $selects[$j], $matches)) {
|
||||
$columnName = trim($matches[1], '"');
|
||||
} else {
|
||||
$columnName = trim(str_replace('"', '', $selects[$j]));
|
||||
}
|
||||
|
||||
if (strpos($selects[$j], 'DISTINCT') === 0) {
|
||||
$columnName = str_ireplace('DISTINCT', '', $columnName);
|
||||
}
|
||||
|
||||
$metaType = false;
|
||||
try {
|
||||
$metaData = (array)$results->getColumnMeta($j);
|
||||
if (!empty($metaData['sqlite:decl_type'])) {
|
||||
$metaType = trim($metaData['sqlite:decl_type']);
|
||||
}
|
||||
} catch (Exception $e) {
|
||||
}
|
||||
|
||||
if (strpos($columnName, '.')) {
|
||||
$parts = explode('.', $columnName);
|
||||
$this->map[$index++] = array(trim($parts[0]), trim($parts[1]), $metaType);
|
||||
} else {
|
||||
$this->map[$index++] = array(0, $columnName, $metaType);
|
||||
}
|
||||
$j++;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the next row from the current result set
|
||||
*
|
||||
* @return mixed array with results fetched and mapped to column names or false if there is no results left to fetch
|
||||
*/
|
||||
public function fetchResult() {
|
||||
if ($row = $this->_result->fetch(PDO::FETCH_NUM)) {
|
||||
$resultRow = array();
|
||||
foreach ($this->map as $col => $meta) {
|
||||
list($table, $column, $type) = $meta;
|
||||
$resultRow[$table][$column] = $row[$col];
|
||||
if ($type === 'boolean' && $row[$col] !== null) {
|
||||
$resultRow[$table][$column] = $this->boolean($resultRow[$table][$column]);
|
||||
}
|
||||
}
|
||||
return $resultRow;
|
||||
}
|
||||
$this->_result->closeCursor();
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a limit statement in the correct format for the particular database.
|
||||
*
|
||||
* @param int $limit Limit of results returned
|
||||
* @param int $offset Offset from which to start results
|
||||
* @return string SQL limit/offset statement
|
||||
*/
|
||||
public function limit($limit, $offset = null) {
|
||||
if ($limit) {
|
||||
$rt = sprintf(' LIMIT %u', $limit);
|
||||
if ($offset) {
|
||||
$rt .= sprintf(' OFFSET %u', $offset);
|
||||
}
|
||||
return $rt;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a database-native column schema string
|
||||
*
|
||||
* @param array $column An array structured like the following: array('name'=>'value', 'type'=>'value'[, options]),
|
||||
* where options can be 'default', 'length', or 'key'.
|
||||
* @return string
|
||||
*/
|
||||
public function buildColumn($column) {
|
||||
$name = $type = null;
|
||||
$column += array('null' => true);
|
||||
extract($column);
|
||||
|
||||
if (empty($name) || empty($type)) {
|
||||
trigger_error(__d('cake_dev', 'Column name or type not defined in schema'), E_USER_WARNING);
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!isset($this->columns[$type])) {
|
||||
trigger_error(__d('cake_dev', 'Column type %s does not exist', $type), E_USER_WARNING);
|
||||
return null;
|
||||
}
|
||||
|
||||
$isPrimary = (isset($column['key']) && $column['key'] === 'primary');
|
||||
if ($isPrimary && $type === 'integer') {
|
||||
return $this->name($name) . ' ' . $this->columns['primary_key']['name'];
|
||||
}
|
||||
$out = parent::buildColumn($column);
|
||||
if ($isPrimary && $type === 'biginteger') {
|
||||
$replacement = 'PRIMARY KEY';
|
||||
if ($column['null'] === false) {
|
||||
$replacement = 'NOT NULL ' . $replacement;
|
||||
}
|
||||
return str_replace($this->columns['primary_key']['name'], $replacement, $out);
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the database encoding
|
||||
*
|
||||
* @param string $enc Database encoding
|
||||
* @return bool
|
||||
*/
|
||||
public function setEncoding($enc) {
|
||||
if (!in_array($enc, array("UTF-8", "UTF-16", "UTF-16le", "UTF-16be"))) {
|
||||
return false;
|
||||
}
|
||||
return $this->_execute("PRAGMA encoding = \"{$enc}\"") !== false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the database encoding
|
||||
*
|
||||
* @return string The database encoding
|
||||
*/
|
||||
public function getEncoding() {
|
||||
return $this->fetchRow('PRAGMA encoding');
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes redundant primary key indexes, as they are handled in the column def of the key.
|
||||
*
|
||||
* @param array $indexes The indexes to build.
|
||||
* @param string $table The table name.
|
||||
* @return string The completed index.
|
||||
*/
|
||||
public function buildIndex($indexes, $table = null) {
|
||||
$join = array();
|
||||
|
||||
$table = str_replace('"', '', $table);
|
||||
list($dbname, $table) = explode('.', $table);
|
||||
$dbname = $this->name($dbname);
|
||||
|
||||
foreach ($indexes as $name => $value) {
|
||||
|
||||
if ($name === 'PRIMARY') {
|
||||
continue;
|
||||
}
|
||||
$out = 'CREATE ';
|
||||
|
||||
if (!empty($value['unique'])) {
|
||||
$out .= 'UNIQUE ';
|
||||
}
|
||||
if (is_array($value['column'])) {
|
||||
$value['column'] = implode(', ', array_map(array(&$this, 'name'), $value['column']));
|
||||
} else {
|
||||
$value['column'] = $this->name($value['column']);
|
||||
}
|
||||
$t = trim($table, '"');
|
||||
$indexname = $this->name($t . '_' . $name);
|
||||
$table = $this->name($table);
|
||||
$out .= "INDEX {$dbname}.{$indexname} ON {$table}({$value['column']});";
|
||||
$join[] = $out;
|
||||
}
|
||||
return $join;
|
||||
}
|
||||
|
||||
/**
|
||||
* Overrides DboSource::index to handle SQLite index introspection
|
||||
* Returns an array of the indexes in given table name.
|
||||
*
|
||||
* @param string $model Name of model to inspect
|
||||
* @return array Fields in table. Keys are column and unique
|
||||
*/
|
||||
public function index($model) {
|
||||
$index = array();
|
||||
$table = $this->fullTableName($model, false, false);
|
||||
if ($table) {
|
||||
$indexes = $this->query('PRAGMA index_list(' . $table . ')');
|
||||
|
||||
if (is_bool($indexes)) {
|
||||
return array();
|
||||
}
|
||||
foreach ($indexes as $info) {
|
||||
$key = array_pop($info);
|
||||
$keyInfo = $this->query('PRAGMA index_info("' . $key['name'] . '")');
|
||||
foreach ($keyInfo as $keyCol) {
|
||||
if (!isset($index[$key['name']])) {
|
||||
$col = array();
|
||||
if (preg_match('/autoindex/', $key['name'])) {
|
||||
$key['name'] = 'PRIMARY';
|
||||
}
|
||||
$index[$key['name']]['column'] = $keyCol[0]['name'];
|
||||
$index[$key['name']]['unique'] = intval($key['unique'] == 1);
|
||||
} else {
|
||||
if (!is_array($index[$key['name']]['column'])) {
|
||||
$col[] = $index[$key['name']]['column'];
|
||||
}
|
||||
$col[] = $keyCol[0]['name'];
|
||||
$index[$key['name']]['column'] = $col;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return $index;
|
||||
}
|
||||
|
||||
/**
|
||||
* Overrides DboSource::renderStatement to handle schema generation with SQLite-style indexes
|
||||
*
|
||||
* @param string $type The type of statement being rendered.
|
||||
* @param array $data The data to convert to SQL.
|
||||
* @return string
|
||||
*/
|
||||
public function renderStatement($type, $data) {
|
||||
switch (strtolower($type)) {
|
||||
case 'schema':
|
||||
extract($data);
|
||||
if (is_array($columns)) {
|
||||
$columns = "\t" . implode(",\n\t", array_filter($columns));
|
||||
}
|
||||
if (is_array($indexes)) {
|
||||
$indexes = "\t" . implode("\n\t", array_filter($indexes));
|
||||
}
|
||||
return "CREATE TABLE {$table} (\n{$columns});\n{$indexes}";
|
||||
default:
|
||||
return parent::renderStatement($type, $data);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* PDO deals in objects, not resources, so overload accordingly.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function hasResult() {
|
||||
return is_object($this->_result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a "drop table" statement for the given table
|
||||
*
|
||||
* @param type $table Name of the table to drop
|
||||
* @return string Drop table SQL statement
|
||||
*/
|
||||
protected function _dropTable($table) {
|
||||
return 'DROP TABLE IF EXISTS ' . $this->fullTableName($table) . ";";
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the schema name
|
||||
*
|
||||
* @return string The schema name
|
||||
*/
|
||||
public function getSchemaName() {
|
||||
return "main"; // Sqlite Datasource does not support multidb
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the server support nested transactions
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function nestedTransactionSupported() {
|
||||
return $this->useNestedTransactions && version_compare($this->getVersion(), '3.6.8', '>=');
|
||||
}
|
||||
|
||||
}
|
||||
813
lib/Cake/Model/Datasource/Database/Sqlserver.php
Normal file
813
lib/Cake/Model/Datasource/Database/Sqlserver.php
Normal file
|
|
@ -0,0 +1,813 @@
|
|||
<?php
|
||||
/**
|
||||
* MS SQL Server layer for DBO
|
||||
*
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @package Cake.Model.Datasource.Database
|
||||
* @since CakePHP(tm) v 0.10.5.1790
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
App::uses('DboSource', 'Model/Datasource');
|
||||
|
||||
/**
|
||||
* Dbo layer for Microsoft's official SQLServer driver
|
||||
*
|
||||
* A Dbo layer for MS SQL Server 2005 and higher. Requires the
|
||||
* `pdo_sqlsrv` extension to be enabled.
|
||||
*
|
||||
* @link http://www.php.net/manual/en/ref.pdo-sqlsrv.php
|
||||
*
|
||||
* @package Cake.Model.Datasource.Database
|
||||
*/
|
||||
class Sqlserver extends DboSource {
|
||||
|
||||
/**
|
||||
* Driver description
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $description = "SQL Server DBO Driver";
|
||||
|
||||
/**
|
||||
* Starting quote character for quoted identifiers
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $startQuote = "[";
|
||||
|
||||
/**
|
||||
* Ending quote character for quoted identifiers
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $endQuote = "]";
|
||||
|
||||
/**
|
||||
* Creates a map between field aliases and numeric indexes. Workaround for the
|
||||
* SQL Server driver's 30-character column name limitation.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_fieldMappings = array();
|
||||
|
||||
/**
|
||||
* Storing the last affected value
|
||||
*
|
||||
* @var mixed
|
||||
*/
|
||||
protected $_lastAffected = false;
|
||||
|
||||
/**
|
||||
* Base configuration settings for MS SQL driver
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_baseConfig = array(
|
||||
'persistent' => true,
|
||||
'host' => 'localhost\SQLEXPRESS',
|
||||
'login' => '',
|
||||
'password' => '',
|
||||
'database' => 'cake',
|
||||
'schema' => '',
|
||||
'flags' => array()
|
||||
);
|
||||
|
||||
/**
|
||||
* MS SQL column definition
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $columns = array(
|
||||
'primary_key' => array('name' => 'IDENTITY (1, 1) NOT NULL'),
|
||||
'string' => array('name' => 'nvarchar', 'limit' => '255'),
|
||||
'text' => array('name' => 'nvarchar', 'limit' => 'MAX'),
|
||||
'integer' => array('name' => 'int', 'formatter' => 'intval'),
|
||||
'biginteger' => array('name' => 'bigint'),
|
||||
'numeric' => array('name' => 'decimal', 'formatter' => 'floatval'),
|
||||
'decimal' => array('name' => 'decimal', 'formatter' => 'floatval'),
|
||||
'float' => array('name' => 'float', 'formatter' => 'floatval'),
|
||||
'real' => array('name' => 'float', 'formatter' => 'floatval'),
|
||||
'datetime' => array('name' => 'datetime', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
|
||||
'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
|
||||
'time' => array('name' => 'datetime', 'format' => 'H:i:s', 'formatter' => 'date'),
|
||||
'date' => array('name' => 'datetime', 'format' => 'Y-m-d', 'formatter' => 'date'),
|
||||
'binary' => array('name' => 'varbinary'),
|
||||
'boolean' => array('name' => 'bit')
|
||||
);
|
||||
|
||||
/**
|
||||
* Magic column name used to provide pagination support for SQLServer 2008
|
||||
* which lacks proper limit/offset support.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
const ROW_COUNTER = '_cake_page_rownum_';
|
||||
|
||||
/**
|
||||
* Connects to the database using options in the given configuration array.
|
||||
*
|
||||
* @return bool True if the database could be connected, else false
|
||||
* @throws MissingConnectionException
|
||||
*/
|
||||
public function connect() {
|
||||
$config = $this->config;
|
||||
$this->connected = false;
|
||||
|
||||
$flags = $config['flags'] + array(
|
||||
PDO::ATTR_PERSISTENT => $config['persistent'],
|
||||
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
|
||||
);
|
||||
|
||||
if (!empty($config['encoding'])) {
|
||||
$flags[PDO::SQLSRV_ATTR_ENCODING] = $config['encoding'];
|
||||
}
|
||||
|
||||
try {
|
||||
$this->_connection = new PDO(
|
||||
"sqlsrv:server={$config['host']};Database={$config['database']}",
|
||||
$config['login'],
|
||||
$config['password'],
|
||||
$flags
|
||||
);
|
||||
$this->connected = true;
|
||||
if (!empty($config['settings'])) {
|
||||
foreach ($config['settings'] as $key => $value) {
|
||||
$this->_execute("SET $key $value");
|
||||
}
|
||||
}
|
||||
} catch (PDOException $e) {
|
||||
throw new MissingConnectionException(array(
|
||||
'class' => get_class($this),
|
||||
'message' => $e->getMessage()
|
||||
));
|
||||
}
|
||||
|
||||
return $this->connected;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check that PDO SQL Server is installed/loaded
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function enabled() {
|
||||
return in_array('sqlsrv', PDO::getAvailableDrivers());
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array of sources (tables) in the database.
|
||||
*
|
||||
* @param mixed $data The names
|
||||
* @return array Array of table names in the database
|
||||
*/
|
||||
public function listSources($data = null) {
|
||||
$cache = parent::listSources();
|
||||
if ($cache !== null) {
|
||||
return $cache;
|
||||
}
|
||||
$result = $this->_execute("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES");
|
||||
|
||||
if (!$result) {
|
||||
$result->closeCursor();
|
||||
return array();
|
||||
}
|
||||
$tables = array();
|
||||
|
||||
while ($line = $result->fetch(PDO::FETCH_NUM)) {
|
||||
$tables[] = $line[0];
|
||||
}
|
||||
|
||||
$result->closeCursor();
|
||||
parent::listSources($tables);
|
||||
return $tables;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array of the fields in given table name.
|
||||
*
|
||||
* @param Model|string $model Model object to describe, or a string table name.
|
||||
* @return array Fields in table. Keys are name and type
|
||||
* @throws CakeException
|
||||
*/
|
||||
public function describe($model) {
|
||||
$table = $this->fullTableName($model, false, false);
|
||||
$fulltable = $this->fullTableName($model, false, true);
|
||||
|
||||
$cache = parent::describe($fulltable);
|
||||
if ($cache) {
|
||||
return $cache;
|
||||
}
|
||||
|
||||
$fields = array();
|
||||
$schema = is_object($model) ? $model->schemaName : false;
|
||||
|
||||
$cols = $this->_execute(
|
||||
"SELECT
|
||||
COLUMN_NAME as Field,
|
||||
DATA_TYPE as Type,
|
||||
COL_LENGTH('" . ($schema ? $fulltable : $table) . "', COLUMN_NAME) as Length,
|
||||
IS_NULLABLE As [Null],
|
||||
COLUMN_DEFAULT as [Default],
|
||||
COLUMNPROPERTY(OBJECT_ID('" . ($schema ? $fulltable : $table) . "'), COLUMN_NAME, 'IsIdentity') as [Key],
|
||||
NUMERIC_SCALE as Size
|
||||
FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_NAME = '" . $table . "'" . ($schema ? " AND TABLE_SCHEMA = '" . $schema . "'" : '')
|
||||
);
|
||||
|
||||
if (!$cols) {
|
||||
throw new CakeException(__d('cake_dev', 'Could not describe table for %s', $table));
|
||||
}
|
||||
|
||||
while ($column = $cols->fetch(PDO::FETCH_OBJ)) {
|
||||
$field = $column->Field;
|
||||
$fields[$field] = array(
|
||||
'type' => $this->column($column),
|
||||
'null' => ($column->Null === 'YES' ? true : false),
|
||||
'default' => $column->Default,
|
||||
'length' => $this->length($column),
|
||||
'key' => ($column->Key == '1') ? 'primary' : false
|
||||
);
|
||||
|
||||
if ($fields[$field]['default'] === 'null') {
|
||||
$fields[$field]['default'] = null;
|
||||
}
|
||||
if ($fields[$field]['default'] !== null) {
|
||||
$fields[$field]['default'] = preg_replace(
|
||||
"/^[(]{1,2}'?([^')]*)?'?[)]{1,2}$/",
|
||||
"$1",
|
||||
$fields[$field]['default']
|
||||
);
|
||||
$this->value($fields[$field]['default'], $fields[$field]['type']);
|
||||
}
|
||||
|
||||
if ($fields[$field]['key'] !== false && $fields[$field]['type'] === 'integer') {
|
||||
$fields[$field]['length'] = 11;
|
||||
} elseif ($fields[$field]['key'] === false) {
|
||||
unset($fields[$field]['key']);
|
||||
}
|
||||
if (in_array($fields[$field]['type'], array('date', 'time', 'datetime', 'timestamp'))) {
|
||||
$fields[$field]['length'] = null;
|
||||
}
|
||||
if ($fields[$field]['type'] === 'float' && !empty($column->Size)) {
|
||||
$fields[$field]['length'] = $fields[$field]['length'] . ',' . $column->Size;
|
||||
}
|
||||
}
|
||||
$this->_cacheDescription($table, $fields);
|
||||
$cols->closeCursor();
|
||||
return $fields;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates the fields list of an SQL query.
|
||||
*
|
||||
* @param Model $model The model to get fields for.
|
||||
* @param string $alias Alias table name
|
||||
* @param array $fields The fields so far.
|
||||
* @param bool $quote Whether or not to quote identfiers.
|
||||
* @return array
|
||||
*/
|
||||
public function fields(Model $model, $alias = null, $fields = array(), $quote = true) {
|
||||
if (empty($alias)) {
|
||||
$alias = $model->alias;
|
||||
}
|
||||
$fields = parent::fields($model, $alias, $fields, false);
|
||||
$count = count($fields);
|
||||
|
||||
if ($count >= 1 && strpos($fields[0], 'COUNT(*)') === false) {
|
||||
$result = array();
|
||||
for ($i = 0; $i < $count; $i++) {
|
||||
$prepend = '';
|
||||
|
||||
if (strpos($fields[$i], 'DISTINCT') !== false && strpos($fields[$i], 'COUNT') === false) {
|
||||
$prepend = 'DISTINCT ';
|
||||
$fields[$i] = trim(str_replace('DISTINCT', '', $fields[$i]));
|
||||
}
|
||||
|
||||
if (!preg_match('/\s+AS\s+/i', $fields[$i])) {
|
||||
if (substr($fields[$i], -1) === '*') {
|
||||
if (strpos($fields[$i], '.') !== false && $fields[$i] != $alias . '.*') {
|
||||
$build = explode('.', $fields[$i]);
|
||||
$AssociatedModel = $model->{$build[0]};
|
||||
} else {
|
||||
$AssociatedModel = $model;
|
||||
}
|
||||
|
||||
$_fields = $this->fields($AssociatedModel, $AssociatedModel->alias, array_keys($AssociatedModel->schema()));
|
||||
$result = array_merge($result, $_fields);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (strpos($fields[$i], '.') === false) {
|
||||
$this->_fieldMappings[$alias . '__' . $fields[$i]] = $alias . '.' . $fields[$i];
|
||||
$fieldName = $this->name($alias . '.' . $fields[$i]);
|
||||
$fieldAlias = $this->name($alias . '__' . $fields[$i]);
|
||||
} else {
|
||||
$build = explode('.', $fields[$i]);
|
||||
$build[0] = trim($build[0], '[]');
|
||||
$build[1] = trim($build[1], '[]');
|
||||
$name = $build[0] . '.' . $build[1];
|
||||
$alias = $build[0] . '__' . $build[1];
|
||||
|
||||
$this->_fieldMappings[$alias] = $name;
|
||||
$fieldName = $this->name($name);
|
||||
$fieldAlias = $this->name($alias);
|
||||
}
|
||||
if ($model->getColumnType($fields[$i]) === 'datetime') {
|
||||
$fieldName = "CONVERT(VARCHAR(20), {$fieldName}, 20)";
|
||||
}
|
||||
$fields[$i] = "{$fieldName} AS {$fieldAlias}";
|
||||
}
|
||||
$result[] = $prepend . $fields[$i];
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
return $fields;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates and executes an SQL INSERT statement for given model, fields, and values.
|
||||
* Removes Identity (primary key) column from update data before returning to parent, if
|
||||
* value is empty.
|
||||
*
|
||||
* @param Model $model The model to insert into.
|
||||
* @param array $fields The fields to set.
|
||||
* @param array $values The values to set.
|
||||
* @return array
|
||||
*/
|
||||
public function create(Model $model, $fields = null, $values = null) {
|
||||
if (!empty($values)) {
|
||||
$fields = array_combine($fields, $values);
|
||||
}
|
||||
$primaryKey = $this->_getPrimaryKey($model);
|
||||
|
||||
if (array_key_exists($primaryKey, $fields)) {
|
||||
if (empty($fields[$primaryKey])) {
|
||||
unset($fields[$primaryKey]);
|
||||
} else {
|
||||
$this->_execute('SET IDENTITY_INSERT ' . $this->fullTableName($model) . ' ON');
|
||||
}
|
||||
}
|
||||
$result = parent::create($model, array_keys($fields), array_values($fields));
|
||||
if (array_key_exists($primaryKey, $fields) && !empty($fields[$primaryKey])) {
|
||||
$this->_execute('SET IDENTITY_INSERT ' . $this->fullTableName($model) . ' OFF');
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates and executes an SQL UPDATE statement for given model, fields, and values.
|
||||
* Removes Identity (primary key) column from update data before returning to parent.
|
||||
*
|
||||
* @param Model $model The model to update.
|
||||
* @param array $fields The fields to set.
|
||||
* @param array $values The values to set.
|
||||
* @param mixed $conditions The conditions to use.
|
||||
* @return array
|
||||
*/
|
||||
public function update(Model $model, $fields = array(), $values = null, $conditions = null) {
|
||||
if (!empty($values)) {
|
||||
$fields = array_combine($fields, $values);
|
||||
}
|
||||
if (isset($fields[$model->primaryKey])) {
|
||||
unset($fields[$model->primaryKey]);
|
||||
}
|
||||
if (empty($fields)) {
|
||||
return true;
|
||||
}
|
||||
return parent::update($model, array_keys($fields), array_values($fields), $conditions);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a limit statement in the correct format for the particular database.
|
||||
*
|
||||
* @param int $limit Limit of results returned
|
||||
* @param int $offset Offset from which to start results
|
||||
* @return string SQL limit/offset statement
|
||||
*/
|
||||
public function limit($limit, $offset = null) {
|
||||
if ($limit) {
|
||||
$rt = '';
|
||||
if (!strpos(strtolower($limit), 'top') || strpos(strtolower($limit), 'top') === 0) {
|
||||
$rt = ' TOP';
|
||||
}
|
||||
$rt .= sprintf(' %u', $limit);
|
||||
if (is_int($offset) && $offset > 0) {
|
||||
$rt = sprintf(' OFFSET %u ROWS FETCH FIRST %u ROWS ONLY', $offset, $limit);
|
||||
}
|
||||
return $rt;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts database-layer column types to basic types
|
||||
*
|
||||
* @param mixed $real Either the string value of the fields type.
|
||||
* or the Result object from Sqlserver::describe()
|
||||
* @return string Abstract column type (i.e. "string")
|
||||
*/
|
||||
public function column($real) {
|
||||
$limit = null;
|
||||
$col = $real;
|
||||
if (is_object($real) && isset($real->Field)) {
|
||||
$limit = $real->Length;
|
||||
$col = $real->Type;
|
||||
}
|
||||
|
||||
if ($col === 'datetime2') {
|
||||
return 'datetime';
|
||||
}
|
||||
if (in_array($col, array('date', 'time', 'datetime', 'timestamp'))) {
|
||||
return $col;
|
||||
}
|
||||
if ($col === 'bit') {
|
||||
return 'boolean';
|
||||
}
|
||||
if (strpos($col, 'bigint') !== false) {
|
||||
return 'biginteger';
|
||||
}
|
||||
if (strpos($col, 'int') !== false) {
|
||||
return 'integer';
|
||||
}
|
||||
if (strpos($col, 'char') !== false && $limit == -1) {
|
||||
return 'text';
|
||||
}
|
||||
if (strpos($col, 'char') !== false) {
|
||||
return 'string';
|
||||
}
|
||||
if (strpos($col, 'text') !== false) {
|
||||
return 'text';
|
||||
}
|
||||
if (strpos($col, 'binary') !== false || $col === 'image') {
|
||||
return 'binary';
|
||||
}
|
||||
if (in_array($col, array('float', 'real'))) {
|
||||
return 'float';
|
||||
}
|
||||
if (in_array($col, array('decimal', 'numeric'))) {
|
||||
return 'decimal';
|
||||
}
|
||||
return 'text';
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle SQLServer specific length properties.
|
||||
* SQLServer handles text types as nvarchar/varchar with a length of -1.
|
||||
*
|
||||
* @param mixed $length Either the length as a string, or a Column descriptor object.
|
||||
* @return mixed null|integer with length of column.
|
||||
*/
|
||||
public function length($length) {
|
||||
if (is_object($length) && isset($length->Length)) {
|
||||
if ($length->Length == -1 && strpos($length->Type, 'char') !== false) {
|
||||
return null;
|
||||
}
|
||||
if (in_array($length->Type, array('nchar', 'nvarchar'))) {
|
||||
return floor($length->Length / 2);
|
||||
}
|
||||
return $length->Length;
|
||||
}
|
||||
return parent::length($length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a map of the columns contained in a result
|
||||
*
|
||||
* @param PDOStatement $results The result to modify.
|
||||
* @return void
|
||||
*/
|
||||
public function resultSet($results) {
|
||||
$this->map = array();
|
||||
$numFields = $results->columnCount();
|
||||
$index = 0;
|
||||
|
||||
while ($numFields-- > 0) {
|
||||
$column = $results->getColumnMeta($index);
|
||||
$name = $column['name'];
|
||||
|
||||
if (strpos($name, '__')) {
|
||||
if (isset($this->_fieldMappings[$name]) && strpos($this->_fieldMappings[$name], '.')) {
|
||||
$map = explode('.', $this->_fieldMappings[$name]);
|
||||
} elseif (isset($this->_fieldMappings[$name])) {
|
||||
$map = array(0, $this->_fieldMappings[$name]);
|
||||
} else {
|
||||
$map = array(0, $name);
|
||||
}
|
||||
} else {
|
||||
$map = array(0, $name);
|
||||
}
|
||||
$map[] = ($column['sqlsrv:decl_type'] === 'bit') ? 'boolean' : $column['native_type'];
|
||||
$this->map[$index++] = $map;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds final SQL statement
|
||||
*
|
||||
* @param string $type Query type
|
||||
* @param array $data Query data
|
||||
* @return string
|
||||
*/
|
||||
public function renderStatement($type, $data) {
|
||||
switch (strtolower($type)) {
|
||||
case 'select':
|
||||
extract($data);
|
||||
$fields = trim($fields);
|
||||
|
||||
if (strpos($limit, 'TOP') !== false && strpos($fields, 'DISTINCT ') === 0) {
|
||||
$limit = 'DISTINCT ' . trim($limit);
|
||||
$fields = substr($fields, 9);
|
||||
}
|
||||
|
||||
// hack order as SQLServer requires an order if there is a limit.
|
||||
if ($limit && !$order) {
|
||||
$order = 'ORDER BY (SELECT NULL)';
|
||||
}
|
||||
|
||||
// For older versions use the subquery version of pagination.
|
||||
if (version_compare($this->getVersion(), '11', '<') && preg_match('/FETCH\sFIRST\s+([0-9]+)/i', $limit, $offset)) {
|
||||
preg_match('/OFFSET\s*(\d+)\s*.*?(\d+)\s*ROWS/', $limit, $limitOffset);
|
||||
|
||||
$limit = 'TOP ' . intval($limitOffset[2]);
|
||||
$page = intval($limitOffset[1] / $limitOffset[2]);
|
||||
$offset = intval($limitOffset[2] * $page);
|
||||
|
||||
$rowCounter = self::ROW_COUNTER;
|
||||
$sql = "SELECT {$limit} * FROM (
|
||||
SELECT {$fields}, ROW_NUMBER() OVER ({$order}) AS {$rowCounter}
|
||||
FROM {$table} {$alias} {$joins} {$conditions} {$group}
|
||||
) AS _cake_paging_
|
||||
WHERE _cake_paging_.{$rowCounter} > {$offset}
|
||||
ORDER BY _cake_paging_.{$rowCounter}
|
||||
";
|
||||
return trim($sql);
|
||||
}
|
||||
if (strpos($limit, 'FETCH') !== false) {
|
||||
return trim("SELECT {$fields} FROM {$table} {$alias} {$joins} {$conditions} {$group} {$order} {$limit}");
|
||||
}
|
||||
return trim("SELECT {$limit} {$fields} FROM {$table} {$alias} {$joins} {$conditions} {$group} {$order}");
|
||||
case "schema":
|
||||
extract($data);
|
||||
|
||||
foreach ($indexes as $i => $index) {
|
||||
if (preg_match('/PRIMARY KEY/', $index)) {
|
||||
unset($indexes[$i]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (array('columns', 'indexes') as $var) {
|
||||
if (is_array(${$var})) {
|
||||
${$var} = "\t" . implode(",\n\t", array_filter(${$var}));
|
||||
}
|
||||
}
|
||||
return trim("CREATE TABLE {$table} (\n{$columns});\n{$indexes}");
|
||||
default:
|
||||
return parent::renderStatement($type, $data);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a quoted and escaped string of $data for use in an SQL statement.
|
||||
*
|
||||
* @param string $data String to be prepared for use in an SQL statement
|
||||
* @param string $column The column into which this data will be inserted
|
||||
* @return string Quoted and escaped data
|
||||
*/
|
||||
public function value($data, $column = null) {
|
||||
if ($data === null || is_array($data) || is_object($data)) {
|
||||
return parent::value($data, $column);
|
||||
}
|
||||
if (in_array($data, array('{$__cakeID__$}', '{$__cakeForeignKey__$}'), true)) {
|
||||
return $data;
|
||||
}
|
||||
|
||||
if (empty($column)) {
|
||||
$column = $this->introspectType($data);
|
||||
}
|
||||
|
||||
switch ($column) {
|
||||
case 'string':
|
||||
case 'text':
|
||||
return 'N' . $this->_connection->quote($data, PDO::PARAM_STR);
|
||||
default:
|
||||
return parent::value($data, $column);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array of all result rows for a given SQL query.
|
||||
* Returns false if no rows matched.
|
||||
*
|
||||
* @param Model $model The model to read from
|
||||
* @param array $queryData The query data
|
||||
* @param int $recursive How many layers to go.
|
||||
* @return array|false Array of resultset rows, or false if no rows matched
|
||||
*/
|
||||
public function read(Model $model, $queryData = array(), $recursive = null) {
|
||||
$results = parent::read($model, $queryData, $recursive);
|
||||
$this->_fieldMappings = array();
|
||||
return $results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the next row from the current result set.
|
||||
* Eats the magic ROW_COUNTER variable.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function fetchResult() {
|
||||
if ($row = $this->_result->fetch(PDO::FETCH_NUM)) {
|
||||
$resultRow = array();
|
||||
foreach ($this->map as $col => $meta) {
|
||||
list($table, $column, $type) = $meta;
|
||||
if ($table === 0 && $column === self::ROW_COUNTER) {
|
||||
continue;
|
||||
}
|
||||
$resultRow[$table][$column] = $row[$col];
|
||||
if ($type === 'boolean' && $row[$col] !== null) {
|
||||
$resultRow[$table][$column] = $this->boolean($resultRow[$table][$column]);
|
||||
}
|
||||
}
|
||||
return $resultRow;
|
||||
}
|
||||
$this->_result->closeCursor();
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts multiple values into a table
|
||||
*
|
||||
* @param string $table The table to insert into.
|
||||
* @param string $fields The fields to set.
|
||||
* @param array $values The values to set.
|
||||
* @return void
|
||||
*/
|
||||
public function insertMulti($table, $fields, $values) {
|
||||
$primaryKey = $this->_getPrimaryKey($table);
|
||||
$hasPrimaryKey = $primaryKey && (
|
||||
(is_array($fields) && in_array($primaryKey, $fields)
|
||||
|| (is_string($fields) && strpos($fields, $this->startQuote . $primaryKey . $this->endQuote) !== false))
|
||||
);
|
||||
|
||||
if ($hasPrimaryKey) {
|
||||
$this->_execute('SET IDENTITY_INSERT ' . $this->fullTableName($table) . ' ON');
|
||||
}
|
||||
|
||||
parent::insertMulti($table, $fields, $values);
|
||||
|
||||
if ($hasPrimaryKey) {
|
||||
$this->_execute('SET IDENTITY_INSERT ' . $this->fullTableName($table) . ' OFF');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a database-native column schema string
|
||||
*
|
||||
* @param array $column An array structured like the
|
||||
* following: array('name'=>'value', 'type'=>'value'[, options]),
|
||||
* where options can be 'default', 'length', or 'key'.
|
||||
* @return string
|
||||
*/
|
||||
public function buildColumn($column) {
|
||||
$result = parent::buildColumn($column);
|
||||
$result = preg_replace('/(bigint|int|integer)\([0-9]+\)/i', '$1', $result);
|
||||
$result = preg_replace('/(bit)\([0-9]+\)/i', '$1', $result);
|
||||
if (strpos($result, 'DEFAULT NULL') !== false) {
|
||||
if (isset($column['default']) && $column['default'] === '') {
|
||||
$result = str_replace('DEFAULT NULL', "DEFAULT ''", $result);
|
||||
} else {
|
||||
$result = str_replace('DEFAULT NULL', 'NULL', $result);
|
||||
}
|
||||
} elseif (array_keys($column) === array('type', 'name')) {
|
||||
$result .= ' NULL';
|
||||
} elseif (strpos($result, "DEFAULT N'")) {
|
||||
$result = str_replace("DEFAULT N'", "DEFAULT '", $result);
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format indexes for create table
|
||||
*
|
||||
* @param array $indexes The indexes to build
|
||||
* @param string $table The table to make indexes for.
|
||||
* @return string
|
||||
*/
|
||||
public function buildIndex($indexes, $table = null) {
|
||||
$join = array();
|
||||
|
||||
foreach ($indexes as $name => $value) {
|
||||
if ($name === 'PRIMARY') {
|
||||
$join[] = 'PRIMARY KEY (' . $this->name($value['column']) . ')';
|
||||
} elseif (isset($value['unique']) && $value['unique']) {
|
||||
$out = "ALTER TABLE {$table} ADD CONSTRAINT {$name} UNIQUE";
|
||||
|
||||
if (is_array($value['column'])) {
|
||||
$value['column'] = implode(', ', array_map(array(&$this, 'name'), $value['column']));
|
||||
} else {
|
||||
$value['column'] = $this->name($value['column']);
|
||||
}
|
||||
$out .= "({$value['column']});";
|
||||
$join[] = $out;
|
||||
}
|
||||
}
|
||||
return $join;
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes sure it will return the primary key
|
||||
*
|
||||
* @param Model|string $model Model instance of table name
|
||||
* @return string
|
||||
*/
|
||||
protected function _getPrimaryKey($model) {
|
||||
$schema = $this->describe($model);
|
||||
foreach ($schema as $field => $props) {
|
||||
if (isset($props['key']) && $props['key'] === 'primary') {
|
||||
return $field;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns number of affected rows in previous database operation. If no previous operation exists,
|
||||
* this returns false.
|
||||
*
|
||||
* @param mixed $source Unused
|
||||
* @return int Number of affected rows
|
||||
*/
|
||||
public function lastAffected($source = null) {
|
||||
$affected = parent::lastAffected();
|
||||
if ($affected === null && $this->_lastAffected !== false) {
|
||||
return $this->_lastAffected;
|
||||
}
|
||||
return $affected;
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes given SQL statement.
|
||||
*
|
||||
* @param string $sql SQL statement
|
||||
* @param array $params list of params to be bound to query (supported only in select)
|
||||
* @param array $prepareOptions Options to be used in the prepare statement
|
||||
* @return mixed PDOStatement if query executes with no problem, true as the result of a successful, false on error
|
||||
* query returning no rows, such as a CREATE statement, false otherwise
|
||||
* @throws PDOException
|
||||
*/
|
||||
protected function _execute($sql, $params = array(), $prepareOptions = array()) {
|
||||
$this->_lastAffected = false;
|
||||
$sql = trim($sql);
|
||||
if (strncasecmp($sql, 'SELECT', 6) === 0 || preg_match('/^EXEC(?:UTE)?\s/mi', $sql) > 0) {
|
||||
$prepareOptions += array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL);
|
||||
return parent::_execute($sql, $params, $prepareOptions);
|
||||
}
|
||||
try {
|
||||
$this->_lastAffected = $this->_connection->exec($sql);
|
||||
if ($this->_lastAffected === false) {
|
||||
$this->_results = null;
|
||||
$error = $this->_connection->errorInfo();
|
||||
$this->error = $error[2];
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} catch (PDOException $e) {
|
||||
if (isset($query->queryString)) {
|
||||
$e->queryString = $query->queryString;
|
||||
} else {
|
||||
$e->queryString = $sql;
|
||||
}
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a "drop table" statement for the given table
|
||||
*
|
||||
* @param type $table Name of the table to drop
|
||||
* @return string Drop table SQL statement
|
||||
*/
|
||||
protected function _dropTable($table) {
|
||||
return "IF OBJECT_ID('" . $this->fullTableName($table, false) . "', 'U') IS NOT NULL DROP TABLE " . $this->fullTableName($table) . ";";
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the schema name
|
||||
*
|
||||
* @return string The schema name
|
||||
*/
|
||||
public function getSchemaName() {
|
||||
return $this->config['schema'];
|
||||
}
|
||||
|
||||
}
|
||||
3545
lib/Cake/Model/Datasource/DboSource.php
Normal file
3545
lib/Cake/Model/Datasource/DboSource.php
Normal file
File diff suppressed because it is too large
Load diff
89
lib/Cake/Model/Datasource/Session/CacheSession.php
Normal file
89
lib/Cake/Model/Datasource/Session/CacheSession.php
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
<?php
|
||||
/**
|
||||
* Cache Session save handler. Allows saving session information into Cache.
|
||||
*
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @package Cake.Model.Datasource.Session
|
||||
* @since CakePHP(tm) v 2.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
App::uses('Cache', 'Cache');
|
||||
App::uses('CakeSessionHandlerInterface', 'Model/Datasource/Session');
|
||||
|
||||
/**
|
||||
* CacheSession provides method for saving sessions into a Cache engine. Used with CakeSession
|
||||
*
|
||||
* @package Cake.Model.Datasource.Session
|
||||
* @see CakeSession for configuration information.
|
||||
*/
|
||||
class CacheSession implements CakeSessionHandlerInterface {
|
||||
|
||||
/**
|
||||
* Method called on open of a database session.
|
||||
*
|
||||
* @return bool Success
|
||||
*/
|
||||
public function open() {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Method called on close of a database session.
|
||||
*
|
||||
* @return bool Success
|
||||
*/
|
||||
public function close() {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Method used to read from a database session.
|
||||
*
|
||||
* @param string $id The key of the value to read
|
||||
* @return mixed The value of the key or false if it does not exist
|
||||
*/
|
||||
public function read($id) {
|
||||
return Cache::read($id, Configure::read('Session.handler.config'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function called on write for database sessions.
|
||||
*
|
||||
* @param int $id ID that uniquely identifies session in database
|
||||
* @param mixed $data The value of the data to be saved.
|
||||
* @return bool True for successful write, false otherwise.
|
||||
*/
|
||||
public function write($id, $data) {
|
||||
return Cache::write($id, $data, Configure::read('Session.handler.config'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Method called on the destruction of a database session.
|
||||
*
|
||||
* @param int $id ID that uniquely identifies session in cache
|
||||
* @return bool True for successful delete, false otherwise.
|
||||
*/
|
||||
public function destroy($id) {
|
||||
return Cache::delete($id, Configure::read('Session.handler.config'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function called on gc for cache sessions.
|
||||
*
|
||||
* @param int $expires Timestamp (defaults to current time)
|
||||
* @return bool Success
|
||||
*/
|
||||
public function gc($expires = null) {
|
||||
return Cache::gc(Configure::read('Session.handler.config'), $expires);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,73 @@
|
|||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @package Cake.Model.Datasource
|
||||
* @since CakePHP(tm) v 2.1
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
/**
|
||||
* Interface for Session handlers. Custom session handler classes should implement
|
||||
* this interface as it allows CakeSession know how to map methods to session_set_save_handler()
|
||||
*
|
||||
* @package Cake.Model.Datasource.Session
|
||||
*/
|
||||
interface CakeSessionHandlerInterface {
|
||||
|
||||
/**
|
||||
* Method called on open of a session.
|
||||
*
|
||||
* @return bool Success
|
||||
*/
|
||||
public function open();
|
||||
|
||||
/**
|
||||
* Method called on close of a session.
|
||||
*
|
||||
* @return bool Success
|
||||
*/
|
||||
public function close();
|
||||
|
||||
/**
|
||||
* Method used to read from a session.
|
||||
*
|
||||
* @param string $id The key of the value to read
|
||||
* @return mixed The value of the key or false if it does not exist
|
||||
*/
|
||||
public function read($id);
|
||||
|
||||
/**
|
||||
* Helper function called on write for sessions.
|
||||
*
|
||||
* @param int $id ID that uniquely identifies session in database
|
||||
* @param mixed $data The value of the data to be saved.
|
||||
* @return bool True for successful write, false otherwise.
|
||||
*/
|
||||
public function write($id, $data);
|
||||
|
||||
/**
|
||||
* Method called on the destruction of a session.
|
||||
*
|
||||
* @param int $id ID that uniquely identifies session in database
|
||||
* @return bool True for successful delete, false otherwise.
|
||||
*/
|
||||
public function destroy($id);
|
||||
|
||||
/**
|
||||
* Run the Garbage collection on the session storage. This method should vacuum all
|
||||
* expired or dead sessions.
|
||||
*
|
||||
* @param int $expires Timestamp (defaults to current time)
|
||||
* @return bool Success
|
||||
*/
|
||||
public function gc($expires = null);
|
||||
|
||||
}
|
||||
145
lib/Cake/Model/Datasource/Session/DatabaseSession.php
Normal file
145
lib/Cake/Model/Datasource/Session/DatabaseSession.php
Normal file
|
|
@ -0,0 +1,145 @@
|
|||
<?php
|
||||
/**
|
||||
* Database Session save handler. Allows saving session information into a model.
|
||||
*
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @package Cake.Model.Datasource.Session
|
||||
* @since CakePHP(tm) v 2.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
App::uses('CakeSessionHandlerInterface', 'Model/Datasource/Session');
|
||||
App::uses('ClassRegistry', 'Utility');
|
||||
|
||||
/**
|
||||
* DatabaseSession provides methods to be used with CakeSession.
|
||||
*
|
||||
* @package Cake.Model.Datasource.Session
|
||||
*/
|
||||
class DatabaseSession implements CakeSessionHandlerInterface {
|
||||
|
||||
/**
|
||||
* Reference to the model handling the session data
|
||||
*
|
||||
* @var Model
|
||||
*/
|
||||
protected $_model;
|
||||
|
||||
/**
|
||||
* Number of seconds to mark the session as expired
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
protected $_timeout;
|
||||
|
||||
/**
|
||||
* Constructor. Looks at Session configuration information and
|
||||
* sets up the session model.
|
||||
*
|
||||
*/
|
||||
public function __construct() {
|
||||
$modelName = Configure::read('Session.handler.model');
|
||||
|
||||
if (empty($modelName)) {
|
||||
$settings = array(
|
||||
'class' => 'Session',
|
||||
'alias' => 'Session',
|
||||
'table' => 'cake_sessions',
|
||||
);
|
||||
} else {
|
||||
$settings = array(
|
||||
'class' => $modelName,
|
||||
'alias' => 'Session',
|
||||
);
|
||||
}
|
||||
$this->_model = ClassRegistry::init($settings);
|
||||
$this->_timeout = Configure::read('Session.timeout') * 60;
|
||||
}
|
||||
|
||||
/**
|
||||
* Method called on open of a database session.
|
||||
*
|
||||
* @return bool Success
|
||||
*/
|
||||
public function open() {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Method called on close of a database session.
|
||||
*
|
||||
* @return bool Success
|
||||
*/
|
||||
public function close() {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Method used to read from a database session.
|
||||
*
|
||||
* @param int|string $id The key of the value to read
|
||||
* @return mixed The value of the key or false if it does not exist
|
||||
*/
|
||||
public function read($id) {
|
||||
$row = $this->_model->find('first', array(
|
||||
'conditions' => array($this->_model->primaryKey => $id)
|
||||
));
|
||||
|
||||
if (empty($row[$this->_model->alias]['data'])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $row[$this->_model->alias]['data'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function called on write for database sessions.
|
||||
*
|
||||
* @param int $id ID that uniquely identifies session in database
|
||||
* @param mixed $data The value of the data to be saved.
|
||||
* @return bool True for successful write, false otherwise.
|
||||
*/
|
||||
public function write($id, $data) {
|
||||
if (!$id) {
|
||||
return false;
|
||||
}
|
||||
$expires = time() + $this->_timeout;
|
||||
$record = compact('id', 'data', 'expires');
|
||||
$record[$this->_model->primaryKey] = $id;
|
||||
return $this->_model->save($record);
|
||||
}
|
||||
|
||||
/**
|
||||
* Method called on the destruction of a database session.
|
||||
*
|
||||
* @param int $id ID that uniquely identifies session in database
|
||||
* @return bool True for successful delete, false otherwise.
|
||||
*/
|
||||
public function destroy($id) {
|
||||
return $this->_model->delete($id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function called on gc for database sessions.
|
||||
*
|
||||
* @param int $expires Timestamp (defaults to current time)
|
||||
* @return bool Success
|
||||
*/
|
||||
public function gc($expires = null) {
|
||||
if (!$expires) {
|
||||
$expires = time();
|
||||
} else {
|
||||
$expires = time() - $expires;
|
||||
}
|
||||
return $this->_model->deleteAll(array($this->_model->alias . ".expires <" => $expires), false, false);
|
||||
}
|
||||
|
||||
}
|
||||
47
lib/Cake/Model/I18nModel.php
Normal file
47
lib/Cake/Model/I18nModel.php
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @package Cake.Model.Behavior
|
||||
* @since CakePHP(tm) v 1.2.0.4525
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
App::uses('AppModel', 'Model');
|
||||
|
||||
/**
|
||||
* A model used by TranslateBehavior to access the translation tables.
|
||||
*
|
||||
* @package Cake.Model
|
||||
*/
|
||||
class I18nModel extends AppModel {
|
||||
|
||||
/**
|
||||
* Model name
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $name = 'I18nModel';
|
||||
|
||||
/**
|
||||
* Table name
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $useTable = 'i18n';
|
||||
|
||||
/**
|
||||
* Display field
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $displayField = 'field';
|
||||
|
||||
}
|
||||
3764
lib/Cake/Model/Model.php
Normal file
3764
lib/Cake/Model/Model.php
Normal file
File diff suppressed because it is too large
Load diff
240
lib/Cake/Model/ModelBehavior.php
Normal file
240
lib/Cake/Model/ModelBehavior.php
Normal file
|
|
@ -0,0 +1,240 @@
|
|||
<?php
|
||||
/**
|
||||
* Model behaviors base class.
|
||||
*
|
||||
* Adds methods and automagic functionality to CakePHP Models.
|
||||
*
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @package Cake.Model
|
||||
* @since CakePHP(tm) v 1.2.0.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
/**
|
||||
* Model behavior base class.
|
||||
*
|
||||
* Defines the Behavior interface, and contains common model interaction functionality. Behaviors
|
||||
* allow you to simulate mixins, and create reusable blocks of application logic, that can be reused across
|
||||
* several models. Behaviors also provide a way to hook into model callbacks and augment their behavior.
|
||||
*
|
||||
* ### Mixin methods
|
||||
*
|
||||
* Behaviors can provide mixin like features by declaring public methods. These methods should expect
|
||||
* the model instance to be shifted onto the parameter list.
|
||||
*
|
||||
* {{{
|
||||
* function doSomething(Model $model, $arg1, $arg2) {
|
||||
* //do something
|
||||
* }
|
||||
* }}}
|
||||
*
|
||||
* Would be called like `$this->Model->doSomething($arg1, $arg2);`.
|
||||
*
|
||||
* ### Mapped methods
|
||||
*
|
||||
* Behaviors can also define mapped methods. Mapped methods use pattern matching for method invocation. This
|
||||
* allows you to create methods similar to Model::findAllByXXX methods on your behaviors. Mapped methods need to
|
||||
* be declared in your behaviors `$mapMethods` array. The method signature for a mapped method is slightly different
|
||||
* than a normal behavior mixin method.
|
||||
*
|
||||
* {{{
|
||||
* public $mapMethods = array('/do(\w+)/' => 'doSomething');
|
||||
*
|
||||
* function doSomething(Model $model, $method, $arg1, $arg2) {
|
||||
* //do something
|
||||
* }
|
||||
* }}}
|
||||
*
|
||||
* The above will map every doXXX() method call to the behavior. As you can see, the model is
|
||||
* still the first parameter, but the called method name will be the 2nd parameter. This allows
|
||||
* you to munge the method name for additional information, much like Model::findAllByXX.
|
||||
*
|
||||
* @package Cake.Model
|
||||
* @see Model::$actsAs
|
||||
* @see BehaviorCollection::load()
|
||||
*/
|
||||
class ModelBehavior extends Object {
|
||||
|
||||
/**
|
||||
* Contains configuration settings for use with individual model objects. This
|
||||
* is used because if multiple models use this Behavior, each will use the same
|
||||
* object instance. Individual model settings should be stored as an
|
||||
* associative array, keyed off of the model name.
|
||||
*
|
||||
* @var array
|
||||
* @see Model::$alias
|
||||
*/
|
||||
public $settings = array();
|
||||
|
||||
/**
|
||||
* Allows the mapping of preg-compatible regular expressions to public or
|
||||
* private methods in this class, where the array key is a /-delimited regular
|
||||
* expression, and the value is a class method. Similar to the functionality of
|
||||
* the findBy* / findAllBy* magic methods.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $mapMethods = array();
|
||||
|
||||
/**
|
||||
* Setup this behavior with the specified configuration settings.
|
||||
*
|
||||
* @param Model $model Model using this behavior
|
||||
* @param array $config Configuration settings for $model
|
||||
* @return void
|
||||
*/
|
||||
public function setup(Model $model, $config = array()) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean up any initialization this behavior has done on a model. Called when a behavior is dynamically
|
||||
* detached from a model using Model::detach().
|
||||
*
|
||||
* @param Model $model Model using this behavior
|
||||
* @return void
|
||||
* @see BehaviorCollection::detach()
|
||||
*/
|
||||
public function cleanup(Model $model) {
|
||||
if (isset($this->settings[$model->alias])) {
|
||||
unset($this->settings[$model->alias]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* beforeFind can be used to cancel find operations, or modify the query that will be executed.
|
||||
* By returning null/false you can abort a find. By returning an array you can modify/replace the query
|
||||
* that is going to be run.
|
||||
*
|
||||
* @param Model $model Model using this behavior
|
||||
* @param array $query Data used to execute this query, i.e. conditions, order, etc.
|
||||
* @return bool|array False or null will abort the operation. You can return an array to replace the
|
||||
* $query that will be eventually run.
|
||||
*/
|
||||
public function beforeFind(Model $model, $query) {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* After find callback. Can be used to modify any results returned by find.
|
||||
*
|
||||
* @param Model $model Model using this behavior
|
||||
* @param mixed $results The results of the find operation
|
||||
* @param bool $primary Whether this model is being queried directly (vs. being queried as an association)
|
||||
* @return mixed An array value will replace the value of $results - any other value will be ignored.
|
||||
*/
|
||||
public function afterFind(Model $model, $results, $primary = false) {
|
||||
}
|
||||
|
||||
/**
|
||||
* beforeValidate is called before a model is validated, you can use this callback to
|
||||
* add behavior validation rules into a models validate array. Returning false
|
||||
* will allow you to make the validation fail.
|
||||
*
|
||||
* @param Model $model Model using this behavior
|
||||
* @param array $options Options passed from Model::save().
|
||||
* @return mixed False or null will abort the operation. Any other result will continue.
|
||||
* @see Model::save()
|
||||
*/
|
||||
public function beforeValidate(Model $model, $options = array()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* afterValidate is called just after model data was validated, you can use this callback
|
||||
* to perform any data cleanup or preparation if needed
|
||||
*
|
||||
* @param Model $model Model using this behavior
|
||||
* @return mixed False will stop this event from being passed to other behaviors
|
||||
*/
|
||||
public function afterValidate(Model $model) {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* beforeSave is called before a model is saved. Returning false from a beforeSave callback
|
||||
* will abort the save operation.
|
||||
*
|
||||
* @param Model $model Model using this behavior
|
||||
* @param array $options Options passed from Model::save().
|
||||
* @return mixed False if the operation should abort. Any other result will continue.
|
||||
* @see Model::save()
|
||||
*/
|
||||
public function beforeSave(Model $model, $options = array()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* afterSave is called after a model is saved.
|
||||
*
|
||||
* @param Model $model Model using this behavior
|
||||
* @param bool $created True if this save created a new record
|
||||
* @param array $options Options passed from Model::save().
|
||||
* @return bool
|
||||
* @see Model::save()
|
||||
*/
|
||||
public function afterSave(Model $model, $created, $options = array()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Before delete is called before any delete occurs on the attached model, but after the model's
|
||||
* beforeDelete is called. Returning false from a beforeDelete will abort the delete.
|
||||
*
|
||||
* @param Model $model Model using this behavior
|
||||
* @param bool $cascade If true records that depend on this record will also be deleted
|
||||
* @return mixed False if the operation should abort. Any other result will continue.
|
||||
*/
|
||||
public function beforeDelete(Model $model, $cascade = true) {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* After delete is called after any delete occurs on the attached model.
|
||||
*
|
||||
* @param Model $model Model using this behavior
|
||||
* @return void
|
||||
*/
|
||||
public function afterDelete(Model $model) {
|
||||
}
|
||||
|
||||
/**
|
||||
* DataSource error callback
|
||||
*
|
||||
* @param Model $model Model using this behavior
|
||||
* @param string $error Error generated in DataSource
|
||||
* @return void
|
||||
*/
|
||||
public function onError(Model $model, $error) {
|
||||
}
|
||||
|
||||
/**
|
||||
* If $model's whitelist property is non-empty, $field will be added to it.
|
||||
* Note: this method should *only* be used in beforeValidate or beforeSave to ensure
|
||||
* that it only modifies the whitelist for the current save operation. Also make sure
|
||||
* you explicitly set the value of the field which you are allowing.
|
||||
*
|
||||
* @param Model $model Model using this behavior
|
||||
* @param string $field Field to be added to $model's whitelist
|
||||
* @return void
|
||||
*/
|
||||
protected function _addToWhitelist(Model $model, $field) {
|
||||
if (is_array($field)) {
|
||||
foreach ($field as $f) {
|
||||
$this->_addToWhitelist($model, $f);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!empty($model->whitelist) && !in_array($field, $model->whitelist)) {
|
||||
$model->whitelist[] = $field;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
600
lib/Cake/Model/ModelValidator.php
Normal file
600
lib/Cake/Model/ModelValidator.php
Normal file
|
|
@ -0,0 +1,600 @@
|
|||
<?php
|
||||
/**
|
||||
* ModelValidator.
|
||||
*
|
||||
* Provides the Model validation logic.
|
||||
*
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @package Cake.Model
|
||||
* @since CakePHP(tm) v 2.2.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
App::uses('CakeValidationSet', 'Model/Validator');
|
||||
App::uses('Hash', 'Utility');
|
||||
|
||||
/**
|
||||
* ModelValidator object encapsulates all methods related to data validations for a model
|
||||
* It also provides an API to dynamically change validation rules for each model field.
|
||||
*
|
||||
* Implements ArrayAccess to easily modify rules as usually done with `Model::$validate`
|
||||
* definition array
|
||||
*
|
||||
* @package Cake.Model
|
||||
* @link http://book.cakephp.org/2.0/en/data-validation.html
|
||||
*/
|
||||
class ModelValidator implements ArrayAccess, IteratorAggregate, Countable {
|
||||
|
||||
/**
|
||||
* Holds the CakeValidationSet objects array
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_fields = array();
|
||||
|
||||
/**
|
||||
* Holds the reference to the model this Validator is attached to
|
||||
*
|
||||
* @var Model
|
||||
*/
|
||||
protected $_model = array();
|
||||
|
||||
/**
|
||||
* The validators $validate property, used for checking whether validation
|
||||
* rules definition changed in the model and should be refreshed in this class
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_validate = array();
|
||||
|
||||
/**
|
||||
* Holds the available custom callback methods, usually taken from model methods
|
||||
* and behavior methods
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_methods = array();
|
||||
|
||||
/**
|
||||
* Holds the available custom callback methods from the model
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_modelMethods = array();
|
||||
|
||||
/**
|
||||
* Holds the list of behavior names that were attached when this object was created
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_behaviors = array();
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param Model $Model A reference to the Model the Validator is attached to
|
||||
*/
|
||||
public function __construct(Model $Model) {
|
||||
$this->_model = $Model;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if all fields pass validation. Will validate hasAndBelongsToMany associations
|
||||
* that use the 'with' key as well. Since `Model::_saveMulti` is incapable of exiting a save operation.
|
||||
*
|
||||
* Will validate the currently set data. Use `Model::set()` or `Model::create()` to set the active data.
|
||||
*
|
||||
* @param array $options An optional array of custom options to be made available in the beforeValidate callback
|
||||
* @return bool True if there are no errors
|
||||
*/
|
||||
public function validates($options = array()) {
|
||||
$errors = $this->errors($options);
|
||||
if (empty($errors) && $errors !== false) {
|
||||
$errors = $this->_validateWithModels($options);
|
||||
}
|
||||
if (is_array($errors)) {
|
||||
return count($errors) === 0;
|
||||
}
|
||||
return $errors;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates a single record, as well as all its directly associated records.
|
||||
*
|
||||
* #### Options
|
||||
*
|
||||
* - atomic: If true (default), returns boolean. If false returns array.
|
||||
* - fieldList: Equivalent to the $fieldList parameter in Model::save()
|
||||
* - deep: If set to true, not only directly associated data , but deeper nested associated data is validated as well.
|
||||
*
|
||||
* Warning: This method could potentially change the passed argument `$data`,
|
||||
* If you do not want this to happen, make a copy of `$data` before passing it
|
||||
* to this method
|
||||
*
|
||||
* @param array &$data Record data to validate. This should be an array indexed by association name.
|
||||
* @param array $options Options to use when validating record data (see above), See also $options of validates().
|
||||
* @return array|bool If atomic: True on success, or false on failure.
|
||||
* Otherwise: array similar to the $data array passed, but values are set to true/false
|
||||
* depending on whether each record validated successfully.
|
||||
*/
|
||||
public function validateAssociated(&$data, $options = array()) {
|
||||
$model = $this->getModel();
|
||||
$options += array('atomic' => true, 'deep' => false);
|
||||
$model->validationErrors = $validationErrors = $return = array();
|
||||
$model->create(null);
|
||||
$return[$model->alias] = true;
|
||||
if (!($model->set($data) && $model->validates($options))) {
|
||||
$validationErrors[$model->alias] = $model->validationErrors;
|
||||
$return[$model->alias] = false;
|
||||
}
|
||||
$data = $model->data;
|
||||
if (!empty($options['deep']) && isset($data[$model->alias])) {
|
||||
$recordData = $data[$model->alias];
|
||||
unset($data[$model->alias]);
|
||||
$data += $recordData;
|
||||
}
|
||||
|
||||
$associations = $model->getAssociated();
|
||||
foreach ($data as $association => &$values) {
|
||||
$validates = true;
|
||||
if (isset($associations[$association])) {
|
||||
if (in_array($associations[$association], array('belongsTo', 'hasOne'))) {
|
||||
if ($options['deep']) {
|
||||
$validates = $model->{$association}->validateAssociated($values, $options);
|
||||
} else {
|
||||
$model->{$association}->create(null);
|
||||
$validates = $model->{$association}->set($values) && $model->{$association}->validates($options);
|
||||
$data[$association] = $model->{$association}->data[$model->{$association}->alias];
|
||||
}
|
||||
if (is_array($validates)) {
|
||||
$validates = !in_array(false, Hash::flatten($validates), true);
|
||||
}
|
||||
$return[$association] = $validates;
|
||||
} elseif ($associations[$association] === 'hasMany') {
|
||||
$validates = $model->{$association}->validateMany($values, $options);
|
||||
$return[$association] = $validates;
|
||||
}
|
||||
if (!$validates || (is_array($validates) && in_array(false, $validates, true))) {
|
||||
$validationErrors[$association] = $model->{$association}->validationErrors;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$model->validationErrors = $validationErrors;
|
||||
if (isset($validationErrors[$model->alias])) {
|
||||
$model->validationErrors = $validationErrors[$model->alias];
|
||||
unset($validationErrors[$model->alias]);
|
||||
$model->validationErrors = array_merge($model->validationErrors, $validationErrors);
|
||||
}
|
||||
if (!$options['atomic']) {
|
||||
return $return;
|
||||
}
|
||||
if ($return[$model->alias] === false || !empty($model->validationErrors)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates multiple individual records for a single model
|
||||
*
|
||||
* #### Options
|
||||
*
|
||||
* - atomic: If true (default), returns boolean. If false returns array.
|
||||
* - fieldList: Equivalent to the $fieldList parameter in Model::save()
|
||||
* - deep: If set to true, all associated data will be validated as well.
|
||||
*
|
||||
* Warning: This method could potentially change the passed argument `$data`,
|
||||
* If you do not want this to happen, make a copy of `$data` before passing it
|
||||
* to this method
|
||||
*
|
||||
* @param array &$data Record data to validate. This should be a numerically-indexed array
|
||||
* @param array $options Options to use when validating record data (see above), See also $options of validates().
|
||||
* @return mixed If atomic: True on success, or false on failure.
|
||||
* Otherwise: array similar to the $data array passed, but values are set to true/false
|
||||
* depending on whether each record validated successfully.
|
||||
*/
|
||||
public function validateMany(&$data, $options = array()) {
|
||||
$model = $this->getModel();
|
||||
$options += array('atomic' => true, 'deep' => false);
|
||||
$model->validationErrors = $validationErrors = $return = array();
|
||||
foreach ($data as $key => &$record) {
|
||||
if ($options['deep']) {
|
||||
$validates = $model->validateAssociated($record, $options);
|
||||
} else {
|
||||
$model->create(null);
|
||||
$validates = $model->set($record) && $model->validates($options);
|
||||
$data[$key] = $model->data;
|
||||
}
|
||||
if ($validates === false || (is_array($validates) && in_array(false, Hash::flatten($validates), true))) {
|
||||
$validationErrors[$key] = $model->validationErrors;
|
||||
$validates = false;
|
||||
} else {
|
||||
$validates = true;
|
||||
}
|
||||
$return[$key] = $validates;
|
||||
}
|
||||
$model->validationErrors = $validationErrors;
|
||||
if (!$options['atomic']) {
|
||||
return $return;
|
||||
}
|
||||
return empty($model->validationErrors);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array of fields that have failed validation. On the current model. This method will
|
||||
* actually run validation rules over data, not just return the messages.
|
||||
*
|
||||
* @param string $options An optional array of custom options to be made available in the beforeValidate callback
|
||||
* @return array Array of invalid fields
|
||||
* @see ModelValidator::validates()
|
||||
*/
|
||||
public function errors($options = array()) {
|
||||
if (!$this->_triggerBeforeValidate($options)) {
|
||||
return false;
|
||||
}
|
||||
$model = $this->getModel();
|
||||
|
||||
if (!$this->_parseRules()) {
|
||||
return $model->validationErrors;
|
||||
}
|
||||
|
||||
$fieldList = $model->whitelist;
|
||||
if (empty($fieldList) && !empty($options['fieldList'])) {
|
||||
if (!empty($options['fieldList'][$model->alias]) && is_array($options['fieldList'][$model->alias])) {
|
||||
$fieldList = $options['fieldList'][$model->alias];
|
||||
} else {
|
||||
$fieldList = $options['fieldList'];
|
||||
}
|
||||
}
|
||||
|
||||
$exists = $model->exists();
|
||||
$methods = $this->getMethods();
|
||||
$fields = $this->_validationList($fieldList);
|
||||
|
||||
foreach ($fields as $field) {
|
||||
$field->setMethods($methods);
|
||||
$field->setValidationDomain($model->validationDomain);
|
||||
$data = isset($model->data[$model->alias]) ? $model->data[$model->alias] : array();
|
||||
$errors = $field->validate($data, $exists);
|
||||
foreach ($errors as $error) {
|
||||
$this->invalidate($field->field, $error);
|
||||
}
|
||||
}
|
||||
|
||||
$model->getEventManager()->dispatch(new CakeEvent('Model.afterValidate', $model));
|
||||
return $model->validationErrors;
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks a field as invalid, optionally setting a message explaining
|
||||
* why the rule failed
|
||||
*
|
||||
* @param string $field The name of the field to invalidate
|
||||
* @param string $message Validation message explaining why the rule failed, defaults to true.
|
||||
* @return void
|
||||
*/
|
||||
public function invalidate($field, $message = true) {
|
||||
$this->getModel()->validationErrors[$field][] = $message;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all possible custom methods from the Model and attached Behaviors
|
||||
* to be used as validators
|
||||
*
|
||||
* @return array List of callables to be used as validation methods
|
||||
*/
|
||||
public function getMethods() {
|
||||
$behaviors = $this->_model->Behaviors->enabled();
|
||||
if (!empty($this->_methods) && $behaviors === $this->_behaviors) {
|
||||
return $this->_methods;
|
||||
}
|
||||
$this->_behaviors = $behaviors;
|
||||
|
||||
if (empty($this->_modelMethods)) {
|
||||
foreach (get_class_methods($this->_model) as $method) {
|
||||
$this->_modelMethods[strtolower($method)] = array($this->_model, $method);
|
||||
}
|
||||
}
|
||||
|
||||
$methods = $this->_modelMethods;
|
||||
foreach (array_keys($this->_model->Behaviors->methods()) as $method) {
|
||||
$methods += array(strtolower($method) => array($this->_model, $method));
|
||||
}
|
||||
|
||||
return $this->_methods = $methods;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a CakeValidationSet object containing all validation rules for a field, if no
|
||||
* params are passed then it returns an array with all CakeValidationSet objects for each field
|
||||
*
|
||||
* @param string $name [optional] The fieldname to fetch. Defaults to null.
|
||||
* @return CakeValidationSet|array
|
||||
*/
|
||||
public function getField($name = null) {
|
||||
$this->_parseRules();
|
||||
if ($name !== null) {
|
||||
if (!empty($this->_fields[$name])) {
|
||||
return $this->_fields[$name];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
return $this->_fields;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the CakeValidationSet objects from the `Model::$validate` property
|
||||
* If `Model::$validate` is not set or empty, this method returns false. True otherwise.
|
||||
*
|
||||
* @return bool true if `Model::$validate` was processed, false otherwise
|
||||
*/
|
||||
protected function _parseRules() {
|
||||
if ($this->_validate === $this->_model->validate) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (empty($this->_model->validate)) {
|
||||
$this->_validate = array();
|
||||
$this->_fields = array();
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->_validate = $this->_model->validate;
|
||||
$this->_fields = array();
|
||||
$methods = $this->getMethods();
|
||||
foreach ($this->_validate as $fieldName => $ruleSet) {
|
||||
$this->_fields[$fieldName] = new CakeValidationSet($fieldName, $ruleSet);
|
||||
$this->_fields[$fieldName]->setMethods($methods);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the I18n domain for validation messages. This method is chainable.
|
||||
*
|
||||
* @param string $validationDomain [optional] The validation domain to be used.
|
||||
* @return $this
|
||||
*/
|
||||
public function setValidationDomain($validationDomain = null) {
|
||||
if (empty($validationDomain)) {
|
||||
$validationDomain = 'default';
|
||||
}
|
||||
$this->getModel()->validationDomain = $validationDomain;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the model related to this validator
|
||||
*
|
||||
* @return Model
|
||||
*/
|
||||
public function getModel() {
|
||||
return $this->_model;
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes the passed fieldList and returns the list of fields to be validated
|
||||
*
|
||||
* @param array $fieldList list of fields to be used for validation
|
||||
* @return array List of validation rules to be applied
|
||||
*/
|
||||
protected function _validationList($fieldList = array()) {
|
||||
if (empty($fieldList) || Hash::dimensions($fieldList) > 1) {
|
||||
return $this->_fields;
|
||||
}
|
||||
|
||||
$validateList = array();
|
||||
$this->validationErrors = array();
|
||||
foreach ((array)$fieldList as $f) {
|
||||
if (!empty($this->_fields[$f])) {
|
||||
$validateList[$f] = $this->_fields[$f];
|
||||
}
|
||||
}
|
||||
|
||||
return $validateList;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs validation for hasAndBelongsToMany associations that have 'with' keys
|
||||
* set and data in the data set.
|
||||
*
|
||||
* @param array $options Array of options to use on Validation of with models
|
||||
* @return bool Failure of validation on with models.
|
||||
* @see Model::validates()
|
||||
*/
|
||||
protected function _validateWithModels($options) {
|
||||
$valid = true;
|
||||
$model = $this->getModel();
|
||||
|
||||
foreach ($model->hasAndBelongsToMany as $assoc => $association) {
|
||||
if (empty($association['with']) || !isset($model->data[$assoc])) {
|
||||
continue;
|
||||
}
|
||||
list($join) = $model->joinModel($model->hasAndBelongsToMany[$assoc]['with']);
|
||||
$data = $model->data[$assoc];
|
||||
|
||||
$newData = array();
|
||||
foreach ((array)$data as $row) {
|
||||
if (isset($row[$model->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
|
||||
$newData[] = $row;
|
||||
} elseif (isset($row[$join]) && isset($row[$join][$model->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
|
||||
$newData[] = $row[$join];
|
||||
}
|
||||
}
|
||||
foreach ($newData as $data) {
|
||||
$data[$model->hasAndBelongsToMany[$assoc]['foreignKey']] = $model->id;
|
||||
$model->{$join}->create($data);
|
||||
$valid = ($valid && $model->{$join}->validator()->validates($options));
|
||||
}
|
||||
}
|
||||
return $valid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Propagates beforeValidate event
|
||||
*
|
||||
* @param array $options Options to pass to callback.
|
||||
* @return bool
|
||||
*/
|
||||
protected function _triggerBeforeValidate($options = array()) {
|
||||
$model = $this->getModel();
|
||||
$event = new CakeEvent('Model.beforeValidate', $model, array($options));
|
||||
list($event->break, $event->breakOn) = array(true, false);
|
||||
$model->getEventManager()->dispatch($event);
|
||||
if ($event->isStopped()) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether a rule set is defined for a field or not
|
||||
*
|
||||
* @param string $field name of the field to check
|
||||
* @return bool
|
||||
*/
|
||||
public function offsetExists($field) {
|
||||
$this->_parseRules();
|
||||
return isset($this->_fields[$field]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the rule set for a field
|
||||
*
|
||||
* @param string $field name of the field to check
|
||||
* @return CakeValidationSet
|
||||
*/
|
||||
public function offsetGet($field) {
|
||||
$this->_parseRules();
|
||||
return $this->_fields[$field];
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the rule set for a field
|
||||
*
|
||||
* @param string $field name of the field to set
|
||||
* @param array|CakeValidationSet $rules set of rules to apply to field
|
||||
* @return void
|
||||
*/
|
||||
public function offsetSet($field, $rules) {
|
||||
$this->_parseRules();
|
||||
if (!$rules instanceof CakeValidationSet) {
|
||||
$rules = new CakeValidationSet($field, $rules);
|
||||
$methods = $this->getMethods();
|
||||
$rules->setMethods($methods);
|
||||
}
|
||||
$this->_fields[$field] = $rules;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unsets the rule set for a field
|
||||
*
|
||||
* @param string $field name of the field to unset
|
||||
* @return void
|
||||
*/
|
||||
public function offsetUnset($field) {
|
||||
$this->_parseRules();
|
||||
unset($this->_fields[$field]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an iterator for each of the fields to be validated
|
||||
*
|
||||
* @return ArrayIterator
|
||||
*/
|
||||
public function getIterator() {
|
||||
$this->_parseRules();
|
||||
return new ArrayIterator($this->_fields);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of fields having validation rules
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function count() {
|
||||
$this->_parseRules();
|
||||
return count($this->_fields);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a new rule to a field's rule set. If second argument is an array or instance of
|
||||
* CakeValidationSet then rules list for the field will be replaced with second argument and
|
||||
* third argument will be ignored.
|
||||
*
|
||||
* ## Example:
|
||||
*
|
||||
* {{{
|
||||
* $validator
|
||||
* ->add('title', 'required', array('rule' => 'notEmpty', 'required' => true))
|
||||
* ->add('user_id', 'valid', array('rule' => 'numeric', 'message' => 'Invalid User'))
|
||||
*
|
||||
* $validator->add('password', array(
|
||||
* 'size' => array('rule' => array('between', 8, 20)),
|
||||
* 'hasSpecialCharacter' => array('rule' => 'validateSpecialchar', 'message' => 'not valid')
|
||||
* ));
|
||||
* }}}
|
||||
*
|
||||
* @param string $field The name of the field where the rule is to be added
|
||||
* @param string|array|CakeValidationSet $name name of the rule to be added or list of rules for the field
|
||||
* @param array|CakeValidationRule $rule or list of rules to be added to the field's rule set
|
||||
* @return $this
|
||||
*/
|
||||
public function add($field, $name, $rule = null) {
|
||||
$this->_parseRules();
|
||||
if ($name instanceof CakeValidationSet) {
|
||||
$this->_fields[$field] = $name;
|
||||
return $this;
|
||||
}
|
||||
|
||||
if (!isset($this->_fields[$field])) {
|
||||
$rule = (is_string($name)) ? array($name => $rule) : $name;
|
||||
$this->_fields[$field] = new CakeValidationSet($field, $rule);
|
||||
} else {
|
||||
if (is_string($name)) {
|
||||
$this->_fields[$field]->setRule($name, $rule);
|
||||
} else {
|
||||
$this->_fields[$field]->setRules($name);
|
||||
}
|
||||
}
|
||||
|
||||
$methods = $this->getMethods();
|
||||
$this->_fields[$field]->setMethods($methods);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a rule from the set by its name
|
||||
*
|
||||
* ## Example:
|
||||
*
|
||||
* {{{
|
||||
* $validator
|
||||
* ->remove('title', 'required')
|
||||
* ->remove('user_id')
|
||||
* }}}
|
||||
*
|
||||
* @param string $field The name of the field from which the rule will be removed
|
||||
* @param string $rule the name of the rule to be removed
|
||||
* @return $this
|
||||
*/
|
||||
public function remove($field, $rule = null) {
|
||||
$this->_parseRules();
|
||||
if ($rule === null) {
|
||||
unset($this->_fields[$field]);
|
||||
} else {
|
||||
$this->_fields[$field]->removeRule($rule);
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
257
lib/Cake/Model/Permission.php
Normal file
257
lib/Cake/Model/Permission.php
Normal file
|
|
@ -0,0 +1,257 @@
|
|||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @package Cake.Model
|
||||
* @since CakePHP(tm) v 0.2.9
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
App::uses('AppModel', 'Model');
|
||||
|
||||
/**
|
||||
* Permissions linking AROs with ACOs
|
||||
*
|
||||
* @package Cake.Model
|
||||
*/
|
||||
class Permission extends AppModel {
|
||||
|
||||
/**
|
||||
* Explicitly disable in-memory query caching
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
public $cacheQueries = false;
|
||||
|
||||
/**
|
||||
* Override default table name
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $useTable = 'aros_acos';
|
||||
|
||||
/**
|
||||
* Permissions link AROs with ACOs
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $belongsTo = array('Aro', 'Aco');
|
||||
|
||||
/**
|
||||
* No behaviors for this model
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $actsAs = null;
|
||||
|
||||
/**
|
||||
* Constructor, used to tell this model to use the
|
||||
* database configured for ACL
|
||||
*/
|
||||
public function __construct() {
|
||||
$config = Configure::read('Acl.database');
|
||||
if (!empty($config)) {
|
||||
$this->useDbConfig = $config;
|
||||
}
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the given $aro has access to action $action in $aco
|
||||
*
|
||||
* @param string $aro ARO The requesting object identifier.
|
||||
* @param string $aco ACO The controlled object identifier.
|
||||
* @param string $action Action (defaults to *)
|
||||
* @return bool Success (true if ARO has access to action in ACO, false otherwise)
|
||||
*/
|
||||
public function check($aro, $aco, $action = '*') {
|
||||
if (!$aro || !$aco) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$permKeys = $this->getAcoKeys($this->schema());
|
||||
$aroPath = $this->Aro->node($aro);
|
||||
$acoPath = $this->Aco->node($aco);
|
||||
|
||||
if (!$aroPath) {
|
||||
$this->log(__d('cake_dev',
|
||||
"%s - Failed ARO node lookup in permissions check. Node references:\nAro: %s\nAco: %s",
|
||||
'DbAcl::check()',
|
||||
print_r($aro, true),
|
||||
print_r($aco, true)),
|
||||
E_USER_WARNING
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!$acoPath) {
|
||||
$this->log(__d('cake_dev',
|
||||
"%s - Failed ACO node lookup in permissions check. Node references:\nAro: %s\nAco: %s",
|
||||
'DbAcl::check()',
|
||||
print_r($aro, true),
|
||||
print_r($aco, true)),
|
||||
E_USER_WARNING
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($action !== '*' && !in_array('_' . $action, $permKeys)) {
|
||||
$this->log(__d('cake_dev', "ACO permissions key %s does not exist in %s", $action, 'DbAcl::check()'), E_USER_NOTICE);
|
||||
return false;
|
||||
}
|
||||
|
||||
$inherited = array();
|
||||
$acoIDs = Hash::extract($acoPath, '{n}.' . $this->Aco->alias . '.id');
|
||||
|
||||
$count = count($aroPath);
|
||||
for ($i = 0; $i < $count; $i++) {
|
||||
$permAlias = $this->alias;
|
||||
|
||||
$perms = $this->find('all', array(
|
||||
'conditions' => array(
|
||||
"{$permAlias}.aro_id" => $aroPath[$i][$this->Aro->alias]['id'],
|
||||
"{$permAlias}.aco_id" => $acoIDs
|
||||
),
|
||||
'order' => array($this->Aco->alias . '.lft' => 'desc'),
|
||||
'recursive' => 0
|
||||
));
|
||||
|
||||
if (empty($perms)) {
|
||||
continue;
|
||||
}
|
||||
$perms = Hash::extract($perms, '{n}.' . $this->alias);
|
||||
foreach ($perms as $perm) {
|
||||
if ($action === '*') {
|
||||
|
||||
foreach ($permKeys as $key) {
|
||||
if (!empty($perm)) {
|
||||
if ($perm[$key] == -1) {
|
||||
return false;
|
||||
} elseif ($perm[$key] == 1) {
|
||||
$inherited[$key] = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (count($inherited) === count($permKeys)) {
|
||||
return true;
|
||||
}
|
||||
} else {
|
||||
switch ($perm['_' . $action]) {
|
||||
case -1:
|
||||
return false;
|
||||
case 0:
|
||||
continue;
|
||||
case 1:
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Allow $aro to have access to action $actions in $aco
|
||||
*
|
||||
* @param string $aro ARO The requesting object identifier.
|
||||
* @param string $aco ACO The controlled object identifier.
|
||||
* @param string $actions Action (defaults to *) Invalid permissions will result in an exception
|
||||
* @param int $value Value to indicate access type (1 to give access, -1 to deny, 0 to inherit)
|
||||
* @return bool Success
|
||||
* @throws AclException on Invalid permission key.
|
||||
*/
|
||||
public function allow($aro, $aco, $actions = '*', $value = 1) {
|
||||
$perms = $this->getAclLink($aro, $aco);
|
||||
$permKeys = $this->getAcoKeys($this->schema());
|
||||
$save = array();
|
||||
|
||||
if (!$perms) {
|
||||
$this->log(__d('cake_dev', '%s - Invalid node', 'DbAcl::allow()'), E_USER_WARNING);
|
||||
return false;
|
||||
}
|
||||
if (isset($perms[0])) {
|
||||
$save = $perms[0][$this->alias];
|
||||
}
|
||||
|
||||
if ($actions === '*') {
|
||||
$save = array_combine($permKeys, array_pad(array(), count($permKeys), $value));
|
||||
} else {
|
||||
if (!is_array($actions)) {
|
||||
$actions = array('_' . $actions);
|
||||
}
|
||||
foreach ($actions as $action) {
|
||||
if ($action{0} !== '_') {
|
||||
$action = '_' . $action;
|
||||
}
|
||||
if (!in_array($action, $permKeys, true)) {
|
||||
throw new AclException(__d('cake_dev', 'Invalid permission key "%s"', $action));
|
||||
}
|
||||
$save[$action] = $value;
|
||||
}
|
||||
}
|
||||
list($save['aro_id'], $save['aco_id']) = array($perms['aro'], $perms['aco']);
|
||||
|
||||
if ($perms['link'] && !empty($perms['link'])) {
|
||||
$save['id'] = $perms['link'][0][$this->alias]['id'];
|
||||
} else {
|
||||
unset($save['id']);
|
||||
$this->id = null;
|
||||
}
|
||||
return ($this->save($save) !== false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an array of access-control links between the given Aro and Aco
|
||||
*
|
||||
* @param string $aro ARO The requesting object identifier.
|
||||
* @param string $aco ACO The controlled object identifier.
|
||||
* @return array Indexed array with: 'aro', 'aco' and 'link'
|
||||
*/
|
||||
public function getAclLink($aro, $aco) {
|
||||
$obj = array();
|
||||
$obj['Aro'] = $this->Aro->node($aro);
|
||||
$obj['Aco'] = $this->Aco->node($aco);
|
||||
|
||||
if (empty($obj['Aro']) || empty($obj['Aco'])) {
|
||||
return false;
|
||||
}
|
||||
$aro = Hash::extract($obj, 'Aro.0.' . $this->Aro->alias . '.id');
|
||||
$aco = Hash::extract($obj, 'Aco.0.' . $this->Aco->alias . '.id');
|
||||
$aro = current($aro);
|
||||
$aco = current($aco);
|
||||
|
||||
return array(
|
||||
'aro' => $aro,
|
||||
'aco' => $aco,
|
||||
'link' => $this->find('all', array('conditions' => array(
|
||||
$this->alias . '.aro_id' => $aro,
|
||||
$this->alias . '.aco_id' => $aco
|
||||
)))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the crud type keys
|
||||
*
|
||||
* @param array $keys Permission schema
|
||||
* @return array permission keys
|
||||
*/
|
||||
public function getAcoKeys($keys) {
|
||||
$newKeys = array();
|
||||
$keys = array_keys($keys);
|
||||
foreach ($keys as $key) {
|
||||
if (!in_array($key, array('id', 'aro_id', 'aco_id'))) {
|
||||
$newKeys[] = $key;
|
||||
}
|
||||
}
|
||||
return $newKeys;
|
||||
}
|
||||
}
|
||||
350
lib/Cake/Model/Validator/CakeValidationRule.php
Normal file
350
lib/Cake/Model/Validator/CakeValidationRule.php
Normal file
|
|
@ -0,0 +1,350 @@
|
|||
<?php
|
||||
/**
|
||||
* CakeValidationRule.
|
||||
*
|
||||
* Provides the Model validation logic.
|
||||
*
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @package Cake.Model.Validator
|
||||
* @since CakePHP(tm) v 2.2.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
App::uses('Validation', 'Utility');
|
||||
|
||||
/**
|
||||
* CakeValidationRule object. Represents a validation method, error message and
|
||||
* rules for applying such method to a field.
|
||||
*
|
||||
* @package Cake.Model.Validator
|
||||
* @link http://book.cakephp.org/2.0/en/data-validation.html
|
||||
*/
|
||||
class CakeValidationRule {
|
||||
|
||||
/**
|
||||
* Whether the field passed this validation rule
|
||||
*
|
||||
* @var mixed
|
||||
*/
|
||||
protected $_valid = true;
|
||||
|
||||
/**
|
||||
* Holds whether the record being validated exists in datasource or not
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected $_recordExists = false;
|
||||
|
||||
/**
|
||||
* Validation method
|
||||
*
|
||||
* @var mixed
|
||||
*/
|
||||
protected $_rule = null;
|
||||
|
||||
/**
|
||||
* Validation method arguments
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_ruleParams = array();
|
||||
|
||||
/**
|
||||
* Holds passed in options
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_passedOptions = array();
|
||||
|
||||
/**
|
||||
* The 'rule' key
|
||||
*
|
||||
* @var mixed
|
||||
*/
|
||||
public $rule = 'blank';
|
||||
|
||||
/**
|
||||
* The 'required' key
|
||||
*
|
||||
* @var mixed
|
||||
*/
|
||||
public $required = null;
|
||||
|
||||
/**
|
||||
* The 'allowEmpty' key
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
public $allowEmpty = null;
|
||||
|
||||
/**
|
||||
* The 'on' key
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $on = null;
|
||||
|
||||
/**
|
||||
* The 'last' key
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
public $last = true;
|
||||
|
||||
/**
|
||||
* The 'message' key
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $message = null;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param array $validator [optional] The validator properties
|
||||
*/
|
||||
public function __construct($validator = array()) {
|
||||
$this->_addValidatorProps($validator);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the rule is valid
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isValid() {
|
||||
if (!$this->_valid || (is_string($this->_valid) && !empty($this->_valid))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the field can be left blank according to this rule
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isEmptyAllowed() {
|
||||
return $this->skip() || $this->allowEmpty === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the field is required according to the `required` property
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isRequired() {
|
||||
if (in_array($this->required, array('create', 'update'), true)) {
|
||||
if ($this->required === 'create' && !$this->isUpdate() || $this->required === 'update' && $this->isUpdate()) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->required;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the field failed the `field should be present` validation
|
||||
*
|
||||
* @param string $field Field name
|
||||
* @param array &$data Data to check rule against
|
||||
* @return bool
|
||||
*/
|
||||
public function checkRequired($field, &$data) {
|
||||
return (
|
||||
(!array_key_exists($field, $data) && $this->isRequired() === true) ||
|
||||
(
|
||||
array_key_exists($field, $data) && (empty($data[$field]) &&
|
||||
!is_numeric($data[$field])) && $this->allowEmpty === false
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the allowEmpty key applies
|
||||
*
|
||||
* @param string $field Field name
|
||||
* @param array &$data data to check rule against
|
||||
* @return bool
|
||||
*/
|
||||
public function checkEmpty($field, &$data) {
|
||||
if (empty($data[$field]) && $data[$field] != '0' && $this->allowEmpty === true) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the validation rule should be skipped
|
||||
*
|
||||
* @return bool True if the ValidationRule can be skipped
|
||||
*/
|
||||
public function skip() {
|
||||
if (!empty($this->on)) {
|
||||
if ($this->on === 'create' && $this->isUpdate() || $this->on === 'update' && !$this->isUpdate()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether this rule should break validation process for associated field
|
||||
* after it fails
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isLast() {
|
||||
return (bool)$this->last;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the validation error message
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getValidationResult() {
|
||||
return $this->_valid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets an array with the rule properties
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function _getPropertiesArray() {
|
||||
$rule = $this->rule;
|
||||
if (!is_string($rule)) {
|
||||
unset($rule[0]);
|
||||
}
|
||||
return array(
|
||||
'rule' => $rule,
|
||||
'required' => $this->required,
|
||||
'allowEmpty' => $this->allowEmpty,
|
||||
'on' => $this->on,
|
||||
'last' => $this->last,
|
||||
'message' => $this->message
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the recordExists configuration value for this rule,
|
||||
* ir refers to whether the model record it is validating exists
|
||||
* exists in the collection or not (create or update operation)
|
||||
*
|
||||
* If called with no parameters it will return whether this rule
|
||||
* is configured for update operations or not.
|
||||
*
|
||||
* @param bool $exists Boolean to indicate if records exists
|
||||
* @return bool
|
||||
*/
|
||||
public function isUpdate($exists = null) {
|
||||
if ($exists === null) {
|
||||
return $this->_recordExists;
|
||||
}
|
||||
return $this->_recordExists = $exists;
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispatches the validation rule to the given validator method
|
||||
*
|
||||
* @param string $field Field name
|
||||
* @param array &$data Data array
|
||||
* @param array &$methods Methods list
|
||||
* @return bool True if the rule could be dispatched, false otherwise
|
||||
*/
|
||||
public function process($field, &$data, &$methods) {
|
||||
$this->_valid = true;
|
||||
$this->_parseRule($field, $data);
|
||||
|
||||
$validator = $this->_getPropertiesArray();
|
||||
$rule = strtolower($this->_rule);
|
||||
if (isset($methods[$rule])) {
|
||||
$this->_ruleParams[] = array_merge($validator, $this->_passedOptions);
|
||||
$this->_ruleParams[0] = array($field => $this->_ruleParams[0]);
|
||||
$this->_valid = call_user_func_array($methods[$rule], $this->_ruleParams);
|
||||
} elseif (class_exists('Validation') && method_exists('Validation', $this->_rule)) {
|
||||
$this->_valid = call_user_func_array(array('Validation', $this->_rule), $this->_ruleParams);
|
||||
} elseif (is_string($validator['rule'])) {
|
||||
$this->_valid = preg_match($this->_rule, $data[$field]);
|
||||
} else {
|
||||
trigger_error(__d('cake_dev', 'Could not find validation handler %s for %s', $this->_rule, $field), E_USER_WARNING);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets internal state for this rule, by default it will become valid
|
||||
* and it will set isUpdate() to false
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function reset() {
|
||||
$this->_valid = true;
|
||||
$this->_recordExists = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns passed options for this rule
|
||||
*
|
||||
* @param string|int $key Array index
|
||||
* @return array
|
||||
*/
|
||||
public function getOptions($key) {
|
||||
if (!isset($this->_passedOptions[$key])) {
|
||||
return null;
|
||||
}
|
||||
return $this->_passedOptions[$key];
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the rule properties from the rule entry in validate
|
||||
*
|
||||
* @param array $validator [optional]
|
||||
* @return void
|
||||
*/
|
||||
protected function _addValidatorProps($validator = array()) {
|
||||
if (!is_array($validator)) {
|
||||
$validator = array('rule' => $validator);
|
||||
}
|
||||
foreach ($validator as $key => $value) {
|
||||
if (isset($value) || !empty($value)) {
|
||||
if (in_array($key, array('rule', 'required', 'allowEmpty', 'on', 'message', 'last'))) {
|
||||
$this->{$key} = $validator[$key];
|
||||
} else {
|
||||
$this->_passedOptions[$key] = $value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the rule and sets the rule and ruleParams
|
||||
*
|
||||
* @param string $field Field name
|
||||
* @param array &$data Data array
|
||||
* @return void
|
||||
*/
|
||||
protected function _parseRule($field, &$data) {
|
||||
if (is_array($this->rule)) {
|
||||
$this->_rule = $this->rule[0];
|
||||
$this->_ruleParams = array_merge(array($data[$field]), array_values(array_slice($this->rule, 1)));
|
||||
} else {
|
||||
$this->_rule = $this->rule;
|
||||
$this->_ruleParams = array($data[$field]);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
370
lib/Cake/Model/Validator/CakeValidationSet.php
Normal file
370
lib/Cake/Model/Validator/CakeValidationSet.php
Normal file
|
|
@ -0,0 +1,370 @@
|
|||
<?php
|
||||
/**
|
||||
* CakeValidationSet.
|
||||
*
|
||||
* Provides the Model validation logic.
|
||||
*
|
||||
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
|
||||
* @link http://cakephp.org CakePHP(tm) Project
|
||||
* @package Cake.Model.Validator
|
||||
* @since CakePHP(tm) v 2.2.0
|
||||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
App::uses('CakeValidationRule', 'Model/Validator');
|
||||
|
||||
/**
|
||||
* CakeValidationSet object. Holds all validation rules for a field and exposes
|
||||
* methods to dynamically add or remove validation rules
|
||||
*
|
||||
* @package Cake.Model.Validator
|
||||
* @link http://book.cakephp.org/2.0/en/data-validation.html
|
||||
*/
|
||||
class CakeValidationSet implements ArrayAccess, IteratorAggregate, Countable {
|
||||
|
||||
/**
|
||||
* Holds the CakeValidationRule objects
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_rules = array();
|
||||
|
||||
/**
|
||||
* List of methods available for validation
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $_methods = array();
|
||||
|
||||
/**
|
||||
* I18n domain for validation messages.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $_validationDomain = null;
|
||||
|
||||
/**
|
||||
* Whether the validation is stopped
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
public $isStopped = false;
|
||||
|
||||
/**
|
||||
* Holds the fieldname
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $field = null;
|
||||
|
||||
/**
|
||||
* Holds the original ruleSet
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $ruleSet = array();
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param string $fieldName The fieldname.
|
||||
* @param array $ruleSet Rules set.
|
||||
*/
|
||||
public function __construct($fieldName, $ruleSet) {
|
||||
$this->field = $fieldName;
|
||||
|
||||
if (!is_array($ruleSet) || (is_array($ruleSet) && isset($ruleSet['rule']))) {
|
||||
$ruleSet = array($ruleSet);
|
||||
}
|
||||
|
||||
foreach ($ruleSet as $index => $validateProp) {
|
||||
$this->_rules[$index] = new CakeValidationRule($validateProp);
|
||||
}
|
||||
$this->ruleSet = $ruleSet;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the list of methods to use for validation
|
||||
*
|
||||
* @param array &$methods Methods list
|
||||
* @return void
|
||||
*/
|
||||
public function setMethods(&$methods) {
|
||||
$this->_methods =& $methods;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the I18n domain for validation messages.
|
||||
*
|
||||
* @param string $validationDomain The validation domain to be used.
|
||||
* @return void
|
||||
*/
|
||||
public function setValidationDomain($validationDomain) {
|
||||
$this->_validationDomain = $validationDomain;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs all validation rules in this set and returns a list of
|
||||
* validation errors
|
||||
*
|
||||
* @param array $data Data array
|
||||
* @param bool $isUpdate Is record being updated or created
|
||||
* @return array list of validation errors for this field
|
||||
*/
|
||||
public function validate($data, $isUpdate = false) {
|
||||
$this->reset();
|
||||
$errors = array();
|
||||
foreach ($this->getRules() as $name => $rule) {
|
||||
$rule->isUpdate($isUpdate);
|
||||
if ($rule->skip()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$checkRequired = $rule->checkRequired($this->field, $data);
|
||||
if (!$checkRequired && array_key_exists($this->field, $data)) {
|
||||
if ($rule->checkEmpty($this->field, $data)) {
|
||||
break;
|
||||
}
|
||||
$rule->process($this->field, $data, $this->_methods);
|
||||
}
|
||||
|
||||
if ($checkRequired || !$rule->isValid()) {
|
||||
$errors[] = $this->_processValidationResponse($name, $rule);
|
||||
if ($rule->isLast()) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $errors;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets internal state for all validation rules in this set
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function reset() {
|
||||
foreach ($this->getRules() as $rule) {
|
||||
$rule->reset();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a rule for a given name if exists
|
||||
*
|
||||
* @param string $name Field name.
|
||||
* @return CakeValidationRule
|
||||
*/
|
||||
public function getRule($name) {
|
||||
if (!empty($this->_rules[$name])) {
|
||||
return $this->_rules[$name];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all rules for this validation set
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getRules() {
|
||||
return $this->_rules;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a CakeValidationRule $rule with a $name
|
||||
*
|
||||
* ## Example:
|
||||
*
|
||||
* {{{
|
||||
* $set
|
||||
* ->setRule('required', array('rule' => 'notEmpty', 'required' => true))
|
||||
* ->setRule('inRange', array('rule' => array('between', 4, 10))
|
||||
* }}}
|
||||
*
|
||||
* @param string $name The name under which the rule should be set
|
||||
* @param CakeValidationRule|array $rule The validation rule to be set
|
||||
* @return $this
|
||||
*/
|
||||
public function setRule($name, $rule) {
|
||||
if (!($rule instanceof CakeValidationRule)) {
|
||||
$rule = new CakeValidationRule($rule);
|
||||
}
|
||||
$this->_rules[$name] = $rule;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a validation rule from the set
|
||||
*
|
||||
* ## Example:
|
||||
*
|
||||
* {{{
|
||||
* $set
|
||||
* ->removeRule('required')
|
||||
* ->removeRule('inRange')
|
||||
* }}}
|
||||
*
|
||||
* @param string $name The name under which the rule should be unset
|
||||
* @return $this
|
||||
*/
|
||||
public function removeRule($name) {
|
||||
unset($this->_rules[$name]);
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the rules for a given field
|
||||
*
|
||||
* ## Example:
|
||||
*
|
||||
* {{{
|
||||
* $set->setRules(array(
|
||||
* 'required' => array('rule' => 'notEmpty', 'required' => true),
|
||||
* 'inRange' => array('rule' => array('between', 4, 10)
|
||||
* ));
|
||||
* }}}
|
||||
*
|
||||
* @param array $rules The rules to be set
|
||||
* @param bool $mergeVars [optional] If true, merges vars instead of replace. Defaults to true.
|
||||
* @return $this
|
||||
*/
|
||||
public function setRules($rules = array(), $mergeVars = true) {
|
||||
if ($mergeVars === false) {
|
||||
$this->_rules = array();
|
||||
}
|
||||
foreach ($rules as $name => $rule) {
|
||||
$this->setRule($name, $rule);
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the correct error message for a failed validation
|
||||
*
|
||||
* @param string $name the name of the rule as it was configured
|
||||
* @param CakeValidationRule $rule the object containing validation information
|
||||
* @return string
|
||||
*/
|
||||
protected function _processValidationResponse($name, $rule) {
|
||||
$message = $rule->getValidationResult();
|
||||
if (is_string($message)) {
|
||||
return $message;
|
||||
}
|
||||
$message = $rule->message;
|
||||
|
||||
if ($message !== null) {
|
||||
$args = null;
|
||||
if (is_array($message)) {
|
||||
$result = $message[0];
|
||||
$args = array_slice($message, 1);
|
||||
} else {
|
||||
$result = $message;
|
||||
}
|
||||
if (is_array($rule->rule) && $args === null) {
|
||||
$args = array_slice($rule->rule, 1);
|
||||
}
|
||||
$args = $this->_translateArgs($args);
|
||||
|
||||
$message = __d($this->_validationDomain, $result, $args);
|
||||
} elseif (is_string($name)) {
|
||||
if (is_array($rule->rule)) {
|
||||
$args = array_slice($rule->rule, 1);
|
||||
$args = $this->_translateArgs($args);
|
||||
$message = __d($this->_validationDomain, $name, $args);
|
||||
} else {
|
||||
$message = __d($this->_validationDomain, $name);
|
||||
}
|
||||
} else {
|
||||
$message = __d('cake', 'This field cannot be left blank');
|
||||
}
|
||||
|
||||
return $message;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies translations to validator arguments.
|
||||
*
|
||||
* @param array $args The args to translate
|
||||
* @return array Translated args.
|
||||
*/
|
||||
protected function _translateArgs($args) {
|
||||
foreach ((array)$args as $k => $arg) {
|
||||
if (is_string($arg)) {
|
||||
$args[$k] = __d($this->_validationDomain, $arg);
|
||||
}
|
||||
}
|
||||
return $args;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether an index exists in the rule set
|
||||
*
|
||||
* @param string $index name of the rule
|
||||
* @return bool
|
||||
*/
|
||||
public function offsetExists($index) {
|
||||
return isset($this->_rules[$index]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a rule object by its index
|
||||
*
|
||||
* @param string $index name of the rule
|
||||
* @return CakeValidationRule
|
||||
*/
|
||||
public function offsetGet($index) {
|
||||
return $this->_rules[$index];
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets or replace a validation rule.
|
||||
*
|
||||
* This is a wrapper for ArrayAccess. Use setRule() directly for
|
||||
* chainable access.
|
||||
*
|
||||
* @param string $index Name of the rule.
|
||||
* @param CakeValidationRule|array $rule Rule to add to $index.
|
||||
* @return void
|
||||
* @see http://www.php.net/manual/en/arrayobject.offsetset.php
|
||||
*/
|
||||
public function offsetSet($index, $rule) {
|
||||
$this->setRule($index, $rule);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unsets a validation rule
|
||||
*
|
||||
* @param string $index name of the rule
|
||||
* @return void
|
||||
*/
|
||||
public function offsetUnset($index) {
|
||||
unset($this->_rules[$index]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an iterator for each of the rules to be applied
|
||||
*
|
||||
* @return ArrayIterator
|
||||
*/
|
||||
public function getIterator() {
|
||||
return new ArrayIterator($this->_rules);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of rules in this set
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function count() {
|
||||
return count($this->_rules);
|
||||
}
|
||||
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue