mirror of
https://github.com/brmlab/brmsklad.git
synced 2025-10-30 07:43:59 +01:00
Upgrade CakePHP from 2.2.5 to 2.9.5
This commit is contained in:
parent
5a580df460
commit
235a541597
793 changed files with 60746 additions and 23753 deletions
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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) {
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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', '>=');
|
||||
|
|
|
|||
|
|
@ -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', '>=');
|
||||
|
|
|
|||
|
|
@ -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
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue