Upgrade CakePHP from 2.2.5 to 2.9.5

This commit is contained in:
Brm Ko 2017-02-26 15:29:44 +01:00
parent 5a580df460
commit 235a541597
793 changed files with 60746 additions and 23753 deletions

View file

@ -1,19 +1,17 @@
<?php
/**
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.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 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @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 MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Model', 'Model');
@ -28,7 +26,7 @@ class AclNode extends Model {
/**
* Explicitly disable in-memory query caching for ACL models
*
* @var boolean
* @var bool
*/
public $cacheQueries = false;
@ -42,13 +40,17 @@ class AclNode extends Model {
/**
* Constructor
*
* @param bool|int|string|array $id Set this ID for this model on startup,
* can also be an array of options, see above.
* @param string $table Name of database table to use.
* @param string $ds DataSource connection name.
*/
public function __construct() {
public function __construct($id = false, $table = null, $ds = null) {
$config = Configure::read('Acl.database');
if (isset($config)) {
$this->useDbConfig = $config;
}
parent::__construct();
parent::__construct($id, $table, $ds);
}
/**
@ -84,47 +86,51 @@ class AclNode extends Model {
'joins' => array(array(
'table' => $table,
'alias' => "{$type}0",
'type' => 'LEFT',
'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' => 'LEFT',
'type' => 'INNER',
'conditions' => array(
$db->name("{$type}{$i}.lft") . ' > ' . $db->name("{$type}{$j}.lft"),
$db->name("{$type}{$i}.rght") . ' < ' . $db->name("{$type}{$j}.rght"),
$db->name("{$type}{$i}.alias") . ' = ' . $db->value($alias, 'string'),
$db->name("{$type}{$j}.id") . ' = ' . $db->name("{$type}{$i}.parent_id")
"{$type}{$i}.alias" => $alias
)
);
// 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]) ||
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) && is_a($ref, 'Model')) {
} 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($plugin, $alias) = pluginSplit($name);
list(, $alias) = pluginSplit($name);
$model = ClassRegistry::init(array('class' => $name, 'alias' => $alias));
@ -162,7 +168,7 @@ class AclNode extends Model {
'joins' => array(array(
'table' => $table,
'alias' => "{$type}0",
'type' => 'LEFT',
'type' => 'INNER',
'conditions' => array(
$db->name("{$type}.lft") . ' <= ' . $db->name("{$type}0.lft"),
$db->name("{$type}.rght") . ' >= ' . $db->name("{$type}0.rght")

View file

@ -1,19 +1,17 @@
<?php
/**
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.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 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @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 MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('AclNode', 'Model');
@ -38,4 +36,4 @@ class Aco extends AclNode {
* @var array
*/
public $hasAndBelongsToMany = array('Aro' => array('with' => 'Permission'));
}
}

View file

@ -1,19 +1,17 @@
<?php
/**
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.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 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @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 MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('AppModel', 'Model');
@ -38,4 +36,4 @@ class AcoAction extends AppModel {
* @var array
*/
public $belongsTo = array('Aco');
}
}

View file

@ -1,19 +1,17 @@
<?php
/**
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.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 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @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 MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('AclNode', 'Model');

View file

@ -4,20 +4,21 @@
*
* Enables objects to easily tie into an ACL system
*
* PHP 5
*
* CakePHP : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc.
* 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 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @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 MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ModelBehavior', 'Model');
App::uses('AclNode', 'Model');
App::uses('Hash', 'Utility');
@ -41,8 +42,8 @@ class AclBehavior extends ModelBehavior {
/**
* Sets up the configuration for the model, and loads ACL models if they haven't been already
*
* @param Model $model
* @param array $config
* @param Model $model Model using this behavior.
* @param array $config Configuration options.
* @return void
*/
public function setup(Model $model, $config = array()) {
@ -62,14 +63,14 @@ class AclBehavior extends ModelBehavior {
$model->{$type} = ClassRegistry::init($type);
}
if (!method_exists($model, 'parentNode')) {
trigger_error(__d('cake_dev', 'Callback parentNode() not defined in %s', $model->alias), E_USER_WARNING);
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
* @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
@ -80,7 +81,7 @@ class AclBehavior extends ModelBehavior {
$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;
return array();
}
}
if (empty($ref)) {
@ -92,17 +93,18 @@ class AclBehavior extends ModelBehavior {
/**
* Creates a new ARO/ACO node bound to this record
*
* @param Model $model
* @param boolean $created True if this is a new 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) {
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();
$parent = $model->parentNode($type);
if (!empty($parent)) {
$parent = $this->node($model, $parent, $type);
}
@ -123,7 +125,7 @@ class AclBehavior extends ModelBehavior {
/**
* Destroys the ARO/ACO node bound to the deleted record
*
* @param Model $model
* @param Model $model Model using this behavior.
* @return void
*/
public function afterDelete(Model $model) {

View file

@ -4,21 +4,22 @@
*
* Behavior to simplify manipulating a model's bindings when doing a find operation
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.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 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @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 MIT License (http://www.opensource.org/licenses/mit-license.php)
* @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
@ -74,7 +75,7 @@ class ContainableBehavior extends ModelBehavior {
*
* `Model->find('all', array('contain' => array('Model1', 'Model2')));`
*
* {{{
* ```
* Model->find('all', array('contain' => array(
* 'Model1' => array('Model11', 'Model12'),
* 'Model2',
@ -83,9 +84,9 @@ class ContainableBehavior extends ModelBehavior {
* 'Model32',
* 'Model33' => array('Model331', 'Model332')
* )));
* }}}
* ```
*
* @param Model $Model Model using the behavior
* @param Model $Model Model using the behavior
* @param array $query Query parameters as set by cake
* @return array
*/
@ -108,9 +109,7 @@ class ContainableBehavior extends ModelBehavior {
}
$noContain = $noContain && empty($contain);
if (
$noContain || empty($contain) || (isset($contain[0]) && $contain[0] === null)
) {
if ($noContain || empty($contain)) {
if ($noContain) {
$query['recursive'] = -1;
}
@ -125,7 +124,7 @@ class ContainableBehavior extends ModelBehavior {
$map = $this->containmentsMap($containments);
$mandatory = array();
foreach ($containments['models'] as $name => $model) {
foreach ($containments['models'] as $model) {
$instance = $model['instance'];
$needed = $this->fieldDependencies($instance, $map, false);
if (!empty($needed)) {
@ -174,7 +173,7 @@ class ContainableBehavior extends ModelBehavior {
}
if ($this->settings[$Model->alias]['recursive']) {
$query['recursive'] = (isset($query['recursive'])) ? $query['recursive'] : $containments['depth'];
$query['recursive'] = (isset($query['recursive'])) ? max($query['recursive'], $containments['depth']) : $containments['depth'];
}
$autoFields = ($this->settings[$Model->alias]['autoFields']
@ -189,7 +188,7 @@ class ContainableBehavior extends ModelBehavior {
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'])) {
if ($Model->useDbConfig === $Model->{$assoc}->useDbConfig && !empty($data['fields'])) {
foreach ((array)$data['fields'] as $field) {
$query['fields'][] = (strpos($field, '.') === false ? $assoc . '.' : '') . $field;
}
@ -200,11 +199,11 @@ class ContainableBehavior extends ModelBehavior {
if (!empty($mandatory[$Model->alias])) {
foreach ($mandatory[$Model->alias] as $field) {
if ($field == '--primaryKey--') {
if ($field === '--primaryKey--') {
$field = $Model->primaryKey;
} elseif (preg_match('/^.+\.\-\-[^-]+\-\-$/', $field)) {
list($modelName, $field) = explode('.', $field);
if ($Model->useDbConfig == $Model->{$modelName}->useDbConfig) {
if ($Model->useDbConfig === $Model->{$modelName}->useDbConfig) {
$field = $modelName . '.' . (
($field === '--primaryKey--') ? $Model->$modelName->primaryKey : $field
);
@ -264,11 +263,11 @@ class ContainableBehavior extends ModelBehavior {
* @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 boolean $throwErrors Whether non-existent bindings show throw errors
* @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', 'deleteQuery', 'insertQuery');
$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']);
@ -307,7 +306,7 @@ class ContainableBehavior extends ModelBehavior {
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} == '(') {
if ($key{0} === '(') {
$val = preg_split('/\s*,\s*/', substr($key, 1, -1));
} elseif (preg_match('/ASC|DESC$/', $key)) {
$option = 'order';
@ -366,7 +365,7 @@ class ContainableBehavior extends ModelBehavior {
*
* @param Model $Model Model
* @param array $map Map of relations for given model
* @param array|boolean $fields If array, fields to initially load, if false use $Model as primary 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()) {
@ -374,9 +373,9 @@ class ContainableBehavior extends ModelBehavior {
foreach ($map as $parent => $children) {
foreach ($children as $type => $bindings) {
foreach ($bindings as $dependency) {
if ($type == 'hasAndBelongsToMany') {
if ($type === 'hasAndBelongsToMany') {
$fields[$parent][] = '--primaryKey--';
} elseif ($type == 'belongsTo') {
} elseif ($type === 'belongsTo') {
$fields[$parent][] = $dependency . '.--primaryKey--';
}
}

View file

@ -1,18 +1,20 @@
<?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.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 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @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 MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ModelBehavior', 'Model');
App::uses('I18n', 'I18n');
App::uses('I18nModel', 'Model');
@ -119,7 +121,7 @@ class TranslateBehavior extends ModelBehavior {
$this->_joinTable = $joinTable;
$this->_runtimeModel = $RuntimeModel;
if (is_string($query['fields']) && "COUNT(*) AS {$db->name('count')}" == $query['fields']) {
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',
@ -128,7 +130,7 @@ class TranslateBehavior extends ModelBehavior {
'conditions' => array(
$Model->escapeField() => $db->identifier($RuntimeModel->escapeField('foreign_key')),
$RuntimeModel->escapeField('model') => $Model->name,
$RuntimeModel->escapeField('locale') => $locale
$RuntimeModel->escapeField('locale') => $locale
)
);
$conditionFields = $this->_checkConditions($Model, $query);
@ -137,6 +139,8 @@ class TranslateBehavior extends ModelBehavior {
}
unset($this->_joinTable, $this->_runtimeModel);
return $query;
} elseif (is_string($query['fields'])) {
$query['fields'] = CakeText::tokenize($query['fields']);
}
$fields = array_merge(
@ -153,8 +157,7 @@ class TranslateBehavior extends ModelBehavior {
);
foreach ($fields as $key => $value) {
$field = (is_numeric($key)) ? $value : $key;
if (
$isAllFields ||
if ($isAllFields ||
in_array($Model->alias . '.' . $field, $query['fields']) ||
in_array($field, $query['fields'])
) {
@ -193,7 +196,7 @@ class TranslateBehavior extends ModelBehavior {
*/
protected function _checkConditions(Model $Model, $query) {
$conditionFields = array();
if (empty($query['conditions']) || (!empty($query['conditions']) && !is_array($query['conditions'])) ) {
if (empty($query['conditions']) || (!empty($query['conditions']) && !is_array($query['conditions']))) {
return $conditionFields;
}
foreach ($query['conditions'] as $col => $val) {
@ -213,12 +216,11 @@ class TranslateBehavior extends ModelBehavior {
* Appends a join for translated fields.
*
* @param Model $Model The model being worked on.
* @param object $joinTable The jointable object.
* @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 modfied query
* @return array The modified query
*/
protected function _addJoin(Model $Model, $query, $field, $aliasField, $locale) {
$db = ConnectionManager::getDataSource($Model->useDbConfig);
@ -271,12 +273,18 @@ class TranslateBehavior extends ModelBehavior {
*
* @param Model $Model Model find was run on
* @param array $results Array of model results.
* @param boolean $primary Did the find originate on $model.
* @param bool $primary Did the find originate on $model.
* @return array Modified results
*/
public function afterFind(Model $Model, $results, $primary) {
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'])) {
@ -304,7 +312,7 @@ class TranslateBehavior extends ModelBehavior {
}
} else {
$value = '';
if (!empty($row[$Model->alias][$aliasVirtual])) {
if (isset($row[$Model->alias][$aliasVirtual])) {
$value = $row[$Model->alias][$aliasVirtual];
}
$row[$Model->alias][$aliasField] = $value;
@ -319,9 +327,11 @@ class TranslateBehavior extends ModelBehavior {
* beforeValidate Callback
*
* @param Model $Model Model invalidFields was called on.
* @return boolean
* @param array $options Options passed from Model::save().
* @return bool
* @see Model::save()
*/
public function beforeValidate(Model $Model) {
public function beforeValidate(Model $Model, $options = array()) {
unset($this->runtime[$Model->alias]['beforeSave']);
$this->_setRuntimeData($Model);
return true;
@ -331,13 +341,15 @@ class TranslateBehavior extends ModelBehavior {
* beforeSave callback.
*
* Copies data into the runtime property when `$options['validate']` is
* disabled. Or the runtime data hasn't been set yet.
* disabled. Or the runtime data hasn't been set yet.
*
* @param Model $Model Model save was called on.
* @return boolean true.
* @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'] == false) {
if (isset($options['validate']) && !$options['validate']) {
unset($this->runtime[$Model->alias]['beforeSave']);
}
if (isset($this->runtime[$Model->alias]['beforeSave'])) {
@ -354,7 +366,7 @@ class TranslateBehavior extends ModelBehavior {
* and to allow translations to be persisted even when validation
* is disabled.
*
* @param Model $Model
* @param Model $Model Model using this behavior.
* @return void
*/
protected function _setRuntimeData(Model $Model) {
@ -387,7 +399,7 @@ class TranslateBehavior extends ModelBehavior {
* Restores model data to the original data.
* This solves issues with saveAssociated and validate = first.
*
* @param Model $model
* @param Model $Model Model using this behavior.
* @return void
*/
public function afterValidate(Model $Model) {
@ -402,14 +414,14 @@ class TranslateBehavior extends ModelBehavior {
* afterSave Callback
*
* @param Model $Model Model the callback is called on
* @param boolean $created Whether or not the save created a record.
* @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) {
public function afterSave(Model $Model, $created, $options = array()) {
if (!isset($this->runtime[$Model->alias]['beforeValidate']) && !isset($this->runtime[$Model->alias]['beforeSave'])) {
return true;
}
$locale = $this->_getLocale($Model);
if (isset($this->runtime[$Model->alias]['beforeValidate'])) {
$tempData = $this->runtime[$Model->alias]['beforeValidate'];
} else {
@ -417,23 +429,16 @@ class TranslateBehavior extends ModelBehavior {
}
unset($this->runtime[$Model->alias]['beforeValidate'], $this->runtime[$Model->alias]['beforeSave']);
$conditions = array('model' => $Model->alias, 'foreign_key' => $Model->id);
$conditions = array('model' => $Model->name, 'foreign_key' => $Model->id);
$RuntimeModel = $this->translateModel($Model);
$fields = array_merge(
$this->settings[$Model->alias],
$this->runtime[$Model->alias]['fields']
);
if ($created) {
// set each field value to an empty string
foreach ($fields as $key => $field) {
if (!is_numeric($key)) {
$field = $key;
}
if (!isset($tempData[$field])) {
$tempData[$field] = '';
}
}
$tempData = $this->_prepareTranslations($Model, $tempData);
}
$locale = $this->_getLocale($Model);
$atomic = array();
if (isset($options['atomic'])) {
$atomic = array('atomic' => $options['atomic']);
}
foreach ($tempData as $field => $value) {
@ -451,7 +456,10 @@ class TranslateBehavior extends ModelBehavior {
}
$translations = $RuntimeModel->find('list', array(
'conditions' => $conditions,
'fields' => array($RuntimeModel->alias . '.locale', $RuntimeModel->alias . '.id')
'fields' => array(
$RuntimeModel->alias . '.locale',
$RuntimeModel->alias . '.id'
)
));
foreach ($value as $_locale => $_value) {
$RuntimeModel->create();
@ -461,15 +469,48 @@ class TranslateBehavior extends ModelBehavior {
$RuntimeModel->save(array(
$RuntimeModel->alias => array_merge(
$conditions, array('id' => $translations[$_locale])
)
),
$atomic
));
} else {
$RuntimeModel->save(array($RuntimeModel->alias => $conditions));
$RuntimeModel->save(array($RuntimeModel->alias => $conditions), $atomic);
}
}
}
}
/**
* 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
*
@ -478,10 +519,7 @@ class TranslateBehavior extends ModelBehavior {
*/
public function afterDelete(Model $Model) {
$RuntimeModel = $this->translateModel($Model);
$conditions = array(
'model' => $Model->alias,
'foreign_key' => $Model->id
);
$conditions = array('model' => $Model->name, 'foreign_key' => $Model->id);
$RuntimeModel->deleteAll($conditions);
}
@ -492,7 +530,7 @@ class TranslateBehavior extends ModelBehavior {
* @return mixed string or false
*/
protected function _getLocale(Model $Model) {
if (!isset($Model->locale) || is_null($Model->locale)) {
if (!isset($Model->locale) || $Model->locale === null) {
$I18n = I18n::getInstance();
$I18n->l10n->get(Configure::read('Config.language'));
$Model->locale = $I18n->l10n->locale;
@ -505,7 +543,7 @@ class TranslateBehavior extends ModelBehavior {
* 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.
* 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
@ -518,7 +556,7 @@ class TranslateBehavior extends ModelBehavior {
$className = $Model->translateModel;
}
$this->runtime[$Model->alias]['model'] = ClassRegistry::init($className, 'Model');
$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);
@ -535,12 +573,12 @@ class TranslateBehavior extends ModelBehavior {
* *Note* You should avoid binding translations that overlap existing model properties.
* This can cause un-expected and un-desirable behavior.
*
* @param Model $Model instance of model
* @param Model $Model using this behavior of model
* @param string|array $fields string with field or array(field1, field2=>AssocName, field3)
* @param boolean $reset Leave true to have the fields only modified for the next operation.
* @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 boolean
* @throws CakeException when attempting to bind a translating called name. This is not allowed
* @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) {
@ -551,7 +589,8 @@ class TranslateBehavior extends ModelBehavior {
$RuntimeModel = $this->translateModel($Model);
$default = array(
'className' => $RuntimeModel->alias,
'foreignKey' => 'foreign_key'
'foreignKey' => 'foreign_key',
'order' => 'id'
);
foreach ($fields as $key => $value) {
@ -567,10 +606,9 @@ class TranslateBehavior extends ModelBehavior {
__d('cake_dev', 'You cannot bind a translation named "name".')
);
}
$this->_removeField($Model, $field);
if (is_null($association)) {
if ($association === null) {
if ($reset) {
$this->runtime[$Model->alias]['fields'][] = $field;
} else {
@ -579,6 +617,7 @@ class TranslateBehavior extends ModelBehavior {
} else {
if ($reset) {
$this->runtime[$Model->alias]['fields'][$field] = $association;
$this->runtime[$Model->alias]['restoreFields'][] = $field;
} else {
$this->settings[$Model->alias][$field] = $association;
}
@ -593,7 +632,7 @@ class TranslateBehavior extends ModelBehavior {
}
}
$associations[$association] = array_merge($default, array('conditions' => array(
'model' => $Model->alias,
'model' => $Model->name,
$RuntimeModel->displayField => $field
)));
}
@ -608,7 +647,9 @@ class TranslateBehavior extends ModelBehavior {
/**
* 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])) {
@ -628,10 +669,10 @@ class TranslateBehavior extends ModelBehavior {
* Unbind translation for fields, optionally unbinds hasMany association for
* fake field
*
* @param Model $Model instance of model
* @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 boolean
* @return bool
*/
public function unbindTranslation(Model $Model, $fields = null) {
if (empty($fields) && empty($this->settings[$Model->alias])) {
@ -657,7 +698,7 @@ class TranslateBehavior extends ModelBehavior {
$this->_removeField($Model, $field);
if (!is_null($association) && (isset($Model->hasMany[$association]) || isset($Model->__backAssociation['hasMany'][$association]))) {
if ($association !== null && (isset($Model->hasMany[$association]) || isset($Model->__backAssociation['hasMany'][$association]))) {
$associations[] = $association;
}
}

File diff suppressed because it is too large Load diff

View file

@ -4,19 +4,18 @@
*
* Provides management and interface for interacting with collections of behaviors.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.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 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @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 MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ObjectCollection', 'Utility');
@ -55,15 +54,15 @@ class BehaviorCollection extends ObjectCollection implements CakeEventListener {
/**
* Attaches a model object and loads a list of behaviors
*
* @param string $modelName
* @param array $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 $behavior => $config) {
foreach (BehaviorCollection::normalizeObjectArray($behaviors) as $config) {
$this->load($config['class'], $config['settings']);
}
}
@ -72,10 +71,10 @@ class BehaviorCollection extends ObjectCollection implements CakeEventListener {
/**
* Backwards compatible alias for load()
*
* @param string $behavior
* @param array $config
* @param string $behavior Behavior name.
* @param array $config Configuration options.
* @return void
* @deprecated Replaced with load()
* @deprecated 3.0.0 Will be removed in 3.0. Replaced with load().
*/
public function attach($behavior, $config = array()) {
return $this->load($behavior, $config);
@ -87,27 +86,28 @@ class BehaviorCollection extends ObjectCollection implements CakeEventListener {
* 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 boolean True on success, false on failure
* @return bool True on success, false on failure
* @throws MissingBehaviorException when a behavior could not be found.
*/
public function load($behavior, $config = array()) {
if (is_array($config) && isset($config['className'])) {
if (isset($config['className'])) {
$alias = $behavior;
$behavior = $config['className'];
}
$configDisabled = isset($config['enabled']) && $config['enabled'] === false;
unset($config['enabled'], $config['className']);
$priority = isset($config['priority']) ? $config['priority'] : $this->defaultPriority;
unset($config['enabled'], $config['className'], $config['priority']);
list($plugin, $name) = pluginSplit($behavior, true);
if (!isset($alias)) {
@ -130,9 +130,6 @@ class BehaviorCollection extends ObjectCollection implements CakeEventListener {
} else {
$this->_loaded[$alias] = new $class();
ClassRegistry::addObject($class, $this->_loaded[$alias]);
if (!empty($plugin)) {
ClassRegistry::addObject($plugin . '.' . $class, $this->_loaded[$alias]);
}
}
} elseif (isset($this->_loaded[$alias]->settings) && isset($this->_loaded[$alias]->settings[$this->modelName])) {
if ($config !== null && $config !== false) {
@ -144,6 +141,7 @@ class BehaviorCollection extends ObjectCollection implements CakeEventListener {
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) {
@ -159,7 +157,7 @@ class BehaviorCollection extends ObjectCollection implements CakeEventListener {
foreach ($methods as $m) {
if (!isset($parentMethods[$m])) {
$methodAllowed = (
$m[0] != '_' && !array_key_exists($m, $this->_methods) &&
$m[0] !== '_' && !array_key_exists($m, $this->_methods) &&
!in_array($m, $callbacks)
);
if ($methodAllowed) {
@ -168,11 +166,14 @@ class BehaviorCollection extends ObjectCollection implements CakeEventListener {
}
}
if (!in_array($alias, $this->_enabled) && !$configDisabled) {
if ($configDisabled) {
$this->disable($alias);
} elseif (!$this->enabled($alias)) {
$this->enable($alias);
} else {
$this->disable($alias);
$this->setPriority($alias, $priority);
}
return true;
}
@ -183,13 +184,13 @@ class BehaviorCollection extends ObjectCollection implements CakeEventListener {
* @return void
*/
public function unload($name) {
list($plugin, $name) = pluginSplit($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) {
if (is_array($callback) && $callback[0] === $name) {
unset($this->_methods[$m]);
}
}
@ -200,14 +201,14 @@ class BehaviorCollection extends ObjectCollection implements CakeEventListener {
*
* @param string $name Name of behavior
* @return void
* @deprecated Use unload instead.
* @deprecated 3.0.0 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.
* 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.
@ -215,14 +216,14 @@ class BehaviorCollection extends ObjectCollection implements CakeEventListener {
* @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 boolean $strict If methods are not found, trigger an error.
* @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', "BehaviorCollection::dispatchMethod() - Method %s not found in any attached behavior", $method), E_USER_WARNING);
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)) {
@ -249,13 +250,13 @@ class BehaviorCollection extends ObjectCollection implements CakeEventListener {
}
/**
* Check to see if a behavior in this collection implements the provided method. Will
* 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 boolean $callback Return the callback for the method.
* @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.
* 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])) {

View file

@ -2,19 +2,18 @@
/**
* Schema database management for CakePHP.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.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 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @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 MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Model', 'Model');
@ -23,49 +22,49 @@ App::uses('ConnectionManager', 'Model');
App::uses('File', 'Utility');
/**
* Base Class for Schema management
* Base Class for Schema management.
*
* @package Cake.Model
*/
class CakeSchema extends Object {
class CakeSchema extends CakeObject {
/**
* Name of the schema
* Name of the schema.
*
* @var string
*/
public $name = null;
/**
* Path to write location
* Path to write location.
*
* @var string
*/
public $path = null;
/**
* File to write
* File to write.
*
* @var string
*/
public $file = 'schema.php';
/**
* Connection used for read
* Connection used for read.
*
* @var string
*/
public $connection = 'default';
/**
* plugin name.
* Plugin name.
*
* @var string
*/
public $plugin = null;
/**
* Set of tables
* Set of tables.
*
* @var array
*/
@ -74,7 +73,7 @@ class CakeSchema extends Object {
/**
* Constructor
*
* @param array $options optional load object properties
* @param array $options Optional load object properties.
*/
public function __construct($options = array()) {
parent::__construct();
@ -87,7 +86,7 @@ class CakeSchema extends Object {
}
if (strtolower($this->name) === 'cake') {
$this->name = Inflector::camelize(Inflector::slug(Configure::read('App.dir')));
$this->name = 'App';
}
if (empty($options['path'])) {
@ -99,9 +98,9 @@ class CakeSchema extends Object {
}
/**
* Builds schema object properties
* Builds schema object properties.
*
* @param array $data loaded object properties
* @param array $data Loaded object properties.
* @return void
*/
public function build($data) {
@ -130,29 +129,29 @@ class CakeSchema extends Object {
}
/**
* Before callback to be implemented in subclasses
* Before callback to be implemented in subclasses.
*
* @param array $event schema object properties
* @return boolean Should process continue
* @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
* After callback to be implemented in subclasses.
*
* @param array $event schema object properties
* @param array $event Schema object properties.
* @return void
*/
public function after($event = array()) {
}
/**
* Reads database and creates schema tables
* Reads database and creates schema tables.
*
* @param array $options schema object properties
* @return array Set of name and tables
* @param array $options Schema object properties.
* @return array Set of name and tables.
*/
public function load($options = array()) {
if (is_string($options)) {
@ -164,11 +163,10 @@ class CakeSchema extends Object {
$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) && !$this->_requireFile($path, $file)) {
$class = Inflector::camelize(Inflector::slug(Configure::read('App.dir'))) . 'Schema';
if (!class_exists($class)) {
$this->_requireFile($path, $file);
}
}
@ -180,7 +178,7 @@ class CakeSchema extends Object {
}
/**
* Reads database and creates schema tables
* Reads database and creates schema tables.
*
* Options
*
@ -188,8 +186,8 @@ class CakeSchema extends Object {
* - '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
* @param array $options Schema object properties.
* @return array Array indexed by name and tables.
*/
public function read($options = array()) {
extract(array_merge(
@ -226,12 +224,12 @@ class CakeSchema extends Object {
foreach ($models as $model) {
$importModel = $model;
$plugin = null;
if ($model == 'AppModel') {
if ($model === 'AppModel') {
continue;
}
if (isset($this->plugin)) {
if ($model == $this->plugin . 'AppModel') {
if ($model === $this->plugin . 'AppModel') {
continue;
}
$importModel = $model;
@ -254,44 +252,50 @@ class CakeSchema extends Object {
continue;
}
if (!is_object($Object) || $Object->useTable === false) {
continue;
}
$db = $Object->getDataSource();
if (is_object($Object) && $Object->useTable !== false) {
$fulltable = $table = $db->fullTableName($Object, false, false);
if ($prefix && strpos($table, $prefix) !== 0) {
$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;
}
$table = $this->_noPrefixTable($prefix, $table);
$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);
if (in_array($fulltable, $currentTables)) {
$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)) {
foreach ($Object->hasAndBelongsToMany as $assocData) {
if (isset($assocData['with'])) {
$class = $assocData['with'];
}
if (is_object($Object->$class)) {
$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]);
}
}
}
}
$tables[$noPrefixWith] = $this->_columns($Object->$class);
$tables[$noPrefixWith]['indexes'] = $db->index($Object->$class);
$tables[$noPrefixWith]['tableParameters'] = $db->readTableParameters($withTable);
unset($currentTables[$key]);
}
}
}
@ -336,11 +340,11 @@ class CakeSchema extends Object {
}
/**
* Writes schema file from object or options
* 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
* @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)) {
@ -393,56 +397,61 @@ class CakeSchema extends Object {
}
/**
* Generate the code for a table. Takes a table name and $fields array
* Returns a completed variable declaration to be used in schema classes
* Generate the schema code for a table.
*
* Takes a table name and $fields array and returns a completed,
* escaped 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
* @return string Variable declaration for a schema class.
* @throws Exception
*/
public function generateTable($table, $fields) {
// Valid var name regex (http://www.php.net/manual/en/language.variables.basics.php)
if (!preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $table)) {
throw new Exception("Invalid table name '{$table}'");
}
$out = "\tpublic \${$table} = array(\n";
if (is_array($fields)) {
$cols = array();
foreach ($fields as $field => $value) {
if ($field != 'indexes' && $field != 'tableParameters') {
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 .= join(', ', $this->_values($value));
} elseif ($field == 'indexes') {
$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(" . join(', ', $this->_values($index)) . ")";
$props[] = "'{$key}' => array(" . implode(', ', $this->_values($index)) . ")";
}
$col .= join(",\n\t\t\t", $props) . "\n\t\t";
} elseif ($field == 'tableParameters') {
$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 .= join(', ', $props);
$props = $this->_values($value);
$col .= implode(', ', $props);
}
$col .= ")";
$cols[] = $col;
}
$out .= join(",\n", $cols);
$out .= implode(",\n", $cols);
}
$out .= "\n\t);\n";
$out .= "\n\t);\n\n";
return $out;
}
/**
* Compares two sets of schemas
* 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)
* @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)) {
@ -465,11 +474,11 @@ class CakeSchema extends Object {
}
$tables = array();
foreach ($new as $table => $fields) {
if ($table == 'missing') {
if ($table === 'missing') {
continue;
}
if (!array_key_exists($table, $old)) {
$tables[$table]['add'] = $fields;
$tables[$table]['create'] = $fields;
} else {
$diff = $this->_arrayDiffAssoc($fields, $old[$table]);
if (!empty($diff)) {
@ -484,6 +493,9 @@ class CakeSchema extends Object {
foreach ($fields as $field => $value) {
if (!empty($old[$table][$field])) {
$diff = $this->_arrayDiffAssoc($value, $old[$table][$field]);
if (empty($diff)) {
$diff = $this->_arrayDiffAssoc($old[$table][$field], $value);
}
if (!empty($diff) && $field !== 'indexes' && $field !== 'tableParameters') {
$tables[$table]['change'][$field] = $value;
}
@ -524,15 +536,15 @@ class CakeSchema extends Object {
}
/**
* Extended array_diff_assoc noticing change from/to NULL values
* 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
* @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.
*/
@ -544,7 +556,7 @@ class CakeSchema extends Object {
continue;
}
$correspondingValue = $array2[$key];
if (is_null($value) !== is_null($correspondingValue)) {
if (($value === null) !== ($correspondingValue === null)) {
$difference[$key] = $value;
continue;
}
@ -564,17 +576,17 @@ class CakeSchema extends Object {
}
/**
* Formats Schema columns from Model Object
* Formats Schema columns from Model Object.
*
* @param array $values options keys(type, null, default, key, length, extra)
* @return array Formatted values
* @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)) . ")";
$vals[] = "'{$key}' => array(" . implode(", ", $this->_values($val)) . ")";
} else {
$val = var_export($val, true);
if ($val === 'NULL') {
@ -592,10 +604,10 @@ class CakeSchema extends Object {
}
/**
* Formats Schema columns from Model Object
* Formats Schema columns from Model Object.
*
* @param array $Obj model object
* @return array Formatted columns
* @param array &$Obj model object.
* @return array Formatted columns.
*/
protected function _columns(&$Obj) {
$db = $Obj->getDataSource();
@ -603,7 +615,7 @@ class CakeSchema extends Object {
$columns = array();
foreach ($fields as $name => $value) {
if ($Obj->primaryKey == $name) {
if ($Obj->primaryKey === $name) {
$value['key'] = 'primary';
}
if (!isset($db->columns[$value['type']])) {
@ -619,7 +631,7 @@ class CakeSchema extends Object {
unset($value['limit']);
}
if (isset($value['default']) && ($value['default'] === '' || $value['default'] === false)) {
if (isset($value['default']) && ($value['default'] === '' || ($value['default'] === false && $value['type'] !== 'boolean'))) {
unset($value['default']);
}
if (empty($value['length'])) {
@ -635,10 +647,10 @@ class CakeSchema extends Object {
}
/**
* Compare two schema files table Parameters
* Compare two schema files table Parameters.
*
* @param array $new New indexes
* @param array $old Old indexes
* @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) {
@ -650,11 +662,11 @@ class CakeSchema extends Object {
}
/**
* Compare two schema indexes
* 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
* @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)) {
@ -701,14 +713,33 @@ class CakeSchema extends Object {
}
/**
* Trim the table prefix from the full table name, and return the prefix-less table
* 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
* @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);
}
/**
* Attempts to require the schema file specified.
*
* @param string $path Filesystem path to the file.
* @param string $file Filesystem basename of the file.
* @return bool True when a file was successfully included, false on failure.
*/
protected function _requireFile($path, $file) {
if (file_exists($path . DS . $file) && is_file($path . DS . $file)) {
require_once $path . DS . $file;
return true;
} elseif (file_exists($path . DS . 'schema.php') && is_file($path . DS . 'schema.php')) {
require_once $path . DS . 'schema.php';
return true;
}
return false;
}
}

View file

@ -4,19 +4,18 @@
*
* Provides an interface for loading and enumerating connections defined in app/Config/database.php
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.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 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @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 MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('DataSource', 'Model/Datasource');
@ -55,7 +54,7 @@ class ConnectionManager {
/**
* Indicates if the init code for this class has already been executed
*
* @var boolean
* @var bool
*/
protected static $_init = false;
@ -67,9 +66,9 @@ class ConnectionManager {
protected static function _init() {
include_once APP . 'Config' . DS . 'database.php';
if (class_exists('DATABASE_CONFIG')) {
self::$config = new DATABASE_CONFIG();
static::$config = new DATABASE_CONFIG();
}
self::$_init = true;
static::$_init = true;
}
/**
@ -77,31 +76,36 @@ class ConnectionManager {
*
* @param string $name The name of the DataSource, as defined in app/Config/database.php
* @return DataSource Instance
* @throws MissingDatasourceConfigException
* @throws MissingDatasourceException
*/
public static function getDataSource($name) {
if (empty(self::$_init)) {
self::_init();
if (empty(static::$_init)) {
static::_init();
}
if (!empty(self::$_dataSources[$name])) {
$return = self::$_dataSources[$name];
return $return;
if (!empty(static::$_dataSources[$name])) {
return static::$_dataSources[$name];
}
if (empty(self::$_connectionsEnum[$name])) {
self::_getConnectionObject($name);
if (empty(static::$_connectionsEnum[$name])) {
static::_getConnectionObject($name);
}
self::loadDataSource($name);
$conn = self::$_connectionsEnum[$name];
static::loadDataSource($name);
$conn = static::$_connectionsEnum[$name];
$class = $conn['classname'];
self::$_dataSources[$name] = new $class(self::$config->{$name});
self::$_dataSources[$name]->configKeyName = $name;
if (strpos(App::location($class), 'Datasource') === false) {
throw new MissingDatasourceException(array(
'class' => $class,
'plugin' => null,
'message' => 'Datasource is not found in Model/Datasource package.'
));
}
static::$_dataSources[$name] = new $class(static::$config->{$name});
static::$_dataSources[$name]->configKeyName = $name;
return self::$_dataSources[$name];
return static::$_dataSources[$name];
}
/**
@ -112,24 +116,24 @@ class ConnectionManager {
* @return array List of available connections
*/
public static function sourceList() {
if (empty(self::$_init)) {
self::_init();
if (empty(static::$_init)) {
static::_init();
}
return array_keys(self::$_dataSources);
return array_keys(static::$_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
* @return string|null Datasource name, or null if source is not present
* in the ConnectionManager.
*/
public static function getSourceName($source) {
if (empty(self::$_init)) {
self::_init();
if (empty(static::$_init)) {
static::_init();
}
foreach (self::$_dataSources as $name => $ds) {
foreach (static::$_dataSources as $name => $ds) {
if ($ds === $source) {
return $name;
}
@ -141,20 +145,20 @@ class ConnectionManager {
* 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 boolean True on success, null on failure or false if the class is already loaded
* 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 (empty(static::$_init)) {
static::_init();
}
if (is_array($connName)) {
$conn = $connName;
} else {
$conn = self::$_connectionsEnum[$connName];
$conn = static::$_connectionsEnum[$connName];
}
if (class_exists($conn['classname'], false)) {
@ -180,16 +184,16 @@ class ConnectionManager {
}
/**
* Return a list of connections
* Returns 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'.
* (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();
if (empty(static::$_init)) {
static::_init();
}
return (array)self::$config;
return (array)static::$config;
}
/**
@ -197,19 +201,19 @@ class ConnectionManager {
*
* @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
* @return DataSource|null 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(static::$_init)) {
static::_init();
}
if (empty($name) || empty($config) || array_key_exists($name, self::$_connectionsEnum)) {
if (empty($name) || empty($config) || array_key_exists($name, static::$_connectionsEnum)) {
return null;
}
self::$config->{$name} = $config;
self::$_connectionsEnum[$name] = self::_connectionData($config);
$return = self::getDataSource($name);
static::$config->{$name} = $config;
static::$_connectionsEnum[$name] = static::_connectionData($config);
$return = static::getDataSource($name);
return $return;
}
@ -217,17 +221,17 @@ class ConnectionManager {
* Removes a connection configuration at runtime given its name
*
* @param string $name the connection name as it was created
* @return boolean success if connection was removed, false if it does not exist
* @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 (empty(static::$_init)) {
static::_init();
}
if (!isset(self::$config->{$name})) {
if (!isset(static::$config->{$name})) {
return false;
}
unset(self::$_connectionsEnum[$name], self::$_dataSources[$name], self::$config->{$name});
unset(static::$_connectionsEnum[$name], static::$_dataSources[$name], static::$config->{$name});
return true;
}
@ -239,8 +243,8 @@ class ConnectionManager {
* @throws MissingDatasourceConfigException
*/
protected static function _getConnectionObject($name) {
if (!empty(self::$config->{$name})) {
self::$_connectionsEnum[$name] = self::_connectionData(self::$config->{$name});
if (!empty(static::$config->{$name})) {
static::$_connectionsEnum[$name] = static::_connectionData(static::$config->{$name});
} else {
throw new MissingDatasourceConfigException(array('config' => $name));
}

View file

@ -1,34 +1,33 @@
<?php
/**
* Session class for Cake.
* Session class for CakePHP.
*
* Cake abstracts the handling of sessions.
* 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.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.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 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @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 MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Hash', 'Utility');
App::uses('Security', 'Utility');
/**
* Session class for Cake.
* Session class for CakePHP.
*
* Cake abstracts the handling of sessions. There are several convenient methods to access session information.
* 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
@ -38,7 +37,7 @@ class CakeSession {
/**
* True if the Session is still valid
*
* @var boolean
* @var bool
*/
public static $valid = false;
@ -66,28 +65,28 @@ class CakeSession {
/**
* Error number of last occurred error
*
* @var integer
* @var int
*/
public static $lastError = null;
/**
* Start time for this session.
*
* @var integer
* @var int
*/
public static $time = false;
/**
* Cookie lifetime
*
* @var integer
* @var int
*/
public static $cookieLifeTime;
/**
* Time when this session becomes invalid.
*
* @var integer
* @var int
*/
public static $sessionTime = false;
@ -108,7 +107,7 @@ class CakeSession {
/**
* Session timeout multiplier factor
*
* @var integer
* @var int
*/
public static $timeout = null;
@ -116,48 +115,66 @@ class CakeSession {
* 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 integer
* @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
* @param string|null $base The base path for the Session
* @return void
*/
public static function init($base = null) {
self::$time = time();
static::$time = time();
$checkAgent = Configure::read('Session.checkAgent');
if (($checkAgent === true || $checkAgent === null) && env('HTTP_USER_AGENT') != null) {
self::$_userAgent = md5(env('HTTP_USER_AGENT') . Configure::read('Security.salt'));
if (env('HTTP_USER_AGENT') && !static::$_userAgent) {
static::$_userAgent = md5(env('HTTP_USER_AGENT') . Configure::read('Security.salt'));
}
self::_setPath($base);
self::_setHost(env('HTTP_HOST'));
register_shutdown_function('session_write_close');
static::_setPath($base);
static::_setHost(env('HTTP_HOST'));
if (!static::$_initialized) {
register_shutdown_function('session_write_close');
}
static::$_initialized = true;
}
/**
* Setup the Path variable
*
* @param string $base base path
* @param string|null $base base path
* @return void
*/
protected static function _setPath($base = null) {
if (empty($base)) {
self::$path = '/';
static::$path = '/';
return;
}
if (strpos($base, 'index.php') !== false) {
$base = str_replace('index.php', '', $base);
$base = str_replace('index.php', '', $base);
}
if (strpos($base, '?') !== false) {
$base = str_replace('?', '', $base);
$base = str_replace('?', '', $base);
}
self::$path = $base;
static::$path = $base;
}
/**
@ -167,41 +184,42 @@ class CakeSession {
* @return void
*/
protected static function _setHost($host) {
self::$host = $host;
if (strpos(self::$host, ':') !== false) {
self::$host = substr(self::$host, 0, strpos(self::$host, ':'));
static::$host = $host;
if (strpos(static::$host, ':') !== false) {
static::$host = substr(static::$host, 0, strpos(static::$host, ':'));
}
}
/**
* Starts the Session.
*
* @return boolean True if session was started
* @return bool True if session was started
*/
public static function start() {
if (self::started()) {
if (static::started()) {
return true;
}
self::init();
$id = self::id();
session_write_close();
self::_configureSession();
self::_startSession();
if (!$id && self::started()) {
self::_checkValid();
$id = static::id();
static::_startSession();
if (!$id && static::started()) {
static::_checkValid();
}
self::$error = false;
return self::started();
static::$error = false;
static::$valid = true;
return static::started();
}
/**
* Determine if Session has been started.
*
* @return boolean True if session has been started.
* @return bool True if session has been started.
*/
public static function started() {
if (function_exists('session_status')) {
return isset($_SESSION) && (session_status() === PHP_SESSION_ACTIVE);
}
return isset($_SESSION) && session_id();
}
@ -209,55 +227,62 @@ class CakeSession {
* Returns true if given variable is set in session.
*
* @param string $name Variable name to check for
* @return boolean True if variable is there
* @return bool True if variable is there
*/
public static function check($name = null) {
if (!self::started() && !self::start()) {
public static function check($name) {
if (!static::_hasSession() || !static::start()) {
return false;
}
if (empty($name)) {
return false;
if (isset($_SESSION[$name])) {
return true;
}
$result = Hash::get($_SESSION, $name);
return isset($result);
return Hash::get($_SESSION, $name) !== null;
}
/**
* Returns the Session id
* Returns the session id.
* Calling this method will not auto start the session. You might have to manually
* assert a started session.
*
* @param string $id
* 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|null $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);
static::$id = $id;
session_id(static::$id);
}
if (self::started()) {
if (static::started()) {
return session_id();
}
return self::$id;
return static::$id;
}
/**
* Removes a variable from session.
*
* @param string $name Session variable to remove
* @return boolean Success
* @return bool Success
*/
public static function delete($name) {
if (self::check($name)) {
self::_overwrite($_SESSION, Hash::remove($_SESSION, $name));
return (self::check($name) == false);
if (static::check($name)) {
static::_overwrite($_SESSION, Hash::remove($_SESSION, $name));
return !static::check($name);
}
self::_setError(2, __d('cake_dev', "%s doesn't exist", $name));
return false;
}
/**
* Used to write new data to _SESSION, since PHP doesn't like us setting the _SESSION var itself
* 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 &$old Set of old variables => values
* @param array $new New set of variable => value
* @return void
*/
@ -277,15 +302,14 @@ class CakeSession {
/**
* Return error description for given error number.
*
* @param integer $errorNumber Error to set
* @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)) {
if (!is_array(static::$error) || !array_key_exists($errorNumber, static::$error)) {
return false;
} else {
return self::$error[$errorNumber];
}
return static::$error[$errorNumber];
}
/**
@ -294,8 +318,8 @@ class CakeSession {
* @return mixed Error description as a string, or false.
*/
public static function error() {
if (self::$lastError) {
return self::_error(self::$lastError);
if (static::$lastError) {
return static::_error(static::$lastError);
}
return false;
}
@ -303,75 +327,73 @@ class CakeSession {
/**
* Returns true if session is valid.
*
* @return boolean Success
* @return bool Success
*/
public static function valid() {
if (self::read('Config')) {
if (self::_validAgentAndTime() && self::$error === false) {
self::$valid = true;
if (static::start() && static::read('Config')) {
if (static::_validAgentAndTime() && static::$error === false) {
static::$valid = true;
} else {
self::$valid = false;
self::_setError(1, 'Session Highjacking Attempted !!!');
static::$valid = false;
static::_setError(1, 'Session Highjacking Attempted !!!');
}
}
return self::$valid;
return static::$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
* Since timeouts are implemented in CakeSession it checks the current static::$time
* against the time the session is set to expire. The User agent is only checked
* if Session.checkAgent == true.
*
* @return boolean
* @return bool
*/
protected static function _validAgentAndTime() {
$config = self::read('Config');
$userAgent = static::read('Config.userAgent');
$time = static::read('Config.time');
$validAgent = (
Configure::read('Session.checkAgent') === false ||
self::$_userAgent == $config['userAgent']
isset($userAgent) && static::$_userAgent === $userAgent
);
return ($validAgent && self::$time <= $config['time']);
return ($validAgent && static::$time <= $time);
}
/**
* Get / Set the userAgent
* Get / Set the user agent
*
* @param string $userAgent Set the userAgent
* @return void
* @param string|null $userAgent Set the user agent
* @return string Current user agent.
*/
public static function userAgent($userAgent = null) {
if ($userAgent) {
self::$_userAgent = $userAgent;
static::$_userAgent = $userAgent;
}
if (empty(self::$_userAgent)) {
CakeSession::init(self::$path);
if (empty(static::$_userAgent)) {
CakeSession::init(static::$path);
}
return self::$_userAgent;
return static::$_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
* @param string|null $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, false on failure.
*/
public static function read($name = null) {
if (!self::started() && !self::start()) {
return false;
if (!static::_hasSession() || !static::start()) {
return null;
}
if (is_null($name)) {
return self::_returnSessionVars();
}
if (empty($name)) {
return false;
if ($name === null) {
return static::_returnSessionVars();
}
$result = Hash::get($_SESSION, $name);
if (isset($result)) {
return $result;
}
self::_setError(2, "$name doesn't exist");
return null;
}
@ -384,7 +406,7 @@ class CakeSession {
if (!empty($_SESSION)) {
return $_SESSION;
}
self::_setError(2, 'No Session vars set');
static::_setError(2, 'No Session vars set');
return false;
}
@ -393,21 +415,19 @@ class CakeSession {
*
* @param string|array $name Name of variable
* @param string $value Value to write
* @return boolean True if the write was successful, false if the write failed
* @return bool True if the write was successful, false if the write failed
*/
public static function write($name, $value = null) {
if (!self::started() && !self::start()) {
return false;
}
if (empty($name)) {
if (!static::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));
static::_overwrite($_SESSION, Hash::insert($_SESSION, $key, $val));
if (Hash::get($_SESSION, $key) !== $val) {
return false;
}
@ -415,32 +435,69 @@ class CakeSession {
return true;
}
/**
* Reads and deletes a variable from session.
*
* @param string $name The key to read and remove (or a path as sent to Hash.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 consume($name) {
if (empty($name)) {
return null;
}
$value = static::read($name);
if ($value !== null) {
static::_overwrite($_SESSION, Hash::remove($_SESSION, $name));
}
return $value;
}
/**
* Helper method to destroy invalid sessions.
*
* @return void
*/
public static function destroy() {
if (self::started()) {
session_destroy();
if (!static::started()) {
static::_startSession();
}
self::clear();
if (static::started()) {
if (session_id() && static::_hasSession()) {
session_write_close();
session_start();
}
session_destroy();
unset($_COOKIE[static::_cookieName()]);
}
$_SESSION = null;
static::$id = null;
static::$_cookieName = null;
}
/**
* Clears the session, the session id, and renew's the session.
* Clears the session.
*
* Optionally also clears the session id and renews the session.
*
* @param bool $renew If the session should also be renewed. Defaults to true.
* @return void
*/
public static function clear() {
public static function clear($renew = true) {
if (!$renew) {
$_SESSION = array();
return;
}
$_SESSION = null;
self::$id = null;
self::start();
self::renew();
static::$id = null;
static::renew();
}
/**
* Helper method to initialize a session, based on Cake core settings.
* 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.
*
@ -451,7 +508,7 @@ class CakeSession {
$sessionConfig = Configure::read('Session');
if (isset($sessionConfig['defaults'])) {
$defaults = self::_defaultConfig($sessionConfig['defaults']);
$defaults = static::_defaultConfig($sessionConfig['defaults']);
if ($defaults) {
$sessionConfig = Hash::merge($defaults, $sessionConfig);
}
@ -465,27 +522,36 @@ class CakeSession {
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'];
}
static::$_cookieName = $sessionConfig['ini']['session.name'];
if (!empty($sessionConfig['handler'])) {
$sessionConfig['ini']['session.save_handler'] = 'user';
} elseif (!empty($sessionConfig['session.save_path']) && Configure::read('debug')) {
if (!is_dir($sessionConfig['session.save_path'])) {
mkdir($sessionConfig['session.save_path'], 0775, true);
}
}
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;
}
// For IE<=8
if (!isset($sessionConfig['cacheLimiter'])) {
$sessionConfig['cacheLimiter'] = 'must-revalidate';
}
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(sprintf(
__d('cake_dev', 'Unable to configure the session, setting %s failed.'),
$setting
));
throw new CakeSessionException(__d('cake_dev', 'Unable to configure the session, setting %s failed.', $setting));
}
}
}
@ -494,7 +560,7 @@ class CakeSession {
call_user_func_array('session_set_save_handler', $sessionConfig['handler']);
}
if (!empty($sessionConfig['handler']['engine'])) {
$handler = self::_getHandler($sessionConfig['handler']['engine']);
$handler = static::_getHandler($sessionConfig['handler']['engine']);
session_set_save_handler(
array($handler, 'open'),
array($handler, 'close'),
@ -505,13 +571,38 @@ class CakeSession {
);
}
Configure::write('Session', $sessionConfig);
self::$sessionTime = self::$time + ($sessionConfig['timeout'] * 60);
static::$sessionTime = static::$time + ($sessionConfig['timeout'] * 60);
}
/**
* Get session cookie name.
*
* @return string
*/
protected static function _cookieName() {
if (static::$_cookieName !== null) {
return static::$_cookieName;
}
static::init();
static::_configureSession();
return static::$_cookieName = session_name();
}
/**
* Returns whether a session exists
*
* @return bool
*/
protected static function _hasSession() {
return static::started() || isset($_COOKIE[static::_cookieName()]) || (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg');
}
/**
* Find the handler class and make sure it implements the correct interface.
*
* @param string $handler
* @param string $handler Handler name.
* @return void
* @throws CakeSessionException
*/
@ -531,8 +622,8 @@ class CakeSession {
/**
* Get one of the prebaked default session configurations.
*
* @param string $name
* @return boolean|array
* @param string $name Config name.
* @return bool|array
*/
protected static function _defaultConfig($name) {
$defaults = array(
@ -541,7 +632,7 @@ class CakeSession {
'timeout' => 240,
'ini' => array(
'session.use_trans_sid' => 0,
'session.cookie_path' => self::$path
'session.cookie_path' => static::$path
)
),
'cake' => array(
@ -552,8 +643,7 @@ class CakeSession {
'url_rewriter.tags' => '',
'session.serialize_handler' => 'php',
'session.use_cookies' => 1,
'session.cookie_path' => self::$path,
'session.auto_start' => 0,
'session.cookie_path' => static::$path,
'session.save_path' => TMP . 'sessions',
'session.save_handler' => 'files'
)
@ -564,9 +654,8 @@ class CakeSession {
'ini' => array(
'session.use_trans_sid' => 0,
'url_rewriter.tags' => '',
'session.auto_start' => 0,
'session.use_cookies' => 1,
'session.cookie_path' => self::$path,
'session.cookie_path' => static::$path,
'session.save_handler' => 'user',
),
'handler' => array(
@ -580,9 +669,8 @@ class CakeSession {
'ini' => array(
'session.use_trans_sid' => 0,
'url_rewriter.tags' => '',
'session.auto_start' => 0,
'session.use_cookies' => 1,
'session.cookie_path' => self::$path,
'session.cookie_path' => static::$path,
'session.save_handler' => 'user',
'session.serialize_handler' => 'php',
),
@ -601,16 +689,22 @@ class CakeSession {
/**
* Helper method to start a session
*
* @return boolean Success
* @return bool Success
*/
protected static function _startSession() {
static::init();
session_write_close();
static::_configureSession();
if (headers_sent()) {
if (empty($_SESSION)) {
$_SESSION = array();
}
} else {
// For IE<=8
session_cache_limiter("must-revalidate");
$limit = Configure::read('Session.cacheLimiter');
if (!empty($limit)) {
session_cache_limiter($limit);
}
session_start();
}
return true;
@ -622,49 +716,60 @@ class CakeSession {
* @return void
*/
protected static function _checkValid() {
if (!self::started() && !self::start()) {
self::$valid = false;
return false;
}
if ($config = self::read('Config')) {
$config = static::read('Config');
if ($config) {
$sessionConfig = Configure::read('Session');
if (self::_validAgentAndTime()) {
self::write('Config.time', self::$sessionTime);
if (static::valid()) {
static::write('Config.time', static::$sessionTime);
if (isset($sessionConfig['autoRegenerate']) && $sessionConfig['autoRegenerate'] === true) {
$check = $config['countdown'];
$check -= 1;
self::write('Config.countdown', $check);
static::write('Config.countdown', $check);
if ($check < 1) {
self::renew();
self::write('Config.countdown', self::$requestCountdown);
static::renew();
static::write('Config.countdown', static::$requestCountdown);
}
}
self::$valid = true;
} else {
self::destroy();
self::$valid = false;
self::_setError(1, 'Session Highjacking Attempted !!!');
$_SESSION = array();
static::destroy();
static::_setError(1, 'Session Highjacking Attempted !!!');
static::_startSession();
static::_writeConfig();
}
} else {
self::write('Config.userAgent', self::$_userAgent);
self::write('Config.time', self::$sessionTime);
self::write('Config.countdown', self::$requestCountdown);
self::$valid = true;
static::_writeConfig();
}
}
/**
* Writes configuration variables to the session
*
* @return void
*/
protected static function _writeConfig() {
static::write('Config.userAgent', static::$_userAgent);
static::write('Config.time', static::$sessionTime);
static::write('Config.countdown', static::$requestCountdown);
}
/**
* Restarts this session.
*
* @return void
*/
public static function renew() {
if (session_id()) {
if (session_id() != '' || isset($_COOKIE[session_name()])) {
setcookie(Configure::read('Session.cookie'), '', time() - 42000, self::$path);
}
if (session_id() === '') {
return;
}
if (isset($_COOKIE[static::_cookieName()])) {
setcookie(Configure::read('Session.cookie'), '', time() - 42000, static::$path);
}
if (!headers_sent()) {
session_write_close();
session_start();
session_regenerate_id(true);
}
}
@ -672,16 +777,16 @@ class CakeSession {
/**
* Helper method to set an internal error message.
*
* @param integer $errorNumber Number of the error
* @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();
if (static::$error === false) {
static::$error = array();
}
self::$error[$errorNumber] = $errorMessage;
self::$lastError = $errorNumber;
static::$error[$errorNumber] = $errorMessage;
static::$lastError = $errorNumber;
}
}

View file

@ -2,32 +2,34 @@
/**
* DataSource base class
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.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 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @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 MIT License (http://www.opensource.org/licenses/mit-license.php)
* @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 {
class DataSource extends CakeObject {
/**
* Are we connected to the DataSource?
*
* @var boolean
* @var bool
*/
public $connected = false;
@ -62,7 +64,7 @@ class DataSource extends Object {
/**
* Whether or not this DataSource is in the middle of a transaction
*
* @var boolean
* @var bool
*/
protected $_transactionStarted = false;
@ -70,7 +72,7 @@ class DataSource extends Object {
* Whether or not source data like available tables and schema descriptions
* should be cached
*
* @var boolean
* @var bool
*/
public $cacheSources = true;
@ -87,8 +89,8 @@ class DataSource extends Object {
/**
* Caches/returns cached results for child instances
*
* @param mixed $data
* @return array Array of sources available in this datasource.
* @param mixed $data Unused in this class.
* @return array|null Array of sources available in this datasource.
*/
public function listSources($data = null) {
if ($this->cacheSources === false) {
@ -114,8 +116,8 @@ class DataSource extends Object {
/**
* Returns a Model description (metadata) or null if none found.
*
* @param Model|string $model
* @return array Array of Metadata for the $model
* @param Model|string $model The model to describe.
* @return array|null Array of Metadata for the $model
*/
public function describe($model) {
if ($this->cacheSources === false) {
@ -142,7 +144,7 @@ class DataSource extends Object {
/**
* Begin a transaction
*
* @return boolean Returns true if a transaction is not in progress
* @return bool Returns true if a transaction is not in progress
*/
public function begin() {
return !$this->_transactionStarted;
@ -151,7 +153,7 @@ class DataSource extends Object {
/**
* Commit a transaction
*
* @return boolean Returns true if a transaction is in progress
* @return bool Returns true if a transaction is in progress
*/
public function commit() {
return $this->_transactionStarted;
@ -160,7 +162,7 @@ class DataSource extends Object {
/**
* Rollback a transaction
*
* @return boolean Returns true if a transaction is in progress
* @return bool Returns true if a transaction is in progress
*/
public function rollback() {
return $this->_transactionStarted;
@ -169,7 +171,7 @@ class DataSource extends Object {
/**
* Converts column types to basic types
*
* @param string $real Real column type (i.e. "varchar(255)")
* @param string $real Real column type (i.e. "varchar(255)")
* @return string Abstract column type (i.e. "string")
*/
public function column($real) {
@ -181,12 +183,12 @@ class DataSource extends Object {
*
* To-be-overridden in subclasses.
*
* @param Model $model The Model to be created.
* @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 boolean success
* @return bool success
*/
public function create(Model $model, $fields = null, $values = null) {
public function create(Model $Model, $fields = null, $values = null) {
return false;
}
@ -195,12 +197,12 @@ class DataSource extends Object {
*
* To-be-overridden in subclasses.
*
* @param Model $model The model being read.
* @param Model $Model The model being read.
* @param array $queryData An array of query data used to find the data you want
* @param integer $recursive Number of levels of association
* @param int $recursive Number of levels of association
* @return mixed
*/
public function read(Model $model, $queryData = array(), $recursive = null) {
public function read(Model $Model, $queryData = array(), $recursive = null) {
return false;
}
@ -209,13 +211,13 @@ class DataSource extends Object {
*
* To-be-overridden in subclasses.
*
* @param Model $model Instance of the model class being updated
* @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
* @return boolean Success
* @param mixed $conditions The array of conditions to use.
* @return bool Success
*/
public function update(Model $model, $fields = null, $values = null, $conditions = null) {
public function update(Model $Model, $fields = null, $values = null, $conditions = null) {
return false;
}
@ -224,18 +226,18 @@ class DataSource extends Object {
*
* To-be-overridden in subclasses.
*
* @param Model $model The model class having record(s) deleted
* @param Model $Model The model class having record(s) deleted
* @param mixed $conditions The conditions to use for deleting.
* @return void
* @return bool Success
*/
public function delete(Model $model, $id = null) {
public function delete(Model $Model, $conditions = null) {
return false;
}
/**
* Returns the ID generated from the previous INSERT operation.
*
* @param mixed $source
* @param mixed $source The source name.
* @return mixed Last ID key generated in previous INSERT
*/
public function lastInsertId($source = null) {
@ -245,8 +247,8 @@ class DataSource extends Object {
/**
* Returns the number of rows returned by last operation.
*
* @param mixed $source
* @return integer 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;
@ -255,8 +257,8 @@ class DataSource extends Object {
/**
* Returns the number of rows affected by last query.
*
* @param mixed $source
* @return integer 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;
@ -264,10 +266,10 @@ class DataSource extends Object {
/**
* Check whether the conditions for the Datasource being available
* are satisfied. Often used from connect() to check for support
* are satisfied. Often used from connect() to check for support
* before establishing a connection.
*
* @return boolean Whether or not the Datasources conditions for use are met.
* @return bool Whether or not the Datasources conditions for use are met.
*/
public function enabled() {
return true;
@ -316,112 +318,105 @@ class DataSource extends Object {
*
* @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 array $assocData
* @param Model $model Instance of the model to replace $__cakeID__$
* @param Model $linkModel Instance of model to replace $__cakeForeignKey__$
* @param array $stack
* @return string String of query data with placeholders replaced.
* @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, $assocData, Model $model, Model $linkModel, $stack) {
public function insertQueryData($query, $data, $association, Model $Model, $stack) {
$keys = array('{$__cakeID__$}', '{$__cakeForeignKey__$}');
$modelAlias = $Model->alias;
foreach ($keys as $key) {
$val = null;
$type = null;
if (strpos($query, $key) !== false) {
switch ($key) {
case '{$__cakeID__$}':
if (isset($data[$model->alias]) || isset($data[$association])) {
if (isset($data[$model->alias][$model->primaryKey])) {
$val = $data[$model->alias][$model->primaryKey];
} elseif (isset($data[$association][$model->primaryKey])) {
$val = $data[$association][$model->primaryKey];
}
} else {
$found = false;
foreach (array_reverse($stack) as $assoc) {
if (isset($data[$assoc]) && isset($data[$assoc][$model->primaryKey])) {
$val = $data[$assoc][$model->primaryKey];
$found = true;
break;
}
}
if (!$found) {
$val = '';
}
}
$type = $model->getColumnType($model->primaryKey);
break;
case '{$__cakeForeignKey__$}':
foreach ($model->associations() as $id => $name) {
foreach ($model->$name as $assocName => $assoc) {
if ($assocName === $association) {
if (isset($assoc['foreignKey'])) {
$foreignKey = $assoc['foreignKey'];
$assocModel = $model->$assocName;
$type = $assocModel->getColumnType($assocModel->primaryKey);
if (isset($data[$model->alias][$foreignKey])) {
$val = $data[$model->alias][$foreignKey];
} elseif (isset($data[$association][$foreignKey])) {
$val = $data[$association][$foreignKey];
} else {
$found = false;
foreach (array_reverse($stack) as $assoc) {
if (isset($data[$assoc]) && isset($data[$assoc][$foreignKey])) {
$val = $data[$assoc][$foreignKey];
$found = true;
break;
}
}
if (!$found) {
$val = '';
}
}
}
break 3;
}
}
}
break;
}
if (empty($val) && $val !== '0') {
return false;
}
$query = str_replace($key, $this->value($val, $type), $query);
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 (is_string($assocData) && 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 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;
public function resolveKey(Model $Model, $key) {
return $Model->alias . $key;
}
/**
* Returns the schema name. Override this in subclasses.
*
* @return string schema name
* @access public
* @return string|null The schema name
*/
public function getSchemaName() {
return null;
}
/**
* Closes a connection. Override in subclasses
* Closes a connection. Override in subclasses.
*
* @return boolean
* @access public
* @return bool
*/
public function close() {
return $this->connected = false;
@ -429,7 +424,6 @@ class DataSource extends Object {
/**
* Closes the current datasource.
*
*/
public function __destruct() {
if ($this->_transactionStarted) {

View file

@ -2,19 +2,18 @@
/**
* MySQL layer for DBO
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.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 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @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 MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('DboSource', 'Model/Datasource');
@ -46,13 +45,14 @@ class Mysql extends DboSource {
'login' => 'root',
'password' => '',
'database' => 'cake',
'port' => '3306'
'port' => '3306',
'flags' => array()
);
/**
* Reference to the PDO object connection
*
* @var PDO $_connection
* @var PDO
*/
protected $_connection = null;
@ -73,7 +73,7 @@ class Mysql extends DboSource {
/**
* use alias for update and delete. Set to true if version >= 4.1
*
* @var boolean
* @var bool
*/
protected $_useAlias = true;
@ -85,7 +85,13 @@ class Mysql extends DboSource {
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')
'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')
)
);
/**
@ -96,7 +102,8 @@ class Mysql extends DboSource {
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')
'engine' => array('value' => 'ENGINE', 'quote' => false, 'join' => '=', 'column' => 'Engine'),
'comment' => array('value' => 'COMMENT', 'quote' => true, 'join' => '=', 'column' => 'Comment'),
);
/**
@ -108,8 +115,10 @@ class Mysql extends DboSource {
'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'),
@ -118,29 +127,55 @@ class Mysql extends DboSource {
'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.
*
* @return boolean True if the database could be connected, else false
* 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 {
$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['unix_socket'])) {
$dsn = "mysql:host={$config['host']};port={$config['port']};dbname={$config['database']}";
} else {
$dsn = "mysql:unix_socket={$config['unix_socket']};dbname={$config['database']}";
}
$this->_connection = new PDO(
$dsn,
$config['login'],
@ -148,6 +183,11 @@ class Mysql extends DboSource {
$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),
@ -155,6 +195,7 @@ class Mysql extends DboSource {
));
}
$this->_charsets = array();
$this->_useAlias = (bool)version_compare($this->getVersion(), "4.1", ">=");
return $this->connected;
@ -163,7 +204,7 @@ class Mysql extends DboSource {
/**
* Check whether the MySQL extension is installed/loaded
*
* @return boolean
* @return bool
*/
public function enabled() {
return in_array('mysql', PDO::getAvailableDrivers());
@ -172,12 +213,12 @@ class Mysql extends DboSource {
/**
* Returns an array of sources (tables) in the database.
*
* @param mixed $data
* @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 != null) {
if ($cache) {
return $cache;
}
$result = $this->_execute('SHOW TABLES FROM ' . $this->name($this->config['database']));
@ -185,23 +226,22 @@ class Mysql extends DboSource {
if (!$result) {
$result->closeCursor();
return array();
} else {
$tables = array();
while ($line = $result->fetch(PDO::FETCH_NUM)) {
$tables[] = $line[0];
}
$result->closeCursor();
parent::listSources($tables);
return $tables;
}
$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
* @param PDOStatement $results The results to format.
* @return void
*/
public function resultSet($results) {
@ -211,10 +251,10 @@ class Mysql extends DboSource {
while ($numFields-- > 0) {
$column = $results->getColumnMeta($index);
if (empty($column['native_type'])) {
$type = ($column['len'] == 1) ? 'boolean' : 'string';
if ($column['len'] === 1 && (empty($column['native_type']) || $column['native_type'] === 'TINY')) {
$type = 'boolean';
} else {
$type = $column['native_type'];
$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);
@ -261,15 +301,24 @@ class Mysql extends DboSource {
* @return string Character set name
*/
public function getCharsetName($name) {
if ((bool)version_compare($this->getVersion(), "5", ">=")) {
$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'])) {
return $cols['CHARACTER_SET_NAME'];
}
if ((bool)version_compare($this->getVersion(), "5", "<")) {
return false;
}
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];
}
/**
@ -282,7 +331,7 @@ class Mysql extends DboSource {
public function describe($model) {
$key = $this->fullTableName($model, false);
$cache = parent::describe($key);
if ($cache != null) {
if ($cache) {
return $cache;
}
$table = $this->fullTableName($model);
@ -298,8 +347,14 @@ class Mysql extends DboSource {
'type' => $this->column($column->Type),
'null' => ($column->Null === 'YES' ? true : false),
'default' => $column->Default,
'length' => $this->length($column->Type),
'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 (in_array($fields[$column->Field]['type'], array('timestamp', 'datetime')) && strtoupper($column->Default) === 'CURRENT_TIMESTAMP') {
$fields[$column->Field]['default'] = null;
}
if (!empty($column->Key) && isset($this->index[$column->Key])) {
$fields[$column->Field]['key'] = $this->index[$column->Key];
}
@ -323,10 +378,10 @@ class Mysql extends DboSource {
/**
* Generates and executes an SQL UPDATE statement for given model, fields, and values.
*
* @param Model $model
* @param array $fields
* @param array $values
* @param mixed $conditions
* @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) {
@ -334,7 +389,7 @@ class Mysql extends DboSource {
return parent::update($model, $fields, $values, $conditions);
}
if ($values == null) {
if (!$values) {
$combined = $fields;
} else {
$combined = array_combine($fields, $values);
@ -347,7 +402,7 @@ class Mysql extends DboSource {
if (!empty($conditions)) {
$alias = $this->name($model->alias);
if ($model->name == $model->alias) {
if ($model->name === $model->alias) {
$joins = implode(' ', $this->_getJoins($model));
}
}
@ -367,9 +422,9 @@ class Mysql extends DboSource {
/**
* Generates and executes an SQL DELETE statement for given id/conditions on given model.
*
* @param Model $model
* @param mixed $conditions
* @return boolean Success
* @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) {
@ -382,13 +437,7 @@ class Mysql extends DboSource {
if (empty($conditions)) {
$alias = $joins = false;
}
$complexConditions = false;
foreach ((array)$conditions as $key => $value) {
if (strpos($key, $model->alias) === false) {
$complexConditions = true;
break;
}
}
$complexConditions = $this->_deleteNeedsComplexConditions($model, $conditions);
if (!$complexConditions) {
$joins = false;
}
@ -404,11 +453,32 @@ class Mysql extends DboSource {
return true;
}
/**
* Checks whether complex conditions are needed for a delete with the given conditions.
*
* @param Model $model The model to delete from.
* @param mixed $conditions The conditions to use.
* @return bool Whether or not complex conditions are needed
*/
protected function _deleteNeedsComplexConditions(Model $model, $conditions) {
$fields = array_keys($this->describe($model));
foreach ((array)$conditions as $key => $value) {
if (in_array(strtolower(trim($key)), $this->_sqlBoolOps, true)) {
if ($this->_deleteNeedsComplexConditions($model, $value)) {
return true;
}
} elseif (strpos($key, $model->alias) === false && !in_array($key, $fields, true)) {
return true;
}
}
return false;
}
/**
* Sets the database encoding
*
* @param string $enc Database encoding
* @return boolean
* @return bool
*/
public function setEncoding($enc) {
return $this->_execute('SET NAMES ' . $enc) !== false;
@ -425,17 +495,22 @@ class Mysql extends DboSource {
$table = $this->fullTableName($model);
$old = version_compare($this->getVersion(), '4.1', '<=');
if ($table) {
$indices = $this->_execute('SHOW INDEX FROM ' . $table);
$indexes = $this->_execute('SHOW INDEX FROM ' . $table);
// @codingStandardsIgnoreStart
// MySQL columns don't match the cakephp conventions.
while ($idx = $indices->fetch(PDO::FETCH_OBJ)) {
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;
$index[$idx->Key_name]['unique'] = intval($idx->Non_unique == 0);
if ($idx->Index_type === 'FULLTEXT') {
$index[$idx->Key_name]['type'] = strtolower($idx->Index_type);
} else {
$index[$idx->Key_name]['unique'] = (int)($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'];
@ -451,7 +526,7 @@ class Mysql extends DboSource {
}
}
// @codingStandardsIgnoreEnd
$indices->closeCursor();
$indexes->closeCursor();
}
return $index;
}
@ -460,7 +535,7 @@ class Mysql extends DboSource {
* Generate a MySQL Alter Table syntax for the given Schema comparison
*
* @param array $compare Result of a CakeSchema::compare()
* @param string $table
* @param string $table The table name.
* @return array Array of alter statements to make.
*/
public function alterSchema($compare, $table = null) {
@ -471,7 +546,7 @@ class Mysql extends DboSource {
$colList = array();
foreach ($compare as $curTable => $types) {
$indexes = $tableParameters = $colList = array();
if (!$table || $table == $curTable) {
if (!$table || $table === $curTable) {
$out .= 'ALTER TABLE ' . $this->fullTableName($curTable) . " \n";
foreach ($types as $type => $column) {
if (isset($column['indexes'])) {
@ -492,21 +567,25 @@ class Mysql extends DboSource {
}
$colList[] = $alter;
}
break;
break;
case 'drop':
foreach ($column as $field => $col) {
$col['name'] = $field;
$colList[] = 'DROP ' . $this->name($field);
}
break;
break;
case 'change':
foreach ($column as $field => $col) {
if (!isset($col['name'])) {
$col['name'] = $field;
}
$colList[] = 'CHANGE ' . $this->name($field) . ' ' . $this->buildColumn($col);
$alter = 'CHANGE ' . $this->name($field) . ' ' . $this->buildColumn($col);
if (isset($col['after'])) {
$alter .= ' AFTER ' . $this->name($col['after']);
}
$colList[] = $alter;
}
break;
break;
}
}
$colList = array_merge($colList, $this->_alterIndexes($curTable, $indexes));
@ -518,21 +597,13 @@ class Mysql extends DboSource {
}
/**
* Generate a MySQL "drop table" statement for the given Schema object
* Generate a "drop table" statement for the given table
*
* @param CakeSchema $schema An instance of a subclass of CakeSchema
* @param string $table Optional. If specified only the table name given will be generated.
* Otherwise, all tables defined in the schema are generated.
* @return string
* @param type $table Name of the table to drop
* @return string Drop table SQL statement
*/
public function dropSchema(CakeSchema $schema, $table = null) {
$out = '';
foreach ($schema->tables as $curTable => $columns) {
if (!$table || $table === $curTable) {
$out .= 'DROP TABLE IF EXISTS ' . $this->fullTableName($curTable) . ";\n";
}
}
return $out;
protected function _dropTable($table) {
return 'DROP TABLE IF EXISTS ' . $this->fullTableName($table) . ";";
}
/**
@ -570,8 +641,11 @@ class Mysql extends DboSource {
}
$name = $this->startQuote . $name . $this->endQuote;
}
// length attribute only used for MySQL datasource, for TEXT/BLOB index columns
if (isset($value['type']) && strtolower($value['type']) === 'fulltext') {
$out .= 'FULLTEXT ';
}
$out .= 'KEY ' . $name . ' (';
if (is_array($value['column'])) {
if (isset($value['length'])) {
$vals = array();
@ -610,7 +684,7 @@ class Mysql extends DboSource {
if (isset($indexes['drop'])) {
foreach ($indexes['drop'] as $name => $value) {
$out = 'DROP ';
if ($name == 'PRIMARY') {
if ($name === 'PRIMARY') {
$out .= 'PRIMARY KEY';
} else {
$out .= 'KEY ' . $this->startQuote . $name . $this->endQuote;
@ -635,7 +709,7 @@ class Mysql extends DboSource {
* @return string Formatted length part of an index field
*/
protected function _buildIndexSubPart($lengths, $column) {
if (is_null($lengths)) {
if ($lengths === null) {
return '';
}
if (!isset($lengths[$column])) {
@ -645,7 +719,7 @@ class Mysql extends DboSource {
}
/**
* Returns an detailed array of sources (tables) in the database.
* Returns a 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
@ -660,24 +734,23 @@ class Mysql extends DboSource {
if (!$result) {
$result->closeCursor();
return array();
} else {
$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;
}
}
$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;
}
$result->closeCursor();
if (is_string($name) && isset($tables[$name])) {
return $tables[$name];
}
return $tables;
}
/**
@ -704,9 +777,12 @@ class Mysql extends DboSource {
if (in_array($col, array('date', 'time', 'datetime', 'timestamp'))) {
return $col;
}
if (($col === 'tinyint' && $limit == 1) || $col === 'boolean') {
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';
}
@ -719,15 +795,32 @@ class Mysql extends DboSource {
if (strpos($col, 'blob') !== false || $col === 'binary') {
return 'binary';
}
if (strpos($col, 'float') !== false || strpos($col, 'double') !== false || strpos($col, 'decimal') !== false) {
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)";
}
if (strpos($col, 'set') !== false) {
return "set($vals)";
}
return 'text';
}
/**
* {@inheritDoc}
*/
public function value($data, $column = null, $null = true) {
$value = parent::value($data, $column, $null);
if (is_numeric($value) && substr($column, 0, 3) === 'set') {
return $this->_connection->quote($value);
}
return $value;
}
/**
* Gets the schema name
*
@ -740,10 +833,73 @@ class Mysql extends DboSource {
/**
* Check if the server support nested transactions
*
* @return boolean
* @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;
}
/**
* Inserts multiple values into a table. Uses a single query in order to insert
* multiple rows.
*
* @param string $table The table being inserted into.
* @param array $fields The array of field/column names being inserted.
* @param array $values The array of values to insert. The values should
* be an array of rows. Each row should have values keyed by the column name.
* Each row must have the values in the same order as $fields.
* @return bool
*/
public function insertMulti($table, $fields, $values) {
$table = $this->fullTableName($table);
$holder = implode(', ', array_fill(0, count($fields), '?'));
$fields = implode(', ', array_map(array($this, 'name'), $fields));
$pdoMap = array(
'integer' => PDO::PARAM_INT,
'float' => PDO::PARAM_STR,
'boolean' => PDO::PARAM_BOOL,
'string' => PDO::PARAM_STR,
'text' => PDO::PARAM_STR
);
$columnMap = array();
$rowHolder = "({$holder})";
$sql = "INSERT INTO {$table} ({$fields}) VALUES ";
$countRows = count($values);
for ($i = 0; $i < $countRows; $i++) {
if ($i !== 0) {
$sql .= ',';
}
$sql .= " $rowHolder";
}
$statement = $this->_connection->prepare($sql);
foreach ($values[key($values)] as $key => $val) {
$type = $this->introspectType($val);
$columnMap[$key] = $pdoMap[$type];
}
$valuesList = array();
$i = 1;
foreach ($values as $value) {
foreach ($value as $col => $val) {
$valuesList[] = $val;
$statement->bindValue($i, $val, $columnMap[$col]);
$i++;
}
}
$result = $statement->execute();
$statement->closeCursor();
if ($this->fullDebug) {
$this->logQuery($sql, $valuesList);
}
return $result;
}
}

View file

@ -1,20 +1,17 @@
<?php
/**
* PostgreSQL layer for DBO.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.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 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @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 MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('DboSource', 'Model/Datasource');
@ -34,7 +31,7 @@ class Postgres extends DboSource {
public $description = "PostgreSQL DBO Driver";
/**
* Base driver configuration settings. Merged with user settings.
* Base driver configuration settings. Merged with user settings.
*
* @var array
*/
@ -46,7 +43,9 @@ class Postgres extends DboSource {
'database' => 'cake',
'schema' => 'public',
'port' => 5432,
'encoding' => ''
'encoding' => '',
'sslmode' => 'allow',
'flags' => array()
);
/**
@ -59,7 +58,9 @@ class Postgres extends DboSource {
'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'),
@ -67,7 +68,8 @@ class Postgres extends DboSource {
'binary' => array('name' => 'bytea'),
'boolean' => array('name' => 'boolean'),
'number' => array('name' => 'numeric'),
'inet' => array('name' => 'inet')
'inet' => array('name' => 'inet'),
'uuid' => array('name' => 'uuid')
);
/**
@ -92,22 +94,31 @@ class Postgres extends DboSource {
*/
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 boolean True if successfully connected.
* @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 {
$flags = array(
PDO::ATTR_PERSISTENT => $config['persistent'],
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
$this->_connection = new PDO(
"pgsql:host={$config['host']};port={$config['port']};dbname={$config['database']}",
"pgsql:host={$config['host']};port={$config['port']};dbname={$config['database']};sslmode={$config['sslmode']}",
$config['login'],
$config['password'],
$flags
@ -118,7 +129,12 @@ class Postgres extends DboSource {
$this->setEncoding($config['encoding']);
}
if (!empty($config['schema'])) {
$this->_execute('SET search_path TO ' . $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(
@ -133,7 +149,7 @@ class Postgres extends DboSource {
/**
* Check if PostgreSQL is enabled/loaded
*
* @return boolean
* @return bool
*/
public function enabled() {
return in_array('pgsql', PDO::getAvailableDrivers());
@ -142,13 +158,13 @@ class Postgres extends DboSource {
/**
* Returns an array of tables in the database. If there are no tables, an error is raised and the application exits.
*
* @param mixed $data
* @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 != null) {
if ($cache) {
return $cache;
}
@ -158,17 +174,17 @@ class Postgres extends DboSource {
if (!$result) {
return array();
} else {
$tables = array();
foreach ($result as $item) {
$tables[] = $item->name;
}
$result->closeCursor();
parent::listSources($tables);
return $tables;
}
$tables = array();
foreach ($result as $item) {
$tables[] = $item->name;
}
$result->closeCursor();
parent::listSources($tables);
return $tables;
}
/**
@ -197,16 +213,17 @@ class Postgres extends DboSource {
foreach ($cols as $c) {
$type = $c->type;
if (!empty($c->oct_length) && $c->char_length === null) {
if ($c->type == 'character varying') {
if ($c->type === 'character varying') {
$length = null;
$type = 'text';
} elseif ($c->type == 'uuid') {
} elseif ($c->type === 'uuid') {
$type = 'uuid';
$length = 36;
} else {
$length = intval($c->oct_length);
$length = (int)$c->oct_length;
}
} elseif (!empty($c->char_length)) {
$length = intval($c->char_length);
$length = (int)$c->char_length;
} else {
$length = $this->length($c->type);
}
@ -215,7 +232,7 @@ class Postgres extends DboSource {
}
$fields[$c->name] = array(
'type' => $this->column($type),
'null' => ($c->null == 'NO' ? false : true),
'null' => ($c->null === 'NO' ? false : true),
'default' => preg_replace(
"/^'(.*)'$/",
"$1",
@ -224,15 +241,19 @@ class Postgres extends DboSource {
'length' => $length
);
if ($model instanceof Model) {
if ($c->name == $model->primaryKey) {
if ($c->name === $model->primaryKey) {
$fields[$c->name]['key'] = 'primary';
if ($fields[$c->name]['type'] !== 'string') {
if (
$fields[$c->name]['type'] !== 'string' &&
$fields[$c->name]['type'] !== 'uuid'
) {
$fields[$c->name]['length'] = 11;
}
}
}
if (
$fields[$c->name]['default'] == 'NULL' ||
$fields[$c->name]['default'] === 'NULL' ||
$c->default === null ||
preg_match('/nextval\([\'"]?([\w.]+)/', $c->default, $seq)
) {
$fields[$c->name]['default'] = null;
@ -245,7 +266,10 @@ class Postgres extends DboSource {
$this->_sequenceMap[$table][$c->name] = $sequenceName;
}
}
if ($fields[$c->name]['type'] == 'boolean' && !empty($fields[$c->name]['default'])) {
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']);
}
}
@ -268,7 +292,7 @@ class Postgres extends DboSource {
*
* @param string $source Name of the database table
* @param string $field Name of the ID database field. Defaults to "id"
* @return integer
* @return int
*/
public function lastInsertId($source = null, $field = 'id') {
$seq = $this->getSequence($source, $field);
@ -286,20 +310,41 @@ class Postgres extends DboSource {
if (is_object($table)) {
$table = $this->fullTableName($table, false, false);
}
if (isset($this->_sequenceMap[$table]) && isset($this->_sequenceMap[$table][$field])) {
return $this->_sequenceMap[$table][$field];
} else {
return "{$table}_{$field}_seq";
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 boolean $reset true for resetting the sequence, false to leave it as is.
* @param bool $reset true for resetting the sequence, false to leave it as is.
* and if 1, sequences are not modified
* @return boolean SQL TRUNCATE TABLE statement, false if not applicable.
* @return bool SQL TRUNCATE TABLE statement, false if not applicable.
*/
public function truncate($table, $reset = false) {
$table = $this->fullTableName($table, false, false);
@ -310,11 +355,10 @@ class Postgres extends DboSource {
$this->cacheSources = $cache;
}
if ($this->execute('DELETE FROM ' . $this->fullTableName($table))) {
$schema = $this->config['schema'];
if (isset($this->_sequenceMap[$table]) && $reset != true) {
foreach ($this->_sequenceMap[$table] as $field => $sequence) {
list($schema, $sequence) = explode('.', $sequence);
$this->_execute("ALTER SEQUENCE \"{$schema}\".\"{$sequence}\" RESTART WITH 1");
foreach ($this->_sequenceMap[$table] as $sequence) {
$quoted = $this->name($sequence);
$this->_execute("ALTER SEQUENCE {$quoted} RESTART WITH 1");
}
}
return true;
@ -325,7 +369,7 @@ class Postgres extends DboSource {
/**
* Prepares field names to be quoted by parent
*
* @param string $data
* @param string $data The name to format.
* @return string SQL field
*/
public function name($data) {
@ -338,10 +382,10 @@ class Postgres extends DboSource {
/**
* Generates the fields list of an SQL query.
*
* @param Model $model
* @param string $alias Alias table name
* @param mixed $fields
* @param boolean $quote
* @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) {
@ -359,7 +403,7 @@ class Postgres extends DboSource {
$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 (substr($fields[$i], -1) === '*') {
if (strpos($fields[$i], '.') !== false && $fields[$i] != $alias . '.*') {
$build = explode('.', $fields[$i]);
$AssociatedModel = $model->{$build[0]};
@ -385,7 +429,7 @@ class Postgres extends DboSource {
$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]);
$fields[$i] = preg_replace_callback('/\(([\s\.\w]+)\)/', array(&$this, '_quoteFunctionField'), $fields[$i]);
}
$result[] = $fields[$i];
}
@ -473,7 +517,7 @@ class Postgres extends DboSource {
$colList = array();
foreach ($compare as $curTable => $types) {
$indexes = $colList = array();
if (!$table || $table == $curTable) {
if (!$table || $table === $curTable) {
$out .= 'ALTER TABLE ' . $this->fullTableName($curTable) . " \n";
foreach ($types as $type => $column) {
if (isset($column['indexes'])) {
@ -486,37 +530,59 @@ class Postgres extends DboSource {
$col['name'] = $field;
$colList[] = 'ADD COLUMN ' . $this->buildColumn($col);
}
break;
break;
case 'drop':
foreach ($column as $field => $col) {
$col['name'] = $field;
$colList[] = 'DROP COLUMN ' . $this->name($field);
}
break;
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']);
$colList[] = 'ALTER COLUMN ' . $fieldName . ' TYPE ' . str_replace(array($fieldName, 'NOT NULL'), '', $this->buildColumn($col));
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 {
if ($original['type'] === 'text' && $col['type'] === 'integer') {
$colList[] = 'ALTER COLUMN ' . $fieldName . ' TYPE ' . str_replace(array($fieldName, 'NOT NULL'), '', $this->buildColumn($col)) . " USING cast({$fieldName} as INTEGER)";
} 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)) {
$colList[] = 'ALTER COLUMN ' . $fieldName . ' SET DEFAULT ' . $this->value($default, $col['type']);
if (!$boolToInt) {
$colList[] = 'ALTER COLUMN ' . $fieldName . ' SET DEFAULT ' . $this->value($default, $col['type']);
}
} else {
$colList[] = 'ALTER COLUMN ' . $fieldName . ' DROP DEFAULT';
}
}
break;
break;
}
}
if (isset($indexes['drop']['PRIMARY'])) {
@ -553,7 +619,7 @@ class Postgres extends DboSource {
if (isset($indexes['drop'])) {
foreach ($indexes['drop'] as $name => $value) {
$out = 'DROP ';
if ($name == 'PRIMARY') {
if ($name === 'PRIMARY') {
continue;
} else {
$out .= 'INDEX ' . $name;
@ -564,7 +630,7 @@ class Postgres extends DboSource {
if (isset($indexes['add'])) {
foreach ($indexes['add'] as $name => $value) {
$out = 'CREATE ';
if ($name == 'PRIMARY') {
if ($name === 'PRIMARY') {
continue;
} else {
if (!empty($value['unique'])) {
@ -586,22 +652,16 @@ class Postgres extends DboSource {
/**
* Returns a limit statement in the correct format for the particular database.
*
* @param integer $limit Limit of results returned
* @param integer $offset Offset from which to start results
* @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), 'limit') || strpos(strtolower($limit), 'limit') === 0) {
$rt = ' LIMIT';
}
$rt .= ' ' . $limit;
$rt = sprintf(' LIMIT %u', $limit);
if ($offset) {
$rt .= ' OFFSET ' . $offset;
$rt .= sprintf(' OFFSET %u', $offset);
}
return $rt;
}
return null;
@ -623,14 +683,13 @@ class Postgres extends DboSource {
}
$col = str_replace(')', '', $real);
$limit = null;
if (strpos($col, '(') !== false) {
list($col, $limit) = explode('(', $col);
}
$floats = array(
'float', 'float4', 'float8', 'double', 'double precision', 'decimal', 'real', 'numeric'
'float', 'float4', 'float8', 'double', 'double precision', 'real'
);
switch (true) {
@ -640,14 +699,20 @@ class Postgres extends DboSource {
return 'datetime';
case (strpos($col, 'time') === 0):
return 'time';
case (strpos($col, 'int') !== false && $col != 'interval'):
case ($col === 'bigint'):
return 'biginteger';
case (strpos($col, 'int') !== false && $col !== 'interval'):
return 'integer';
case (strpos($col, 'char') !== false || $col == 'uuid'):
case (strpos($col, 'char') !== false):
return 'string';
case (strpos($col, 'uuid') !== false):
return 'uuid';
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:
@ -659,28 +724,23 @@ class Postgres extends DboSource {
* 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 integer An integer representing the length of the column
* @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);
$col = $real;
if (strpos($real, '(') !== false) {
list($col, $limit) = explode('(', $real);
}
if ($col == 'uuid') {
if ($col === 'uuid') {
return 36;
}
if ($limit != null) {
return intval($limit);
}
return null;
return parent::length($real);
}
/**
* resultSet method
*
* @param array $results
* @param array &$results The results
* @return void
*/
public function resultSet(&$results) {
@ -715,30 +775,28 @@ class Postgres extends DboSource {
switch ($type) {
case 'bool':
$resultRow[$table][$column] = is_null($row[$index]) ? null : $this->boolean($row[$index]);
break;
$resultRow[$table][$column] = $row[$index] === null ? null : $this->boolean($row[$index]);
break;
case 'binary':
case 'bytea':
$resultRow[$table][$column] = is_null($row[$index]) ? null : stream_get_contents($row[$index]);
break;
$resultRow[$table][$column] = $row[$index] === null ? null : stream_get_contents($row[$index]);
break;
default:
$resultRow[$table][$column] = $row[$index];
break;
}
}
return $resultRow;
} else {
$this->_result->closeCursor();
return false;
}
$this->_result->closeCursor();
return false;
}
/**
* Translates between PHP boolean values and PostgreSQL boolean values
*
* @param mixed $data Value to be translated
* @param boolean $quote true to quote a boolean to be used in a query, false to return the boolean value
* @return boolean Converted boolean value
* @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) {
@ -756,7 +814,6 @@ class Postgres extends DboSource {
break;
default:
$result = (bool)$data;
break;
}
if ($quote) {
@ -769,7 +826,7 @@ class Postgres extends DboSource {
* Sets the database encoding
*
* @param mixed $enc Database encoding
* @return boolean True on success, false on failure
* @return bool True on success, false on failure
*/
public function setEncoding($enc) {
return $this->_execute('SET NAMES ' . $this->value($enc)) !== false;
@ -801,8 +858,21 @@ class Postgres extends DboSource {
if (!isset($col['length']) && !isset($col['limit'])) {
unset($column['length']);
}
$out = preg_replace('/integer\([0-9]+\)/', 'integer', parent::buildColumn($column));
$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);
@ -815,7 +885,7 @@ class Postgres extends DboSource {
$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') {
} elseif ($column['type'] === 'boolean') {
$out = str_replace('DEFAULT DEFAULT', 'DEFAULT FALSE', $out);
}
}
@ -825,8 +895,8 @@ class Postgres extends DboSource {
/**
* Format indexes for create table
*
* @param array $indexes
* @param string $table
* @param array $indexes The index to build
* @param string $table The table name.
* @return string
*/
public function buildIndex($indexes, $table = null) {
@ -835,7 +905,7 @@ class Postgres extends DboSource {
return array();
}
foreach ($indexes as $name => $value) {
if ($name == 'PRIMARY') {
if ($name === 'PRIMARY') {
$out = 'PRIMARY KEY (' . $this->name($value['column']) . ')';
} else {
$out = 'CREATE ';
@ -854,11 +924,22 @@ class Postgres extends DboSource {
return $join;
}
/**
* {@inheritDoc}
*/
public function value($data, $column = null, $null = true) {
$value = parent::value($data, $column, $null);
if ($column === 'uuid' && is_scalar($data) && $data === '') {
return 'NULL';
}
return $value;
}
/**
* Overrides DboSource::renderStatement to handle schema generation with Postgres-style indexes
*
* @param string $type
* @param array $data
* @param string $type The query type.
* @param array $data The array of data to render.
* @return string
*/
public function renderStatement($type, $data) {
@ -898,7 +979,7 @@ class Postgres extends DboSource {
/**
* Check if the server support nested transactions
*
* @return boolean
* @return bool
*/
public function nestedTransactionSupported() {
return $this->useNestedTransactions && version_compare($this->getVersion(), '8.0', '>=');

View file

@ -2,23 +2,22 @@
/**
* SQLite layer for DBO
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.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 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @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 MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('DboSource', 'Model/Datasource');
App::uses('String', 'Utility');
App::uses('CakeText', 'Utility');
/**
* DBO implementation for the SQLite3 DBMS.
@ -57,7 +56,8 @@ class Sqlite extends DboSource {
*/
protected $_baseConfig = array(
'persistent' => false,
'database' => null
'database' => null,
'flags' => array()
);
/**
@ -70,7 +70,9 @@ class Sqlite extends DboSource {
'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'),
@ -100,12 +102,12 @@ class Sqlite extends DboSource {
/**
* Connects to the database using config['database'] as a filename.
*
* @return boolean
* @return bool
* @throws MissingConnectionException
*/
public function connect() {
$config = $this->config;
$flags = array(
$flags = $config['flags'] + array(
PDO::ATTR_PERSISTENT => $config['persistent'],
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
@ -124,7 +126,7 @@ class Sqlite extends DboSource {
/**
* Check whether the SQLite extension is installed/loaded
*
* @return boolean
* @return bool
*/
public function enabled() {
return in_array('sqlite', PDO::getAvailableDrivers());
@ -133,12 +135,12 @@ class Sqlite extends DboSource {
/**
* Returns an array of tables in the database. If there are no tables, an error is raised and the application exits.
*
* @param mixed $data
* @param mixed $data Unused.
* @return array Array of table names in the database
*/
public function listSources($data = null) {
$cache = parent::listSources();
if ($cache != null) {
if ($cache) {
return $cache;
}
@ -146,14 +148,14 @@ class Sqlite extends DboSource {
if (!$result || empty($result)) {
return array();
} else {
$tables = array();
foreach ($result as $table) {
$tables[] = $table[0]['name'];
}
parent::listSources($tables);
return $tables;
}
$tables = array();
foreach ($result as $table) {
$tables[] = $table[0]['name'];
}
parent::listSources($tables);
return $tables;
}
/**
@ -165,7 +167,7 @@ class Sqlite extends DboSource {
public function describe($model) {
$table = $this->fullTableName($model, false, false);
$cache = parent::describe($table);
if ($cache != null) {
if ($cache) {
return $cache;
}
$fields = array();
@ -183,6 +185,9 @@ class Sqlite extends DboSource {
'default' => $default,
'length' => $this->length($column['type'])
);
if (in_array($fields[$column['name']]['type'], array('timestamp', 'datetime')) && strtoupper($fields[$column['name']]['default']) === 'CURRENT_TIMESTAMP') {
$fields[$column['name']]['default'] = null;
}
if ($column['pk'] == 1) {
$fields[$column['name']]['key'] = $this->index['PRI'];
$fields[$column['name']]['null'] = false;
@ -200,10 +205,10 @@ class Sqlite extends DboSource {
/**
* Generates and executes an SQL UPDATE statement for given model, fields, and values.
*
* @param Model $model
* @param array $fields
* @param array $values
* @param mixed $conditions
* @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) {
@ -225,10 +230,12 @@ class Sqlite extends DboSource {
* primary key, where applicable.
*
* @param string|Model $table A string or model class representing the table to be truncated
* @return boolean SQL TRUNCATE TABLE statement, false if not applicable.
* @return bool SQL TRUNCATE TABLE statement, false if not applicable.
*/
public function truncate($table) {
$this->_execute('DELETE FROM sqlite_sequence where name=' . $this->startQuote . $this->fullTableName($table, false, false) . $this->endQuote);
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));
}
@ -248,14 +255,26 @@ class Sqlite extends DboSource {
}
$col = strtolower(str_replace(')', '', $real));
$limit = null;
if (strpos($col, '(') !== false) {
list($col, $limit) = explode('(', $col);
list($col) = explode('(', $col);
}
if (in_array($col, array('text', 'integer', 'float', 'boolean', 'timestamp', 'date', 'datetime', 'time'))) {
$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';
}
@ -263,7 +282,7 @@ class Sqlite extends DboSource {
return 'binary';
}
if (strpos($col, 'numeric') !== false || strpos($col, 'decimal') !== false) {
return 'float';
return 'decimal';
}
return 'text';
}
@ -271,7 +290,7 @@ class Sqlite extends DboSource {
/**
* Generate ResultSet
*
* @param mixed $results
* @param mixed $results The results to modify.
* @return void
*/
public function resultSet($results) {
@ -281,14 +300,19 @@ class Sqlite extends DboSource {
$index = 0;
$j = 0;
//PDO::getColumnMeta is experimental and does not work with sqlite3,
// so try to figure it out based on the querystring
// 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, ',', '(', ')');
if (stripos($querystring, 'SELECT') === 0 && stripos($querystring, 'FROM') > 0) {
$selectpart = substr($querystring, 7);
$selects = array();
foreach (CakeText::tokenize($selectpart, ',', '(', ')') as $part) {
$fromPos = stripos($part, ' FROM ');
if ($fromPos !== false) {
$selects[] = trim(substr($part, 0, $fromPos));
break;
}
$selects[] = $part;
}
} elseif (strpos($querystring, 'PRAGMA table_info') === 0) {
$selects = array('cid', 'name', 'type', 'notnull', 'dflt_value', 'pk');
@ -302,8 +326,8 @@ class Sqlite extends DboSource {
$j++;
continue;
}
if (preg_match('/\bAS\s+(.*)/i', $selects[$j], $matches)) {
$columnName = trim($matches[1], '"');
if (preg_match('/\bAS(?!.*\bAS\b)\s+(.*)/i', $selects[$j], $matches)) {
$columnName = trim($matches[1], '"');
} else {
$columnName = trim(str_replace('"', '', $selects[$j]));
}
@ -342,33 +366,28 @@ class Sqlite extends DboSource {
foreach ($this->map as $col => $meta) {
list($table, $column, $type) = $meta;
$resultRow[$table][$column] = $row[$col];
if ($type == 'boolean' && !is_null($row[$col])) {
if ($type === 'boolean' && $row[$col] !== null) {
$resultRow[$table][$column] = $this->boolean($resultRow[$table][$column]);
}
}
return $resultRow;
} else {
$this->_result->closeCursor();
return false;
}
$this->_result->closeCursor();
return false;
}
/**
* Returns a limit statement in the correct format for the particular database.
*
* @param integer $limit Limit of results returned
* @param integer $offset Offset from which to start results
* @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), 'limit') || strpos(strtolower($limit), 'limit') === 0) {
$rt = ' LIMIT';
}
$rt .= ' ' . $limit;
$rt = sprintf(' LIMIT %u', $limit);
if ($offset) {
$rt .= ' OFFSET ' . $offset;
$rt .= sprintf(' OFFSET %u', $offset);
}
return $rt;
}
@ -384,7 +403,7 @@ class Sqlite extends DboSource {
*/
public function buildColumn($column) {
$name = $type = null;
$column = array_merge(array('null' => true), $column);
$column += array('null' => true);
extract($column);
if (empty($name) || empty($type)) {
@ -397,17 +416,26 @@ class Sqlite extends DboSource {
return null;
}
if (isset($column['key']) && $column['key'] == 'primary' && $type == 'integer') {
$isPrimary = (isset($column['key']) && $column['key'] === 'primary');
if ($isPrimary && $type === 'integer') {
return $this->name($name) . ' ' . $this->columns['primary_key']['name'];
}
return parent::buildColumn($column);
$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 boolean
* @return bool
*/
public function setEncoding($enc) {
if (!in_array($enc, array("UTF-8", "UTF-16", "UTF-16le", "UTF-16be"))) {
@ -428,9 +456,9 @@ class Sqlite extends DboSource {
/**
* Removes redundant primary key indexes, as they are handled in the column def of the key.
*
* @param array $indexes
* @param string $table
* @return string
* @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();
@ -441,7 +469,7 @@ class Sqlite extends DboSource {
foreach ($indexes as $name => $value) {
if ($name == 'PRIMARY') {
if ($name === 'PRIMARY') {
continue;
}
$out = 'CREATE ';
@ -450,7 +478,7 @@ class Sqlite extends DboSource {
$out .= 'UNIQUE ';
}
if (is_array($value['column'])) {
$value['column'] = join(', ', array_map(array(&$this, 'name'), $value['column']));
$value['column'] = implode(', ', array_map(array(&$this, 'name'), $value['column']));
} else {
$value['column'] = $this->name($value['column']);
}
@ -489,7 +517,7 @@ class Sqlite extends DboSource {
$key['name'] = 'PRIMARY';
}
$index[$key['name']]['column'] = $keyCol[0]['name'];
$index[$key['name']]['unique'] = intval($key['unique'] == 1);
$index[$key['name']]['unique'] = (int)$key['unique'] === 1;
} else {
if (!is_array($index[$key['name']]['column'])) {
$col[] = $index[$key['name']]['column'];
@ -506,8 +534,8 @@ class Sqlite extends DboSource {
/**
* Overrides DboSource::renderStatement to handle schema generation with SQLite-style indexes
*
* @param string $type
* @param array $data
* @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) {
@ -515,10 +543,10 @@ class Sqlite extends DboSource {
case 'schema':
extract($data);
if (is_array($columns)) {
$columns = "\t" . join(",\n\t", array_filter($columns));
$columns = "\t" . implode(",\n\t", array_filter($columns));
}
if (is_array($indexes)) {
$indexes = "\t" . join("\n\t", array_filter($indexes));
$indexes = "\t" . implode("\n\t", array_filter($indexes));
}
return "CREATE TABLE {$table} (\n{$columns});\n{$indexes}";
default:
@ -529,28 +557,20 @@ class Sqlite extends DboSource {
/**
* PDO deals in objects, not resources, so overload accordingly.
*
* @return boolean
* @return bool
*/
public function hasResult() {
return is_object($this->_result);
}
/**
* Generate a "drop table" statement for the given Schema object
* Generate a "drop table" statement for the given table
*
* @param CakeSchema $schema An instance of a subclass of CakeSchema
* @param string $table Optional. If specified only the table name given will be generated.
* Otherwise, all tables defined in the schema are generated.
* @return string
* @param type $table Name of the table to drop
* @return string Drop table SQL statement
*/
public function dropSchema(CakeSchema $schema, $table = null) {
$out = '';
foreach ($schema->tables as $curTable => $columns) {
if (!$table || $table == $curTable) {
$out .= 'DROP TABLE IF EXISTS ' . $this->fullTableName($curTable) . ";\n";
}
}
return $out;
protected function _dropTable($table) {
return 'DROP TABLE IF EXISTS ' . $this->fullTableName($table) . ";";
}
/**
@ -565,7 +585,7 @@ class Sqlite extends DboSource {
/**
* Check if the server support nested transactions
*
* @return boolean
* @return bool
*/
public function nestedTransactionSupported() {
return $this->useNestedTransactions && version_compare($this->getVersion(), '3.6.8', '>=');

View file

@ -2,28 +2,29 @@
/**
* MS SQL Server layer for DBO
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.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 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @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 MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('DboSource', 'Model/Datasource');
/**
* Dbo driver for SQLServer
* Dbo layer for Microsoft's official SQLServer driver
*
* A Dbo driver for SQLServer 2008 and higher. Requires the `sqlsrv`
* and `pdo_sqlsrv` extensions to be enabled.
* 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
*/
@ -51,7 +52,7 @@ class Sqlserver extends DboSource {
public $endQuote = "]";
/**
* Creates a map between field aliases and numeric indexes. Workaround for the
* Creates a map between field aliases and numeric indexes. Workaround for the
* SQL Server driver's 30-character column name limitation.
*
* @var array
@ -77,6 +78,7 @@ class Sqlserver extends DboSource {
'password' => '',
'database' => 'cake',
'schema' => '',
'flags' => array()
);
/**
@ -86,41 +88,50 @@ class Sqlserver extends DboSource {
*/
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'),
'float' => array('name' => 'numeric', 'formatter' => 'floatval'),
'datetime' => array('name' => 'datetime', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
'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')
'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 boolean True if the database could be connected, else false
* @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 {
$flags = array(
PDO::ATTR_PERSISTENT => $config['persistent'],
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
if (!empty($config['encoding'])) {
$flags[PDO::SQLSRV_ATTR_ENCODING] = $config['encoding'];
}
$this->_connection = new PDO(
"sqlsrv:server={$config['host']};Database={$config['database']}",
$config['login'],
@ -128,6 +139,11 @@ class Sqlserver extends DboSource {
$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),
@ -141,7 +157,7 @@ class Sqlserver extends DboSource {
/**
* Check that PDO SQL Server is installed/loaded
*
* @return boolean
* @return bool
*/
public function enabled() {
return in_array('sqlsrv', PDO::getAvailableDrivers());
@ -150,7 +166,7 @@ class Sqlserver extends DboSource {
/**
* Returns an array of sources (tables) in the database.
*
* @param mixed $data
* @param mixed $data The names
* @return array Array of table names in the database
*/
public function listSources($data = null) {
@ -163,17 +179,16 @@ class Sqlserver extends DboSource {
if (!$result) {
$result->closeCursor();
return array();
} else {
$tables = array();
while ($line = $result->fetch(PDO::FETCH_NUM)) {
$tables[] = $line[0];
}
$result->closeCursor();
parent::listSources($tables);
return $tables;
}
$tables = array();
while ($line = $result->fetch(PDO::FETCH_NUM)) {
$tables[] = $line[0];
}
$result->closeCursor();
parent::listSources($tables);
return $tables;
}
/**
@ -184,25 +199,30 @@ class Sqlserver extends DboSource {
* @throws CakeException
*/
public function describe($model) {
$table = $this->fullTableName($model, false);
$cache = parent::describe($table);
if ($cache != null) {
$table = $this->fullTableName($model, false, false);
$fulltable = $this->fullTableName($model, false, true);
$cache = parent::describe($fulltable);
if ($cache) {
return $cache;
}
$fields = array();
$table = $this->fullTableName($model, false);
$schema = is_object($model) ? $model->schemaName : false;
$cols = $this->_execute(
"SELECT
COLUMN_NAME as Field,
DATA_TYPE as Type,
COL_LENGTH('" . $table . "', COLUMN_NAME) as Length,
COL_LENGTH('" . ($schema ? $fulltable : $table) . "', COLUMN_NAME) as Length,
IS_NULLABLE As [Null],
COLUMN_DEFAULT as [Default],
COLUMNPROPERTY(OBJECT_ID('" . $table . "'), COLUMN_NAME, 'IsIdentity') as [Key],
COLUMNPROPERTY(OBJECT_ID('" . ($schema ? $fulltable : $table) . "'), COLUMN_NAME, 'IsIdentity') as [Key],
NUMERIC_SCALE as Size
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = '" . $table . "'"
WHERE TABLE_NAME = '" . $table . "'" . ($schema ? " AND TABLE_SCHEMA = '" . $schema . "'" : '')
);
if (!$cols) {
throw new CakeException(__d('cake_dev', 'Could not describe table for %s', $table));
}
@ -212,18 +232,24 @@ class Sqlserver extends DboSource {
$fields[$field] = array(
'type' => $this->column($column),
'null' => ($column->Null === 'YES' ? true : false),
'default' => preg_replace("/^[(]{1,2}'?([^')]*)?'?[)]{1,2}$/", "$1", $column->Default),
'default' => $column->Default,
'length' => $this->length($column),
'key' => ($column->Key == '1') ? 'primary' : false
);
if ($fields[$field]['default'] === 'null') {
$fields[$field]['default'] = null;
} else {
}
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') {
if ($fields[$field]['key'] !== false && $fields[$field]['type'] === 'integer') {
$fields[$field]['length'] = 11;
} elseif ($fields[$field]['key'] === false) {
unset($fields[$field]['key']);
@ -231,7 +257,7 @@ class Sqlserver extends DboSource {
if (in_array($fields[$field]['type'], array('date', 'time', 'datetime', 'timestamp'))) {
$fields[$field]['length'] = null;
}
if ($fields[$field]['type'] == 'float' && !empty($column->Size)) {
if ($fields[$field]['type'] === 'float' && !empty($column->Size)) {
$fields[$field]['length'] = $fields[$field]['length'] . ',' . $column->Size;
}
}
@ -243,10 +269,10 @@ class Sqlserver extends DboSource {
/**
* Generates the fields list of an SQL query.
*
* @param Model $model
* @param Model $model The model to get fields for.
* @param string $alias Alias table name
* @param array $fields
* @param boolean $quote
* @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) {
@ -261,13 +287,13 @@ class Sqlserver extends DboSource {
for ($i = 0; $i < $count; $i++) {
$prepend = '';
if (strpos($fields[$i], 'DISTINCT') !== false) {
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 (substr($fields[$i], -1) === '*') {
if (strpos($fields[$i], '.') !== false && $fields[$i] != $alias . '.*') {
$build = explode('.', $fields[$i]);
$AssociatedModel = $model->{$build[0]};
@ -282,7 +308,7 @@ class Sqlserver extends DboSource {
if (strpos($fields[$i], '.') === false) {
$this->_fieldMappings[$alias . '__' . $fields[$i]] = $alias . '.' . $fields[$i];
$fieldName = $this->name($alias . '.' . $fields[$i]);
$fieldName = $this->name($alias . '.' . $fields[$i]);
$fieldAlias = $this->name($alias . '__' . $fields[$i]);
} else {
$build = explode('.', $fields[$i]);
@ -295,7 +321,7 @@ class Sqlserver extends DboSource {
$fieldName = $this->name($name);
$fieldAlias = $this->name($alias);
}
if ($model->getColumnType($fields[$i]) == 'datetime') {
if ($model->getColumnType($fields[$i]) === 'datetime') {
$fieldName = "CONVERT(VARCHAR(20), {$fieldName}, 20)";
}
$fields[$i] = "{$fieldName} AS {$fieldAlias}";
@ -303,9 +329,8 @@ class Sqlserver extends DboSource {
$result[] = $prepend . $fields[$i];
}
return $result;
} else {
return $fields;
}
return $fields;
}
/**
@ -313,9 +338,9 @@ class Sqlserver extends DboSource {
* Removes Identity (primary key) column from update data before returning to parent, if
* value is empty.
*
* @param Model $model
* @param array $fields
* @param array $values
* @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) {
@ -342,10 +367,10 @@ class Sqlserver extends DboSource {
* 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
* @param array $fields
* @param array $values
* @param mixed $conditions
* @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) {
@ -364,8 +389,8 @@ class Sqlserver extends DboSource {
/**
* Returns a limit statement in the correct format for the particular database.
*
* @param integer $limit Limit of results returned
* @param integer $offset Offset from which to start results
* @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) {
@ -374,9 +399,9 @@ class Sqlserver extends DboSource {
if (!strpos(strtolower($limit), 'top') || strpos(strtolower($limit), 'top') === 0) {
$rt = ' TOP';
}
$rt .= ' ' . $limit;
$rt .= sprintf(' %u', $limit);
if (is_int($offset) && $offset > 0) {
$rt = ' OFFSET ' . intval($offset) . ' ROWS FETCH FIRST ' . intval($limit) . ' ROWS ONLY';
$rt = sprintf(' OFFSET %u ROWS FETCH FIRST %u ROWS ONLY', $offset, $limit);
}
return $rt;
}
@ -398,15 +423,18 @@ class Sqlserver extends DboSource {
$col = $real->Type;
}
if ($col == 'datetime2') {
if ($col === 'datetime2') {
return 'datetime';
}
if (in_array($col, array('date', 'time', 'datetime', 'timestamp'))) {
return $col;
}
if ($col == 'bit') {
if ($col === 'bit') {
return 'boolean';
}
if (strpos($col, 'bigint') !== false) {
return 'biginteger';
}
if (strpos($col, 'int') !== false) {
return 'integer';
}
@ -419,12 +447,15 @@ class Sqlserver extends DboSource {
if (strpos($col, 'text') !== false) {
return 'text';
}
if (strpos($col, 'binary') !== false || $col == 'image') {
if (strpos($col, 'binary') !== false || $col === 'image') {
return 'binary';
}
if (in_array($col, array('float', 'real', 'decimal', 'numeric'))) {
if (in_array($col, array('float', 'real'))) {
return 'float';
}
if (in_array($col, array('decimal', 'numeric'))) {
return 'decimal';
}
return 'text';
}
@ -443,6 +474,9 @@ class Sqlserver extends DboSource {
if (in_array($length->Type, array('nchar', 'nvarchar'))) {
return floor($length->Length / 2);
}
if ($length->Type === 'text') {
return null;
}
return $length->Length;
}
return parent::length($length);
@ -451,7 +485,7 @@ class Sqlserver extends DboSource {
/**
* Builds a map of the columns contained in a result
*
* @param PDOStatement $results
* @param PDOStatement $results The result to modify.
* @return void
*/
public function resultSet($results) {
@ -474,7 +508,7 @@ class Sqlserver extends DboSource {
} else {
$map = array(0, $name);
}
$map[] = ($column['sqlsrv:decl_type'] == 'bit') ? 'boolean' : $column['native_type'];
$map[] = ($column['sqlsrv:decl_type'] === 'bit') ? 'boolean' : $column['native_type'];
$this->map[$index++] = $map;
}
}
@ -506,25 +540,24 @@ class Sqlserver extends DboSource {
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);
$limit = 'TOP ' . (int)$limitOffset[2];
$page = (int)($limitOffset[1] / $limitOffset[2]);
$offset = (int)($limitOffset[2] * $page);
$rowCounter = self::ROW_COUNTER;
return "
SELECT {$limit} * FROM (
$rowCounter = static::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}
";
} elseif (strpos($limit, 'FETCH') !== false) {
return "SELECT {$fields} FROM {$table} {$alias} {$joins} {$conditions} {$group} {$order} {$limit}";
} else {
return "SELECT {$limit} {$fields} FROM {$table} {$alias} {$joins} {$conditions} {$group} {$order}";
return trim($sql);
}
break;
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);
@ -540,7 +573,7 @@ class Sqlserver extends DboSource {
${$var} = "\t" . implode(",\n\t", array_filter(${$var}));
}
}
return "CREATE TABLE {$table} (\n{$columns});\n{$indexes}";
return trim("CREATE TABLE {$table} (\n{$columns});\n{$indexes}");
default:
return parent::renderStatement($type, $data);
}
@ -551,12 +584,14 @@ class Sqlserver extends DboSource {
*
* @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
* @param bool $null Column allows NULL values
* @return string Quoted and escaped data
*/
public function value($data, $column = null) {
if (is_array($data) || is_object($data)) {
return parent::value($data, $column);
} elseif (in_array($data, array('{$__cakeID__$}', '{$__cakeForeignKey__$}'), true)) {
public function value($data, $column = null, $null = true) {
if ($data === null || is_array($data) || is_object($data)) {
return parent::value($data, $column, $null);
}
if (in_array($data, array('{$__cakeID__$}', '{$__cakeForeignKey__$}'), true)) {
return $data;
}
@ -569,7 +604,7 @@ class Sqlserver extends DboSource {
case 'text':
return 'N' . $this->_connection->quote($data, PDO::PARAM_STR);
default:
return parent::value($data, $column);
return parent::value($data, $column, $null);
}
}
@ -577,10 +612,10 @@ class Sqlserver extends DboSource {
* Returns an array of all result rows for a given SQL query.
* Returns false if no rows matched.
*
* @param Model $model
* @param array $queryData
* @param integer $recursive
* @return array Array of resultset rows, or 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);
@ -599,11 +634,11 @@ class Sqlserver extends DboSource {
$resultRow = array();
foreach ($this->map as $col => $meta) {
list($table, $column, $type) = $meta;
if ($table === 0 && $column === self::ROW_COUNTER) {
if ($table === 0 && $column === static::ROW_COUNTER) {
continue;
}
$resultRow[$table][$column] = $row[$col];
if ($type === 'boolean' && !is_null($row[$col])) {
if ($type === 'boolean' && $row[$col] !== null) {
$resultRow[$table][$column] = $this->boolean($resultRow[$table][$column]);
}
}
@ -616,14 +651,14 @@ class Sqlserver extends DboSource {
/**
* Inserts multiple values into a table
*
* @param string $table
* @param string $fields
* @param array $values
* @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 != null && (
$hasPrimaryKey = $primaryKey && (
(is_array($fields) && in_array($primaryKey, $fields)
|| (is_string($fields) && strpos($fields, $this->startQuote . $primaryKey . $this->endQuote) !== false))
);
@ -649,7 +684,7 @@ class Sqlserver extends DboSource {
*/
public function buildColumn($column) {
$result = parent::buildColumn($column);
$result = preg_replace('/(int|integer)\([0-9]+\)/i', '$1', $result);
$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'] === '') {
@ -657,7 +692,7 @@ class Sqlserver extends DboSource {
} else {
$result = str_replace('DEFAULT NULL', 'NULL', $result);
}
} elseif (array_keys($column) == array('type', 'name')) {
} elseif (array_keys($column) === array('type', 'name')) {
$result .= ' NULL';
} elseif (strpos($result, "DEFAULT N'")) {
$result = str_replace("DEFAULT N'", "DEFAULT '", $result);
@ -668,15 +703,15 @@ class Sqlserver extends DboSource {
/**
* Format indexes for create table
*
* @param array $indexes
* @param string $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') {
if ($name === 'PRIMARY') {
$join[] = 'PRIMARY KEY (' . $this->name($value['column']) . ')';
} elseif (isset($value['unique']) && $value['unique']) {
$out = "ALTER TABLE {$table} ADD CONSTRAINT {$name} UNIQUE";
@ -702,7 +737,7 @@ class Sqlserver extends DboSource {
protected function _getPrimaryKey($model) {
$schema = $this->describe($model);
foreach ($schema as $field => $props) {
if (isset($props['key']) && $props['key'] == 'primary') {
if (isset($props['key']) && $props['key'] === 'primary') {
return $field;
}
}
@ -713,8 +748,8 @@ class Sqlserver extends DboSource {
* Returns number of affected rows in previous database operation. If no previous operation exists,
* this returns false.
*
* @param mixed $source
* @return integer Number of affected rows
* @param mixed $source Unused
* @return int Number of affected rows
*/
public function lastAffected($source = null) {
$affected = parent::lastAffected();
@ -736,7 +771,8 @@ class Sqlserver extends DboSource {
*/
protected function _execute($sql, $params = array(), $prepareOptions = array()) {
$this->_lastAffected = false;
if (strncasecmp($sql, 'SELECT', 6) == 0 || preg_match('/^EXEC(?:UTE)?\s/mi', $sql) > 0) {
$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);
}
@ -760,21 +796,13 @@ class Sqlserver extends DboSource {
}
/**
* Generate a "drop table" statement for the given Schema object
* Generate a "drop table" statement for the given table
*
* @param CakeSchema $schema An instance of a subclass of CakeSchema
* @param string $table Optional. If specified only the table name given will be generated.
* Otherwise, all tables defined in the schema are generated.
* @return string
* @param type $table Name of the table to drop
* @return string Drop table SQL statement
*/
public function dropSchema(CakeSchema $schema, $table = null) {
$out = '';
foreach ($schema->tables as $curTable => $columns) {
if (!$table || $table == $curTable) {
$out .= "IF OBJECT_ID('" . $this->fullTableName($curTable, false) . "', 'U') IS NOT NULL DROP TABLE " . $this->fullTableName($curTable) . ";\n";
}
}
return $out;
protected function _dropTable($table) {
return "IF OBJECT_ID('" . $this->fullTableName($table, false) . "', 'U') IS NOT NULL DROP TABLE " . $this->fullTableName($table) . ";";
}
/**

File diff suppressed because it is too large Load diff

View file

@ -1,20 +1,19 @@
<?php
/**
* Cache Session save handler. Allows saving session information into Cache.
*
* PHP 5
* Cache Session save handler. Allows saving session information into Cache.
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.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 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @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 MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Cache', 'Cache');
@ -31,7 +30,7 @@ class CacheSession implements CakeSessionHandlerInterface {
/**
* Method called on open of a database session.
*
* @return boolean Success
* @return bool Success
*/
public function open() {
return true;
@ -40,7 +39,7 @@ class CacheSession implements CakeSessionHandlerInterface {
/**
* Method called on close of a database session.
*
* @return boolean Success
* @return bool Success
*/
public function close() {
return true;
@ -53,38 +52,43 @@ class CacheSession implements CakeSessionHandlerInterface {
* @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'));
$data = Cache::read($id, Configure::read('Session.handler.config'));
if (!is_numeric($data) && empty($data)) {
return '';
}
return $data;
}
/**
* Helper function called on write for database sessions.
*
* @param integer $id ID that uniquely identifies session in database
* @param int $id ID that uniquely identifies session in database
* @param mixed $data The value of the data to be saved.
* @return boolean True for successful write, false otherwise.
* @return bool True for successful write, false otherwise.
*/
public function write($id, $data) {
return Cache::write($id, $data, Configure::read('Session.handler.config'));
return (bool)Cache::write($id, $data, Configure::read('Session.handler.config'));
}
/**
* Method called on the destruction of a database session.
*
* @param integer $id ID that uniquely identifies session in cache
* @return boolean True for successful delete, false otherwise.
* @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'));
return (bool)Cache::delete($id, Configure::read('Session.handler.config'));
}
/**
* Helper function called on gc for cache sessions.
*
* @param integer $expires Timestamp (defaults to current time)
* @return boolean Success
* @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);
return (bool)Cache::gc(Configure::read('Session.handler.config'), $expires);
}
}

View file

@ -1,20 +1,21 @@
<?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.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 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @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 MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**
* Interface for Session handlers. Custom session handler classes should implement
* 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
@ -24,14 +25,14 @@ interface CakeSessionHandlerInterface {
/**
* Method called on open of a session.
*
* @return boolean Success
* @return bool Success
*/
public function open();
/**
* Method called on close of a session.
*
* @return boolean Success
* @return bool Success
*/
public function close();
@ -46,26 +47,26 @@ interface CakeSessionHandlerInterface {
/**
* Helper function called on write for sessions.
*
* @param integer $id ID that uniquely identifies session in database
* @param int $id ID that uniquely identifies session in database
* @param mixed $data The value of the data to be saved.
* @return boolean True for successful write, false otherwise.
* @return bool True for successful write, false otherwise.
*/
public function write($id, $data);
/**
* Method called on the destruction of a session.
*
* @param integer $id ID that uniquely identifies session in database
* @return boolean True for successful delete, false otherwise.
* @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
* Run the Garbage collection on the session storage. This method should vacuum all
* expired or dead sessions.
*
* @param integer $expires Timestamp (defaults to current time)
* @return boolean Success
* @param int $expires Timestamp (defaults to current time)
* @return bool Success
*/
public function gc($expires = null);

View file

@ -1,20 +1,19 @@
<?php
/**
* Database Session save handler. Allows saving session information into a model.
*
* PHP 5
* Database Session save handler. Allows saving session information into a model.
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.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 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @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 MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('CakeSessionHandlerInterface', 'Model/Datasource/Session');
@ -42,9 +41,8 @@ class DatabaseSession implements CakeSessionHandlerInterface {
protected $_timeout;
/**
* Constructor. Looks at Session configuration information and
* Constructor. Looks at Session configuration information and
* sets up the session model.
*
*/
public function __construct() {
$modelName = Configure::read('Session.handler.model');
@ -68,7 +66,7 @@ class DatabaseSession implements CakeSessionHandlerInterface {
/**
* Method called on open of a database session.
*
* @return boolean Success
* @return bool Success
*/
public function open() {
return true;
@ -77,7 +75,7 @@ class DatabaseSession implements CakeSessionHandlerInterface {
/**
* Method called on close of a database session.
*
* @return boolean Success
* @return bool Success
*/
public function close() {
return true;
@ -86,27 +84,34 @@ class DatabaseSession implements CakeSessionHandlerInterface {
/**
* Method used to read from a database session.
*
* @param integer|string $id The key of the value to read
* @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)
'conditions' => array($this->_model->alias . '.' . $this->_model->primaryKey => $id)
));
if (empty($row[$this->_model->alias]['data'])) {
return false;
if (empty($row[$this->_model->alias])) {
return '';
}
return $row[$this->_model->alias]['data'];
if (!is_numeric($row[$this->_model->alias]['data']) && empty($row[$this->_model->alias]['data'])) {
return '';
}
return (string)$row[$this->_model->alias]['data'];
}
/**
* Helper function called on write for database sessions.
*
* @param integer $id ID that uniquely identifies session in database
* Will retry, once, if the save triggers a PDOException which
* can happen if a race condition is encountered
*
* @param int $id ID that uniquely identifies session in database
* @param mixed $data The value of the data to be saved.
* @return boolean True for successful write, false otherwise.
* @return bool True for successful write, false otherwise.
*/
public function write($id, $data) {
if (!$id) {
@ -115,24 +120,34 @@ class DatabaseSession implements CakeSessionHandlerInterface {
$expires = time() + $this->_timeout;
$record = compact('id', 'data', 'expires');
$record[$this->_model->primaryKey] = $id;
return $this->_model->save($record);
$options = array(
'validate' => false,
'callbacks' => false,
'counterCache' => false
);
try {
return (bool)$this->_model->save($record, $options);
} catch (PDOException $e) {
return (bool)$this->_model->save($record, $options);
}
}
/**
* Method called on the destruction of a database session.
*
* @param integer $id ID that uniquely identifies session in database
* @return boolean True for successful delete, false otherwise.
* @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);
return (bool)$this->_model->delete($id);
}
/**
* Helper function called on gc for database sessions.
*
* @param integer $expires Timestamp (defaults to current time)
* @return boolean Success
* @param int $expires Timestamp (defaults to current time)
* @return bool Success
*/
public function gc($expires = null) {
if (!$expires) {
@ -140,7 +155,8 @@ class DatabaseSession implements CakeSessionHandlerInterface {
} else {
$expires = time() - $expires;
}
return $this->_model->deleteAll(array($this->_model->alias . ".expires <" => $expires), false, false);
$this->_model->deleteAll(array($this->_model->alias . ".expires <" => $expires), false, false);
return true;
}
}

View file

@ -1,18 +1,21 @@
<?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.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 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @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 MIT License (http://www.opensource.org/licenses/mit-license.php)
* @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.
*

File diff suppressed because it is too large Load diff

View file

@ -2,72 +2,71 @@
/**
* Model behaviors base class.
*
* Adds methods and automagic functionality to Cake Models.
*
* PHP 5
* Adds methods and automagic functionality to CakePHP Models.
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.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 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @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 MIT License (http://www.opensource.org/licenses/mit-license.php)
* @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
* 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.
* 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
* 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
* 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
* 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 {
class ModelBehavior extends CakeObject {
/**
* Contains configuration settings for use with individual model objects. This
* 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
* object instance. Individual model settings should be stored as an
* associative array, keyed off of the model name.
*
* @var array
@ -78,7 +77,7 @@ class ModelBehavior extends Object {
/**
* 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
* expression, and the value is a class method. Similar to the functionality of
* the findBy* / findAllBy* magic methods.
*
* @var array
@ -96,7 +95,7 @@ class ModelBehavior extends Object {
}
/**
* Clean up any initialization this behavior has done on a model. Called when a behavior is dynamically
* 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
@ -111,12 +110,12 @@ class ModelBehavior extends Object {
/**
* 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
* 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 boolean|array False or null will abort the operation. You can return an array to replace the
* @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) {
@ -128,21 +127,23 @@ class ModelBehavior extends Object {
*
* @param Model $model Model using this behavior
* @param mixed $results The results of the find operation
* @param boolean $primary Whether this model is being queried directly (vs. being queried as an association)
* @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) {
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
* 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) {
public function beforeValidate(Model $model, $options = array()) {
return true;
}
@ -158,13 +159,15 @@ class ModelBehavior extends Object {
}
/**
* beforeSave is called before a model is saved. Returning false from a beforeSave callback
* 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) {
public function beforeSave(Model $model, $options = array()) {
return true;
}
@ -172,19 +175,21 @@ class ModelBehavior extends Object {
* afterSave is called after a model is saved.
*
* @param Model $model Model using this behavior
* @param boolean $created True if this save created a new record
* @return boolean
* @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) {
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.
* beforeDelete is called. Returning false from a beforeDelete will abort the delete.
*
* @param Model $model Model using this behavior
* @param boolean $cascade If true records that depend on this record will also be deleted
* @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) {
@ -213,7 +218,7 @@ class ModelBehavior extends Object {
/**
* 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
* 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
@ -233,4 +238,3 @@ class ModelBehavior extends Object {
}
}

View file

@ -4,22 +4,22 @@
*
* Provides the Model validation logic.
*
* PHP versions 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.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 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @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 MIT License (http://www.opensource.org/licenses/mit-license.php)
* @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
@ -36,7 +36,7 @@ class ModelValidator implements ArrayAccess, IteratorAggregate, Countable {
/**
* Holds the CakeValidationSet objects array
*
* @var array
* @var CakeValidationSet[]
*/
protected $_fields = array();
@ -48,7 +48,7 @@ class ModelValidator implements ArrayAccess, IteratorAggregate, Countable {
protected $_model = array();
/**
* The validators $validate property, used for checking wheter validation
* The validators $validate property, used for checking whether validation
* rules definition changed in the model and should be refreshed in this class
*
* @var array
@ -90,10 +90,10 @@ class ModelValidator implements ArrayAccess, IteratorAggregate, Countable {
* 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.
* 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 boolean True if there are no errors
* @return bool True if there are no errors
*/
public function validates($options = array()) {
$errors = $this->errors($options);
@ -119,28 +119,27 @@ class ModelValidator implements ArrayAccess, IteratorAggregate, Countable {
* 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 &$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|boolean If atomic: True on success, or false on failure.
* @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_merge(array('atomic' => true, 'deep' => false), $options);
$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;
} else {
$return[$model->alias] = true;
}
$data = $model->data;
if (!empty($options['deep']) && isset($data[$model->alias])) {
$recordData = $data[$model->alias];
unset($data[$model->alias]);
$data = array_merge($data, $recordData);
$data += $recordData;
}
$associations = $model->getAssociated();
@ -156,11 +155,7 @@ class ModelValidator implements ArrayAccess, IteratorAggregate, Countable {
$data[$association] = $model->{$association}->data[$model->{$association}->alias];
}
if (is_array($validates)) {
if (in_array(false, Hash::flatten($validates), true)) {
$validates = false;
} else {
$validates = true;
}
$validates = !in_array(false, Hash::flatten($validates), true);
}
$return[$association] = $validates;
} elseif ($associations[$association] === 'hasMany') {
@ -201,16 +196,15 @@ class ModelValidator implements ArrayAccess, IteratorAggregate, Countable {
* 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 &$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 boolean True on success, or false on failure.
* @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_merge(array('atomic' => true, 'deep' => false), $options);
$options += array('atomic' => true, 'deep' => false);
$model->validationErrors = $validationErrors = $return = array();
foreach ($data as $key => &$record) {
if ($options['deep']) {
@ -232,10 +226,7 @@ class ModelValidator implements ArrayAccess, IteratorAggregate, Countable {
if (!$options['atomic']) {
return $return;
}
if (empty($model->validationErrors)) {
return true;
}
return false;
return empty($model->validationErrors);
}
/**
@ -244,6 +235,7 @@ class ModelValidator implements ArrayAccess, IteratorAggregate, Countable {
*
* @param string $options An optional array of custom options to be made available in the beforeValidate callback
* @return array Array of invalid fields
* @triggers Model.afterValidate $model
* @see ModelValidator::validates()
*/
public function errors($options = array()) {
@ -256,7 +248,15 @@ class ModelValidator implements ArrayAccess, IteratorAggregate, Countable {
return $model->validationErrors;
}
$fieldList = isset($options['fieldList']) ? $options['fieldList'] : array();
$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);
@ -319,13 +319,14 @@ class ModelValidator implements ArrayAccess, IteratorAggregate, Countable {
* 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
* @return CakeValidationSet|array|null
*/
public function getField($name = null) {
$this->_parseRules();
if ($name !== null && !empty($this->_fields[$name])) {
return $this->_fields[$name];
} elseif ($name !== null) {
if ($name !== null) {
if (!empty($this->_fields[$name])) {
return $this->_fields[$name];
}
return null;
}
return $this->_fields;
@ -335,7 +336,7 @@ class ModelValidator implements ArrayAccess, IteratorAggregate, Countable {
* Sets the CakeValidationSet objects from the `Model::$validate` property
* If `Model::$validate` is not set or empty, this method returns false. True otherwise.
*
* @return boolean true if `Model::$validate` was processed, false otherwise
* @return bool true if `Model::$validate` was processed, false otherwise
*/
protected function _parseRules() {
if ($this->_validate === $this->_model->validate) {
@ -362,7 +363,7 @@ class ModelValidator implements ArrayAccess, IteratorAggregate, Countable {
* Sets the I18n domain for validation messages. This method is chainable.
*
* @param string $validationDomain [optional] The validation domain to be used.
* @return ModelValidator
* @return self
*/
public function setValidationDomain($validationDomain = null) {
if (empty($validationDomain)) {
@ -382,36 +383,22 @@ class ModelValidator implements ArrayAccess, IteratorAggregate, Countable {
}
/**
* Processes the Model's whitelist or passed fieldList and returns the list of fields
* to be validated
* 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
* @return CakeValidationSet[] List of validation rules to be applied
*/
protected function _validationList($fieldList = array()) {
$model = $this->getModel();
$whitelist = $model->whitelist;
if (!empty($fieldList)) {
if (!empty($fieldList[$model->alias]) && is_array($fieldList[$model->alias])) {
$whitelist = $fieldList[$model->alias];
} else {
$whitelist = $fieldList;
}
if (empty($fieldList) || Hash::dimensions($fieldList) > 1) {
return $this->_fields;
}
unset($fieldList);
$validateList = array();
if (!empty($whitelist)) {
$this->validationErrors = array();
foreach ((array)$whitelist as $f) {
if (!empty($this->_fields[$f])) {
$validateList[$f] = $this->_fields[$f];
}
$this->validationErrors = array();
foreach ((array)$fieldList as $f) {
if (!empty($this->_fields[$f])) {
$validateList[$f] = $this->_fields[$f];
}
} else {
return $this->_fields;
}
return $validateList;
@ -422,7 +409,7 @@ class ModelValidator implements ArrayAccess, IteratorAggregate, Countable {
* set and data in the data set.
*
* @param array $options Array of options to use on Validation of with models
* @return boolean Failure of validation on with models.
* @return bool Failure of validation on with models.
* @see Model::validates()
*/
protected function _validateWithModels($options) {
@ -444,9 +431,6 @@ class ModelValidator implements ArrayAccess, IteratorAggregate, Countable {
$newData[] = $row[$join];
}
}
if (empty($newData)) {
continue;
}
foreach ($newData as $data) {
$data[$model->hasAndBelongsToMany[$assoc]['foreignKey']] = $model->id;
$model->{$join}->create($data);
@ -459,8 +443,9 @@ class ModelValidator implements ArrayAccess, IteratorAggregate, Countable {
/**
* Propagates beforeValidate event
*
* @param array $options
* @return boolean
* @param array $options Options to pass to callback.
* @return bool
* @triggers Model.beforeValidate $model, array($options)
*/
protected function _triggerBeforeValidate($options = array()) {
$model = $this->getModel();
@ -474,11 +459,11 @@ class ModelValidator implements ArrayAccess, IteratorAggregate, Countable {
}
/**
* Returns wheter a rule set is defined for a field or not
* Returns whether a rule set is defined for a field or not
*
* @param string $field name of the field to check
* @return boolean
**/
* @return bool
*/
public function offsetExists($field) {
$this->_parseRules();
return isset($this->_fields[$field]);
@ -489,7 +474,7 @@ class ModelValidator implements ArrayAccess, IteratorAggregate, Countable {
*
* @param string $field name of the field to check
* @return CakeValidationSet
**/
*/
public function offsetGet($field) {
$this->_parseRules();
return $this->_fields[$field];
@ -501,7 +486,7 @@ class ModelValidator implements ArrayAccess, IteratorAggregate, Countable {
* @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) {
@ -513,11 +498,11 @@ class ModelValidator implements ArrayAccess, IteratorAggregate, Countable {
}
/**
* Unsets the rulset for a field
* 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]);
@ -527,7 +512,7 @@ class ModelValidator implements ArrayAccess, IteratorAggregate, Countable {
* Returns an iterator for each of the fields to be validated
*
* @return ArrayIterator
**/
*/
public function getIterator() {
$this->_parseRules();
return new ArrayIterator($this->_fields);
@ -537,35 +522,35 @@ class ModelValidator implements ArrayAccess, IteratorAggregate, Countable {
* 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 argumet is an array or instance of
* 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('title', 'required', array('rule' => 'notBlank', 'required' => true))
* ->add('user_id', 'valid', array('rule' => 'numeric', 'message' => 'Invalid User'))
*
* $validator->add('password', array(
* 'size' => array('rule' => array('between', 8, 20)),
* 'size' => array('rule' => array('lengthBetween', 8, 20)),
* 'hasSpecialCharacter' => array('rule' => 'validateSpecialchar', 'message' => 'not valid')
* ));
* }}}
* ```
*
* @param string $field The name of the field from wich the rule will be removed
* @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 ModelValidator this instance
**/
* @return self
*/
public function add($field, $name, $rule = null) {
$this->_parseRules();
if ($name instanceof CakeValidationSet) {
@ -595,16 +580,16 @@ class ModelValidator implements ArrayAccess, IteratorAggregate, Countable {
*
* ## Example:
*
* {{{
* ```
* $validator
* ->remove('title', 'required')
* ->remove('user_id')
* }}}
* ```
*
* @param string $field The name of the field from wich the rule will be removed
* @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 ModelValidator this instance
**/
* @return self
*/
public function remove($field, $rule = null) {
$this->_parseRules();
if ($rule === null) {

View file

@ -1,19 +1,17 @@
<?php
/**
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.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 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @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 MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('AppModel', 'Model');
@ -25,17 +23,10 @@ App::uses('AppModel', 'Model');
*/
class Permission extends AppModel {
/**
* Model name
*
* @var string
*/
public $name = 'Permission';
/**
* Explicitly disable in-memory query caching
*
* @var boolean
* @var bool
*/
public $cacheQueries = false;
@ -78,10 +69,10 @@ class Permission extends AppModel {
* @param string $aro ARO The requesting object identifier.
* @param string $aco ACO The controlled object identifier.
* @param string $action Action (defaults to *)
* @return boolean Success (true if ARO has access to action in ACO, false otherwise)
* @return bool Success (true if ARO has access to action in ACO, false otherwise)
*/
public function check($aro, $aco, $action = "*") {
if ($aro == null || $aco == null) {
public function check($aro, $aco, $action = '*') {
if (!$aro || !$aco) {
return false;
}
@ -89,25 +80,37 @@ class Permission extends AppModel {
$aroPath = $this->Aro->node($aro);
$acoPath = $this->Aco->node($aco);
if (empty($aroPath) || empty($acoPath)) {
trigger_error(__d('cake_dev', "DbAcl::check() - Failed ARO/ACO node lookup in permissions check. Node references:\nAro: ") . print_r($aro, true) . "\nAco: " . print_r($aco, true), E_USER_WARNING);
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 == null || $acoPath == array()) {
trigger_error(__d('cake_dev', "DbAcl::check() - Failed ACO node lookup in permissions check. Node references:\nAro: ") . print_r($aro, true) . "\nAco: " . print_r($aco, true), E_USER_WARNING);
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)) {
trigger_error(__d('cake_dev', "ACO permissions key %s does not exist in DbAcl::check()", $action), E_USER_NOTICE);
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);
$inherited = array();
for ($i = 0; $i < $count; $i++) {
$permAlias = $this->alias;
@ -122,36 +125,37 @@ class Permission extends AppModel {
if (empty($perms)) {
continue;
} else {
$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;
}
$perms = Hash::extract($perms, '{n}.' . $this->alias);
foreach ($perms as $perm) {
if ($action === '*') {
if (empty($perm)) {
continue;
}
foreach ($permKeys as $key) {
if ($perm[$key] == -1 && !(isset($inherited[$key]) && $inherited[$key] == 1)) {
// Deny, but only if a child node didnt't explicitly allow
return false;
} elseif ($perm[$key] == 1) {
// Allow & inherit from parent nodes
$inherited[$key] = $perm[$key];
}
}
} else {
switch ($perm['_' . $action]) {
case -1:
return false;
case 0:
continue;
case 1:
return true;
}
}
}
if ($action === '*' && count($inherited) === count($permKeys)) {
return true;
}
}
return false;
}
@ -161,43 +165,43 @@ class Permission extends AppModel {
*
* @param string $aro ARO The requesting object identifier.
* @param string $aco ACO The controlled object identifier.
* @param string $actions Action (defaults to *)
* @param integer $value Value to indicate access type (1 to give access, -1 to deny, 0 to inherit)
* @return boolean Success
* @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) {
public function allow($aro, $aco, $actions = '*', $value = 1) {
$perms = $this->getAclLink($aro, $aco);
$permKeys = $this->getAcoKeys($this->schema());
$save = array();
if ($perms == false) {
trigger_error(__d('cake_dev', 'DbAcl::allow() - Invalid node'), E_USER_WARNING);
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 == "*") {
if ($actions === '*') {
$save = array_combine($permKeys, array_pad(array(), count($permKeys), $value));
} else {
if (!is_array($actions)) {
$actions = array('_' . $actions);
}
if (is_array($actions)) {
foreach ($actions as $action) {
if ($action{0} != '_') {
$action = '_' . $action;
}
if (in_array($action, $permKeys)) {
$save[$action] = $value;
}
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'] != null && !empty($perms['link'])) {
if ($perms['link'] && !empty($perms['link'])) {
$save['id'] = $perms['link'][0][$this->alias]['id'];
} else {
unset($save['id']);

View file

@ -4,19 +4,18 @@
*
* Provides the Model validation logic.
*
* PHP versions 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.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 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @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 MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Validation', 'Utility');
@ -40,7 +39,7 @@ class CakeValidationRule {
/**
* Holds whether the record being validated exists in datasource or not
*
* @var boolean
* @var bool
*/
protected $_recordExists = false;
@ -82,7 +81,7 @@ class CakeValidationRule {
/**
* The 'allowEmpty' key
*
* @var boolean
* @var bool
*/
public $allowEmpty = null;
@ -96,7 +95,7 @@ class CakeValidationRule {
/**
* The 'last' key
*
* @var boolean
* @var bool
*/
public $last = true;
@ -119,7 +118,7 @@ class CakeValidationRule {
/**
* Checks if the rule is valid
*
* @return boolean
* @return bool
*/
public function isValid() {
if (!$this->_valid || (is_string($this->_valid) && !empty($this->_valid))) {
@ -132,7 +131,7 @@ class CakeValidationRule {
/**
* Returns whether the field can be left blank according to this rule
*
* @return boolean
* @return bool
*/
public function isEmptyAllowed() {
return $this->skip() || $this->allowEmpty === true;
@ -141,15 +140,14 @@ class CakeValidationRule {
/**
* Checks if the field is required according to the `required` property
*
* @return boolean
* @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;
} else {
return false;
}
return false;
}
return $this->required;
@ -158,8 +156,9 @@ class CakeValidationRule {
/**
* Checks whether the field failed the `field should be present` validation
*
* @param array $data data to check rule against
* @return boolean
* @param string $field Field name
* @param array &$data Data to check rule against
* @return bool
*/
public function checkRequired($field, &$data) {
return (
@ -174,8 +173,9 @@ class CakeValidationRule {
/**
* Checks if the allowEmpty key applies
*
* @param array $data data to check rule against
* @return boolean
* @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) {
@ -187,11 +187,11 @@ class CakeValidationRule {
/**
* Checks if the validation rule should be skipped
*
* @return boolean True if the ValidationRule can 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()) {
if ($this->on === 'create' && $this->isUpdate() || $this->on === 'update' && !$this->isUpdate()) {
return true;
}
}
@ -199,10 +199,10 @@ class CakeValidationRule {
}
/**
* Returns whethere this rule should break validation process for associated field
* Returns whether this rule should break validation process for associated field
* after it fails
*
* @return boolean
* @return bool
*/
public function isLast() {
return (bool)$this->last;
@ -239,14 +239,15 @@ class CakeValidationRule {
/**
* Sets the recordExists configuration value for this rule,
* ir refers to wheter the model record it is validating exists
* 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.
*
* @return boolean
**/
* @param bool $exists Boolean to indicate if records exists
* @return bool
*/
public function isUpdate($exists = null) {
if ($exists === null) {
return $this->_recordExists;
@ -257,7 +258,10 @@ class CakeValidationRule {
/**
* Dispatches the validation rule to the given validator method
*
* @return boolean True if the rule could be dispatched, false otherwise
* @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;
@ -273,7 +277,7 @@ class CakeValidationRule {
$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]);
} elseif (Configure::read('debug') > 0) {
} else {
trigger_error(__d('cake_dev', 'Could not find validation handler %s for %s', $this->_rule, $field), E_USER_WARNING);
return false;
}
@ -282,11 +286,11 @@ class CakeValidationRule {
}
/**
* Resets interal state for this rule, by default it will become valid
* 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;
@ -295,8 +299,9 @@ class CakeValidationRule {
/**
* Returns passed options for this rule
*
* @return array
**/
* @param string|int $key Array index
* @return array|null
*/
public function getOptions($key) {
if (!isset($this->_passedOptions[$key])) {
return null;
@ -328,6 +333,8 @@ class CakeValidationRule {
/**
* 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) {

View file

@ -4,19 +4,18 @@
*
* Provides the Model validation logic.
*
* PHP versions 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.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 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @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 MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('CakeValidationRule', 'Model/Validator');
@ -33,7 +32,7 @@ class CakeValidationSet implements ArrayAccess, IteratorAggregate, Countable {
/**
* Holds the CakeValidationRule objects
*
* @var array
* @var CakeValidationRule[]
*/
protected $_rules = array();
@ -41,20 +40,20 @@ class CakeValidationSet implements ArrayAccess, IteratorAggregate, Countable {
* 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 boolean
* @var bool
*/
public $isStopped = false;
@ -75,8 +74,8 @@ class CakeValidationSet implements ArrayAccess, IteratorAggregate, Countable {
/**
* Constructor
*
* @param string $fieldName The fieldname
* @param array $ruleset
* @param string $fieldName The fieldname.
* @param array $ruleSet Rules set.
*/
public function __construct($fieldName, $ruleSet) {
$this->field = $fieldName;
@ -94,8 +93,9 @@ class CakeValidationSet implements ArrayAccess, IteratorAggregate, Countable {
/**
* Sets the list of methods to use for validation
*
* @param array &$methods Methods list
* @return void
**/
*/
public function setMethods(&$methods) {
$this->_methods =& $methods;
}
@ -114,6 +114,8 @@ class CakeValidationSet implements ArrayAccess, IteratorAggregate, Countable {
* 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) {
@ -145,10 +147,10 @@ class CakeValidationSet implements ArrayAccess, IteratorAggregate, Countable {
}
/**
* Resets interal state for all validation rules in this set
* Resets internal state for all validation rules in this set
*
* @return void
**/
*/
public function reset() {
foreach ($this->getRules() as $rule) {
$rule->reset();
@ -158,7 +160,7 @@ class CakeValidationSet implements ArrayAccess, IteratorAggregate, Countable {
/**
* Gets a rule for a given name if exists
*
* @param string $name
* @param string $name Field name.
* @return CakeValidationRule
*/
public function getRule($name) {
@ -170,7 +172,7 @@ class CakeValidationSet implements ArrayAccess, IteratorAggregate, Countable {
/**
* Returns all rules for this validation set
*
* @return array
* @return CakeValidationRule[]
*/
public function getRules() {
return $this->_rules;
@ -181,15 +183,15 @@ class CakeValidationSet implements ArrayAccess, IteratorAggregate, Countable {
*
* ## Example:
*
* {{{
* ```
* $set
* ->setRule('required', array('rule' => 'notEmpty', 'required' => true))
* ->setRule('inRange', array('rule' => array('between', 4, 10))
* }}}
* ->setRule('required', array('rule' => 'notBlank', 'required' => true))
* ->setRule('between', array('rule' => array('lengthBetween', 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 CakeValidationSet this instance
* @return self
*/
public function setRule($name, $rule) {
if (!($rule instanceof CakeValidationRule)) {
@ -204,14 +206,14 @@ class CakeValidationSet implements ArrayAccess, IteratorAggregate, Countable {
*
* ## Example:
*
* {{{
* ```
* $set
* ->removeRule('required')
* ->removeRule('inRange')
* }}}
* ```
*
* @param string $name The name under which the rule should be unset
* @return CakeValidationSet this instance
* @return self
*/
public function removeRule($name) {
unset($this->_rules[$name]);
@ -223,16 +225,16 @@ class CakeValidationSet implements ArrayAccess, IteratorAggregate, Countable {
*
* ## Example:
*
* {{{
* ```
* $set->setRules(array(
* 'required' => array('rule' => 'notEmpty', 'required' => true),
* 'required' => array('rule' => 'notBlank', 'required' => true),
* 'inRange' => array('rule' => array('between', 4, 10)
* ));
* }}}
* ```
*
* @param array $rules The rules to be set
* @param bolean $mergeVars [optional] If true, merges vars instead of replace. Defaults to true.
* @return ModelField
* @param bool $mergeVars [optional] If true, merges vars instead of replace. Defaults to true.
* @return self
*/
public function setRules($rules = array(), $mergeVars = true) {
if ($mergeVars === false) {
@ -303,11 +305,11 @@ class CakeValidationSet implements ArrayAccess, IteratorAggregate, Countable {
}
/**
* Returns wheter an index exists in the rule set
* Returns whether an index exists in the rule set
*
* @param string $index name of the rule
* @return boolean
**/
* @return bool
*/
public function offsetExists($index) {
return isset($this->_rules[$index]);
}
@ -317,17 +319,22 @@ class CakeValidationSet implements ArrayAccess, IteratorAggregate, Countable {
*
* @param string $index name of the rule
* @return CakeValidationRule
**/
*/
public function offsetGet($index) {
return $this->_rules[$index];
}
/**
* Sets or replace a validation rule
* Sets or replace a validation rule.
*
* @param string $index name of the rule
* @param CakeValidationRule|array rule to add to $index
**/
* 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);
}
@ -337,7 +344,7 @@ class CakeValidationSet implements ArrayAccess, IteratorAggregate, Countable {
*
* @param string $index name of the rule
* @return void
**/
*/
public function offsetUnset($index) {
unset($this->_rules[$index]);
}
@ -346,7 +353,7 @@ class CakeValidationSet implements ArrayAccess, IteratorAggregate, Countable {
* Returns an iterator for each of the rules to be applied
*
* @return ArrayIterator
**/
*/
public function getIterator() {
return new ArrayIterator($this->_rules);
}
@ -355,7 +362,7 @@ class CakeValidationSet implements ArrayAccess, IteratorAggregate, Countable {
* Returns the number of rules in this set
*
* @return int
**/
*/
public function count() {
return count($this->_rules);
}