PDF rausgenommen

This commit is contained in:
aschwarz
2023-01-23 11:03:31 +01:00
parent 82d562a322
commit a6523903eb
28078 changed files with 4247552 additions and 2 deletions

View File

@ -0,0 +1,250 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Cache.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @package Zend_Cache
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
abstract class Zend_Cache
{
/**
* Standard frontends
*
* @var array
*/
public static $standardFrontends = array('Core', 'Output', 'Class', 'File', 'Function', 'Page');
/**
* Standard backends
*
* @var array
*/
public static $standardBackends = array('File', 'Sqlite', 'Memcached', 'Libmemcached', 'Apc', 'ZendPlatform',
'Xcache', 'TwoLevels', 'WinCache', 'ZendServer_Disk', 'ZendServer_ShMem');
/**
* Standard backends which implement the ExtendedInterface
*
* @var array
*/
public static $standardExtendedBackends = array('File', 'Apc', 'TwoLevels', 'Memcached', 'Libmemcached', 'Sqlite', 'WinCache');
/**
* Only for backward compatibility (may be removed in next major release)
*
* @var array
* @deprecated
*/
public static $availableFrontends = array('Core', 'Output', 'Class', 'File', 'Function', 'Page');
/**
* Only for backward compatibility (may be removed in next major release)
*
* @var array
* @deprecated
*/
public static $availableBackends = array('File', 'Sqlite', 'Memcached', 'Libmemcached', 'Apc', 'ZendPlatform', 'Xcache', 'WinCache', 'TwoLevels');
/**
* Consts for clean() method
*/
const CLEANING_MODE_ALL = 'all';
const CLEANING_MODE_OLD = 'old';
const CLEANING_MODE_MATCHING_TAG = 'matchingTag';
const CLEANING_MODE_NOT_MATCHING_TAG = 'notMatchingTag';
const CLEANING_MODE_MATCHING_ANY_TAG = 'matchingAnyTag';
/**
* Factory
*
* @param mixed $frontend frontend name (string) or Zend_Cache_Frontend_ object
* @param mixed $backend backend name (string) or Zend_Cache_Backend_ object
* @param array $frontendOptions associative array of options for the corresponding frontend constructor
* @param array $backendOptions associative array of options for the corresponding backend constructor
* @param boolean $customFrontendNaming if true, the frontend argument is used as a complete class name ; if false, the frontend argument is used as the end of "Zend_Cache_Frontend_[...]" class name
* @param boolean $customBackendNaming if true, the backend argument is used as a complete class name ; if false, the backend argument is used as the end of "Zend_Cache_Backend_[...]" class name
* @param boolean $autoload if true, there will no // require_once for backend and frontend (useful only for custom backends/frontends)
* @throws Zend_Cache_Exception
* @return Zend_Cache_Core|Zend_Cache_Frontend
*/
public static function factory($frontend, $backend, $frontendOptions = array(), $backendOptions = array(), $customFrontendNaming = false, $customBackendNaming = false, $autoload = false)
{
if (is_string($backend)) {
$backendObject = self::_makeBackend($backend, $backendOptions, $customBackendNaming, $autoload);
} else {
if ((is_object($backend)) && (in_array('Zend_Cache_Backend_Interface', class_implements($backend)))) {
$backendObject = $backend;
} else {
self::throwException('backend must be a backend name (string) or an object which implements Zend_Cache_Backend_Interface');
}
}
if (is_string($frontend)) {
$frontendObject = self::_makeFrontend($frontend, $frontendOptions, $customFrontendNaming, $autoload);
} else {
if (is_object($frontend)) {
$frontendObject = $frontend;
} else {
self::throwException('frontend must be a frontend name (string) or an object');
}
}
$frontendObject->setBackend($backendObject);
return $frontendObject;
}
/**
* Backend Constructor
*
* @param string $backend
* @param array $backendOptions
* @param boolean $customBackendNaming
* @param boolean $autoload
* @return Zend_Cache_Backend
*/
public static function _makeBackend($backend, $backendOptions, $customBackendNaming = false, $autoload = false)
{
if (!$customBackendNaming) {
$backend = self::_normalizeName($backend);
}
if (in_array($backend, Zend_Cache::$standardBackends)) {
// we use a standard backend
$backendClass = 'Zend_Cache_Backend_' . $backend;
// security controls are explicit
// require_once str_replace('_', DIRECTORY_SEPARATOR, $backendClass) . '.php';
} else {
// we use a custom backend
if (!preg_match('~^[\w]+$~D', $backend)) {
Zend_Cache::throwException("Invalid backend name [$backend]");
}
if (!$customBackendNaming) {
// we use this boolean to avoid an API break
$backendClass = 'Zend_Cache_Backend_' . $backend;
} else {
$backendClass = $backend;
}
if (!$autoload) {
$file = str_replace('_', DIRECTORY_SEPARATOR, $backendClass) . '.php';
if (!(self::_isReadable($file))) {
self::throwException("file $file not found in include_path");
}
// require_once $file;
}
}
return new $backendClass($backendOptions);
}
/**
* Frontend Constructor
*
* @param string $frontend
* @param array $frontendOptions
* @param boolean $customFrontendNaming
* @param boolean $autoload
* @return Zend_Cache_Core|Zend_Cache_Frontend
*/
public static function _makeFrontend($frontend, $frontendOptions = array(), $customFrontendNaming = false, $autoload = false)
{
if (!$customFrontendNaming) {
$frontend = self::_normalizeName($frontend);
}
if (in_array($frontend, self::$standardFrontends)) {
// we use a standard frontend
// For perfs reasons, with frontend == 'Core', we can interact with the Core itself
$frontendClass = 'Zend_Cache_' . ($frontend != 'Core' ? 'Frontend_' : '') . $frontend;
// security controls are explicit
// require_once str_replace('_', DIRECTORY_SEPARATOR, $frontendClass) . '.php';
} else {
// we use a custom frontend
if (!preg_match('~^[\w]+$~D', $frontend)) {
Zend_Cache::throwException("Invalid frontend name [$frontend]");
}
if (!$customFrontendNaming) {
// we use this boolean to avoid an API break
$frontendClass = 'Zend_Cache_Frontend_' . $frontend;
} else {
$frontendClass = $frontend;
}
if (!$autoload) {
$file = str_replace('_', DIRECTORY_SEPARATOR, $frontendClass) . '.php';
if (!(self::_isReadable($file))) {
self::throwException("file $file not found in include_path");
}
// require_once $file;
}
}
return new $frontendClass($frontendOptions);
}
/**
* Throw an exception
*
* Note : for perf reasons, the "load" of Zend/Cache/Exception is dynamic
* @param string $msg Message for the exception
* @throws Zend_Cache_Exception
*/
public static function throwException($msg, Exception $e = null)
{
// For perfs reasons, we use this dynamic inclusion
// require_once 'Zend/Cache/Exception.php';
throw new Zend_Cache_Exception($msg, 0, $e);
}
/**
* Normalize frontend and backend names to allow multiple words TitleCased
*
* @param string $name Name to normalize
* @return string
*/
protected static function _normalizeName($name)
{
$name = ucfirst(strtolower($name));
$name = str_replace(array('-', '_', '.'), ' ', $name);
$name = ucwords($name);
$name = str_replace(' ', '', $name);
if (stripos($name, 'ZendServer') === 0) {
$name = 'ZendServer_' . substr($name, strlen('ZendServer'));
}
return $name;
}
/**
* Returns TRUE if the $filename is readable, or FALSE otherwise.
* This function uses the PHP include_path, where PHP's is_readable()
* does not.
*
* Note : this method comes from Zend_Loader (see #ZF-2891 for details)
*
* @param string $filename
* @return boolean
*/
private static function _isReadable($filename)
{
if (!$fh = @fopen($filename, 'r', true)) {
return false;
}
@fclose($fh);
return true;
}
}

View File

@ -0,0 +1,268 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Backend.php 23800 2011-03-10 20:52:08Z mabe $
*/
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Backend
{
/**
* Frontend or Core directives
*
* =====> (int) lifetime :
* - Cache lifetime (in seconds)
* - If null, the cache is valid forever
*
* =====> (int) logging :
* - if set to true, a logging is activated throw Zend_Log
*
* @var array directives
*/
protected $_directives = array(
'lifetime' => 3600,
'logging' => false,
'logger' => null
);
/**
* Available options
*
* @var array available options
*/
protected $_options = array();
/**
* Constructor
*
* @param array $options Associative array of options
* @throws Zend_Cache_Exception
* @return void
*/
public function __construct(array $options = array())
{
while (list($name, $value) = each($options)) {
$this->setOption($name, $value);
}
}
/**
* Set the frontend directives
*
* @param array $directives Assoc of directives
* @throws Zend_Cache_Exception
* @return void
*/
public function setDirectives($directives)
{
if (!is_array($directives)) Zend_Cache::throwException('Directives parameter must be an array');
while (list($name, $value) = each($directives)) {
if (!is_string($name)) {
Zend_Cache::throwException("Incorrect option name : $name");
}
$name = strtolower($name);
if (array_key_exists($name, $this->_directives)) {
$this->_directives[$name] = $value;
}
}
$this->_loggerSanity();
}
/**
* Set an option
*
* @param string $name
* @param mixed $value
* @throws Zend_Cache_Exception
* @return void
*/
public function setOption($name, $value)
{
if (!is_string($name)) {
Zend_Cache::throwException("Incorrect option name : $name");
}
$name = strtolower($name);
if (array_key_exists($name, $this->_options)) {
$this->_options[$name] = $value;
}
}
/**
* Get the life time
*
* if $specificLifetime is not false, the given specific life time is used
* else, the global lifetime is used
*
* @param int $specificLifetime
* @return int Cache life time
*/
public function getLifetime($specificLifetime)
{
if ($specificLifetime === false) {
return $this->_directives['lifetime'];
}
return $specificLifetime;
}
/**
* Return true if the automatic cleaning is available for the backend
*
* DEPRECATED : use getCapabilities() instead
*
* @deprecated
* @return boolean
*/
public function isAutomaticCleaningAvailable()
{
return true;
}
/**
* Determine system TMP directory and detect if we have read access
*
* inspired from Zend_File_Transfer_Adapter_Abstract
*
* @return string
* @throws Zend_Cache_Exception if unable to determine directory
*/
public function getTmpDir()
{
$tmpdir = array();
foreach (array($_ENV, $_SERVER) as $tab) {
foreach (array('TMPDIR', 'TEMP', 'TMP', 'windir', 'SystemRoot') as $key) {
if (isset($tab[$key])) {
if (($key == 'windir') or ($key == 'SystemRoot')) {
$dir = realpath($tab[$key] . '\\temp');
} else {
$dir = realpath($tab[$key]);
}
if ($this->_isGoodTmpDir($dir)) {
return $dir;
}
}
}
}
$upload = ini_get('upload_tmp_dir');
if ($upload) {
$dir = realpath($upload);
if ($this->_isGoodTmpDir($dir)) {
return $dir;
}
}
if (function_exists('sys_get_temp_dir')) {
$dir = sys_get_temp_dir();
if ($this->_isGoodTmpDir($dir)) {
return $dir;
}
}
// Attemp to detect by creating a temporary file
$tempFile = tempnam(md5(uniqid(rand(), TRUE)), '');
if ($tempFile) {
$dir = realpath(dirname($tempFile));
unlink($tempFile);
if ($this->_isGoodTmpDir($dir)) {
return $dir;
}
}
if ($this->_isGoodTmpDir('/tmp')) {
return '/tmp';
}
if ($this->_isGoodTmpDir('\\temp')) {
return '\\temp';
}
Zend_Cache::throwException('Could not determine temp directory, please specify a cache_dir manually');
}
/**
* Verify if the given temporary directory is readable and writable
*
* @param string $dir temporary directory
* @return boolean true if the directory is ok
*/
protected function _isGoodTmpDir($dir)
{
if (is_readable($dir)) {
if (is_writable($dir)) {
return true;
}
}
return false;
}
/**
* Make sure if we enable logging that the Zend_Log class
* is available.
* Create a default log object if none is set.
*
* @throws Zend_Cache_Exception
* @return void
*/
protected function _loggerSanity()
{
if (!isset($this->_directives['logging']) || !$this->_directives['logging']) {
return;
}
if (isset($this->_directives['logger'])) {
if ($this->_directives['logger'] instanceof Zend_Log) {
return;
}
Zend_Cache::throwException('Logger object is not an instance of Zend_Log class.');
}
// Create a default logger to the standard output stream
// require_once 'Zend/Log.php';
// require_once 'Zend/Log/Writer/Stream.php';
// require_once 'Zend/Log/Filter/Priority.php';
$logger = new Zend_Log(new Zend_Log_Writer_Stream('php://output'));
$logger->addFilter(new Zend_Log_Filter_Priority(Zend_Log::WARN, '<='));
$this->_directives['logger'] = $logger;
}
/**
* Log a message at the WARN (4) priority.
*
* @param string $message
* @throws Zend_Cache_Exception
* @return void
*/
protected function _log($message, $priority = 4)
{
if (!$this->_directives['logging']) {
return;
}
if (!isset($this->_directives['logger'])) {
Zend_Cache::throwException('Logging is enabled but logger is not set.');
}
$logger = $this->_directives['logger'];
if (!$logger instanceof Zend_Log) {
Zend_Cache::throwException('Logger object is not an instance of Zend_Log class.');
}
$logger->log($message, $priority);
}
}

View File

@ -0,0 +1,355 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Apc.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Cache_Backend_Interface
*/
// require_once 'Zend/Cache/Backend/ExtendedInterface.php';
/**
* @see Zend_Cache_Backend
*/
// require_once 'Zend/Cache/Backend.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Backend_Apc extends Zend_Cache_Backend implements Zend_Cache_Backend_ExtendedInterface
{
/**
* Log message
*/
const TAGS_UNSUPPORTED_BY_CLEAN_OF_APC_BACKEND = 'Zend_Cache_Backend_Apc::clean() : tags are unsupported by the Apc backend';
const TAGS_UNSUPPORTED_BY_SAVE_OF_APC_BACKEND = 'Zend_Cache_Backend_Apc::save() : tags are unsupported by the Apc backend';
/**
* Constructor
*
* @param array $options associative array of options
* @throws Zend_Cache_Exception
* @return void
*/
public function __construct(array $options = array())
{
if (!extension_loaded('apc')) {
Zend_Cache::throwException('The apc extension must be loaded for using this backend !');
}
parent::__construct($options);
}
/**
* Test if a cache is available for the given id and (if yes) return it (false else)
*
* WARNING $doNotTestCacheValidity=true is unsupported by the Apc backend
*
* @param string $id cache id
* @param boolean $doNotTestCacheValidity if set to true, the cache validity won't be tested
* @return string cached datas (or false)
*/
public function load($id, $doNotTestCacheValidity = false)
{
$tmp = apc_fetch($id);
if (is_array($tmp)) {
return $tmp[0];
}
return false;
}
/**
* Test if a cache is available or not (for the given id)
*
* @param string $id cache id
* @return mixed false (a cache is not available) or "last modified" timestamp (int) of the available cache record
*/
public function test($id)
{
$tmp = apc_fetch($id);
if (is_array($tmp)) {
return $tmp[1];
}
return false;
}
/**
* Save some string datas into a cache record
*
* Note : $data is always "string" (serialization is done by the
* core not by the backend)
*
* @param string $data datas to cache
* @param string $id cache id
* @param array $tags array of strings, the cache record will be tagged by each string entry
* @param int $specificLifetime if != false, set a specific lifetime for this cache record (null => infinite lifetime)
* @return boolean true if no problem
*/
public function save($data, $id, $tags = array(), $specificLifetime = false)
{
$lifetime = $this->getLifetime($specificLifetime);
$result = apc_store($id, array($data, time(), $lifetime), $lifetime);
if (count($tags) > 0) {
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_APC_BACKEND);
}
return $result;
}
/**
* Remove a cache record
*
* @param string $id cache id
* @return boolean true if no problem
*/
public function remove($id)
{
return apc_delete($id);
}
/**
* Clean some cache records
*
* Available modes are :
* 'all' (default) => remove all cache entries ($tags is not used)
* 'old' => unsupported
* 'matchingTag' => unsupported
* 'notMatchingTag' => unsupported
* 'matchingAnyTag' => unsupported
*
* @param string $mode clean mode
* @param array $tags array of tags
* @throws Zend_Cache_Exception
* @return boolean true if no problem
*/
public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
{
switch ($mode) {
case Zend_Cache::CLEANING_MODE_ALL:
return apc_clear_cache('user');
break;
case Zend_Cache::CLEANING_MODE_OLD:
$this->_log("Zend_Cache_Backend_Apc::clean() : CLEANING_MODE_OLD is unsupported by the Apc backend");
break;
case Zend_Cache::CLEANING_MODE_MATCHING_TAG:
case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG:
case Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG:
$this->_log(self::TAGS_UNSUPPORTED_BY_CLEAN_OF_APC_BACKEND);
break;
default:
Zend_Cache::throwException('Invalid mode for clean() method');
break;
}
}
/**
* Return true if the automatic cleaning is available for the backend
*
* DEPRECATED : use getCapabilities() instead
*
* @deprecated
* @return boolean
*/
public function isAutomaticCleaningAvailable()
{
return false;
}
/**
* Return the filling percentage of the backend storage
*
* @throws Zend_Cache_Exception
* @return int integer between 0 and 100
*/
public function getFillingPercentage()
{
$mem = apc_sma_info(true);
$memSize = $mem['num_seg'] * $mem['seg_size'];
$memAvailable= $mem['avail_mem'];
$memUsed = $memSize - $memAvailable;
if ($memSize == 0) {
Zend_Cache::throwException('can\'t get apc memory size');
}
if ($memUsed > $memSize) {
return 100;
}
return ((int) (100. * ($memUsed / $memSize)));
}
/**
* Return an array of stored tags
*
* @return array array of stored tags (string)
*/
public function getTags()
{
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_APC_BACKEND);
return array();
}
/**
* Return an array of stored cache ids which match given tags
*
* In case of multiple tags, a logical AND is made between tags
*
* @param array $tags array of tags
* @return array array of matching cache ids (string)
*/
public function getIdsMatchingTags($tags = array())
{
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_APC_BACKEND);
return array();
}
/**
* Return an array of stored cache ids which don't match given tags
*
* In case of multiple tags, a logical OR is made between tags
*
* @param array $tags array of tags
* @return array array of not matching cache ids (string)
*/
public function getIdsNotMatchingTags($tags = array())
{
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_APC_BACKEND);
return array();
}
/**
* Return an array of stored cache ids which match any given tags
*
* In case of multiple tags, a logical AND is made between tags
*
* @param array $tags array of tags
* @return array array of any matching cache ids (string)
*/
public function getIdsMatchingAnyTags($tags = array())
{
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_APC_BACKEND);
return array();
}
/**
* Return an array of stored cache ids
*
* @return array array of stored cache ids (string)
*/
public function getIds()
{
$res = array();
$array = apc_cache_info('user', false);
$records = $array['cache_list'];
foreach ($records as $record) {
$res[] = $record['info'];
}
return $res;
}
/**
* Return an array of metadatas for the given cache id
*
* The array must include these keys :
* - expire : the expire timestamp
* - tags : a string array of tags
* - mtime : timestamp of last modification time
*
* @param string $id cache id
* @return array array of metadatas (false if the cache id is not found)
*/
public function getMetadatas($id)
{
$tmp = apc_fetch($id);
if (is_array($tmp)) {
$data = $tmp[0];
$mtime = $tmp[1];
if (!isset($tmp[2])) {
// because this record is only with 1.7 release
// if old cache records are still there...
return false;
}
$lifetime = $tmp[2];
return array(
'expire' => $mtime + $lifetime,
'tags' => array(),
'mtime' => $mtime
);
}
return false;
}
/**
* Give (if possible) an extra lifetime to the given cache id
*
* @param string $id cache id
* @param int $extraLifetime
* @return boolean true if ok
*/
public function touch($id, $extraLifetime)
{
$tmp = apc_fetch($id);
if (is_array($tmp)) {
$data = $tmp[0];
$mtime = $tmp[1];
if (!isset($tmp[2])) {
// because this record is only with 1.7 release
// if old cache records are still there...
return false;
}
$lifetime = $tmp[2];
$newLifetime = $lifetime - (time() - $mtime) + $extraLifetime;
if ($newLifetime <=0) {
return false;
}
apc_store($id, array($data, time(), $newLifetime), $newLifetime);
return true;
}
return false;
}
/**
* Return an associative array of capabilities (booleans) of the backend
*
* The array must include these keys :
* - automatic_cleaning (is automating cleaning necessary)
* - tags (are tags supported)
* - expired_read (is it possible to read expired cache records
* (for doNotTestCacheValidity option for example))
* - priority does the backend deal with priority when saving
* - infinite_lifetime (is infinite lifetime can work with this backend)
* - get_list (is it possible to get the list of cache ids and the complete list of tags)
*
* @return array associative of with capabilities
*/
public function getCapabilities()
{
return array(
'automatic_cleaning' => false,
'tags' => false,
'expired_read' => false,
'priority' => false,
'infinite_lifetime' => false,
'get_list' => true
);
}
}

View File

@ -0,0 +1,250 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: BlackHole.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Cache_Backend_Interface
*/
// require_once 'Zend/Cache/Backend/ExtendedInterface.php';
/**
* @see Zend_Cache_Backend
*/
// require_once 'Zend/Cache/Backend.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Backend_BlackHole
extends Zend_Cache_Backend
implements Zend_Cache_Backend_ExtendedInterface
{
/**
* Test if a cache is available for the given id and (if yes) return it (false else)
*
* @param string $id cache id
* @param boolean $doNotTestCacheValidity if set to true, the cache validity won't be tested
* @return string|false cached datas
*/
public function load($id, $doNotTestCacheValidity = false)
{
return false;
}
/**
* Test if a cache is available or not (for the given id)
*
* @param string $id cache id
* @return mixed false (a cache is not available) or "last modified" timestamp (int) of the available cache record
*/
public function test($id)
{
return false;
}
/**
* Save some string datas into a cache record
*
* Note : $data is always "string" (serialization is done by the
* core not by the backend)
*
* @param string $data Datas to cache
* @param string $id Cache id
* @param array $tags Array of strings, the cache record will be tagged by each string entry
* @param int $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
* @return boolean true if no problem
*/
public function save($data, $id, $tags = array(), $specificLifetime = false)
{
return true;
}
/**
* Remove a cache record
*
* @param string $id cache id
* @return boolean true if no problem
*/
public function remove($id)
{
return true;
}
/**
* Clean some cache records
*
* Available modes are :
* 'all' (default) => remove all cache entries ($tags is not used)
* 'old' => remove too old cache entries ($tags is not used)
* 'matchingTag' => remove cache entries matching all given tags
* ($tags can be an array of strings or a single string)
* 'notMatchingTag' => remove cache entries not matching one of the given tags
* ($tags can be an array of strings or a single string)
* 'matchingAnyTag' => remove cache entries matching any given tags
* ($tags can be an array of strings or a single string)
*
* @param string $mode clean mode
* @param tags array $tags array of tags
* @return boolean true if no problem
*/
public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
{
return true;
}
/**
* Return an array of stored cache ids
*
* @return array array of stored cache ids (string)
*/
public function getIds()
{
return array();
}
/**
* Return an array of stored tags
*
* @return array array of stored tags (string)
*/
public function getTags()
{
return array();
}
/**
* Return an array of stored cache ids which match given tags
*
* In case of multiple tags, a logical AND is made between tags
*
* @param array $tags array of tags
* @return array array of matching cache ids (string)
*/
public function getIdsMatchingTags($tags = array())
{
return array();
}
/**
* Return an array of stored cache ids which don't match given tags
*
* In case of multiple tags, a logical OR is made between tags
*
* @param array $tags array of tags
* @return array array of not matching cache ids (string)
*/
public function getIdsNotMatchingTags($tags = array())
{
return array();
}
/**
* Return an array of stored cache ids which match any given tags
*
* In case of multiple tags, a logical AND is made between tags
*
* @param array $tags array of tags
* @return array array of any matching cache ids (string)
*/
public function getIdsMatchingAnyTags($tags = array())
{
return array();
}
/**
* Return the filling percentage of the backend storage
*
* @return int integer between 0 and 100
* @throws Zend_Cache_Exception
*/
public function getFillingPercentage()
{
return 0;
}
/**
* Return an array of metadatas for the given cache id
*
* The array must include these keys :
* - expire : the expire timestamp
* - tags : a string array of tags
* - mtime : timestamp of last modification time
*
* @param string $id cache id
* @return array array of metadatas (false if the cache id is not found)
*/
public function getMetadatas($id)
{
return false;
}
/**
* Give (if possible) an extra lifetime to the given cache id
*
* @param string $id cache id
* @param int $extraLifetime
* @return boolean true if ok
*/
public function touch($id, $extraLifetime)
{
return false;
}
/**
* Return an associative array of capabilities (booleans) of the backend
*
* The array must include these keys :
* - automatic_cleaning (is automating cleaning necessary)
* - tags (are tags supported)
* - expired_read (is it possible to read expired cache records
* (for doNotTestCacheValidity option for example))
* - priority does the backend deal with priority when saving
* - infinite_lifetime (is infinite lifetime can work with this backend)
* - get_list (is it possible to get the list of cache ids and the complete list of tags)
*
* @return array associative of with capabilities
*/
public function getCapabilities()
{
return array(
'automatic_cleaning' => true,
'tags' => true,
'expired_read' => true,
'priority' => true,
'infinite_lifetime' => true,
'get_list' => true,
);
}
/**
* PUBLIC METHOD FOR UNIT TESTING ONLY !
*
* Force a cache record to expire
*
* @param string $id cache id
*/
public function ___expire($id)
{
}
}

View File

@ -0,0 +1,126 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: ExtendedInterface.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Cache_Backend_Interface
*/
// require_once 'Zend/Cache/Backend/Interface.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
interface Zend_Cache_Backend_ExtendedInterface extends Zend_Cache_Backend_Interface
{
/**
* Return an array of stored cache ids
*
* @return array array of stored cache ids (string)
*/
public function getIds();
/**
* Return an array of stored tags
*
* @return array array of stored tags (string)
*/
public function getTags();
/**
* Return an array of stored cache ids which match given tags
*
* In case of multiple tags, a logical AND is made between tags
*
* @param array $tags array of tags
* @return array array of matching cache ids (string)
*/
public function getIdsMatchingTags($tags = array());
/**
* Return an array of stored cache ids which don't match given tags
*
* In case of multiple tags, a logical OR is made between tags
*
* @param array $tags array of tags
* @return array array of not matching cache ids (string)
*/
public function getIdsNotMatchingTags($tags = array());
/**
* Return an array of stored cache ids which match any given tags
*
* In case of multiple tags, a logical AND is made between tags
*
* @param array $tags array of tags
* @return array array of any matching cache ids (string)
*/
public function getIdsMatchingAnyTags($tags = array());
/**
* Return the filling percentage of the backend storage
*
* @return int integer between 0 and 100
*/
public function getFillingPercentage();
/**
* Return an array of metadatas for the given cache id
*
* The array must include these keys :
* - expire : the expire timestamp
* - tags : a string array of tags
* - mtime : timestamp of last modification time
*
* @param string $id cache id
* @return array array of metadatas (false if the cache id is not found)
*/
public function getMetadatas($id);
/**
* Give (if possible) an extra lifetime to the given cache id
*
* @param string $id cache id
* @param int $extraLifetime
* @return boolean true if ok
*/
public function touch($id, $extraLifetime);
/**
* Return an associative array of capabilities (booleans) of the backend
*
* The array must include these keys :
* - automatic_cleaning (is automating cleaning necessary)
* - tags (are tags supported)
* - expired_read (is it possible to read expired cache records
* (for doNotTestCacheValidity option for example))
* - priority does the backend deal with priority when saving
* - infinite_lifetime (is infinite lifetime can work with this backend)
* - get_list (is it possible to get the list of cache ids and the complete list of tags)
*
* @return array associative of with capabilities
*/
public function getCapabilities();
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,99 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Interface.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
interface Zend_Cache_Backend_Interface
{
/**
* Set the frontend directives
*
* @param array $directives assoc of directives
*/
public function setDirectives($directives);
/**
* Test if a cache is available for the given id and (if yes) return it (false else)
*
* Note : return value is always "string" (unserialization is done by the core not by the backend)
*
* @param string $id Cache id
* @param boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
* @return string|false cached datas
*/
public function load($id, $doNotTestCacheValidity = false);
/**
* Test if a cache is available or not (for the given id)
*
* @param string $id cache id
* @return mixed|false (a cache is not available) or "last modified" timestamp (int) of the available cache record
*/
public function test($id);
/**
* Save some string datas into a cache record
*
* Note : $data is always "string" (serialization is done by the
* core not by the backend)
*
* @param string $data Datas to cache
* @param string $id Cache id
* @param array $tags Array of strings, the cache record will be tagged by each string entry
* @param int $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
* @return boolean true if no problem
*/
public function save($data, $id, $tags = array(), $specificLifetime = false);
/**
* Remove a cache record
*
* @param string $id Cache id
* @return boolean True if no problem
*/
public function remove($id);
/**
* Clean some cache records
*
* Available modes are :
* Zend_Cache::CLEANING_MODE_ALL (default) => remove all cache entries ($tags is not used)
* Zend_Cache::CLEANING_MODE_OLD => remove too old cache entries ($tags is not used)
* Zend_Cache::CLEANING_MODE_MATCHING_TAG => remove cache entries matching all given tags
* ($tags can be an array of strings or a single string)
* Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG => remove cache entries not {matching one of the given tags}
* ($tags can be an array of strings or a single string)
* Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG => remove cache entries matching any given tags
* ($tags can be an array of strings or a single string)
*
* @param string $mode Clean mode
* @param array $tags Array of tags
* @return boolean true if no problem
*/
public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array());
}

View File

@ -0,0 +1,484 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Libmemcached.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Cache_Backend_Interface
*/
// require_once 'Zend/Cache/Backend/ExtendedInterface.php';
/**
* @see Zend_Cache_Backend
*/
// require_once 'Zend/Cache/Backend.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Backend_Libmemcached extends Zend_Cache_Backend implements Zend_Cache_Backend_ExtendedInterface
{
/**
* Default Server Values
*/
const DEFAULT_HOST = '127.0.0.1';
const DEFAULT_PORT = 11211;
const DEFAULT_WEIGHT = 1;
/**
* Log message
*/
const TAGS_UNSUPPORTED_BY_CLEAN_OF_LIBMEMCACHED_BACKEND = 'Zend_Cache_Backend_Libmemcached::clean() : tags are unsupported by the Libmemcached backend';
const TAGS_UNSUPPORTED_BY_SAVE_OF_LIBMEMCACHED_BACKEND = 'Zend_Cache_Backend_Libmemcached::save() : tags are unsupported by the Libmemcached backend';
/**
* Available options
*
* =====> (array) servers :
* an array of memcached server ; each memcached server is described by an associative array :
* 'host' => (string) : the name of the memcached server
* 'port' => (int) : the port of the memcached server
* 'weight' => (int) : number of buckets to create for this server which in turn control its
* probability of it being selected. The probability is relative to the total
* weight of all servers.
* =====> (array) client :
* an array of memcached client options ; the memcached client is described by an associative array :
* @see http://php.net/manual/memcached.constants.php
* - The option name can be the name of the constant without the prefix 'OPT_'
* or the integer value of this option constant
*
* @var array available options
*/
protected $_options = array(
'servers' => array(array(
'host' => self::DEFAULT_HOST,
'port' => self::DEFAULT_PORT,
'weight' => self::DEFAULT_WEIGHT,
)),
'client' => array()
);
/**
* Memcached object
*
* @var mixed memcached object
*/
protected $_memcache = null;
/**
* Constructor
*
* @param array $options associative array of options
* @throws Zend_Cache_Exception
* @return void
*/
public function __construct(array $options = array())
{
if (!extension_loaded('memcached')) {
Zend_Cache::throwException('The memcached extension must be loaded for using this backend !');
}
// override default client options
$this->_options['client'] = array(
Memcached::OPT_DISTRIBUTION => Memcached::DISTRIBUTION_CONSISTENT,
Memcached::OPT_HASH => Memcached::HASH_MD5,
Memcached::OPT_LIBKETAMA_COMPATIBLE => true,
);
parent::__construct($options);
if (isset($this->_options['servers'])) {
$value = $this->_options['servers'];
if (isset($value['host'])) {
// in this case, $value seems to be a simple associative array (one server only)
$value = array(0 => $value); // let's transform it into a classical array of associative arrays
}
$this->setOption('servers', $value);
}
$this->_memcache = new Memcached;
// setup memcached client options
foreach ($this->_options['client'] as $name => $value) {
$optId = null;
if (is_int($name)) {
$optId = $name;
} else {
$optConst = 'Memcached::OPT_' . strtoupper($name);
if (defined($optConst)) {
$optId = constant($optConst);
} else {
$this->_log("Unknown memcached client option '{$name}' ({$optConst})");
}
}
if ($optId) {
if (!$this->_memcache->setOption($optId, $value)) {
$this->_log("Setting memcached client option '{$optId}' failed");
}
}
}
// setup memcached servers
$servers = array();
foreach ($this->_options['servers'] as $server) {
if (!array_key_exists('port', $server)) {
$server['port'] = self::DEFAULT_PORT;
}
if (!array_key_exists('weight', $server)) {
$server['weight'] = self::DEFAULT_WEIGHT;
}
$servers[] = array($server['host'], $server['port'], $server['weight']);
}
$this->_memcache->addServers($servers);
}
/**
* Test if a cache is available for the given id and (if yes) return it (false else)
*
* @param string $id Cache id
* @param boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
* @return string|false cached datas
*/
public function load($id, $doNotTestCacheValidity = false)
{
$tmp = $this->_memcache->get($id);
if (isset($tmp[0])) {
return $tmp[0];
}
return false;
}
/**
* Test if a cache is available or not (for the given id)
*
* @param string $id Cache id
* @return int|false (a cache is not available) or "last modified" timestamp (int) of the available cache record
*/
public function test($id)
{
$tmp = $this->_memcache->get($id);
if (isset($tmp[0], $tmp[1])) {
return (int)$tmp[1];
}
return false;
}
/**
* Save some string datas into a cache record
*
* Note : $data is always "string" (serialization is done by the
* core not by the backend)
*
* @param string $data Datas to cache
* @param string $id Cache id
* @param array $tags Array of strings, the cache record will be tagged by each string entry
* @param int $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
* @return boolean True if no problem
*/
public function save($data, $id, $tags = array(), $specificLifetime = false)
{
$lifetime = $this->getLifetime($specificLifetime);
// ZF-8856: using set because add needs a second request if item already exists
$result = @$this->_memcache->set($id, array($data, time(), $lifetime), $lifetime);
if ($result === false) {
$rsCode = $this->_memcache->getResultCode();
$rsMsg = $this->_memcache->getResultMessage();
$this->_log("Memcached::set() failed: [{$rsCode}] {$rsMsg}");
}
if (count($tags) > 0) {
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_LIBMEMCACHED_BACKEND);
}
return $result;
}
/**
* Remove a cache record
*
* @param string $id Cache id
* @return boolean True if no problem
*/
public function remove($id)
{
return $this->_memcache->delete($id);
}
/**
* Clean some cache records
*
* Available modes are :
* 'all' (default) => remove all cache entries ($tags is not used)
* 'old' => unsupported
* 'matchingTag' => unsupported
* 'notMatchingTag' => unsupported
* 'matchingAnyTag' => unsupported
*
* @param string $mode Clean mode
* @param array $tags Array of tags
* @throws Zend_Cache_Exception
* @return boolean True if no problem
*/
public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
{
switch ($mode) {
case Zend_Cache::CLEANING_MODE_ALL:
return $this->_memcache->flush();
break;
case Zend_Cache::CLEANING_MODE_OLD:
$this->_log("Zend_Cache_Backend_Libmemcached::clean() : CLEANING_MODE_OLD is unsupported by the Libmemcached backend");
break;
case Zend_Cache::CLEANING_MODE_MATCHING_TAG:
case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG:
case Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG:
$this->_log(self::TAGS_UNSUPPORTED_BY_CLEAN_OF_LIBMEMCACHED_BACKEND);
break;
default:
Zend_Cache::throwException('Invalid mode for clean() method');
break;
}
}
/**
* Return true if the automatic cleaning is available for the backend
*
* @return boolean
*/
public function isAutomaticCleaningAvailable()
{
return false;
}
/**
* Set the frontend directives
*
* @param array $directives Assoc of directives
* @throws Zend_Cache_Exception
* @return void
*/
public function setDirectives($directives)
{
parent::setDirectives($directives);
$lifetime = $this->getLifetime(false);
if ($lifetime > 2592000) {
// #ZF-3490 : For the memcached backend, there is a lifetime limit of 30 days (2592000 seconds)
$this->_log('memcached backend has a limit of 30 days (2592000 seconds) for the lifetime');
}
if ($lifetime === null) {
// #ZF-4614 : we tranform null to zero to get the maximal lifetime
parent::setDirectives(array('lifetime' => 0));
}
}
/**
* Return an array of stored cache ids
*
* @return array array of stored cache ids (string)
*/
public function getIds()
{
$this->_log("Zend_Cache_Backend_Libmemcached::save() : getting the list of cache ids is unsupported by the Libmemcached backend");
return array();
}
/**
* Return an array of stored tags
*
* @return array array of stored tags (string)
*/
public function getTags()
{
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_LIBMEMCACHED_BACKEND);
return array();
}
/**
* Return an array of stored cache ids which match given tags
*
* In case of multiple tags, a logical AND is made between tags
*
* @param array $tags array of tags
* @return array array of matching cache ids (string)
*/
public function getIdsMatchingTags($tags = array())
{
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_LIBMEMCACHED_BACKEND);
return array();
}
/**
* Return an array of stored cache ids which don't match given tags
*
* In case of multiple tags, a logical OR is made between tags
*
* @param array $tags array of tags
* @return array array of not matching cache ids (string)
*/
public function getIdsNotMatchingTags($tags = array())
{
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_LIBMEMCACHED_BACKEND);
return array();
}
/**
* Return an array of stored cache ids which match any given tags
*
* In case of multiple tags, a logical AND is made between tags
*
* @param array $tags array of tags
* @return array array of any matching cache ids (string)
*/
public function getIdsMatchingAnyTags($tags = array())
{
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_LIBMEMCACHED_BACKEND);
return array();
}
/**
* Return the filling percentage of the backend storage
*
* @throws Zend_Cache_Exception
* @return int integer between 0 and 100
*/
public function getFillingPercentage()
{
$mems = $this->_memcache->getStats();
if ($mems === false) {
return 0;
}
$memSize = null;
$memUsed = null;
foreach ($mems as $key => $mem) {
if ($mem === false) {
$this->_log('can\'t get stat from ' . $key);
continue;
}
$eachSize = $mem['limit_maxbytes'];
$eachUsed = $mem['bytes'];
if ($eachUsed > $eachSize) {
$eachUsed = $eachSize;
}
$memSize += $eachSize;
$memUsed += $eachUsed;
}
if ($memSize === null || $memUsed === null) {
Zend_Cache::throwException('Can\'t get filling percentage');
}
return ((int) (100. * ($memUsed / $memSize)));
}
/**
* Return an array of metadatas for the given cache id
*
* The array must include these keys :
* - expire : the expire timestamp
* - tags : a string array of tags
* - mtime : timestamp of last modification time
*
* @param string $id cache id
* @return array array of metadatas (false if the cache id is not found)
*/
public function getMetadatas($id)
{
$tmp = $this->_memcache->get($id);
if (isset($tmp[0], $tmp[1], $tmp[2])) {
$data = $tmp[0];
$mtime = $tmp[1];
$lifetime = $tmp[2];
return array(
'expire' => $mtime + $lifetime,
'tags' => array(),
'mtime' => $mtime
);
}
return false;
}
/**
* Give (if possible) an extra lifetime to the given cache id
*
* @param string $id cache id
* @param int $extraLifetime
* @return boolean true if ok
*/
public function touch($id, $extraLifetime)
{
$tmp = $this->_memcache->get($id);
if (isset($tmp[0], $tmp[1], $tmp[2])) {
$data = $tmp[0];
$mtime = $tmp[1];
$lifetime = $tmp[2];
$newLifetime = $lifetime - (time() - $mtime) + $extraLifetime;
if ($newLifetime <=0) {
return false;
}
// #ZF-5702 : we try replace() first becase set() seems to be slower
if (!($result = $this->_memcache->replace($id, array($data, time(), $newLifetime), $newLifetime))) {
$result = $this->_memcache->set($id, array($data, time(), $newLifetime), $newLifetime);
if ($result === false) {
$rsCode = $this->_memcache->getResultCode();
$rsMsg = $this->_memcache->getResultMessage();
$this->_log("Memcached::set() failed: [{$rsCode}] {$rsMsg}");
}
}
return $result;
}
return false;
}
/**
* Return an associative array of capabilities (booleans) of the backend
*
* The array must include these keys :
* - automatic_cleaning (is automating cleaning necessary)
* - tags (are tags supported)
* - expired_read (is it possible to read expired cache records
* (for doNotTestCacheValidity option for example))
* - priority does the backend deal with priority when saving
* - infinite_lifetime (is infinite lifetime can work with this backend)
* - get_list (is it possible to get the list of cache ids and the complete list of tags)
*
* @return array associative of with capabilities
*/
public function getCapabilities()
{
return array(
'automatic_cleaning' => false,
'tags' => false,
'expired_read' => false,
'priority' => false,
'infinite_lifetime' => false,
'get_list' => false
);
}
}

View File

@ -0,0 +1,504 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Memcached.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Cache_Backend_Interface
*/
// require_once 'Zend/Cache/Backend/ExtendedInterface.php';
/**
* @see Zend_Cache_Backend
*/
// require_once 'Zend/Cache/Backend.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Backend_Memcached extends Zend_Cache_Backend implements Zend_Cache_Backend_ExtendedInterface
{
/**
* Default Values
*/
const DEFAULT_HOST = '127.0.0.1';
const DEFAULT_PORT = 11211;
const DEFAULT_PERSISTENT = true;
const DEFAULT_WEIGHT = 1;
const DEFAULT_TIMEOUT = 1;
const DEFAULT_RETRY_INTERVAL = 15;
const DEFAULT_STATUS = true;
const DEFAULT_FAILURE_CALLBACK = null;
/**
* Log message
*/
const TAGS_UNSUPPORTED_BY_CLEAN_OF_MEMCACHED_BACKEND = 'Zend_Cache_Backend_Memcached::clean() : tags are unsupported by the Memcached backend';
const TAGS_UNSUPPORTED_BY_SAVE_OF_MEMCACHED_BACKEND = 'Zend_Cache_Backend_Memcached::save() : tags are unsupported by the Memcached backend';
/**
* Available options
*
* =====> (array) servers :
* an array of memcached server ; each memcached server is described by an associative array :
* 'host' => (string) : the name of the memcached server
* 'port' => (int) : the port of the memcached server
* 'persistent' => (bool) : use or not persistent connections to this memcached server
* 'weight' => (int) : number of buckets to create for this server which in turn control its
* probability of it being selected. The probability is relative to the total
* weight of all servers.
* 'timeout' => (int) : value in seconds which will be used for connecting to the daemon. Think twice
* before changing the default value of 1 second - you can lose all the
* advantages of caching if your connection is too slow.
* 'retry_interval' => (int) : controls how often a failed server will be retried, the default value
* is 15 seconds. Setting this parameter to -1 disables automatic retry.
* 'status' => (bool) : controls if the server should be flagged as online.
* 'failure_callback' => (callback) : Allows the user to specify a callback function to run upon
* encountering an error. The callback is run before failover
* is attempted. The function takes two parameters, the hostname
* and port of the failed server.
*
* =====> (boolean) compression :
* true if you want to use on-the-fly compression
*
* =====> (boolean) compatibility :
* true if you use old memcache server or extension
*
* @var array available options
*/
protected $_options = array(
'servers' => array(array(
'host' => self::DEFAULT_HOST,
'port' => self::DEFAULT_PORT,
'persistent' => self::DEFAULT_PERSISTENT,
'weight' => self::DEFAULT_WEIGHT,
'timeout' => self::DEFAULT_TIMEOUT,
'retry_interval' => self::DEFAULT_RETRY_INTERVAL,
'status' => self::DEFAULT_STATUS,
'failure_callback' => self::DEFAULT_FAILURE_CALLBACK
)),
'compression' => false,
'compatibility' => false,
);
/**
* Memcache object
*
* @var mixed memcache object
*/
protected $_memcache = null;
/**
* Constructor
*
* @param array $options associative array of options
* @throws Zend_Cache_Exception
* @return void
*/
public function __construct(array $options = array())
{
if (!extension_loaded('memcache')) {
Zend_Cache::throwException('The memcache extension must be loaded for using this backend !');
}
parent::__construct($options);
if (isset($this->_options['servers'])) {
$value= $this->_options['servers'];
if (isset($value['host'])) {
// in this case, $value seems to be a simple associative array (one server only)
$value = array(0 => $value); // let's transform it into a classical array of associative arrays
}
$this->setOption('servers', $value);
}
$this->_memcache = new Memcache;
foreach ($this->_options['servers'] as $server) {
if (!array_key_exists('port', $server)) {
$server['port'] = self::DEFAULT_PORT;
}
if (!array_key_exists('persistent', $server)) {
$server['persistent'] = self::DEFAULT_PERSISTENT;
}
if (!array_key_exists('weight', $server)) {
$server['weight'] = self::DEFAULT_WEIGHT;
}
if (!array_key_exists('timeout', $server)) {
$server['timeout'] = self::DEFAULT_TIMEOUT;
}
if (!array_key_exists('retry_interval', $server)) {
$server['retry_interval'] = self::DEFAULT_RETRY_INTERVAL;
}
if (!array_key_exists('status', $server)) {
$server['status'] = self::DEFAULT_STATUS;
}
if (!array_key_exists('failure_callback', $server)) {
$server['failure_callback'] = self::DEFAULT_FAILURE_CALLBACK;
}
if ($this->_options['compatibility']) {
// No status for compatibility mode (#ZF-5887)
$this->_memcache->addServer($server['host'], $server['port'], $server['persistent'],
$server['weight'], $server['timeout'],
$server['retry_interval']);
} else {
$this->_memcache->addServer($server['host'], $server['port'], $server['persistent'],
$server['weight'], $server['timeout'],
$server['retry_interval'],
$server['status'], $server['failure_callback']);
}
}
}
/**
* Test if a cache is available for the given id and (if yes) return it (false else)
*
* @param string $id Cache id
* @param boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
* @return string|false cached datas
*/
public function load($id, $doNotTestCacheValidity = false)
{
$tmp = $this->_memcache->get($id);
if (is_array($tmp) && isset($tmp[0])) {
return $tmp[0];
}
return false;
}
/**
* Test if a cache is available or not (for the given id)
*
* @param string $id Cache id
* @return mixed|false (a cache is not available) or "last modified" timestamp (int) of the available cache record
*/
public function test($id)
{
$tmp = $this->_memcache->get($id);
if (is_array($tmp)) {
return $tmp[1];
}
return false;
}
/**
* Save some string datas into a cache record
*
* Note : $data is always "string" (serialization is done by the
* core not by the backend)
*
* @param string $data Datas to cache
* @param string $id Cache id
* @param array $tags Array of strings, the cache record will be tagged by each string entry
* @param int $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
* @return boolean True if no problem
*/
public function save($data, $id, $tags = array(), $specificLifetime = false)
{
$lifetime = $this->getLifetime($specificLifetime);
if ($this->_options['compression']) {
$flag = MEMCACHE_COMPRESSED;
} else {
$flag = 0;
}
// ZF-8856: using set because add needs a second request if item already exists
$result = @$this->_memcache->set($id, array($data, time(), $lifetime), $flag, $lifetime);
if (count($tags) > 0) {
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_MEMCACHED_BACKEND);
}
return $result;
}
/**
* Remove a cache record
*
* @param string $id Cache id
* @return boolean True if no problem
*/
public function remove($id)
{
return $this->_memcache->delete($id, 0);
}
/**
* Clean some cache records
*
* Available modes are :
* 'all' (default) => remove all cache entries ($tags is not used)
* 'old' => unsupported
* 'matchingTag' => unsupported
* 'notMatchingTag' => unsupported
* 'matchingAnyTag' => unsupported
*
* @param string $mode Clean mode
* @param array $tags Array of tags
* @throws Zend_Cache_Exception
* @return boolean True if no problem
*/
public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
{
switch ($mode) {
case Zend_Cache::CLEANING_MODE_ALL:
return $this->_memcache->flush();
break;
case Zend_Cache::CLEANING_MODE_OLD:
$this->_log("Zend_Cache_Backend_Memcached::clean() : CLEANING_MODE_OLD is unsupported by the Memcached backend");
break;
case Zend_Cache::CLEANING_MODE_MATCHING_TAG:
case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG:
case Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG:
$this->_log(self::TAGS_UNSUPPORTED_BY_CLEAN_OF_MEMCACHED_BACKEND);
break;
default:
Zend_Cache::throwException('Invalid mode for clean() method');
break;
}
}
/**
* Return true if the automatic cleaning is available for the backend
*
* @return boolean
*/
public function isAutomaticCleaningAvailable()
{
return false;
}
/**
* Set the frontend directives
*
* @param array $directives Assoc of directives
* @throws Zend_Cache_Exception
* @return void
*/
public function setDirectives($directives)
{
parent::setDirectives($directives);
$lifetime = $this->getLifetime(false);
if ($lifetime > 2592000) {
// #ZF-3490 : For the memcached backend, there is a lifetime limit of 30 days (2592000 seconds)
$this->_log('memcached backend has a limit of 30 days (2592000 seconds) for the lifetime');
}
if ($lifetime === null) {
// #ZF-4614 : we tranform null to zero to get the maximal lifetime
parent::setDirectives(array('lifetime' => 0));
}
}
/**
* Return an array of stored cache ids
*
* @return array array of stored cache ids (string)
*/
public function getIds()
{
$this->_log("Zend_Cache_Backend_Memcached::save() : getting the list of cache ids is unsupported by the Memcache backend");
return array();
}
/**
* Return an array of stored tags
*
* @return array array of stored tags (string)
*/
public function getTags()
{
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_MEMCACHED_BACKEND);
return array();
}
/**
* Return an array of stored cache ids which match given tags
*
* In case of multiple tags, a logical AND is made between tags
*
* @param array $tags array of tags
* @return array array of matching cache ids (string)
*/
public function getIdsMatchingTags($tags = array())
{
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_MEMCACHED_BACKEND);
return array();
}
/**
* Return an array of stored cache ids which don't match given tags
*
* In case of multiple tags, a logical OR is made between tags
*
* @param array $tags array of tags
* @return array array of not matching cache ids (string)
*/
public function getIdsNotMatchingTags($tags = array())
{
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_MEMCACHED_BACKEND);
return array();
}
/**
* Return an array of stored cache ids which match any given tags
*
* In case of multiple tags, a logical AND is made between tags
*
* @param array $tags array of tags
* @return array array of any matching cache ids (string)
*/
public function getIdsMatchingAnyTags($tags = array())
{
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_MEMCACHED_BACKEND);
return array();
}
/**
* Return the filling percentage of the backend storage
*
* @throws Zend_Cache_Exception
* @return int integer between 0 and 100
*/
public function getFillingPercentage()
{
$mems = $this->_memcache->getExtendedStats();
$memSize = null;
$memUsed = null;
foreach ($mems as $key => $mem) {
if ($mem === false) {
$this->_log('can\'t get stat from ' . $key);
continue;
}
$eachSize = $mem['limit_maxbytes'];
$eachUsed = $mem['bytes'];
if ($eachUsed > $eachSize) {
$eachUsed = $eachSize;
}
$memSize += $eachSize;
$memUsed += $eachUsed;
}
if ($memSize === null || $memUsed === null) {
Zend_Cache::throwException('Can\'t get filling percentage');
}
return ((int) (100. * ($memUsed / $memSize)));
}
/**
* Return an array of metadatas for the given cache id
*
* The array must include these keys :
* - expire : the expire timestamp
* - tags : a string array of tags
* - mtime : timestamp of last modification time
*
* @param string $id cache id
* @return array array of metadatas (false if the cache id is not found)
*/
public function getMetadatas($id)
{
$tmp = $this->_memcache->get($id);
if (is_array($tmp)) {
$data = $tmp[0];
$mtime = $tmp[1];
if (!isset($tmp[2])) {
// because this record is only with 1.7 release
// if old cache records are still there...
return false;
}
$lifetime = $tmp[2];
return array(
'expire' => $mtime + $lifetime,
'tags' => array(),
'mtime' => $mtime
);
}
return false;
}
/**
* Give (if possible) an extra lifetime to the given cache id
*
* @param string $id cache id
* @param int $extraLifetime
* @return boolean true if ok
*/
public function touch($id, $extraLifetime)
{
if ($this->_options['compression']) {
$flag = MEMCACHE_COMPRESSED;
} else {
$flag = 0;
}
$tmp = $this->_memcache->get($id);
if (is_array($tmp)) {
$data = $tmp[0];
$mtime = $tmp[1];
if (!isset($tmp[2])) {
// because this record is only with 1.7 release
// if old cache records are still there...
return false;
}
$lifetime = $tmp[2];
$newLifetime = $lifetime - (time() - $mtime) + $extraLifetime;
if ($newLifetime <=0) {
return false;
}
// #ZF-5702 : we try replace() first becase set() seems to be slower
if (!($result = $this->_memcache->replace($id, array($data, time(), $newLifetime), $flag, $newLifetime))) {
$result = $this->_memcache->set($id, array($data, time(), $newLifetime), $flag, $newLifetime);
}
return $result;
}
return false;
}
/**
* Return an associative array of capabilities (booleans) of the backend
*
* The array must include these keys :
* - automatic_cleaning (is automating cleaning necessary)
* - tags (are tags supported)
* - expired_read (is it possible to read expired cache records
* (for doNotTestCacheValidity option for example))
* - priority does the backend deal with priority when saving
* - infinite_lifetime (is infinite lifetime can work with this backend)
* - get_list (is it possible to get the list of cache ids and the complete list of tags)
*
* @return array associative of with capabilities
*/
public function getCapabilities()
{
return array(
'automatic_cleaning' => false,
'tags' => false,
'expired_read' => false,
'priority' => false,
'infinite_lifetime' => false,
'get_list' => false
);
}
}

View File

@ -0,0 +1,678 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Sqlite.php 24348 2011-08-04 17:51:24Z mabe $
*/
/**
* @see Zend_Cache_Backend_Interface
*/
// require_once 'Zend/Cache/Backend/ExtendedInterface.php';
/**
* @see Zend_Cache_Backend
*/
// require_once 'Zend/Cache/Backend.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Backend_Sqlite extends Zend_Cache_Backend implements Zend_Cache_Backend_ExtendedInterface
{
/**
* Available options
*
* =====> (string) cache_db_complete_path :
* - the complete path (filename included) of the SQLITE database
*
* ====> (int) automatic_vacuum_factor :
* - Disable / Tune the automatic vacuum process
* - The automatic vacuum process defragment the database file (and make it smaller)
* when a clean() or delete() is called
* 0 => no automatic vacuum
* 1 => systematic vacuum (when delete() or clean() methods are called)
* x (integer) > 1 => automatic vacuum randomly 1 times on x clean() or delete()
*
* @var array Available options
*/
protected $_options = array(
'cache_db_complete_path' => null,
'automatic_vacuum_factor' => 10
);
/**
* DB ressource
*
* @var mixed $_db
*/
private $_db = null;
/**
* Boolean to store if the structure has benn checked or not
*
* @var boolean $_structureChecked
*/
private $_structureChecked = false;
/**
* Constructor
*
* @param array $options Associative array of options
* @throws Zend_cache_Exception
* @return void
*/
public function __construct(array $options = array())
{
parent::__construct($options);
if ($this->_options['cache_db_complete_path'] === null) {
Zend_Cache::throwException('cache_db_complete_path option has to set');
}
if (!extension_loaded('sqlite')) {
Zend_Cache::throwException("Cannot use SQLite storage because the 'sqlite' extension is not loaded in the current PHP environment");
}
$this->_getConnection();
}
/**
* Destructor
*
* @return void
*/
public function __destruct()
{
@sqlite_close($this->_getConnection());
}
/**
* Test if a cache is available for the given id and (if yes) return it (false else)
*
* @param string $id Cache id
* @param boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
* @return string|false Cached datas
*/
public function load($id, $doNotTestCacheValidity = false)
{
$this->_checkAndBuildStructure();
$sql = "SELECT content FROM cache WHERE id='$id'";
if (!$doNotTestCacheValidity) {
$sql = $sql . " AND (expire=0 OR expire>" . time() . ')';
}
$result = $this->_query($sql);
$row = @sqlite_fetch_array($result);
if ($row) {
return $row['content'];
}
return false;
}
/**
* Test if a cache is available or not (for the given id)
*
* @param string $id Cache id
* @return mixed|false (a cache is not available) or "last modified" timestamp (int) of the available cache record
*/
public function test($id)
{
$this->_checkAndBuildStructure();
$sql = "SELECT lastModified FROM cache WHERE id='$id' AND (expire=0 OR expire>" . time() . ')';
$result = $this->_query($sql);
$row = @sqlite_fetch_array($result);
if ($row) {
return ((int) $row['lastModified']);
}
return false;
}
/**
* Save some string datas into a cache record
*
* Note : $data is always "string" (serialization is done by the
* core not by the backend)
*
* @param string $data Datas to cache
* @param string $id Cache id
* @param array $tags Array of strings, the cache record will be tagged by each string entry
* @param int $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
* @throws Zend_Cache_Exception
* @return boolean True if no problem
*/
public function save($data, $id, $tags = array(), $specificLifetime = false)
{
$this->_checkAndBuildStructure();
$lifetime = $this->getLifetime($specificLifetime);
$data = @sqlite_escape_string($data);
$mktime = time();
if ($lifetime === null) {
$expire = 0;
} else {
$expire = $mktime + $lifetime;
}
$this->_query("DELETE FROM cache WHERE id='$id'");
$sql = "INSERT INTO cache (id, content, lastModified, expire) VALUES ('$id', '$data', $mktime, $expire)";
$res = $this->_query($sql);
if (!$res) {
$this->_log("Zend_Cache_Backend_Sqlite::save() : impossible to store the cache id=$id");
return false;
}
$res = true;
foreach ($tags as $tag) {
$res = $this->_registerTag($id, $tag) && $res;
}
return $res;
}
/**
* Remove a cache record
*
* @param string $id Cache id
* @return boolean True if no problem
*/
public function remove($id)
{
$this->_checkAndBuildStructure();
$res = $this->_query("SELECT COUNT(*) AS nbr FROM cache WHERE id='$id'");
$result1 = @sqlite_fetch_single($res);
$result2 = $this->_query("DELETE FROM cache WHERE id='$id'");
$result3 = $this->_query("DELETE FROM tag WHERE id='$id'");
$this->_automaticVacuum();
return ($result1 && $result2 && $result3);
}
/**
* Clean some cache records
*
* Available modes are :
* Zend_Cache::CLEANING_MODE_ALL (default) => remove all cache entries ($tags is not used)
* Zend_Cache::CLEANING_MODE_OLD => remove too old cache entries ($tags is not used)
* Zend_Cache::CLEANING_MODE_MATCHING_TAG => remove cache entries matching all given tags
* ($tags can be an array of strings or a single string)
* Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG => remove cache entries not {matching one of the given tags}
* ($tags can be an array of strings or a single string)
* Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG => remove cache entries matching any given tags
* ($tags can be an array of strings or a single string)
*
* @param string $mode Clean mode
* @param array $tags Array of tags
* @return boolean True if no problem
*/
public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
{
$this->_checkAndBuildStructure();
$return = $this->_clean($mode, $tags);
$this->_automaticVacuum();
return $return;
}
/**
* Return an array of stored cache ids
*
* @return array array of stored cache ids (string)
*/
public function getIds()
{
$this->_checkAndBuildStructure();
$res = $this->_query("SELECT id FROM cache WHERE (expire=0 OR expire>" . time() . ")");
$result = array();
while ($id = @sqlite_fetch_single($res)) {
$result[] = $id;
}
return $result;
}
/**
* Return an array of stored tags
*
* @return array array of stored tags (string)
*/
public function getTags()
{
$this->_checkAndBuildStructure();
$res = $this->_query("SELECT DISTINCT(name) AS name FROM tag");
$result = array();
while ($id = @sqlite_fetch_single($res)) {
$result[] = $id;
}
return $result;
}
/**
* Return an array of stored cache ids which match given tags
*
* In case of multiple tags, a logical AND is made between tags
*
* @param array $tags array of tags
* @return array array of matching cache ids (string)
*/
public function getIdsMatchingTags($tags = array())
{
$first = true;
$ids = array();
foreach ($tags as $tag) {
$res = $this->_query("SELECT DISTINCT(id) AS id FROM tag WHERE name='$tag'");
if (!$res) {
return array();
}
$rows = @sqlite_fetch_all($res, SQLITE_ASSOC);
$ids2 = array();
foreach ($rows as $row) {
$ids2[] = $row['id'];
}
if ($first) {
$ids = $ids2;
$first = false;
} else {
$ids = array_intersect($ids, $ids2);
}
}
$result = array();
foreach ($ids as $id) {
$result[] = $id;
}
return $result;
}
/**
* Return an array of stored cache ids which don't match given tags
*
* In case of multiple tags, a logical OR is made between tags
*
* @param array $tags array of tags
* @return array array of not matching cache ids (string)
*/
public function getIdsNotMatchingTags($tags = array())
{
$res = $this->_query("SELECT id FROM cache");
$rows = @sqlite_fetch_all($res, SQLITE_ASSOC);
$result = array();
foreach ($rows as $row) {
$id = $row['id'];
$matching = false;
foreach ($tags as $tag) {
$res = $this->_query("SELECT COUNT(*) AS nbr FROM tag WHERE name='$tag' AND id='$id'");
if (!$res) {
return array();
}
$nbr = (int) @sqlite_fetch_single($res);
if ($nbr > 0) {
$matching = true;
}
}
if (!$matching) {
$result[] = $id;
}
}
return $result;
}
/**
* Return an array of stored cache ids which match any given tags
*
* In case of multiple tags, a logical AND is made between tags
*
* @param array $tags array of tags
* @return array array of any matching cache ids (string)
*/
public function getIdsMatchingAnyTags($tags = array())
{
$first = true;
$ids = array();
foreach ($tags as $tag) {
$res = $this->_query("SELECT DISTINCT(id) AS id FROM tag WHERE name='$tag'");
if (!$res) {
return array();
}
$rows = @sqlite_fetch_all($res, SQLITE_ASSOC);
$ids2 = array();
foreach ($rows as $row) {
$ids2[] = $row['id'];
}
if ($first) {
$ids = $ids2;
$first = false;
} else {
$ids = array_merge($ids, $ids2);
}
}
$result = array();
foreach ($ids as $id) {
$result[] = $id;
}
return $result;
}
/**
* Return the filling percentage of the backend storage
*
* @throws Zend_Cache_Exception
* @return int integer between 0 and 100
*/
public function getFillingPercentage()
{
$dir = dirname($this->_options['cache_db_complete_path']);
$free = disk_free_space($dir);
$total = disk_total_space($dir);
if ($total == 0) {
Zend_Cache::throwException('can\'t get disk_total_space');
} else {
if ($free >= $total) {
return 100;
}
return ((int) (100. * ($total - $free) / $total));
}
}
/**
* Return an array of metadatas for the given cache id
*
* The array must include these keys :
* - expire : the expire timestamp
* - tags : a string array of tags
* - mtime : timestamp of last modification time
*
* @param string $id cache id
* @return array array of metadatas (false if the cache id is not found)
*/
public function getMetadatas($id)
{
$tags = array();
$res = $this->_query("SELECT name FROM tag WHERE id='$id'");
if ($res) {
$rows = @sqlite_fetch_all($res, SQLITE_ASSOC);
foreach ($rows as $row) {
$tags[] = $row['name'];
}
}
$this->_query('CREATE TABLE cache (id TEXT PRIMARY KEY, content BLOB, lastModified INTEGER, expire INTEGER)');
$res = $this->_query("SELECT lastModified,expire FROM cache WHERE id='$id'");
if (!$res) {
return false;
}
$row = @sqlite_fetch_array($res, SQLITE_ASSOC);
return array(
'tags' => $tags,
'mtime' => $row['lastModified'],
'expire' => $row['expire']
);
}
/**
* Give (if possible) an extra lifetime to the given cache id
*
* @param string $id cache id
* @param int $extraLifetime
* @return boolean true if ok
*/
public function touch($id, $extraLifetime)
{
$sql = "SELECT expire FROM cache WHERE id='$id' AND (expire=0 OR expire>" . time() . ')';
$res = $this->_query($sql);
if (!$res) {
return false;
}
$expire = @sqlite_fetch_single($res);
$newExpire = $expire + $extraLifetime;
$res = $this->_query("UPDATE cache SET lastModified=" . time() . ", expire=$newExpire WHERE id='$id'");
if ($res) {
return true;
} else {
return false;
}
}
/**
* Return an associative array of capabilities (booleans) of the backend
*
* The array must include these keys :
* - automatic_cleaning (is automating cleaning necessary)
* - tags (are tags supported)
* - expired_read (is it possible to read expired cache records
* (for doNotTestCacheValidity option for example))
* - priority does the backend deal with priority when saving
* - infinite_lifetime (is infinite lifetime can work with this backend)
* - get_list (is it possible to get the list of cache ids and the complete list of tags)
*
* @return array associative of with capabilities
*/
public function getCapabilities()
{
return array(
'automatic_cleaning' => true,
'tags' => true,
'expired_read' => true,
'priority' => false,
'infinite_lifetime' => true,
'get_list' => true
);
}
/**
* PUBLIC METHOD FOR UNIT TESTING ONLY !
*
* Force a cache record to expire
*
* @param string $id Cache id
*/
public function ___expire($id)
{
$time = time() - 1;
$this->_query("UPDATE cache SET lastModified=$time, expire=$time WHERE id='$id'");
}
/**
* Return the connection resource
*
* If we are not connected, the connection is made
*
* @throws Zend_Cache_Exception
* @return resource Connection resource
*/
private function _getConnection()
{
if (is_resource($this->_db)) {
return $this->_db;
} else {
$this->_db = @sqlite_open($this->_options['cache_db_complete_path']);
if (!(is_resource($this->_db))) {
Zend_Cache::throwException("Impossible to open " . $this->_options['cache_db_complete_path'] . " cache DB file");
}
return $this->_db;
}
}
/**
* Execute an SQL query silently
*
* @param string $query SQL query
* @return mixed|false query results
*/
private function _query($query)
{
$db = $this->_getConnection();
if (is_resource($db)) {
$res = @sqlite_query($db, $query);
if ($res === false) {
return false;
} else {
return $res;
}
}
return false;
}
/**
* Deal with the automatic vacuum process
*
* @return void
*/
private function _automaticVacuum()
{
if ($this->_options['automatic_vacuum_factor'] > 0) {
$rand = rand(1, $this->_options['automatic_vacuum_factor']);
if ($rand == 1) {
$this->_query('VACUUM');
}
}
}
/**
* Register a cache id with the given tag
*
* @param string $id Cache id
* @param string $tag Tag
* @return boolean True if no problem
*/
private function _registerTag($id, $tag) {
$res = $this->_query("DELETE FROM TAG WHERE name='$tag' AND id='$id'");
$res = $this->_query("INSERT INTO tag (name, id) VALUES ('$tag', '$id')");
if (!$res) {
$this->_log("Zend_Cache_Backend_Sqlite::_registerTag() : impossible to register tag=$tag on id=$id");
return false;
}
return true;
}
/**
* Build the database structure
*
* @return false
*/
private function _buildStructure()
{
$this->_query('DROP INDEX tag_id_index');
$this->_query('DROP INDEX tag_name_index');
$this->_query('DROP INDEX cache_id_expire_index');
$this->_query('DROP TABLE version');
$this->_query('DROP TABLE cache');
$this->_query('DROP TABLE tag');
$this->_query('CREATE TABLE version (num INTEGER PRIMARY KEY)');
$this->_query('CREATE TABLE cache (id TEXT PRIMARY KEY, content BLOB, lastModified INTEGER, expire INTEGER)');
$this->_query('CREATE TABLE tag (name TEXT, id TEXT)');
$this->_query('CREATE INDEX tag_id_index ON tag(id)');
$this->_query('CREATE INDEX tag_name_index ON tag(name)');
$this->_query('CREATE INDEX cache_id_expire_index ON cache(id, expire)');
$this->_query('INSERT INTO version (num) VALUES (1)');
}
/**
* Check if the database structure is ok (with the good version)
*
* @return boolean True if ok
*/
private function _checkStructureVersion()
{
$result = $this->_query("SELECT num FROM version");
if (!$result) return false;
$row = @sqlite_fetch_array($result);
if (!$row) {
return false;
}
if (((int) $row['num']) != 1) {
// old cache structure
$this->_log('Zend_Cache_Backend_Sqlite::_checkStructureVersion() : old cache structure version detected => the cache is going to be dropped');
return false;
}
return true;
}
/**
* Clean some cache records
*
* Available modes are :
* Zend_Cache::CLEANING_MODE_ALL (default) => remove all cache entries ($tags is not used)
* Zend_Cache::CLEANING_MODE_OLD => remove too old cache entries ($tags is not used)
* Zend_Cache::CLEANING_MODE_MATCHING_TAG => remove cache entries matching all given tags
* ($tags can be an array of strings or a single string)
* Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG => remove cache entries not {matching one of the given tags}
* ($tags can be an array of strings or a single string)
* Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG => remove cache entries matching any given tags
* ($tags can be an array of strings or a single string)
*
* @param string $mode Clean mode
* @param array $tags Array of tags
* @return boolean True if no problem
*/
private function _clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
{
switch ($mode) {
case Zend_Cache::CLEANING_MODE_ALL:
$res1 = $this->_query('DELETE FROM cache');
$res2 = $this->_query('DELETE FROM tag');
return $res1 && $res2;
break;
case Zend_Cache::CLEANING_MODE_OLD:
$mktime = time();
$res1 = $this->_query("DELETE FROM tag WHERE id IN (SELECT id FROM cache WHERE expire>0 AND expire<=$mktime)");
$res2 = $this->_query("DELETE FROM cache WHERE expire>0 AND expire<=$mktime");
return $res1 && $res2;
break;
case Zend_Cache::CLEANING_MODE_MATCHING_TAG:
$ids = $this->getIdsMatchingTags($tags);
$result = true;
foreach ($ids as $id) {
$result = $this->remove($id) && $result;
}
return $result;
break;
case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG:
$ids = $this->getIdsNotMatchingTags($tags);
$result = true;
foreach ($ids as $id) {
$result = $this->remove($id) && $result;
}
return $result;
break;
case Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG:
$ids = $this->getIdsMatchingAnyTags($tags);
$result = true;
foreach ($ids as $id) {
$result = $this->remove($id) && $result;
}
return $result;
break;
default:
break;
}
return false;
}
/**
* Check if the database structure is ok (with the good version), if no : build it
*
* @throws Zend_Cache_Exception
* @return boolean True if ok
*/
private function _checkAndBuildStructure()
{
if (!($this->_structureChecked)) {
if (!$this->_checkStructureVersion()) {
$this->_buildStructure();
if (!$this->_checkStructureVersion()) {
Zend_Cache::throwException("Impossible to build cache structure in " . $this->_options['cache_db_complete_path']);
}
}
$this->_structureChecked = true;
}
return true;
}
}

View File

@ -0,0 +1,564 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Static.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Cache_Backend_Interface
*/
// require_once 'Zend/Cache/Backend/Interface.php';
/**
* @see Zend_Cache_Backend
*/
// require_once 'Zend/Cache/Backend.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Backend_Static
extends Zend_Cache_Backend
implements Zend_Cache_Backend_Interface
{
const INNER_CACHE_NAME = 'zend_cache_backend_static_tagcache';
/**
* Static backend options
* @var array
*/
protected $_options = array(
'public_dir' => null,
'sub_dir' => 'html',
'file_extension' => '.html',
'index_filename' => 'index',
'file_locking' => true,
'cache_file_umask' => 0600,
'cache_directory_umask' => 0700,
'debug_header' => false,
'tag_cache' => null,
'disable_caching' => false
);
/**
* Cache for handling tags
* @var Zend_Cache_Core
*/
protected $_tagCache = null;
/**
* Tagged items
* @var array
*/
protected $_tagged = null;
/**
* Interceptor child method to handle the case where an Inner
* Cache object is being set since it's not supported by the
* standard backend interface
*
* @param string $name
* @param mixed $value
* @return Zend_Cache_Backend_Static
*/
public function setOption($name, $value)
{
if ($name == 'tag_cache') {
$this->setInnerCache($value);
} else {
parent::setOption($name, $value);
}
return $this;
}
/**
* Retrieve any option via interception of the parent's statically held
* options including the local option for a tag cache.
*
* @param string $name
* @return mixed
*/
public function getOption($name)
{
if ($name == 'tag_cache') {
return $this->getInnerCache();
} else {
if (in_array($name, $this->_options)) {
return $this->_options[$name];
}
if ($name == 'lifetime') {
return parent::getLifetime();
}
return null;
}
}
/**
* Test if a cache is available for the given id and (if yes) return it (false else)
*
* Note : return value is always "string" (unserialization is done by the core not by the backend)
*
* @param string $id Cache id
* @param boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
* @return string|false cached datas
*/
public function load($id, $doNotTestCacheValidity = false)
{
if (($id = (string)$id) === '') {
$id = $this->_detectId();
} else {
$id = $this->_decodeId($id);
}
if (!$this->_verifyPath($id)) {
Zend_Cache::throwException('Invalid cache id: does not match expected public_dir path');
}
if ($doNotTestCacheValidity) {
$this->_log("Zend_Cache_Backend_Static::load() : \$doNotTestCacheValidity=true is unsupported by the Static backend");
}
$fileName = basename($id);
if ($fileName === '') {
$fileName = $this->_options['index_filename'];
}
$pathName = $this->_options['public_dir'] . dirname($id);
$file = rtrim($pathName, '/') . '/' . $fileName . $this->_options['file_extension'];
if (file_exists($file)) {
$content = file_get_contents($file);
return $content;
}
return false;
}
/**
* Test if a cache is available or not (for the given id)
*
* @param string $id cache id
* @return bool
*/
public function test($id)
{
$id = $this->_decodeId($id);
if (!$this->_verifyPath($id)) {
Zend_Cache::throwException('Invalid cache id: does not match expected public_dir path');
}
$fileName = basename($id);
if ($fileName === '') {
$fileName = $this->_options['index_filename'];
}
if ($this->_tagged === null && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) {
$this->_tagged = $tagged;
} elseif (!$this->_tagged) {
return false;
}
$pathName = $this->_options['public_dir'] . dirname($id);
// Switch extension if needed
if (isset($this->_tagged[$id])) {
$extension = $this->_tagged[$id]['extension'];
} else {
$extension = $this->_options['file_extension'];
}
$file = $pathName . '/' . $fileName . $extension;
if (file_exists($file)) {
return true;
}
return false;
}
/**
* Save some string datas into a cache record
*
* Note : $data is always "string" (serialization is done by the
* core not by the backend)
*
* @param string $data Datas to cache
* @param string $id Cache id
* @param array $tags Array of strings, the cache record will be tagged by each string entry
* @param int $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
* @return boolean true if no problem
*/
public function save($data, $id, $tags = array(), $specificLifetime = false)
{
if ($this->_options['disable_caching']) {
return true;
}
$extension = null;
if ($this->_isSerialized($data)) {
$data = unserialize($data);
$extension = '.' . ltrim($data[1], '.');
$data = $data[0];
}
clearstatcache();
if (($id = (string)$id) === '') {
$id = $this->_detectId();
} else {
$id = $this->_decodeId($id);
}
$fileName = basename($id);
if ($fileName === '') {
$fileName = $this->_options['index_filename'];
}
$pathName = realpath($this->_options['public_dir']) . dirname($id);
$this->_createDirectoriesFor($pathName);
if ($id === null || strlen($id) == 0) {
$dataUnserialized = unserialize($data);
$data = $dataUnserialized['data'];
}
$ext = $this->_options['file_extension'];
if ($extension) $ext = $extension;
$file = rtrim($pathName, '/') . '/' . $fileName . $ext;
if ($this->_options['file_locking']) {
$result = file_put_contents($file, $data, LOCK_EX);
} else {
$result = file_put_contents($file, $data);
}
@chmod($file, $this->_octdec($this->_options['cache_file_umask']));
if ($this->_tagged === null && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) {
$this->_tagged = $tagged;
} elseif ($this->_tagged === null) {
$this->_tagged = array();
}
if (!isset($this->_tagged[$id])) {
$this->_tagged[$id] = array();
}
if (!isset($this->_tagged[$id]['tags'])) {
$this->_tagged[$id]['tags'] = array();
}
$this->_tagged[$id]['tags'] = array_unique(array_merge($this->_tagged[$id]['tags'], $tags));
$this->_tagged[$id]['extension'] = $ext;
$this->getInnerCache()->save($this->_tagged, self::INNER_CACHE_NAME);
return (bool) $result;
}
/**
* Recursively create the directories needed to write the static file
*/
protected function _createDirectoriesFor($path)
{
if (!is_dir($path)) {
$oldUmask = umask(0);
if ( !@mkdir($path, $this->_octdec($this->_options['cache_directory_umask']), true)) {
$lastErr = error_get_last();
umask($oldUmask);
Zend_Cache::throwException("Can't create directory: {$lastErr['message']}");
}
umask($oldUmask);
}
}
/**
* Detect serialization of data (cannot predict since this is the only way
* to obey the interface yet pass in another parameter).
*
* In future, ZF 2.0, check if we can just avoid the interface restraints.
*
* This format is the only valid one possible for the class, so it's simple
* to just run a regular expression for the starting serialized format.
*/
protected function _isSerialized($data)
{
return preg_match("/a:2:\{i:0;s:\d+:\"/", $data);
}
/**
* Remove a cache record
*
* @param string $id Cache id
* @return boolean True if no problem
*/
public function remove($id)
{
if (!$this->_verifyPath($id)) {
Zend_Cache::throwException('Invalid cache id: does not match expected public_dir path');
}
$fileName = basename($id);
if ($this->_tagged === null && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) {
$this->_tagged = $tagged;
} elseif (!$this->_tagged) {
return false;
}
if (isset($this->_tagged[$id])) {
$extension = $this->_tagged[$id]['extension'];
} else {
$extension = $this->_options['file_extension'];
}
if ($fileName === '') {
$fileName = $this->_options['index_filename'];
}
$pathName = $this->_options['public_dir'] . dirname($id);
$file = realpath($pathName) . '/' . $fileName . $extension;
if (!file_exists($file)) {
return false;
}
return unlink($file);
}
/**
* Remove a cache record recursively for the given directory matching a
* REQUEST_URI based relative path (deletes the actual file matching this
* in addition to the matching directory)
*
* @param string $id Cache id
* @return boolean True if no problem
*/
public function removeRecursively($id)
{
if (!$this->_verifyPath($id)) {
Zend_Cache::throwException('Invalid cache id: does not match expected public_dir path');
}
$fileName = basename($id);
if ($fileName === '') {
$fileName = $this->_options['index_filename'];
}
$pathName = $this->_options['public_dir'] . dirname($id);
$file = $pathName . '/' . $fileName . $this->_options['file_extension'];
$directory = $pathName . '/' . $fileName;
if (file_exists($directory)) {
if (!is_writable($directory)) {
return false;
}
if (is_dir($directory)) {
foreach (new DirectoryIterator($directory) as $file) {
if (true === $file->isFile()) {
if (false === unlink($file->getPathName())) {
return false;
}
}
}
}
rmdir($directory);
}
if (file_exists($file)) {
if (!is_writable($file)) {
return false;
}
return unlink($file);
}
return true;
}
/**
* Clean some cache records
*
* Available modes are :
* Zend_Cache::CLEANING_MODE_ALL (default) => remove all cache entries ($tags is not used)
* Zend_Cache::CLEANING_MODE_OLD => remove too old cache entries ($tags is not used)
* Zend_Cache::CLEANING_MODE_MATCHING_TAG => remove cache entries matching all given tags
* ($tags can be an array of strings or a single string)
* Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG => remove cache entries not {matching one of the given tags}
* ($tags can be an array of strings or a single string)
* Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG => remove cache entries matching any given tags
* ($tags can be an array of strings or a single string)
*
* @param string $mode Clean mode
* @param array $tags Array of tags
* @return boolean true if no problem
*/
public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
{
$result = false;
switch ($mode) {
case Zend_Cache::CLEANING_MODE_MATCHING_TAG:
case Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG:
if (empty($tags)) {
throw new Zend_Exception('Cannot use tag matching modes as no tags were defined');
}
if ($this->_tagged === null && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) {
$this->_tagged = $tagged;
} elseif (!$this->_tagged) {
return true;
}
foreach ($tags as $tag) {
$urls = array_keys($this->_tagged);
foreach ($urls as $url) {
if (isset($this->_tagged[$url]['tags']) && in_array($tag, $this->_tagged[$url]['tags'])) {
$this->remove($url);
unset($this->_tagged[$url]);
}
}
}
$this->getInnerCache()->save($this->_tagged, self::INNER_CACHE_NAME);
$result = true;
break;
case Zend_Cache::CLEANING_MODE_ALL:
if ($this->_tagged === null) {
$tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME);
$this->_tagged = $tagged;
}
if ($this->_tagged === null || empty($this->_tagged)) {
return true;
}
$urls = array_keys($this->_tagged);
foreach ($urls as $url) {
$this->remove($url);
unset($this->_tagged[$url]);
}
$this->getInnerCache()->save($this->_tagged, self::INNER_CACHE_NAME);
$result = true;
break;
case Zend_Cache::CLEANING_MODE_OLD:
$this->_log("Zend_Cache_Backend_Static : Selected Cleaning Mode Currently Unsupported By This Backend");
break;
case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG:
if (empty($tags)) {
throw new Zend_Exception('Cannot use tag matching modes as no tags were defined');
}
if ($this->_tagged === null) {
$tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME);
$this->_tagged = $tagged;
}
if ($this->_tagged === null || empty($this->_tagged)) {
return true;
}
$urls = array_keys($this->_tagged);
foreach ($urls as $url) {
$difference = array_diff($tags, $this->_tagged[$url]['tags']);
if (count($tags) == count($difference)) {
$this->remove($url);
unset($this->_tagged[$url]);
}
}
$this->getInnerCache()->save($this->_tagged, self::INNER_CACHE_NAME);
$result = true;
break;
default:
Zend_Cache::throwException('Invalid mode for clean() method');
break;
}
return $result;
}
/**
* Set an Inner Cache, used here primarily to store Tags associated
* with caches created by this backend. Note: If Tags are lost, the cache
* should be completely cleaned as the mapping of tags to caches will
* have been irrevocably lost.
*
* @param Zend_Cache_Core
* @return void
*/
public function setInnerCache(Zend_Cache_Core $cache)
{
$this->_tagCache = $cache;
$this->_options['tag_cache'] = $cache;
}
/**
* Get the Inner Cache if set
*
* @return Zend_Cache_Core
*/
public function getInnerCache()
{
if ($this->_tagCache === null) {
Zend_Cache::throwException('An Inner Cache has not been set; use setInnerCache()');
}
return $this->_tagCache;
}
/**
* Verify path exists and is non-empty
*
* @param string $path
* @return bool
*/
protected function _verifyPath($path)
{
$path = realpath($path);
$base = realpath($this->_options['public_dir']);
return strncmp($path, $base, strlen($base)) !== 0;
}
/**
* Determine the page to save from the request
*
* @return string
*/
protected function _detectId()
{
return $_SERVER['REQUEST_URI'];
}
/**
* Validate a cache id or a tag (security, reliable filenames, reserved prefixes...)
*
* Throw an exception if a problem is found
*
* @param string $string Cache id or tag
* @throws Zend_Cache_Exception
* @return void
* @deprecated Not usable until perhaps ZF 2.0
*/
protected static function _validateIdOrTag($string)
{
if (!is_string($string)) {
Zend_Cache::throwException('Invalid id or tag : must be a string');
}
// Internal only checked in Frontend - not here!
if (substr($string, 0, 9) == 'internal-') {
return;
}
// Validation assumes no query string, fragments or scheme included - only the path
if (!preg_match(
'/^(?:\/(?:(?:%[[:xdigit:]]{2}|[A-Za-z0-9-_.!~*\'()\[\]:@&=+$,;])*)?)+$/',
$string
)
) {
Zend_Cache::throwException("Invalid id or tag '$string' : must be a valid URL path");
}
}
/**
* Detect an octal string and return its octal value for file permission ops
* otherwise return the non-string (assumed octal or decimal int already)
*
* @param string $val The potential octal in need of conversion
* @return int
*/
protected function _octdec($val)
{
if (is_string($val) && decoct(octdec($val)) == $val) {
return octdec($val);
}
return $val;
}
/**
* Decode a request URI from the provided ID
*
* @param string $id
* @return string
*/
protected function _decodeId($id)
{
return pack('H*', $id);
}
}

View File

@ -0,0 +1,413 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Test.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Cache_Backend_Interface
*/
// require_once 'Zend/Cache/Backend/ExtendedInterface.php';
/**
* @see Zend_Cache_Backend
*/
// require_once 'Zend/Cache/Backend.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Backend_Test extends Zend_Cache_Backend implements Zend_Cache_Backend_ExtendedInterface
{
/**
* Available options
*
* @var array available options
*/
protected $_options = array();
/**
* Frontend or Core directives
*
* @var array directives
*/
protected $_directives = array();
/**
* Array to log actions
*
* @var array $_log
*/
private $_log = array();
/**
* Current index for log array
*
* @var int $_index
*/
private $_index = 0;
/**
* Constructor
*
* @param array $options associative array of options
* @return void
*/
public function __construct($options = array())
{
$this->_addLog('construct', array($options));
}
/**
* Set the frontend directives
*
* @param array $directives assoc of directives
* @return void
*/
public function setDirectives($directives)
{
$this->_addLog('setDirectives', array($directives));
}
/**
* Test if a cache is available for the given id and (if yes) return it (false else)
*
* For this test backend only, if $id == 'false', then the method will return false
* if $id == 'serialized', the method will return a serialized array
* ('foo' else)
*
* @param string $id Cache id
* @param boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
* @return string Cached datas (or false)
*/
public function load($id, $doNotTestCacheValidity = false)
{
$this->_addLog('get', array($id, $doNotTestCacheValidity));
if ( $id == 'false'
|| $id == 'd8523b3ee441006261eeffa5c3d3a0a7'
|| $id == 'e83249ea22178277d5befc2c5e2e9ace'
|| $id == '40f649b94977c0a6e76902e2a0b43587'
|| $id == '88161989b73a4cbfd0b701c446115a99'
|| $id == '205fc79cba24f0f0018eb92c7c8b3ba4'
|| $id == '170720e35f38150b811f68a937fb042d')
{
return false;
}
if ($id=='serialized') {
return serialize(array('foo'));
}
if ($id=='serialized2') {
return serialize(array('headers' => array(), 'data' => 'foo'));
}
if ( $id == '71769f39054f75894288e397df04e445' || $id == '615d222619fb20b527168340cebd0578'
|| $id == '8a02d218a5165c467e7a5747cc6bd4b6' || $id == '648aca1366211d17cbf48e65dc570bee'
|| $id == '4a923ef02d7f997ca14d56dfeae25ea7') {
return serialize(array('foo', 'bar'));
}
return 'foo';
}
/**
* Test if a cache is available or not (for the given id)
*
* For this test backend only, if $id == 'false', then the method will return false
* (123456 else)
*
* @param string $id Cache id
* @return mixed|false false (a cache is not available) or "last modified" timestamp (int) of the available cache record
*/
public function test($id)
{
$this->_addLog('test', array($id));
if ($id=='false') {
return false;
}
if (($id=='3c439c922209e2cb0b54d6deffccd75a')) {
return false;
}
return 123456;
}
/**
* Save some string datas into a cache record
*
* For this test backend only, if $id == 'false', then the method will return false
* (true else)
*
* @param string $data Datas to cache
* @param string $id Cache id
* @param array $tags Array of strings, the cache record will be tagged by each string entry
* @param int $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
* @return boolean True if no problem
*/
public function save($data, $id, $tags = array(), $specificLifetime = false)
{
$this->_addLog('save', array($data, $id, $tags));
if (substr($id,-5)=='false') {
return false;
}
return true;
}
/**
* Remove a cache record
*
* For this test backend only, if $id == 'false', then the method will return false
* (true else)
*
* @param string $id Cache id
* @return boolean True if no problem
*/
public function remove($id)
{
$this->_addLog('remove', array($id));
if (substr($id,-5)=='false') {
return false;
}
return true;
}
/**
* Clean some cache records
*
* For this test backend only, if $mode == 'false', then the method will return false
* (true else)
*
* Available modes are :
* Zend_Cache::CLEANING_MODE_ALL (default) => remove all cache entries ($tags is not used)
* Zend_Cache::CLEANING_MODE_OLD => remove too old cache entries ($tags is not used)
* Zend_Cache::CLEANING_MODE_MATCHING_TAG => remove cache entries matching all given tags
* ($tags can be an array of strings or a single string)
* Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG => remove cache entries not {matching one of the given tags}
* ($tags can be an array of strings or a single string)
*
* @param string $mode Clean mode
* @param array $tags Array of tags
* @return boolean True if no problem
*/
public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
{
$this->_addLog('clean', array($mode, $tags));
if ($mode=='false') {
return false;
}
return true;
}
/**
* Get the last log
*
* @return string The last log
*/
public function getLastLog()
{
return $this->_log[$this->_index - 1];
}
/**
* Get the log index
*
* @return int Log index
*/
public function getLogIndex()
{
return $this->_index;
}
/**
* Get the complete log array
*
* @return array Complete log array
*/
public function getAllLogs()
{
return $this->_log;
}
/**
* Return true if the automatic cleaning is available for the backend
*
* @return boolean
*/
public function isAutomaticCleaningAvailable()
{
return true;
}
/**
* Return an array of stored cache ids
*
* @return array array of stored cache ids (string)
*/
public function getIds()
{
return array(
'prefix_id1', 'prefix_id2'
);
}
/**
* Return an array of stored tags
*
* @return array array of stored tags (string)
*/
public function getTags()
{
return array(
'tag1', 'tag2'
);
}
/**
* Return an array of stored cache ids which match given tags
*
* In case of multiple tags, a logical AND is made between tags
*
* @param array $tags array of tags
* @return array array of matching cache ids (string)
*/
public function getIdsMatchingTags($tags = array())
{
if ($tags == array('tag1', 'tag2')) {
return array('prefix_id1', 'prefix_id2');
}
return array();
}
/**
* Return an array of stored cache ids which don't match given tags
*
* In case of multiple tags, a logical OR is made between tags
*
* @param array $tags array of tags
* @return array array of not matching cache ids (string)
*/
public function getIdsNotMatchingTags($tags = array())
{
if ($tags == array('tag3', 'tag4')) {
return array('prefix_id3', 'prefix_id4');
}
return array();
}
/**
* Return an array of stored cache ids which match any given tags
*
* In case of multiple tags, a logical AND is made between tags
*
* @param array $tags array of tags
* @return array array of any matching cache ids (string)
*/
public function getIdsMatchingAnyTags($tags = array())
{
if ($tags == array('tag5', 'tag6')) {
return array('prefix_id5', 'prefix_id6');
}
return array();
}
/**
* Return the filling percentage of the backend storage
*
* @return int integer between 0 and 100
*/
public function getFillingPercentage()
{
return 50;
}
/**
* Return an array of metadatas for the given cache id
*
* The array must include these keys :
* - expire : the expire timestamp
* - tags : a string array of tags
* - mtime : timestamp of last modification time
*
* @param string $id cache id
* @return array array of metadatas (false if the cache id is not found)
*/
public function getMetadatas($id)
{
return false;
}
/**
* Give (if possible) an extra lifetime to the given cache id
*
* @param string $id cache id
* @param int $extraLifetime
* @return boolean true if ok
*/
public function touch($id, $extraLifetime)
{
return true;
}
/**
* Return an associative array of capabilities (booleans) of the backend
*
* The array must include these keys :
* - automatic_cleaning (is automating cleaning necessary)
* - tags (are tags supported)
* - expired_read (is it possible to read expired cache records
* (for doNotTestCacheValidity option for example))
* - priority does the backend deal with priority when saving
* - infinite_lifetime (is infinite lifetime can work with this backend)
* - get_list (is it possible to get the list of cache ids and the complete list of tags)
*
* @return array associative of with capabilities
*/
public function getCapabilities()
{
return array(
'automatic_cleaning' => true,
'tags' => true,
'expired_read' => false,
'priority' => true,
'infinite_lifetime' => true,
'get_list' => true
);
}
/**
* Add an event to the log array
*
* @param string $methodName MethodName
* @param array $args Arguments
* @return void
*/
private function _addLog($methodName, $args)
{
$this->_log[$this->_index] = array(
'methodName' => $methodName,
'args' => $args
);
$this->_index = $this->_index + 1;
}
}

View File

@ -0,0 +1,536 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: TwoLevels.php 24254 2011-07-22 12:04:41Z mabe $
*/
/**
* @see Zend_Cache_Backend_ExtendedInterface
*/
// require_once 'Zend/Cache/Backend/ExtendedInterface.php';
/**
* @see Zend_Cache_Backend
*/
// require_once 'Zend/Cache/Backend.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Backend_TwoLevels extends Zend_Cache_Backend implements Zend_Cache_Backend_ExtendedInterface
{
/**
* Available options
*
* =====> (string) slow_backend :
* - Slow backend name
* - Must implement the Zend_Cache_Backend_ExtendedInterface
* - Should provide a big storage
*
* =====> (string) fast_backend :
* - Flow backend name
* - Must implement the Zend_Cache_Backend_ExtendedInterface
* - Must be much faster than slow_backend
*
* =====> (array) slow_backend_options :
* - Slow backend options (see corresponding backend)
*
* =====> (array) fast_backend_options :
* - Fast backend options (see corresponding backend)
*
* =====> (int) stats_update_factor :
* - Disable / Tune the computation of the fast backend filling percentage
* - When saving a record into cache :
* 1 => systematic computation of the fast backend filling percentage
* x (integer) > 1 => computation of the fast backend filling percentage randomly 1 times on x cache write
*
* =====> (boolean) slow_backend_custom_naming :
* =====> (boolean) fast_backend_custom_naming :
* =====> (boolean) slow_backend_autoload :
* =====> (boolean) fast_backend_autoload :
* - See Zend_Cache::factory() method
*
* =====> (boolean) auto_refresh_fast_cache
* - If true, auto refresh the fast cache when a cache record is hit
*
* @var array available options
*/
protected $_options = array(
'slow_backend' => 'File',
'fast_backend' => 'Apc',
'slow_backend_options' => array(),
'fast_backend_options' => array(),
'stats_update_factor' => 10,
'slow_backend_custom_naming' => false,
'fast_backend_custom_naming' => false,
'slow_backend_autoload' => false,
'fast_backend_autoload' => false,
'auto_refresh_fast_cache' => true
);
/**
* Slow Backend
*
* @var Zend_Cache_Backend_ExtendedInterface
*/
protected $_slowBackend;
/**
* Fast Backend
*
* @var Zend_Cache_Backend_ExtendedInterface
*/
protected $_fastBackend;
/**
* Cache for the fast backend filling percentage
*
* @var int
*/
protected $_fastBackendFillingPercentage = null;
/**
* Constructor
*
* @param array $options Associative array of options
* @throws Zend_Cache_Exception
* @return void
*/
public function __construct(array $options = array())
{
parent::__construct($options);
if ($this->_options['slow_backend'] === null) {
Zend_Cache::throwException('slow_backend option has to set');
} elseif ($this->_options['slow_backend'] instanceof Zend_Cache_Backend_ExtendedInterface) {
$this->_slowBackend = $this->_options['slow_backend'];
} else {
$this->_slowBackend = Zend_Cache::_makeBackend(
$this->_options['slow_backend'],
$this->_options['slow_backend_options'],
$this->_options['slow_backend_custom_naming'],
$this->_options['slow_backend_autoload']
);
if (!in_array('Zend_Cache_Backend_ExtendedInterface', class_implements($this->_slowBackend))) {
Zend_Cache::throwException('slow_backend must implement the Zend_Cache_Backend_ExtendedInterface interface');
}
}
if ($this->_options['fast_backend'] === null) {
Zend_Cache::throwException('fast_backend option has to set');
} elseif ($this->_options['fast_backend'] instanceof Zend_Cache_Backend_ExtendedInterface) {
$this->_fastBackend = $this->_options['fast_backend'];
} else {
$this->_fastBackend = Zend_Cache::_makeBackend(
$this->_options['fast_backend'],
$this->_options['fast_backend_options'],
$this->_options['fast_backend_custom_naming'],
$this->_options['fast_backend_autoload']
);
if (!in_array('Zend_Cache_Backend_ExtendedInterface', class_implements($this->_fastBackend))) {
Zend_Cache::throwException('fast_backend must implement the Zend_Cache_Backend_ExtendedInterface interface');
}
}
$this->_slowBackend->setDirectives($this->_directives);
$this->_fastBackend->setDirectives($this->_directives);
}
/**
* Test if a cache is available or not (for the given id)
*
* @param string $id cache id
* @return mixed|false (a cache is not available) or "last modified" timestamp (int) of the available cache record
*/
public function test($id)
{
$fastTest = $this->_fastBackend->test($id);
if ($fastTest) {
return $fastTest;
} else {
return $this->_slowBackend->test($id);
}
}
/**
* Save some string datas into a cache record
*
* Note : $data is always "string" (serialization is done by the
* core not by the backend)
*
* @param string $data Datas to cache
* @param string $id Cache id
* @param array $tags Array of strings, the cache record will be tagged by each string entry
* @param int $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
* @param int $priority integer between 0 (very low priority) and 10 (maximum priority) used by some particular backends
* @return boolean true if no problem
*/
public function save($data, $id, $tags = array(), $specificLifetime = false, $priority = 8)
{
$usage = $this->_getFastFillingPercentage('saving');
$boolFast = true;
$lifetime = $this->getLifetime($specificLifetime);
$preparedData = $this->_prepareData($data, $lifetime, $priority);
if (($priority > 0) && (10 * $priority >= $usage)) {
$fastLifetime = $this->_getFastLifetime($lifetime, $priority);
$boolFast = $this->_fastBackend->save($preparedData, $id, array(), $fastLifetime);
$boolSlow = $this->_slowBackend->save($preparedData, $id, $tags, $lifetime);
} else {
$boolSlow = $this->_slowBackend->save($preparedData, $id, $tags, $lifetime);
if ($boolSlow === true) {
$boolFast = $this->_fastBackend->remove($id);
if (!$boolFast && !$this->_fastBackend->test($id)) {
// some backends return false on remove() even if the key never existed. (and it won't if fast is full)
// all we care about is that the key doesn't exist now
$boolFast = true;
}
}
}
return ($boolFast && $boolSlow);
}
/**
* Test if a cache is available for the given id and (if yes) return it (false else)
*
* Note : return value is always "string" (unserialization is done by the core not by the backend)
*
* @param string $id Cache id
* @param boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
* @return string|false cached datas
*/
public function load($id, $doNotTestCacheValidity = false)
{
$res = $this->_fastBackend->load($id, $doNotTestCacheValidity);
if ($res === false) {
$res = $this->_slowBackend->load($id, $doNotTestCacheValidity);
if ($res === false) {
// there is no cache at all for this id
return false;
}
}
$array = unserialize($res);
// maybe, we have to refresh the fast cache ?
if ($this->_options['auto_refresh_fast_cache']) {
if ($array['priority'] == 10) {
// no need to refresh the fast cache with priority = 10
return $array['data'];
}
$newFastLifetime = $this->_getFastLifetime($array['lifetime'], $array['priority'], time() - $array['expire']);
// we have the time to refresh the fast cache
$usage = $this->_getFastFillingPercentage('loading');
if (($array['priority'] > 0) && (10 * $array['priority'] >= $usage)) {
// we can refresh the fast cache
$preparedData = $this->_prepareData($array['data'], $array['lifetime'], $array['priority']);
$this->_fastBackend->save($preparedData, $id, array(), $newFastLifetime);
}
}
return $array['data'];
}
/**
* Remove a cache record
*
* @param string $id Cache id
* @return boolean True if no problem
*/
public function remove($id)
{
$boolFast = $this->_fastBackend->remove($id);
$boolSlow = $this->_slowBackend->remove($id);
return $boolFast && $boolSlow;
}
/**
* Clean some cache records
*
* Available modes are :
* Zend_Cache::CLEANING_MODE_ALL (default) => remove all cache entries ($tags is not used)
* Zend_Cache::CLEANING_MODE_OLD => remove too old cache entries ($tags is not used)
* Zend_Cache::CLEANING_MODE_MATCHING_TAG => remove cache entries matching all given tags
* ($tags can be an array of strings or a single string)
* Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG => remove cache entries not {matching one of the given tags}
* ($tags can be an array of strings or a single string)
* Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG => remove cache entries matching any given tags
* ($tags can be an array of strings or a single string)
*
* @param string $mode Clean mode
* @param array $tags Array of tags
* @throws Zend_Cache_Exception
* @return boolean true if no problem
*/
public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
{
switch($mode) {
case Zend_Cache::CLEANING_MODE_ALL:
$boolFast = $this->_fastBackend->clean(Zend_Cache::CLEANING_MODE_ALL);
$boolSlow = $this->_slowBackend->clean(Zend_Cache::CLEANING_MODE_ALL);
return $boolFast && $boolSlow;
break;
case Zend_Cache::CLEANING_MODE_OLD:
return $this->_slowBackend->clean(Zend_Cache::CLEANING_MODE_OLD);
case Zend_Cache::CLEANING_MODE_MATCHING_TAG:
$ids = $this->_slowBackend->getIdsMatchingTags($tags);
$res = true;
foreach ($ids as $id) {
$bool = $this->remove($id);
$res = $res && $bool;
}
return $res;
break;
case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG:
$ids = $this->_slowBackend->getIdsNotMatchingTags($tags);
$res = true;
foreach ($ids as $id) {
$bool = $this->remove($id);
$res = $res && $bool;
}
return $res;
break;
case Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG:
$ids = $this->_slowBackend->getIdsMatchingAnyTags($tags);
$res = true;
foreach ($ids as $id) {
$bool = $this->remove($id);
$res = $res && $bool;
}
return $res;
break;
default:
Zend_Cache::throwException('Invalid mode for clean() method');
break;
}
}
/**
* Return an array of stored cache ids
*
* @return array array of stored cache ids (string)
*/
public function getIds()
{
return $this->_slowBackend->getIds();
}
/**
* Return an array of stored tags
*
* @return array array of stored tags (string)
*/
public function getTags()
{
return $this->_slowBackend->getTags();
}
/**
* Return an array of stored cache ids which match given tags
*
* In case of multiple tags, a logical AND is made between tags
*
* @param array $tags array of tags
* @return array array of matching cache ids (string)
*/
public function getIdsMatchingTags($tags = array())
{
return $this->_slowBackend->getIdsMatchingTags($tags);
}
/**
* Return an array of stored cache ids which don't match given tags
*
* In case of multiple tags, a logical OR is made between tags
*
* @param array $tags array of tags
* @return array array of not matching cache ids (string)
*/
public function getIdsNotMatchingTags($tags = array())
{
return $this->_slowBackend->getIdsNotMatchingTags($tags);
}
/**
* Return an array of stored cache ids which match any given tags
*
* In case of multiple tags, a logical AND is made between tags
*
* @param array $tags array of tags
* @return array array of any matching cache ids (string)
*/
public function getIdsMatchingAnyTags($tags = array())
{
return $this->_slowBackend->getIdsMatchingAnyTags($tags);
}
/**
* Return the filling percentage of the backend storage
*
* @return int integer between 0 and 100
*/
public function getFillingPercentage()
{
return $this->_slowBackend->getFillingPercentage();
}
/**
* Return an array of metadatas for the given cache id
*
* The array must include these keys :
* - expire : the expire timestamp
* - tags : a string array of tags
* - mtime : timestamp of last modification time
*
* @param string $id cache id
* @return array array of metadatas (false if the cache id is not found)
*/
public function getMetadatas($id)
{
return $this->_slowBackend->getMetadatas($id);
}
/**
* Give (if possible) an extra lifetime to the given cache id
*
* @param string $id cache id
* @param int $extraLifetime
* @return boolean true if ok
*/
public function touch($id, $extraLifetime)
{
return $this->_slowBackend->touch($id, $extraLifetime);
}
/**
* Return an associative array of capabilities (booleans) of the backend
*
* The array must include these keys :
* - automatic_cleaning (is automating cleaning necessary)
* - tags (are tags supported)
* - expired_read (is it possible to read expired cache records
* (for doNotTestCacheValidity option for example))
* - priority does the backend deal with priority when saving
* - infinite_lifetime (is infinite lifetime can work with this backend)
* - get_list (is it possible to get the list of cache ids and the complete list of tags)
*
* @return array associative of with capabilities
*/
public function getCapabilities()
{
$slowBackendCapabilities = $this->_slowBackend->getCapabilities();
return array(
'automatic_cleaning' => $slowBackendCapabilities['automatic_cleaning'],
'tags' => $slowBackendCapabilities['tags'],
'expired_read' => $slowBackendCapabilities['expired_read'],
'priority' => $slowBackendCapabilities['priority'],
'infinite_lifetime' => $slowBackendCapabilities['infinite_lifetime'],
'get_list' => $slowBackendCapabilities['get_list']
);
}
/**
* Prepare a serialized array to store datas and metadatas informations
*
* @param string $data data to store
* @param int $lifetime original lifetime
* @param int $priority priority
* @return string serialize array to store into cache
*/
private function _prepareData($data, $lifetime, $priority)
{
$lt = $lifetime;
if ($lt === null) {
$lt = 9999999999;
}
return serialize(array(
'data' => $data,
'lifetime' => $lifetime,
'expire' => time() + $lt,
'priority' => $priority
));
}
/**
* Compute and return the lifetime for the fast backend
*
* @param int $lifetime original lifetime
* @param int $priority priority
* @param int $maxLifetime maximum lifetime
* @return int lifetime for the fast backend
*/
private function _getFastLifetime($lifetime, $priority, $maxLifetime = null)
{
if ($lifetime <= 0) {
// if no lifetime, we have an infinite lifetime
// we need to use arbitrary lifetimes
$fastLifetime = (int) (2592000 / (11 - $priority));
} else {
// prevent computed infinite lifetime (0) by ceil
$fastLifetime = (int) ceil($lifetime / (11 - $priority));
}
if ($maxLifetime >= 0 && $fastLifetime > $maxLifetime) {
return $maxLifetime;
}
return $fastLifetime;
}
/**
* PUBLIC METHOD FOR UNIT TESTING ONLY !
*
* Force a cache record to expire
*
* @param string $id cache id
*/
public function ___expire($id)
{
$this->_fastBackend->remove($id);
$this->_slowBackend->___expire($id);
}
private function _getFastFillingPercentage($mode)
{
if ($mode == 'saving') {
// mode saving
if ($this->_fastBackendFillingPercentage === null) {
$this->_fastBackendFillingPercentage = $this->_fastBackend->getFillingPercentage();
} else {
$rand = rand(1, $this->_options['stats_update_factor']);
if ($rand == 1) {
// we force a refresh
$this->_fastBackendFillingPercentage = $this->_fastBackend->getFillingPercentage();
}
}
} else {
// mode loading
// we compute the percentage only if it's not available in cache
if ($this->_fastBackendFillingPercentage === null) {
$this->_fastBackendFillingPercentage = $this->_fastBackend->getFillingPercentage();
}
}
return $this->_fastBackendFillingPercentage;
}
}

View File

@ -0,0 +1,349 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @see Zend_Cache_Backend_Interface
*/
// require_once 'Zend/Cache/Backend/ExtendedInterface.php';
/**
* @see Zend_Cache_Backend
*/
// require_once 'Zend/Cache/Backend.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Backend_WinCache extends Zend_Cache_Backend implements Zend_Cache_Backend_ExtendedInterface
{
/**
* Log message
*/
const TAGS_UNSUPPORTED_BY_CLEAN_OF_WINCACHE_BACKEND = 'Zend_Cache_Backend_WinCache::clean() : tags are unsupported by the WinCache backend';
const TAGS_UNSUPPORTED_BY_SAVE_OF_WINCACHE_BACKEND = 'Zend_Cache_Backend_WinCache::save() : tags are unsupported by the WinCache backend';
/**
* Constructor
*
* @param array $options associative array of options
* @throws Zend_Cache_Exception
* @return void
*/
public function __construct(array $options = array())
{
if (!extension_loaded('wincache')) {
Zend_Cache::throwException('The wincache extension must be loaded for using this backend !');
}
parent::__construct($options);
}
/**
* Test if a cache is available for the given id and (if yes) return it (false else)
*
* WARNING $doNotTestCacheValidity=true is unsupported by the WinCache backend
*
* @param string $id cache id
* @param boolean $doNotTestCacheValidity if set to true, the cache validity won't be tested
* @return string cached datas (or false)
*/
public function load($id, $doNotTestCacheValidity = false)
{
$tmp = wincache_ucache_get($id);
if (is_array($tmp)) {
return $tmp[0];
}
return false;
}
/**
* Test if a cache is available or not (for the given id)
*
* @param string $id cache id
* @return mixed false (a cache is not available) or "last modified" timestamp (int) of the available cache record
*/
public function test($id)
{
$tmp = wincache_ucache_get($id);
if (is_array($tmp)) {
return $tmp[1];
}
return false;
}
/**
* Save some string datas into a cache record
*
* Note : $data is always "string" (serialization is done by the
* core not by the backend)
*
* @param string $data datas to cache
* @param string $id cache id
* @param array $tags array of strings, the cache record will be tagged by each string entry
* @param int $specificLifetime if != false, set a specific lifetime for this cache record (null => infinite lifetime)
* @return boolean true if no problem
*/
public function save($data, $id, $tags = array(), $specificLifetime = false)
{
$lifetime = $this->getLifetime($specificLifetime);
$result = wincache_ucache_set($id, array($data, time(), $lifetime), $lifetime);
if (count($tags) > 0) {
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_WINCACHE_BACKEND);
}
return $result;
}
/**
* Remove a cache record
*
* @param string $id cache id
* @return boolean true if no problem
*/
public function remove($id)
{
return wincache_ucache_delete($id);
}
/**
* Clean some cache records
*
* Available modes are :
* 'all' (default) => remove all cache entries ($tags is not used)
* 'old' => unsupported
* 'matchingTag' => unsupported
* 'notMatchingTag' => unsupported
* 'matchingAnyTag' => unsupported
*
* @param string $mode clean mode
* @param array $tags array of tags
* @throws Zend_Cache_Exception
* @return boolean true if no problem
*/
public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
{
switch ($mode) {
case Zend_Cache::CLEANING_MODE_ALL:
return wincache_ucache_clear();
break;
case Zend_Cache::CLEANING_MODE_OLD:
$this->_log("Zend_Cache_Backend_WinCache::clean() : CLEANING_MODE_OLD is unsupported by the WinCache backend");
break;
case Zend_Cache::CLEANING_MODE_MATCHING_TAG:
case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG:
case Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG:
$this->_log(self::TAGS_UNSUPPORTED_BY_CLEAN_OF_WINCACHE_BACKEND);
break;
default:
Zend_Cache::throwException('Invalid mode for clean() method');
break;
}
}
/**
* Return true if the automatic cleaning is available for the backend
*
* DEPRECATED : use getCapabilities() instead
*
* @deprecated
* @return boolean
*/
public function isAutomaticCleaningAvailable()
{
return false;
}
/**
* Return the filling percentage of the backend storage
*
* @throws Zend_Cache_Exception
* @return int integer between 0 and 100
*/
public function getFillingPercentage()
{
$mem = wincache_ucache_meminfo();
$memSize = $mem['memory_total'];
$memUsed = $mem['memory_free'];
if ($memSize == 0) {
Zend_Cache::throwException('can\'t get WinCache memory size');
}
if ($memUsed > $memSize) {
return 100;
}
return ((int) (100. * ($memUsed / $memSize)));
}
/**
* Return an array of stored tags
*
* @return array array of stored tags (string)
*/
public function getTags()
{
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_WINCACHE_BACKEND);
return array();
}
/**
* Return an array of stored cache ids which match given tags
*
* In case of multiple tags, a logical AND is made between tags
*
* @param array $tags array of tags
* @return array array of matching cache ids (string)
*/
public function getIdsMatchingTags($tags = array())
{
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_WINCACHE_BACKEND);
return array();
}
/**
* Return an array of stored cache ids which don't match given tags
*
* In case of multiple tags, a logical OR is made between tags
*
* @param array $tags array of tags
* @return array array of not matching cache ids (string)
*/
public function getIdsNotMatchingTags($tags = array())
{
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_WINCACHE_BACKEND);
return array();
}
/**
* Return an array of stored cache ids which match any given tags
*
* In case of multiple tags, a logical AND is made between tags
*
* @param array $tags array of tags
* @return array array of any matching cache ids (string)
*/
public function getIdsMatchingAnyTags($tags = array())
{
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_WINCACHE_BACKEND);
return array();
}
/**
* Return an array of stored cache ids
*
* @return array array of stored cache ids (string)
*/
public function getIds()
{
$res = array();
$array = wincache_ucache_info();
$records = $array['ucache_entries'];
foreach ($records as $record) {
$res[] = $record['key_name'];
}
return $res;
}
/**
* Return an array of metadatas for the given cache id
*
* The array must include these keys :
* - expire : the expire timestamp
* - tags : a string array of tags
* - mtime : timestamp of last modification time
*
* @param string $id cache id
* @return array array of metadatas (false if the cache id is not found)
*/
public function getMetadatas($id)
{
$tmp = wincache_ucache_get($id);
if (is_array($tmp)) {
$data = $tmp[0];
$mtime = $tmp[1];
if (!isset($tmp[2])) {
return false;
}
$lifetime = $tmp[2];
return array(
'expire' => $mtime + $lifetime,
'tags' => array(),
'mtime' => $mtime
);
}
return false;
}
/**
* Give (if possible) an extra lifetime to the given cache id
*
* @param string $id cache id
* @param int $extraLifetime
* @return boolean true if ok
*/
public function touch($id, $extraLifetime)
{
$tmp = wincache_ucache_get($id);
if (is_array($tmp)) {
$data = $tmp[0];
$mtime = $tmp[1];
if (!isset($tmp[2])) {
return false;
}
$lifetime = $tmp[2];
$newLifetime = $lifetime - (time() - $mtime) + $extraLifetime;
if ($newLifetime <=0) {
return false;
}
return wincache_ucache_set($id, array($data, time(), $newLifetime), $newLifetime);
}
return false;
}
/**
* Return an associative array of capabilities (booleans) of the backend
*
* The array must include these keys :
* - automatic_cleaning (is automating cleaning necessary)
* - tags (are tags supported)
* - expired_read (is it possible to read expired cache records
* (for doNotTestCacheValidity option for example))
* - priority does the backend deal with priority when saving
* - infinite_lifetime (is infinite lifetime can work with this backend)
* - get_list (is it possible to get the list of cache ids and the complete list of tags)
*
* @return array associative of with capabilities
*/
public function getCapabilities()
{
return array(
'automatic_cleaning' => false,
'tags' => false,
'expired_read' => false,
'priority' => false,
'infinite_lifetime' => false,
'get_list' => true
);
}
}

View File

@ -0,0 +1,221 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Xcache.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Cache_Backend_Interface
*/
// require_once 'Zend/Cache/Backend/Interface.php';
/**
* @see Zend_Cache_Backend
*/
// require_once 'Zend/Cache/Backend.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Backend_Xcache extends Zend_Cache_Backend implements Zend_Cache_Backend_Interface
{
/**
* Log message
*/
const TAGS_UNSUPPORTED_BY_CLEAN_OF_XCACHE_BACKEND = 'Zend_Cache_Backend_Xcache::clean() : tags are unsupported by the Xcache backend';
const TAGS_UNSUPPORTED_BY_SAVE_OF_XCACHE_BACKEND = 'Zend_Cache_Backend_Xcache::save() : tags are unsupported by the Xcache backend';
/**
* Available options
*
* =====> (string) user :
* xcache.admin.user (necessary for the clean() method)
*
* =====> (string) password :
* xcache.admin.pass (clear, not MD5) (necessary for the clean() method)
*
* @var array available options
*/
protected $_options = array(
'user' => null,
'password' => null
);
/**
* Constructor
*
* @param array $options associative array of options
* @throws Zend_Cache_Exception
* @return void
*/
public function __construct(array $options = array())
{
if (!extension_loaded('xcache')) {
Zend_Cache::throwException('The xcache extension must be loaded for using this backend !');
}
parent::__construct($options);
}
/**
* Test if a cache is available for the given id and (if yes) return it (false else)
*
* WARNING $doNotTestCacheValidity=true is unsupported by the Xcache backend
*
* @param string $id cache id
* @param boolean $doNotTestCacheValidity if set to true, the cache validity won't be tested
* @return string cached datas (or false)
*/
public function load($id, $doNotTestCacheValidity = false)
{
if ($doNotTestCacheValidity) {
$this->_log("Zend_Cache_Backend_Xcache::load() : \$doNotTestCacheValidity=true is unsupported by the Xcache backend");
}
$tmp = xcache_get($id);
if (is_array($tmp)) {
return $tmp[0];
}
return false;
}
/**
* Test if a cache is available or not (for the given id)
*
* @param string $id cache id
* @return mixed false (a cache is not available) or "last modified" timestamp (int) of the available cache record
*/
public function test($id)
{
if (xcache_isset($id)) {
$tmp = xcache_get($id);
if (is_array($tmp)) {
return $tmp[1];
}
}
return false;
}
/**
* Save some string datas into a cache record
*
* Note : $data is always "string" (serialization is done by the
* core not by the backend)
*
* @param string $data datas to cache
* @param string $id cache id
* @param array $tags array of strings, the cache record will be tagged by each string entry
* @param int $specificLifetime if != false, set a specific lifetime for this cache record (null => infinite lifetime)
* @return boolean true if no problem
*/
public function save($data, $id, $tags = array(), $specificLifetime = false)
{
$lifetime = $this->getLifetime($specificLifetime);
$result = xcache_set($id, array($data, time()), $lifetime);
if (count($tags) > 0) {
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_XCACHE_BACKEND);
}
return $result;
}
/**
* Remove a cache record
*
* @param string $id cache id
* @return boolean true if no problem
*/
public function remove($id)
{
return xcache_unset($id);
}
/**
* Clean some cache records
*
* Available modes are :
* 'all' (default) => remove all cache entries ($tags is not used)
* 'old' => unsupported
* 'matchingTag' => unsupported
* 'notMatchingTag' => unsupported
* 'matchingAnyTag' => unsupported
*
* @param string $mode clean mode
* @param array $tags array of tags
* @throws Zend_Cache_Exception
* @return boolean true if no problem
*/
public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
{
switch ($mode) {
case Zend_Cache::CLEANING_MODE_ALL:
// Necessary because xcache_clear_cache() need basic authentification
$backup = array();
if (isset($_SERVER['PHP_AUTH_USER'])) {
$backup['PHP_AUTH_USER'] = $_SERVER['PHP_AUTH_USER'];
}
if (isset($_SERVER['PHP_AUTH_PW'])) {
$backup['PHP_AUTH_PW'] = $_SERVER['PHP_AUTH_PW'];
}
if ($this->_options['user']) {
$_SERVER['PHP_AUTH_USER'] = $this->_options['user'];
}
if ($this->_options['password']) {
$_SERVER['PHP_AUTH_PW'] = $this->_options['password'];
}
$cnt = xcache_count(XC_TYPE_VAR);
for ($i=0; $i < $cnt; $i++) {
xcache_clear_cache(XC_TYPE_VAR, $i);
}
if (isset($backup['PHP_AUTH_USER'])) {
$_SERVER['PHP_AUTH_USER'] = $backup['PHP_AUTH_USER'];
$_SERVER['PHP_AUTH_PW'] = $backup['PHP_AUTH_PW'];
}
return true;
break;
case Zend_Cache::CLEANING_MODE_OLD:
$this->_log("Zend_Cache_Backend_Xcache::clean() : CLEANING_MODE_OLD is unsupported by the Xcache backend");
break;
case Zend_Cache::CLEANING_MODE_MATCHING_TAG:
case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG:
case Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG:
$this->_log(self::TAGS_UNSUPPORTED_BY_CLEAN_OF_XCACHE_BACKEND);
break;
default:
Zend_Cache::throwException('Invalid mode for clean() method');
break;
}
}
/**
* Return true if the automatic cleaning is available for the backend
*
* @return boolean
*/
public function isAutomaticCleaningAvailable()
{
return false;
}
}

View File

@ -0,0 +1,317 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: ZendPlatform.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Cache_Backend_Interface
*/
// require_once 'Zend/Cache/Backend.php';
/**
* @see Zend_Cache_Backend_Interface
*/
// require_once 'Zend/Cache/Backend/Interface.php';
/**
* Impementation of Zend Cache Backend using the Zend Platform (Output Content Caching)
*
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Backend_ZendPlatform extends Zend_Cache_Backend implements Zend_Cache_Backend_Interface
{
/**
* internal ZP prefix
*/
const TAGS_PREFIX = "internal_ZPtag:";
/**
* Constructor
* Validate that the Zend Platform is loaded and licensed
*
* @param array $options Associative array of options
* @throws Zend_Cache_Exception
* @return void
*/
public function __construct(array $options = array())
{
if (!function_exists('accelerator_license_info')) {
Zend_Cache::throwException('The Zend Platform extension must be loaded for using this backend !');
}
if (!function_exists('accelerator_get_configuration')) {
$licenseInfo = accelerator_license_info();
Zend_Cache::throwException('The Zend Platform extension is not loaded correctly: '.$licenseInfo['failure_reason']);
}
$accConf = accelerator_get_configuration();
if (@!$accConf['output_cache_licensed']) {
Zend_Cache::throwException('The Zend Platform extension does not have the proper license to use content caching features');
}
if (@!$accConf['output_cache_enabled']) {
Zend_Cache::throwException('The Zend Platform content caching feature must be enabled for using this backend, set the \'zend_accelerator.output_cache_enabled\' directive to On !');
}
if (!is_writable($accConf['output_cache_dir'])) {
Zend_Cache::throwException('The cache copies directory \''. ini_get('zend_accelerator.output_cache_dir') .'\' must be writable !');
}
parent:: __construct($options);
}
/**
* Test if a cache is available for the given id and (if yes) return it (false else)
*
* @param string $id Cache id
* @param boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
* @return string Cached data (or false)
*/
public function load($id, $doNotTestCacheValidity = false)
{
// doNotTestCacheValidity implemented by giving zero lifetime to the cache
if ($doNotTestCacheValidity) {
$lifetime = 0;
} else {
$lifetime = $this->_directives['lifetime'];
}
$res = output_cache_get($id, $lifetime);
if($res) {
return $res[0];
} else {
return false;
}
}
/**
* Test if a cache is available or not (for the given id)
*
* @param string $id Cache id
* @return mixed|false false (a cache is not available) or "last modified" timestamp (int) of the available cache record
*/
public function test($id)
{
$result = output_cache_get($id, $this->_directives['lifetime']);
if ($result) {
return $result[1];
}
return false;
}
/**
* Save some string datas into a cache record
*
* Note : $data is always "string" (serialization is done by the
* core not by the backend)
*
* @param string $data Data to cache
* @param string $id Cache id
* @param array $tags Array of strings, the cache record will be tagged by each string entry
* @param int $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
* @return boolean true if no problem
*/
public function save($data, $id, $tags = array(), $specificLifetime = false)
{
if (!($specificLifetime === false)) {
$this->_log("Zend_Cache_Backend_ZendPlatform::save() : non false specifc lifetime is unsuported for this backend");
}
$lifetime = $this->_directives['lifetime'];
$result1 = output_cache_put($id, array($data, time()));
$result2 = (count($tags) == 0);
foreach ($tags as $tag) {
$tagid = self::TAGS_PREFIX.$tag;
$old_tags = output_cache_get($tagid, $lifetime);
if ($old_tags === false) {
$old_tags = array();
}
$old_tags[$id] = $id;
output_cache_remove_key($tagid);
$result2 = output_cache_put($tagid, $old_tags);
}
return $result1 && $result2;
}
/**
* Remove a cache record
*
* @param string $id Cache id
* @return boolean True if no problem
*/
public function remove($id)
{
return output_cache_remove_key($id);
}
/**
* Clean some cache records
*
* Available modes are :
* Zend_Cache::CLEANING_MODE_ALL (default) => remove all cache entries ($tags is not used)
* Zend_Cache::CLEANING_MODE_OLD => remove too old cache entries ($tags is not used)
* This mode is not supported in this backend
* Zend_Cache::CLEANING_MODE_MATCHING_TAG => remove cache entries matching all given tags
* ($tags can be an array of strings or a single string)
* Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG => unsupported
* Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG => remove cache entries matching any given tags
* ($tags can be an array of strings or a single string)
*
* @param string $mode Clean mode
* @param array $tags Array of tags
* @throws Zend_Cache_Exception
* @return boolean True if no problem
*/
public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
{
switch ($mode) {
case Zend_Cache::CLEANING_MODE_ALL:
case Zend_Cache::CLEANING_MODE_OLD:
$cache_dir = ini_get('zend_accelerator.output_cache_dir');
if (!$cache_dir) {
return false;
}
$cache_dir .= '/.php_cache_api/';
return $this->_clean($cache_dir, $mode);
break;
case Zend_Cache::CLEANING_MODE_MATCHING_TAG:
$idlist = null;
foreach ($tags as $tag) {
$next_idlist = output_cache_get(self::TAGS_PREFIX.$tag, $this->_directives['lifetime']);
if ($idlist) {
$idlist = array_intersect_assoc($idlist, $next_idlist);
} else {
$idlist = $next_idlist;
}
if (count($idlist) == 0) {
// if ID list is already empty - we may skip checking other IDs
$idlist = null;
break;
}
}
if ($idlist) {
foreach ($idlist as $id) {
output_cache_remove_key($id);
}
}
return true;
break;
case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG:
$this->_log("Zend_Cache_Backend_ZendPlatform::clean() : CLEANING_MODE_NOT_MATCHING_TAG is not supported by the Zend Platform backend");
return false;
break;
case Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG:
$idlist = null;
foreach ($tags as $tag) {
$next_idlist = output_cache_get(self::TAGS_PREFIX.$tag, $this->_directives['lifetime']);
if ($idlist) {
$idlist = array_merge_recursive($idlist, $next_idlist);
} else {
$idlist = $next_idlist;
}
if (count($idlist) == 0) {
// if ID list is already empty - we may skip checking other IDs
$idlist = null;
break;
}
}
if ($idlist) {
foreach ($idlist as $id) {
output_cache_remove_key($id);
}
}
return true;
break;
default:
Zend_Cache::throwException('Invalid mode for clean() method');
break;
}
}
/**
* Clean a directory and recursivly go over it's subdirectories
*
* Remove all the cached files that need to be cleaned (according to mode and files mtime)
*
* @param string $dir Path of directory ot clean
* @param string $mode The same parameter as in Zend_Cache_Backend_ZendPlatform::clean()
* @return boolean True if ok
*/
private function _clean($dir, $mode)
{
$d = @dir($dir);
if (!$d) {
return false;
}
$result = true;
while (false !== ($file = $d->read())) {
if ($file == '.' || $file == '..') {
continue;
}
$file = $d->path . $file;
if (is_dir($file)) {
$result = ($this->_clean($file .'/', $mode)) && ($result);
} else {
if ($mode == Zend_Cache::CLEANING_MODE_ALL) {
$result = ($this->_remove($file)) && ($result);
} else if ($mode == Zend_Cache::CLEANING_MODE_OLD) {
// Files older than lifetime get deleted from cache
if ($this->_directives['lifetime'] !== null) {
if ((time() - @filemtime($file)) > $this->_directives['lifetime']) {
$result = ($this->_remove($file)) && ($result);
}
}
}
}
}
$d->close();
return $result;
}
/**
* Remove a file
*
* If we can't remove the file (because of locks or any problem), we will touch
* the file to invalidate it
*
* @param string $file Complete file path
* @return boolean True if ok
*/
private function _remove($file)
{
if (!@unlink($file)) {
# If we can't remove the file (because of locks or any problem), we will touch
# the file to invalidate it
$this->_log("Zend_Cache_Backend_ZendPlatform::_remove() : we can't remove $file => we are going to try to invalidate it");
if ($this->_directives['lifetime'] === null) {
return false;
}
if (!file_exists($file)) {
return false;
}
return @touch($file, time() - 2*abs($this->_directives['lifetime']));
}
return true;
}
}

View File

@ -0,0 +1,207 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: ZendServer.php 23775 2011-03-01 17:25:24Z ralph $
*/
/** @see Zend_Cache_Backend_Interface */
// require_once 'Zend/Cache/Backend/Interface.php';
/** @see Zend_Cache_Backend */
// require_once 'Zend/Cache/Backend.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
abstract class Zend_Cache_Backend_ZendServer extends Zend_Cache_Backend implements Zend_Cache_Backend_Interface
{
/**
* Available options
*
* =====> (string) namespace :
* Namespace to be used for chaching operations
*
* @var array available options
*/
protected $_options = array(
'namespace' => 'zendframework'
);
/**
* Store data
*
* @param mixed $data Object to store
* @param string $id Cache id
* @param int $timeToLive Time to live in seconds
* @throws Zend_Cache_Exception
*/
abstract protected function _store($data, $id, $timeToLive);
/**
* Fetch data
*
* @param string $id Cache id
* @throws Zend_Cache_Exception
*/
abstract protected function _fetch($id);
/**
* Unset data
*
* @param string $id Cache id
*/
abstract protected function _unset($id);
/**
* Clear cache
*/
abstract protected function _clear();
/**
* Test if a cache is available for the given id and (if yes) return it (false else)
*
* @param string $id cache id
* @param boolean $doNotTestCacheValidity if set to true, the cache validity won't be tested
* @return string cached datas (or false)
*/
public function load($id, $doNotTestCacheValidity = false)
{
$tmp = $this->_fetch($id);
if ($tmp !== null) {
return $tmp;
}
return false;
}
/**
* Test if a cache is available or not (for the given id)
*
* @param string $id cache id
* @return mixed false (a cache is not available) or "last modified" timestamp (int) of the available cache record
* @throws Zend_Cache_Exception
*/
public function test($id)
{
$tmp = $this->_fetch('internal-metadatas---' . $id);
if ($tmp !== false) {
if (!is_array($tmp) || !isset($tmp['mtime'])) {
Zend_Cache::throwException('Cache metadata for \'' . $id . '\' id is corrupted' );
}
return $tmp['mtime'];
}
return false;
}
/**
* Compute & return the expire time
*
* @return int expire time (unix timestamp)
*/
private function _expireTime($lifetime)
{
if ($lifetime === null) {
return 9999999999;
}
return time() + $lifetime;
}
/**
* Save some string datas into a cache record
*
* Note : $data is always "string" (serialization is done by the
* core not by the backend)
*
* @param string $data datas to cache
* @param string $id cache id
* @param array $tags array of strings, the cache record will be tagged by each string entry
* @param int $specificLifetime if != false, set a specific lifetime for this cache record (null => infinite lifetime)
* @return boolean true if no problem
*/
public function save($data, $id, $tags = array(), $specificLifetime = false)
{
$lifetime = $this->getLifetime($specificLifetime);
$metadatas = array(
'mtime' => time(),
'expire' => $this->_expireTime($lifetime),
);
if (count($tags) > 0) {
$this->_log('Zend_Cache_Backend_ZendServer::save() : tags are unsupported by the ZendServer backends');
}
return $this->_store($data, $id, $lifetime) &&
$this->_store($metadatas, 'internal-metadatas---' . $id, $lifetime);
}
/**
* Remove a cache record
*
* @param string $id cache id
* @return boolean true if no problem
*/
public function remove($id)
{
$result1 = $this->_unset($id);
$result2 = $this->_unset('internal-metadatas---' . $id);
return $result1 && $result2;
}
/**
* Clean some cache records
*
* Available modes are :
* 'all' (default) => remove all cache entries ($tags is not used)
* 'old' => unsupported
* 'matchingTag' => unsupported
* 'notMatchingTag' => unsupported
* 'matchingAnyTag' => unsupported
*
* @param string $mode clean mode
* @param array $tags array of tags
* @throws Zend_Cache_Exception
* @return boolean true if no problem
*/
public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
{
switch ($mode) {
case Zend_Cache::CLEANING_MODE_ALL:
$this->_clear();
return true;
break;
case Zend_Cache::CLEANING_MODE_OLD:
$this->_log("Zend_Cache_Backend_ZendServer::clean() : CLEANING_MODE_OLD is unsupported by the Zend Server backends.");
break;
case Zend_Cache::CLEANING_MODE_MATCHING_TAG:
case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG:
case Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG:
$this->_clear();
$this->_log('Zend_Cache_Backend_ZendServer::clean() : tags are unsupported by the Zend Server backends.');
break;
default:
Zend_Cache::throwException('Invalid mode for clean() method');
break;
}
}
}

View File

@ -0,0 +1,100 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Disk.php 23775 2011-03-01 17:25:24Z ralph $
*/
/** @see Zend_Cache_Backend_Interface */
// require_once 'Zend/Cache/Backend/Interface.php';
/** @see Zend_Cache_Backend_ZendServer */
// require_once 'Zend/Cache/Backend/ZendServer.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Backend_ZendServer_Disk extends Zend_Cache_Backend_ZendServer implements Zend_Cache_Backend_Interface
{
/**
* Constructor
*
* @param array $options associative array of options
* @throws Zend_Cache_Exception
*/
public function __construct(array $options = array())
{
if (!function_exists('zend_disk_cache_store')) {
Zend_Cache::throwException('Zend_Cache_ZendServer_Disk backend has to be used within Zend Server environment.');
}
parent::__construct($options);
}
/**
* Store data
*
* @param mixed $data Object to store
* @param string $id Cache id
* @param int $timeToLive Time to live in seconds
* @return boolean true if no problem
*/
protected function _store($data, $id, $timeToLive)
{
if (zend_disk_cache_store($this->_options['namespace'] . '::' . $id,
$data,
$timeToLive) === false) {
$this->_log('Store operation failed.');
return false;
}
return true;
}
/**
* Fetch data
*
* @param string $id Cache id
*/
protected function _fetch($id)
{
return zend_disk_cache_fetch($this->_options['namespace'] . '::' . $id);
}
/**
* Unset data
*
* @param string $id Cache id
* @return boolean true if no problem
*/
protected function _unset($id)
{
return zend_disk_cache_delete($this->_options['namespace'] . '::' . $id);
}
/**
* Clear cache
*/
protected function _clear()
{
zend_disk_cache_clear($this->_options['namespace']);
}
}

View File

@ -0,0 +1,100 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: ShMem.php 23775 2011-03-01 17:25:24Z ralph $
*/
/** @see Zend_Cache_Backend_Interface */
// require_once 'Zend/Cache/Backend/Interface.php';
/** @see Zend_Cache_Backend_ZendServer */
// require_once 'Zend/Cache/Backend/ZendServer.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Backend_ZendServer_ShMem extends Zend_Cache_Backend_ZendServer implements Zend_Cache_Backend_Interface
{
/**
* Constructor
*
* @param array $options associative array of options
* @throws Zend_Cache_Exception
*/
public function __construct(array $options = array())
{
if (!function_exists('zend_shm_cache_store')) {
Zend_Cache::throwException('Zend_Cache_ZendServer_ShMem backend has to be used within Zend Server environment.');
}
parent::__construct($options);
}
/**
* Store data
*
* @param mixed $data Object to store
* @param string $id Cache id
* @param int $timeToLive Time to live in seconds
*
*/
protected function _store($data, $id, $timeToLive)
{
if (zend_shm_cache_store($this->_options['namespace'] . '::' . $id,
$data,
$timeToLive) === false) {
$this->_log('Store operation failed.');
return false;
}
return true;
}
/**
* Fetch data
*
* @param string $id Cache id
*/
protected function _fetch($id)
{
return zend_shm_cache_fetch($this->_options['namespace'] . '::' . $id);
}
/**
* Unset data
*
* @param string $id Cache id
* @return boolean true if no problem
*/
protected function _unset($id)
{
return zend_shm_cache_delete($this->_options['namespace'] . '::' . $id);
}
/**
* Clear cache
*/
protected function _clear()
{
zend_shm_cache_clear($this->_options['namespace']);
}
}

View File

@ -0,0 +1,764 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Core.php 23800 2011-03-10 20:52:08Z mabe $
*/
/**
* @package Zend_Cache
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Core
{
/**
* Messages
*/
const BACKEND_NOT_SUPPORTS_TAG = 'tags are not supported by the current backend';
const BACKEND_NOT_IMPLEMENTS_EXTENDED_IF = 'Current backend doesn\'t implement the Zend_Cache_Backend_ExtendedInterface, so this method is not available';
/**
* Backend Object
*
* @var Zend_Cache_Backend_Interface $_backend
*/
protected $_backend = null;
/**
* Available options
*
* ====> (boolean) write_control :
* - Enable / disable write control (the cache is read just after writing to detect corrupt entries)
* - Enable write control will lightly slow the cache writing but not the cache reading
* Write control can detect some corrupt cache files but maybe it's not a perfect control
*
* ====> (boolean) caching :
* - Enable / disable caching
* (can be very useful for the debug of cached scripts)
*
* =====> (string) cache_id_prefix :
* - prefix for cache ids (namespace)
*
* ====> (boolean) automatic_serialization :
* - Enable / disable automatic serialization
* - It can be used to save directly datas which aren't strings (but it's slower)
*
* ====> (int) automatic_cleaning_factor :
* - Disable / Tune the automatic cleaning process
* - The automatic cleaning process destroy too old (for the given life time)
* cache files when a new cache file is written :
* 0 => no automatic cache cleaning
* 1 => systematic cache cleaning
* x (integer) > 1 => automatic cleaning randomly 1 times on x cache write
*
* ====> (int) lifetime :
* - Cache lifetime (in seconds)
* - If null, the cache is valid forever.
*
* ====> (boolean) logging :
* - If set to true, logging is activated (but the system is slower)
*
* ====> (boolean) ignore_user_abort
* - If set to true, the core will set the ignore_user_abort PHP flag inside the
* save() method to avoid cache corruptions in some cases (default false)
*
* @var array $_options available options
*/
protected $_options = array(
'write_control' => true,
'caching' => true,
'cache_id_prefix' => null,
'automatic_serialization' => false,
'automatic_cleaning_factor' => 10,
'lifetime' => 3600,
'logging' => false,
'logger' => null,
'ignore_user_abort' => false
);
/**
* Array of options which have to be transfered to backend
*
* @var array $_directivesList
*/
protected static $_directivesList = array('lifetime', 'logging', 'logger');
/**
* Not used for the core, just a sort a hint to get a common setOption() method (for the core and for frontends)
*
* @var array $_specificOptions
*/
protected $_specificOptions = array();
/**
* Last used cache id
*
* @var string $_lastId
*/
private $_lastId = null;
/**
* True if the backend implements Zend_Cache_Backend_ExtendedInterface
*
* @var boolean $_extendedBackend
*/
protected $_extendedBackend = false;
/**
* Array of capabilities of the backend (only if it implements Zend_Cache_Backend_ExtendedInterface)
*
* @var array
*/
protected $_backendCapabilities = array();
/**
* Constructor
*
* @param array|Zend_Config $options Associative array of options or Zend_Config instance
* @throws Zend_Cache_Exception
* @return void
*/
public function __construct($options = array())
{
if ($options instanceof Zend_Config) {
$options = $options->toArray();
}
if (!is_array($options)) {
Zend_Cache::throwException("Options passed were not an array"
. " or Zend_Config instance.");
}
while (list($name, $value) = each($options)) {
$this->setOption($name, $value);
}
$this->_loggerSanity();
}
/**
* Set options using an instance of type Zend_Config
*
* @param Zend_Config $config
* @return Zend_Cache_Core
*/
public function setConfig(Zend_Config $config)
{
$options = $config->toArray();
while (list($name, $value) = each($options)) {
$this->setOption($name, $value);
}
return $this;
}
/**
* Set the backend
*
* @param Zend_Cache_Backend $backendObject
* @throws Zend_Cache_Exception
* @return void
*/
public function setBackend(Zend_Cache_Backend $backendObject)
{
$this->_backend= $backendObject;
// some options (listed in $_directivesList) have to be given
// to the backend too (even if they are not "backend specific")
$directives = array();
foreach (Zend_Cache_Core::$_directivesList as $directive) {
$directives[$directive] = $this->_options[$directive];
}
$this->_backend->setDirectives($directives);
if (in_array('Zend_Cache_Backend_ExtendedInterface', class_implements($this->_backend))) {
$this->_extendedBackend = true;
$this->_backendCapabilities = $this->_backend->getCapabilities();
}
}
/**
* Returns the backend
*
* @return Zend_Cache_Backend backend object
*/
public function getBackend()
{
return $this->_backend;
}
/**
* Public frontend to set an option
*
* There is an additional validation (relatively to the protected _setOption method)
*
* @param string $name Name of the option
* @param mixed $value Value of the option
* @throws Zend_Cache_Exception
* @return void
*/
public function setOption($name, $value)
{
if (!is_string($name)) {
Zend_Cache::throwException("Incorrect option name : $name");
}
$name = strtolower($name);
if (array_key_exists($name, $this->_options)) {
// This is a Core option
$this->_setOption($name, $value);
return;
}
if (array_key_exists($name, $this->_specificOptions)) {
// This a specic option of this frontend
$this->_specificOptions[$name] = $value;
return;
}
}
/**
* Public frontend to get an option value
*
* @param string $name Name of the option
* @throws Zend_Cache_Exception
* @return mixed option value
*/
public function getOption($name)
{
if (is_string($name)) {
$name = strtolower($name);
if (array_key_exists($name, $this->_options)) {
// This is a Core option
return $this->_options[$name];
}
if (array_key_exists($name, $this->_specificOptions)) {
// This a specic option of this frontend
return $this->_specificOptions[$name];
}
}
Zend_Cache::throwException("Incorrect option name : $name");
}
/**
* Set an option
*
* @param string $name Name of the option
* @param mixed $value Value of the option
* @throws Zend_Cache_Exception
* @return void
*/
private function _setOption($name, $value)
{
if (!is_string($name) || !array_key_exists($name, $this->_options)) {
Zend_Cache::throwException("Incorrect option name : $name");
}
if ($name == 'lifetime' && empty($value)) {
$value = null;
}
$this->_options[$name] = $value;
}
/**
* Force a new lifetime
*
* The new value is set for the core/frontend but for the backend too (directive)
*
* @param int $newLifetime New lifetime (in seconds)
* @return void
*/
public function setLifetime($newLifetime)
{
$this->_options['lifetime'] = $newLifetime;
$this->_backend->setDirectives(array(
'lifetime' => $newLifetime
));
}
/**
* Test if a cache is available for the given id and (if yes) return it (false else)
*
* @param string $id Cache id
* @param boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
* @param boolean $doNotUnserialize Do not serialize (even if automatic_serialization is true) => for internal use
* @return mixed|false Cached datas
*/
public function load($id, $doNotTestCacheValidity = false, $doNotUnserialize = false)
{
if (!$this->_options['caching']) {
return false;
}
$id = $this->_id($id); // cache id may need prefix
$this->_lastId = $id;
self::_validateIdOrTag($id);
$this->_log("Zend_Cache_Core: load item '{$id}'", 7);
$data = $this->_backend->load($id, $doNotTestCacheValidity);
if ($data===false) {
// no cache available
return false;
}
if ((!$doNotUnserialize) && $this->_options['automatic_serialization']) {
// we need to unserialize before sending the result
return unserialize($data);
}
return $data;
}
/**
* Test if a cache is available for the given id
*
* @param string $id Cache id
* @return int|false Last modified time of cache entry if it is available, false otherwise
*/
public function test($id)
{
if (!$this->_options['caching']) {
return false;
}
$id = $this->_id($id); // cache id may need prefix
self::_validateIdOrTag($id);
$this->_lastId = $id;
$this->_log("Zend_Cache_Core: test item '{$id}'", 7);
return $this->_backend->test($id);
}
/**
* Save some data in a cache
*
* @param mixed $data Data to put in cache (can be another type than string if automatic_serialization is on)
* @param string $id Cache id (if not set, the last cache id will be used)
* @param array $tags Cache tags
* @param int $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
* @param int $priority integer between 0 (very low priority) and 10 (maximum priority) used by some particular backends
* @throws Zend_Cache_Exception
* @return boolean True if no problem
*/
public function save($data, $id = null, $tags = array(), $specificLifetime = false, $priority = 8)
{
if (!$this->_options['caching']) {
return true;
}
if ($id === null) {
$id = $this->_lastId;
} else {
$id = $this->_id($id);
}
self::_validateIdOrTag($id);
self::_validateTagsArray($tags);
if ($this->_options['automatic_serialization']) {
// we need to serialize datas before storing them
$data = serialize($data);
} else {
if (!is_string($data)) {
Zend_Cache::throwException("Datas must be string or set automatic_serialization = true");
}
}
// automatic cleaning
if ($this->_options['automatic_cleaning_factor'] > 0) {
$rand = rand(1, $this->_options['automatic_cleaning_factor']);
if ($rand==1) {
// new way || deprecated way
if ($this->_extendedBackend || method_exists($this->_backend, 'isAutomaticCleaningAvailable')) {
$this->_log("Zend_Cache_Core::save(): automatic cleaning running", 7);
$this->clean(Zend_Cache::CLEANING_MODE_OLD);
} else {
$this->_log("Zend_Cache_Core::save(): automatic cleaning is not available/necessary with current backend", 4);
}
}
}
$this->_log("Zend_Cache_Core: save item '{$id}'", 7);
if ($this->_options['ignore_user_abort']) {
$abort = ignore_user_abort(true);
}
if (($this->_extendedBackend) && ($this->_backendCapabilities['priority'])) {
$result = $this->_backend->save($data, $id, $tags, $specificLifetime, $priority);
} else {
$result = $this->_backend->save($data, $id, $tags, $specificLifetime);
}
if ($this->_options['ignore_user_abort']) {
ignore_user_abort($abort);
}
if (!$result) {
// maybe the cache is corrupted, so we remove it !
$this->_log("Zend_Cache_Core::save(): failed to save item '{$id}' -> removing it", 4);
$this->_backend->remove($id);
return false;
}
if ($this->_options['write_control']) {
$data2 = $this->_backend->load($id, true);
if ($data!=$data2) {
$this->_log("Zend_Cache_Core::save(): write control of item '{$id}' failed -> removing it", 4);
$this->_backend->remove($id);
return false;
}
}
return true;
}
/**
* Remove a cache
*
* @param string $id Cache id to remove
* @return boolean True if ok
*/
public function remove($id)
{
if (!$this->_options['caching']) {
return true;
}
$id = $this->_id($id); // cache id may need prefix
self::_validateIdOrTag($id);
$this->_log("Zend_Cache_Core: remove item '{$id}'", 7);
return $this->_backend->remove($id);
}
/**
* Clean cache entries
*
* Available modes are :
* 'all' (default) => remove all cache entries ($tags is not used)
* 'old' => remove too old cache entries ($tags is not used)
* 'matchingTag' => remove cache entries matching all given tags
* ($tags can be an array of strings or a single string)
* 'notMatchingTag' => remove cache entries not matching one of the given tags
* ($tags can be an array of strings or a single string)
* 'matchingAnyTag' => remove cache entries matching any given tags
* ($tags can be an array of strings or a single string)
*
* @param string $mode
* @param array|string $tags
* @throws Zend_Cache_Exception
* @return boolean True if ok
*/
public function clean($mode = 'all', $tags = array())
{
if (!$this->_options['caching']) {
return true;
}
if (!in_array($mode, array(Zend_Cache::CLEANING_MODE_ALL,
Zend_Cache::CLEANING_MODE_OLD,
Zend_Cache::CLEANING_MODE_MATCHING_TAG,
Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG,
Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG))) {
Zend_Cache::throwException('Invalid cleaning mode');
}
self::_validateTagsArray($tags);
return $this->_backend->clean($mode, $tags);
}
/**
* Return an array of stored cache ids which match given tags
*
* In case of multiple tags, a logical AND is made between tags
*
* @param array $tags array of tags
* @return array array of matching cache ids (string)
*/
public function getIdsMatchingTags($tags = array())
{
if (!$this->_extendedBackend) {
Zend_Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF);
}
if (!($this->_backendCapabilities['tags'])) {
Zend_Cache::throwException(self::BACKEND_NOT_SUPPORTS_TAG);
}
$ids = $this->_backend->getIdsMatchingTags($tags);
// we need to remove cache_id_prefix from ids (see #ZF-6178, #ZF-7600)
if (isset($this->_options['cache_id_prefix']) && $this->_options['cache_id_prefix'] !== '') {
$prefix = & $this->_options['cache_id_prefix'];
$prefixLen = strlen($prefix);
foreach ($ids as &$id) {
if (strpos($id, $prefix) === 0) {
$id = substr($id, $prefixLen);
}
}
}
return $ids;
}
/**
* Return an array of stored cache ids which don't match given tags
*
* In case of multiple tags, a logical OR is made between tags
*
* @param array $tags array of tags
* @return array array of not matching cache ids (string)
*/
public function getIdsNotMatchingTags($tags = array())
{
if (!$this->_extendedBackend) {
Zend_Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF);
}
if (!($this->_backendCapabilities['tags'])) {
Zend_Cache::throwException(self::BACKEND_NOT_SUPPORTS_TAG);
}
$ids = $this->_backend->getIdsNotMatchingTags($tags);
// we need to remove cache_id_prefix from ids (see #ZF-6178, #ZF-7600)
if (isset($this->_options['cache_id_prefix']) && $this->_options['cache_id_prefix'] !== '') {
$prefix = & $this->_options['cache_id_prefix'];
$prefixLen = strlen($prefix);
foreach ($ids as &$id) {
if (strpos($id, $prefix) === 0) {
$id = substr($id, $prefixLen);
}
}
}
return $ids;
}
/**
* Return an array of stored cache ids which match any given tags
*
* In case of multiple tags, a logical OR is made between tags
*
* @param array $tags array of tags
* @return array array of matching any cache ids (string)
*/
public function getIdsMatchingAnyTags($tags = array())
{
if (!$this->_extendedBackend) {
Zend_Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF);
}
if (!($this->_backendCapabilities['tags'])) {
Zend_Cache::throwException(self::BACKEND_NOT_SUPPORTS_TAG);
}
$ids = $this->_backend->getIdsMatchingAnyTags($tags);
// we need to remove cache_id_prefix from ids (see #ZF-6178, #ZF-7600)
if (isset($this->_options['cache_id_prefix']) && $this->_options['cache_id_prefix'] !== '') {
$prefix = & $this->_options['cache_id_prefix'];
$prefixLen = strlen($prefix);
foreach ($ids as &$id) {
if (strpos($id, $prefix) === 0) {
$id = substr($id, $prefixLen);
}
}
}
return $ids;
}
/**
* Return an array of stored cache ids
*
* @return array array of stored cache ids (string)
*/
public function getIds()
{
if (!$this->_extendedBackend) {
Zend_Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF);
}
$ids = $this->_backend->getIds();
// we need to remove cache_id_prefix from ids (see #ZF-6178, #ZF-7600)
if (isset($this->_options['cache_id_prefix']) && $this->_options['cache_id_prefix'] !== '') {
$prefix = & $this->_options['cache_id_prefix'];
$prefixLen = strlen($prefix);
foreach ($ids as &$id) {
if (strpos($id, $prefix) === 0) {
$id = substr($id, $prefixLen);
}
}
}
return $ids;
}
/**
* Return an array of stored tags
*
* @return array array of stored tags (string)
*/
public function getTags()
{
if (!$this->_extendedBackend) {
Zend_Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF);
}
if (!($this->_backendCapabilities['tags'])) {
Zend_Cache::throwException(self::BACKEND_NOT_SUPPORTS_TAG);
}
return $this->_backend->getTags();
}
/**
* Return the filling percentage of the backend storage
*
* @return int integer between 0 and 100
*/
public function getFillingPercentage()
{
if (!$this->_extendedBackend) {
Zend_Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF);
}
return $this->_backend->getFillingPercentage();
}
/**
* Return an array of metadatas for the given cache id
*
* The array will include these keys :
* - expire : the expire timestamp
* - tags : a string array of tags
* - mtime : timestamp of last modification time
*
* @param string $id cache id
* @return array array of metadatas (false if the cache id is not found)
*/
public function getMetadatas($id)
{
if (!$this->_extendedBackend) {
Zend_Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF);
}
$id = $this->_id($id); // cache id may need prefix
return $this->_backend->getMetadatas($id);
}
/**
* Give (if possible) an extra lifetime to the given cache id
*
* @param string $id cache id
* @param int $extraLifetime
* @return boolean true if ok
*/
public function touch($id, $extraLifetime)
{
if (!$this->_extendedBackend) {
Zend_Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF);
}
$id = $this->_id($id); // cache id may need prefix
$this->_log("Zend_Cache_Core: touch item '{$id}'", 7);
return $this->_backend->touch($id, $extraLifetime);
}
/**
* Validate a cache id or a tag (security, reliable filenames, reserved prefixes...)
*
* Throw an exception if a problem is found
*
* @param string $string Cache id or tag
* @throws Zend_Cache_Exception
* @return void
*/
protected static function _validateIdOrTag($string)
{
if (!is_string($string)) {
Zend_Cache::throwException('Invalid id or tag : must be a string');
}
if (substr($string, 0, 9) == 'internal-') {
Zend_Cache::throwException('"internal-*" ids or tags are reserved');
}
if (!preg_match('~^[a-zA-Z0-9_]+$~D', $string)) {
Zend_Cache::throwException("Invalid id or tag '$string' : must use only [a-zA-Z0-9_]");
}
}
/**
* Validate a tags array (security, reliable filenames, reserved prefixes...)
*
* Throw an exception if a problem is found
*
* @param array $tags Array of tags
* @throws Zend_Cache_Exception
* @return void
*/
protected static function _validateTagsArray($tags)
{
if (!is_array($tags)) {
Zend_Cache::throwException('Invalid tags array : must be an array');
}
foreach($tags as $tag) {
self::_validateIdOrTag($tag);
}
reset($tags);
}
/**
* Make sure if we enable logging that the Zend_Log class
* is available.
* Create a default log object if none is set.
*
* @throws Zend_Cache_Exception
* @return void
*/
protected function _loggerSanity()
{
if (!isset($this->_options['logging']) || !$this->_options['logging']) {
return;
}
if (isset($this->_options['logger']) && $this->_options['logger'] instanceof Zend_Log) {
return;
}
// Create a default logger to the standard output stream
// require_once 'Zend/Log.php';
// require_once 'Zend/Log/Writer/Stream.php';
// require_once 'Zend/Log/Filter/Priority.php';
$logger = new Zend_Log(new Zend_Log_Writer_Stream('php://output'));
$logger->addFilter(new Zend_Log_Filter_Priority(Zend_Log::WARN, '<='));
$this->_options['logger'] = $logger;
}
/**
* Log a message at the WARN (4) priority.
*
* @param string $message
* @throws Zend_Cache_Exception
* @return void
*/
protected function _log($message, $priority = 4)
{
if (!$this->_options['logging']) {
return;
}
if (!(isset($this->_options['logger']) || $this->_options['logger'] instanceof Zend_Log)) {
Zend_Cache::throwException('Logging is enabled but logger is not set');
}
$logger = $this->_options['logger'];
$logger->log($message, $priority);
}
/**
* Make and return a cache id
*
* Checks 'cache_id_prefix' and returns new id with prefix or simply the id if null
*
* @param string $id Cache id
* @return string Cache id (with or without prefix)
*/
protected function _id($id)
{
if (($id !== null) && isset($this->_options['cache_id_prefix'])) {
return $this->_options['cache_id_prefix'] . $id; // return with prefix
}
return $id; // no prefix, just return the $id passed
}
}

View File

@ -0,0 +1,32 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Exception.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Exception
*/
// require_once 'Zend/Exception.php';
/**
* @package Zend_Cache
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Exception extends Zend_Exception {}

View File

@ -0,0 +1,88 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Frontend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Capture.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Cache_Core
*/
// require_once 'Zend/Cache/Core.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Frontend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Frontend_Capture extends Zend_Cache_Core
{
/**
* Page identifiers
* @var array
*/
protected $_idStack = array();
/**
* Tags
* @var array
*/
protected $_tags = array();
protected $_extension = null;
/**
* Start the cache
*
* @param string $id Cache id
* @return mixed True if the cache is hit (false else) with $echoData=true (default) ; string else (datas)
*/
public function start($id, array $tags, $extension = null)
{
$this->_tags = $tags;
$this->_extension = $extension;
ob_start(array($this, '_flush'));
ob_implicit_flush(false);
$this->_idStack[] = $id;
return false;
}
/**
* callback for output buffering
* (shouldn't really be called manually)
*
* @param string $data Buffered output
* @return string Data to send to browser
*/
public function _flush($data)
{
$id = array_pop($this->_idStack);
if ($id === null) {
Zend_Cache::throwException('use of _flush() without a start()');
}
if ($this->_extension) {
$this->save(serialize(array($data, $this->_extension)), $id, $this->_tags);
} else {
$this->save($data, $id, $this->_tags);
}
return $data;
}
}

View File

@ -0,0 +1,265 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Frontend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Class.php 24032 2011-05-10 21:08:20Z mabe $
*/
/**
* @see Zend_Cache_Core
*/
// require_once 'Zend/Cache/Core.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Frontend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Frontend_Class extends Zend_Cache_Core
{
/**
* Available options
*
* ====> (mixed) cached_entity :
* - if set to a class name, we will cache an abstract class and will use only static calls
* - if set to an object, we will cache this object methods
*
* ====> (boolean) cache_by_default :
* - if true, method calls will be cached by default
*
* ====> (array) cached_methods :
* - an array of method names which will be cached (even if cache_by_default = false)
*
* ====> (array) non_cached_methods :
* - an array of method names which won't be cached (even if cache_by_default = true)
*
* @var array available options
*/
protected $_specificOptions = array(
'cached_entity' => null,
'cache_by_default' => true,
'cached_methods' => array(),
'non_cached_methods' => array()
);
/**
* Tags array
*
* @var array
*/
private $_tags = array();
/**
* SpecificLifetime value
*
* false => no specific life time
*
* @var int
*/
private $_specificLifetime = false;
/**
* The cached object or the name of the cached abstract class
*
* @var mixed
*/
private $_cachedEntity = null;
/**
* The class name of the cached object or cached abstract class
*
* Used to differentiate between different classes with the same method calls.
*
* @var string
*/
private $_cachedEntityLabel = '';
/**
* Priority (used by some particular backends)
*
* @var int
*/
private $_priority = 8;
/**
* Constructor
*
* @param array $options Associative array of options
* @throws Zend_Cache_Exception
* @return void
*/
public function __construct(array $options = array())
{
while (list($name, $value) = each($options)) {
$this->setOption($name, $value);
}
if ($this->_specificOptions['cached_entity'] === null) {
Zend_Cache::throwException('cached_entity must be set !');
}
$this->setCachedEntity($this->_specificOptions['cached_entity']);
$this->setOption('automatic_serialization', true);
}
/**
* Set a specific life time
*
* @param int $specificLifetime
* @return void
*/
public function setSpecificLifetime($specificLifetime = false)
{
$this->_specificLifetime = $specificLifetime;
}
/**
* Set the priority (used by some particular backends)
*
* @param int $priority integer between 0 (very low priority) and 10 (maximum priority)
*/
public function setPriority($priority)
{
$this->_priority = $priority;
}
/**
* Public frontend to set an option
*
* Just a wrapper to get a specific behaviour for cached_entity
*
* @param string $name Name of the option
* @param mixed $value Value of the option
* @throws Zend_Cache_Exception
* @return void
*/
public function setOption($name, $value)
{
if ($name == 'cached_entity') {
$this->setCachedEntity($value);
} else {
parent::setOption($name, $value);
}
}
/**
* Specific method to set the cachedEntity
*
* if set to a class name, we will cache an abstract class and will use only static calls
* if set to an object, we will cache this object methods
*
* @param mixed $cachedEntity
*/
public function setCachedEntity($cachedEntity)
{
if (!is_string($cachedEntity) && !is_object($cachedEntity)) {
Zend_Cache::throwException('cached_entity must be an object or a class name');
}
$this->_cachedEntity = $cachedEntity;
$this->_specificOptions['cached_entity'] = $cachedEntity;
if (is_string($this->_cachedEntity)){
$this->_cachedEntityLabel = $this->_cachedEntity;
} else {
$ro = new ReflectionObject($this->_cachedEntity);
$this->_cachedEntityLabel = $ro->getName();
}
}
/**
* Set the cache array
*
* @param array $tags
* @return void
*/
public function setTagsArray($tags = array())
{
$this->_tags = $tags;
}
/**
* Main method : call the specified method or get the result from cache
*
* @param string $name Method name
* @param array $parameters Method parameters
* @return mixed Result
*/
public function __call($name, $parameters)
{
$callback = array($this->_cachedEntity, $name);
if (!is_callable($callback, false)) {
Zend_Cache::throwException('Invalid callback');
}
$cacheBool1 = $this->_specificOptions['cache_by_default'];
$cacheBool2 = in_array($name, $this->_specificOptions['cached_methods']);
$cacheBool3 = in_array($name, $this->_specificOptions['non_cached_methods']);
$cache = (($cacheBool1 || $cacheBool2) && (!$cacheBool3));
if (!$cache) {
// We do not have not cache
return call_user_func_array($callback, $parameters);
}
$id = $this->_makeId($name, $parameters);
if ( ($rs = $this->load($id)) && isset($rs[0], $rs[1]) ) {
// A cache is available
$output = $rs[0];
$return = $rs[1];
} else {
// A cache is not available (or not valid for this frontend)
ob_start();
ob_implicit_flush(false);
try {
$return = call_user_func_array($callback, $parameters);
$output = ob_get_clean();
$data = array($output, $return);
$this->save($data, $id, $this->_tags, $this->_specificLifetime, $this->_priority);
} catch (Exception $e) {
ob_end_clean();
throw $e;
}
}
echo $output;
return $return;
}
/**
* ZF-9970
*
* @deprecated
*/
private function _makeId($name, $args)
{
return $this->makeId($name, $args);
}
/**
* Make a cache id from the method name and parameters
*
* @param string $name Method name
* @param array $args Method parameters
* @return string Cache id
*/
public function makeId($name, array $args = array())
{
return md5($this->_cachedEntityLabel . '__' . $name . '__' . serialize($args));
}
}

View File

@ -0,0 +1,222 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Frontend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: File.php 24218 2011-07-10 01:22:58Z ramon $
*/
/**
* @see Zend_Cache_Core
*/
// require_once 'Zend/Cache/Core.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Frontend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Frontend_File extends Zend_Cache_Core
{
/**
* Consts for master_files_mode
*/
const MODE_AND = 'AND';
const MODE_OR = 'OR';
/**
* Available options
*
* ====> (string) master_file :
* - a complete path of the master file
* - deprecated (see master_files)
*
* ====> (array) master_files :
* - an array of complete path of master files
* - this option has to be set !
*
* ====> (string) master_files_mode :
* - Zend_Cache_Frontend_File::MODE_AND or Zend_Cache_Frontend_File::MODE_OR
* - if MODE_AND, then all master files have to be touched to get a cache invalidation
* - if MODE_OR (default), then a single touched master file is enough to get a cache invalidation
*
* ====> (boolean) ignore_missing_master_files
* - if set to true, missing master files are ignored silently
* - if set to false (default), an exception is thrown if there is a missing master file
* @var array available options
*/
protected $_specificOptions = array(
'master_file' => null,
'master_files' => null,
'master_files_mode' => 'OR',
'ignore_missing_master_files' => false
);
/**
* Master file mtimes
*
* Array of int
*
* @var array
*/
private $_masterFile_mtimes = null;
/**
* Constructor
*
* @param array $options Associative array of options
* @throws Zend_Cache_Exception
* @return void
*/
public function __construct(array $options = array())
{
while (list($name, $value) = each($options)) {
$this->setOption($name, $value);
}
if (!isset($this->_specificOptions['master_files'])) {
Zend_Cache::throwException('master_files option must be set');
}
}
/**
* Change the master_files option
*
* @param array $masterFiles the complete paths and name of the master files
*/
public function setMasterFiles(array $masterFiles)
{
$this->_specificOptions['master_file'] = null; // to keep a compatibility
$this->_specificOptions['master_files'] = null;
$this->_masterFile_mtimes = array();
clearstatcache();
$i = 0;
foreach ($masterFiles as $masterFile) {
if (file_exists($masterFile)) {
$mtime = filemtime($masterFile);
} else {
$mtime = false;
}
if (!$this->_specificOptions['ignore_missing_master_files'] && !$mtime) {
Zend_Cache::throwException('Unable to read master_file : ' . $masterFile);
}
$this->_masterFile_mtimes[$i] = $mtime;
$this->_specificOptions['master_files'][$i] = $masterFile;
if ($i === 0) { // to keep a compatibility
$this->_specificOptions['master_file'] = $masterFile;
}
$i++;
}
}
/**
* Change the master_file option
*
* To keep the compatibility
*
* @deprecated
* @param string $masterFile the complete path and name of the master file
*/
public function setMasterFile($masterFile)
{
$this->setMasterFiles(array($masterFile));
}
/**
* Public frontend to set an option
*
* Just a wrapper to get a specific behaviour for master_file
*
* @param string $name Name of the option
* @param mixed $value Value of the option
* @throws Zend_Cache_Exception
* @return void
*/
public function setOption($name, $value)
{
if ($name == 'master_file') {
$this->setMasterFile($value);
} else if ($name == 'master_files') {
$this->setMasterFiles($value);
} else {
parent::setOption($name, $value);
}
}
/**
* Test if a cache is available for the given id and (if yes) return it (false else)
*
* @param string $id Cache id
* @param boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
* @param boolean $doNotUnserialize Do not serialize (even if automatic_serialization is true) => for internal use
* @return mixed|false Cached datas
*/
public function load($id, $doNotTestCacheValidity = false, $doNotUnserialize = false)
{
if (!$doNotTestCacheValidity) {
if ($this->test($id)) {
return parent::load($id, true, $doNotUnserialize);
}
return false;
}
return parent::load($id, true, $doNotUnserialize);
}
/**
* Test if a cache is available for the given id
*
* @param string $id Cache id
* @return int|false Last modified time of cache entry if it is available, false otherwise
*/
public function test($id)
{
$lastModified = parent::test($id);
if ($lastModified) {
if ($this->_specificOptions['master_files_mode'] == self::MODE_AND) {
// MODE_AND
foreach($this->_masterFile_mtimes as $masterFileMTime) {
if ($masterFileMTime) {
if ($lastModified > $masterFileMTime) {
return $lastModified;
}
}
}
} else {
// MODE_OR
$res = true;
foreach($this->_masterFile_mtimes as $masterFileMTime) {
if ($masterFileMTime) {
if ($lastModified <= $masterFileMTime) {
return false;
}
}
}
return $lastModified;
}
}
return false;
}
}

View File

@ -0,0 +1,179 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Frontend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Function.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Cache_Core
*/
// require_once 'Zend/Cache/Core.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Frontend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Frontend_Function extends Zend_Cache_Core
{
/**
* This frontend specific options
*
* ====> (boolean) cache_by_default :
* - if true, function calls will be cached by default
*
* ====> (array) cached_functions :
* - an array of function names which will be cached (even if cache_by_default = false)
*
* ====> (array) non_cached_functions :
* - an array of function names which won't be cached (even if cache_by_default = true)
*
* @var array options
*/
protected $_specificOptions = array(
'cache_by_default' => true,
'cached_functions' => array(),
'non_cached_functions' => array()
);
/**
* Constructor
*
* @param array $options Associative array of options
* @return void
*/
public function __construct(array $options = array())
{
while (list($name, $value) = each($options)) {
$this->setOption($name, $value);
}
$this->setOption('automatic_serialization', true);
}
/**
* Main method : call the specified function or get the result from cache
*
* @param callback $callback A valid callback
* @param array $parameters Function parameters
* @param array $tags Cache tags
* @param int $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
* @param int $priority integer between 0 (very low priority) and 10 (maximum priority) used by some particular backends
* @return mixed Result
*/
public function call($callback, array $parameters = array(), $tags = array(), $specificLifetime = false, $priority = 8)
{
if (!is_callable($callback, true, $name)) {
Zend_Cache::throwException('Invalid callback');
}
$cacheBool1 = $this->_specificOptions['cache_by_default'];
$cacheBool2 = in_array($name, $this->_specificOptions['cached_functions']);
$cacheBool3 = in_array($name, $this->_specificOptions['non_cached_functions']);
$cache = (($cacheBool1 || $cacheBool2) && (!$cacheBool3));
if (!$cache) {
// Caching of this callback is disabled
return call_user_func_array($callback, $parameters);
}
$id = $this->_makeId($callback, $parameters);
if ( ($rs = $this->load($id)) && isset($rs[0], $rs[1])) {
// A cache is available
$output = $rs[0];
$return = $rs[1];
} else {
// A cache is not available (or not valid for this frontend)
ob_start();
ob_implicit_flush(false);
$return = call_user_func_array($callback, $parameters);
$output = ob_get_clean();
$data = array($output, $return);
$this->save($data, $id, $tags, $specificLifetime, $priority);
}
echo $output;
return $return;
}
/**
* ZF-9970
*
* @deprecated
*/
private function _makeId($callback, array $args)
{
return $this->makeId($callback, $args);
}
/**
* Make a cache id from the function name and parameters
*
* @param callback $callback A valid callback
* @param array $args Function parameters
* @throws Zend_Cache_Exception
* @return string Cache id
*/
public function makeId($callback, array $args = array())
{
if (!is_callable($callback, true, $name)) {
Zend_Cache::throwException('Invalid callback');
}
// functions, methods and classnames are case-insensitive
$name = strtolower($name);
// generate a unique id for object callbacks
if (is_object($callback)) { // Closures & __invoke
$object = $callback;
} elseif (isset($callback[0])) { // array($object, 'method')
$object = $callback[0];
}
if (isset($object)) {
try {
$tmp = @serialize($callback);
} catch (Exception $e) {
Zend_Cache::throwException($e->getMessage());
}
if (!$tmp) {
$lastErr = error_get_last();
Zend_Cache::throwException("Can't serialize callback object to generate id: {$lastErr['message']}");
}
$name.= '__' . $tmp;
}
// generate a unique id for arguments
$argsStr = '';
if ($args) {
try {
$argsStr = @serialize(array_values($args));
} catch (Exception $e) {
Zend_Cache::throwException($e->getMessage());
}
if (!$argsStr) {
$lastErr = error_get_last();
throw Zend_Cache::throwException("Can't serialize arguments to generate id: {$lastErr['message']}");
}
}
return md5($name . $argsStr);
}
}

View File

@ -0,0 +1,105 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Frontend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Output.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Cache_Core
*/
// require_once 'Zend/Cache/Core.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Frontend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Frontend_Output extends Zend_Cache_Core
{
private $_idStack = array();
/**
* Constructor
*
* @param array $options Associative array of options
* @return void
*/
public function __construct(array $options = array())
{
parent::__construct($options);
$this->_idStack = array();
}
/**
* Start the cache
*
* @param string $id Cache id
* @param boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
* @param boolean $echoData If set to true, datas are sent to the browser if the cache is hit (simpy returned else)
* @return mixed True if the cache is hit (false else) with $echoData=true (default) ; string else (datas)
*/
public function start($id, $doNotTestCacheValidity = false, $echoData = true)
{
$data = $this->load($id, $doNotTestCacheValidity);
if ($data !== false) {
if ( $echoData ) {
echo($data);
return true;
} else {
return $data;
}
}
ob_start();
ob_implicit_flush(false);
$this->_idStack[] = $id;
return false;
}
/**
* Stop the cache
*
* @param array $tags Tags array
* @param int $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
* @param string $forcedDatas If not null, force written datas with this
* @param boolean $echoData If set to true, datas are sent to the browser
* @param int $priority integer between 0 (very low priority) and 10 (maximum priority) used by some particular backends
* @return void
*/
public function end($tags = array(), $specificLifetime = false, $forcedDatas = null, $echoData = true, $priority = 8)
{
if ($forcedDatas === null) {
$data = ob_get_clean();
} else {
$data =& $forcedDatas;
}
$id = array_pop($this->_idStack);
if ($id === null) {
Zend_Cache::throwException('use of end() without a start()');
}
$this->save($data, $id, $tags, $specificLifetime, $priority);
if ($echoData) {
echo($data);
}
}
}

View File

@ -0,0 +1,404 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Frontend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Page.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Cache_Core
*/
// require_once 'Zend/Cache/Core.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Frontend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Frontend_Page extends Zend_Cache_Core
{
/**
* This frontend specific options
*
* ====> (boolean) http_conditional :
* - if true, http conditional mode is on
* WARNING : http_conditional OPTION IS NOT IMPLEMENTED FOR THE MOMENT (TODO)
*
* ====> (boolean) debug_header :
* - if true, a debug text is added before each cached pages
*
* ====> (boolean) content_type_memorization :
* - deprecated => use memorize_headers instead
* - if the Content-Type header is sent after the cache was started, the
* corresponding value can be memorized and replayed when the cache is hit
* (if false (default), the frontend doesn't take care of Content-Type header)
*
* ====> (array) memorize_headers :
* - an array of strings corresponding to some HTTP headers name. Listed headers
* will be stored with cache datas and "replayed" when the cache is hit
*
* ====> (array) default_options :
* - an associative array of default options :
* - (boolean) cache : cache is on by default if true
* - (boolean) cacheWithXXXVariables (XXXX = 'Get', 'Post', 'Session', 'Files' or 'Cookie') :
* if true, cache is still on even if there are some variables in this superglobal array
* if false, cache is off if there are some variables in this superglobal array
* - (boolean) makeIdWithXXXVariables (XXXX = 'Get', 'Post', 'Session', 'Files' or 'Cookie') :
* if true, we have to use the content of this superglobal array to make a cache id
* if false, the cache id won't be dependent of the content of this superglobal array
* - (int) specific_lifetime : cache specific lifetime
* (false => global lifetime is used, null => infinite lifetime,
* integer => this lifetime is used), this "lifetime" is probably only
* usefull when used with "regexps" array
* - (array) tags : array of tags (strings)
* - (int) priority : integer between 0 (very low priority) and 10 (maximum priority) used by
* some particular backends
*
* ====> (array) regexps :
* - an associative array to set options only for some REQUEST_URI
* - keys are (pcre) regexps
* - values are associative array with specific options to set if the regexp matchs on $_SERVER['REQUEST_URI']
* (see default_options for the list of available options)
* - if several regexps match the $_SERVER['REQUEST_URI'], only the last one will be used
*
* @var array options
*/
protected $_specificOptions = array(
'http_conditional' => false,
'debug_header' => false,
'content_type_memorization' => false,
'memorize_headers' => array(),
'default_options' => array(
'cache_with_get_variables' => false,
'cache_with_post_variables' => false,
'cache_with_session_variables' => false,
'cache_with_files_variables' => false,
'cache_with_cookie_variables' => false,
'make_id_with_get_variables' => true,
'make_id_with_post_variables' => true,
'make_id_with_session_variables' => true,
'make_id_with_files_variables' => true,
'make_id_with_cookie_variables' => true,
'cache' => true,
'specific_lifetime' => false,
'tags' => array(),
'priority' => null
),
'regexps' => array()
);
/**
* Internal array to store some options
*
* @var array associative array of options
*/
protected $_activeOptions = array();
/**
* If true, the page won't be cached
*
* @var boolean
*/
protected $_cancel = false;
/**
* Constructor
*
* @param array $options Associative array of options
* @param boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
* @throws Zend_Cache_Exception
* @return void
*/
public function __construct(array $options = array())
{
while (list($name, $value) = each($options)) {
$name = strtolower($name);
switch ($name) {
case 'regexps':
$this->_setRegexps($value);
break;
case 'default_options':
$this->_setDefaultOptions($value);
break;
case 'content_type_memorization':
$this->_setContentTypeMemorization($value);
break;
default:
$this->setOption($name, $value);
}
}
if (isset($this->_specificOptions['http_conditional'])) {
if ($this->_specificOptions['http_conditional']) {
Zend_Cache::throwException('http_conditional is not implemented for the moment !');
}
}
$this->setOption('automatic_serialization', true);
}
/**
* Specific setter for the 'default_options' option (with some additional tests)
*
* @param array $options Associative array
* @throws Zend_Cache_Exception
* @return void
*/
protected function _setDefaultOptions($options)
{
if (!is_array($options)) {
Zend_Cache::throwException('default_options must be an array !');
}
foreach ($options as $key=>$value) {
if (!is_string($key)) {
Zend_Cache::throwException("invalid option [$key] !");
}
$key = strtolower($key);
if (isset($this->_specificOptions['default_options'][$key])) {
$this->_specificOptions['default_options'][$key] = $value;
}
}
}
/**
* Set the deprecated contentTypeMemorization option
*
* @param boolean $value value
* @return void
* @deprecated
*/
protected function _setContentTypeMemorization($value)
{
$found = null;
foreach ($this->_specificOptions['memorize_headers'] as $key => $value) {
if (strtolower($value) == 'content-type') {
$found = $key;
}
}
if ($value) {
if (!$found) {
$this->_specificOptions['memorize_headers'][] = 'Content-Type';
}
} else {
if ($found) {
unset($this->_specificOptions['memorize_headers'][$found]);
}
}
}
/**
* Specific setter for the 'regexps' option (with some additional tests)
*
* @param array $options Associative array
* @throws Zend_Cache_Exception
* @return void
*/
protected function _setRegexps($regexps)
{
if (!is_array($regexps)) {
Zend_Cache::throwException('regexps option must be an array !');
}
foreach ($regexps as $regexp=>$conf) {
if (!is_array($conf)) {
Zend_Cache::throwException('regexps option must be an array of arrays !');
}
$validKeys = array_keys($this->_specificOptions['default_options']);
foreach ($conf as $key=>$value) {
if (!is_string($key)) {
Zend_Cache::throwException("unknown option [$key] !");
}
$key = strtolower($key);
if (!in_array($key, $validKeys)) {
unset($regexps[$regexp][$key]);
}
}
}
$this->setOption('regexps', $regexps);
}
/**
* Start the cache
*
* @param string $id (optional) A cache id (if you set a value here, maybe you have to use Output frontend instead)
* @param boolean $doNotDie For unit testing only !
* @return boolean True if the cache is hit (false else)
*/
public function start($id = false, $doNotDie = false)
{
$this->_cancel = false;
$lastMatchingRegexp = null;
if (isset($_SERVER['REQUEST_URI'])) {
foreach ($this->_specificOptions['regexps'] as $regexp => $conf) {
if (preg_match("`$regexp`", $_SERVER['REQUEST_URI'])) {
$lastMatchingRegexp = $regexp;
}
}
}
$this->_activeOptions = $this->_specificOptions['default_options'];
if ($lastMatchingRegexp !== null) {
$conf = $this->_specificOptions['regexps'][$lastMatchingRegexp];
foreach ($conf as $key=>$value) {
$this->_activeOptions[$key] = $value;
}
}
if (!($this->_activeOptions['cache'])) {
return false;
}
if (!$id) {
$id = $this->_makeId();
if (!$id) {
return false;
}
}
$array = $this->load($id);
if ($array !== false) {
$data = $array['data'];
$headers = $array['headers'];
if (!headers_sent()) {
foreach ($headers as $key=>$headerCouple) {
$name = $headerCouple[0];
$value = $headerCouple[1];
header("$name: $value");
}
}
if ($this->_specificOptions['debug_header']) {
echo 'DEBUG HEADER : This is a cached page !';
}
echo $data;
if ($doNotDie) {
return true;
}
die();
}
ob_start(array($this, '_flush'));
ob_implicit_flush(false);
return false;
}
/**
* Cancel the current caching process
*/
public function cancel()
{
$this->_cancel = true;
}
/**
* callback for output buffering
* (shouldn't really be called manually)
*
* @param string $data Buffered output
* @return string Data to send to browser
*/
public function _flush($data)
{
if ($this->_cancel) {
return $data;
}
$contentType = null;
$storedHeaders = array();
$headersList = headers_list();
foreach($this->_specificOptions['memorize_headers'] as $key=>$headerName) {
foreach ($headersList as $headerSent) {
$tmp = explode(':', $headerSent);
$headerSentName = trim(array_shift($tmp));
if (strtolower($headerName) == strtolower($headerSentName)) {
$headerSentValue = trim(implode(':', $tmp));
$storedHeaders[] = array($headerSentName, $headerSentValue);
}
}
}
$array = array(
'data' => $data,
'headers' => $storedHeaders
);
$this->save($array, null, $this->_activeOptions['tags'], $this->_activeOptions['specific_lifetime'], $this->_activeOptions['priority']);
return $data;
}
/**
* Make an id depending on REQUEST_URI and superglobal arrays (depending on options)
*
* @return mixed|false a cache id (string), false if the cache should have not to be used
*/
protected function _makeId()
{
$tmp = $_SERVER['REQUEST_URI'];
$array = explode('?', $tmp, 2);
$tmp = $array[0];
foreach (array('Get', 'Post', 'Session', 'Files', 'Cookie') as $arrayName) {
$tmp2 = $this->_makePartialId($arrayName, $this->_activeOptions['cache_with_' . strtolower($arrayName) . '_variables'], $this->_activeOptions['make_id_with_' . strtolower($arrayName) . '_variables']);
if ($tmp2===false) {
return false;
}
$tmp = $tmp . $tmp2;
}
return md5($tmp);
}
/**
* Make a partial id depending on options
*
* @param string $arrayName Superglobal array name
* @param bool $bool1 If true, cache is still on even if there are some variables in the superglobal array
* @param bool $bool2 If true, we have to use the content of the superglobal array to make a partial id
* @return mixed|false Partial id (string) or false if the cache should have not to be used
*/
protected function _makePartialId($arrayName, $bool1, $bool2)
{
switch ($arrayName) {
case 'Get':
$var = $_GET;
break;
case 'Post':
$var = $_POST;
break;
case 'Session':
if (isset($_SESSION)) {
$var = $_SESSION;
} else {
$var = null;
}
break;
case 'Cookie':
if (isset($_COOKIE)) {
$var = $_COOKIE;
} else {
$var = null;
}
break;
case 'Files':
$var = $_FILES;
break;
default:
return false;
}
if ($bool1) {
if ($bool2) {
return serialize($var);
}
return '';
}
if (count($var) > 0) {
return false;
}
return '';
}
}

View File

@ -0,0 +1,298 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Manager.php 23775 2011-03-01 17:25:24Z ralph $
*/
/** @see Zend_Cache_Exception */
// require_once 'Zend/Cache/Exception.php';
/** @see Zend_Cache */
// require_once 'Zend/Cache.php';
/**
* @category Zend
* @package Zend_Cache
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Manager
{
/**
* Constant holding reserved name for default Page Cache
*/
const PAGECACHE = 'page';
/**
* Constant holding reserved name for default Page Tag Cache
*/
const PAGETAGCACHE = 'pagetag';
/**
* Array of caches stored by the Cache Manager instance
*
* @var array
*/
protected $_caches = array();
/**
* Array of ready made configuration templates for lazy
* loading caches.
*
* @var array
*/
protected $_optionTemplates = array(
// Simple Common Default
'default' => array(
'frontend' => array(
'name' => 'Core',
'options' => array(
'automatic_serialization' => true,
),
),
'backend' => array(
'name' => 'File',
'options' => array(
// use system temp dir by default of file backend
// 'cache_dir' => '../cache',
),
),
),
// Static Page HTML Cache
'page' => array(
'frontend' => array(
'name' => 'Capture',
'options' => array(
'ignore_user_abort' => true,
),
),
'backend' => array(
'name' => 'Static',
'options' => array(
'public_dir' => '../public',
),
),
),
// Tag Cache
'pagetag' => array(
'frontend' => array(
'name' => 'Core',
'options' => array(
'automatic_serialization' => true,
'lifetime' => null
),
),
'backend' => array(
'name' => 'File',
'options' => array(
// use system temp dir by default of file backend
// 'cache_dir' => '../cache',
// use default umask of file backend
// 'cache_file_umask' => 0644
),
),
),
);
/**
* Set a new cache for the Cache Manager to contain
*
* @param string $name
* @param Zend_Cache_Core $cache
* @return Zend_Cache_Manager
*/
public function setCache($name, Zend_Cache_Core $cache)
{
$this->_caches[$name] = $cache;
return $this;
}
/**
* Check if the Cache Manager contains the named cache object, or a named
* configuration template to lazy load the cache object
*
* @param string $name
* @return bool
*/
public function hasCache($name)
{
if (isset($this->_caches[$name])
|| $this->hasCacheTemplate($name)
) {
return true;
}
return false;
}
/**
* Fetch the named cache object, or instantiate and return a cache object
* using a named configuration template
*
* @param string $name
* @return Zend_Cache_Core
*/
public function getCache($name)
{
if (isset($this->_caches[$name])) {
return $this->_caches[$name];
}
if (isset($this->_optionTemplates[$name])) {
if ($name == self::PAGECACHE
&& (!isset($this->_optionTemplates[$name]['backend']['options']['tag_cache'])
|| !$this->_optionTemplates[$name]['backend']['options']['tag_cache'] instanceof Zend_Cache_Core)
) {
$this->_optionTemplates[$name]['backend']['options']['tag_cache']
= $this->getCache(self::PAGETAGCACHE);
}
$this->_caches[$name] = Zend_Cache::factory(
$this->_optionTemplates[$name]['frontend']['name'],
$this->_optionTemplates[$name]['backend']['name'],
isset($this->_optionTemplates[$name]['frontend']['options']) ? $this->_optionTemplates[$name]['frontend']['options'] : array(),
isset($this->_optionTemplates[$name]['backend']['options']) ? $this->_optionTemplates[$name]['backend']['options'] : array(),
isset($this->_optionTemplates[$name]['frontend']['customFrontendNaming']) ? $this->_optionTemplates[$name]['frontend']['customFrontendNaming'] : false,
isset($this->_optionTemplates[$name]['backend']['customBackendNaming']) ? $this->_optionTemplates[$name]['backend']['customBackendNaming'] : false,
isset($this->_optionTemplates[$name]['frontendBackendAutoload']) ? $this->_optionTemplates[$name]['frontendBackendAutoload'] : false
);
return $this->_caches[$name];
}
}
/**
* Fetch all available caches
*
* @return array An array of all available caches with it's names as key
*/
public function getCaches()
{
$caches = $this->_caches;
foreach ($this->_optionTemplates as $name => $tmp) {
if (!isset($caches[$name])) {
$caches[$name] = $this->getCache($name);
}
}
return $caches;
}
/**
* Set a named configuration template from which a cache object can later
* be lazy loaded
*
* @param string $name
* @param array $options
* @return Zend_Cache_Manager
*/
public function setCacheTemplate($name, $options)
{
if ($options instanceof Zend_Config) {
$options = $options->toArray();
} elseif (!is_array($options)) {
// require_once 'Zend/Cache/Exception.php';
throw new Zend_Cache_Exception('Options passed must be in'
. ' an associative array or instance of Zend_Config');
}
$this->_optionTemplates[$name] = $options;
return $this;
}
/**
* Check if the named configuration template
*
* @param string $name
* @return bool
*/
public function hasCacheTemplate($name)
{
if (isset($this->_optionTemplates[$name])) {
return true;
}
return false;
}
/**
* Get the named configuration template
*
* @param string $name
* @return array
*/
public function getCacheTemplate($name)
{
if (isset($this->_optionTemplates[$name])) {
return $this->_optionTemplates[$name];
}
}
/**
* Pass an array containing changes to be applied to a named
* configuration
* template
*
* @param string $name
* @param array $options
* @return Zend_Cache_Manager
* @throws Zend_Cache_Exception for invalid options format or if option templates do not have $name
*/
public function setTemplateOptions($name, $options)
{
if ($options instanceof Zend_Config) {
$options = $options->toArray();
} elseif (!is_array($options)) {
// require_once 'Zend/Cache/Exception.php';
throw new Zend_Cache_Exception('Options passed must be in'
. ' an associative array or instance of Zend_Config');
}
if (!isset($this->_optionTemplates[$name])) {
throw new Zend_Cache_Exception('A cache configuration template'
. 'does not exist with the name "' . $name . '"');
}
$this->_optionTemplates[$name]
= $this->_mergeOptions($this->_optionTemplates[$name], $options);
return $this;
}
/**
* Simple method to merge two configuration arrays
*
* @param array $current
* @param array $options
* @return array
*/
protected function _mergeOptions(array $current, array $options)
{
if (isset($options['frontend']['name'])) {
$current['frontend']['name'] = $options['frontend']['name'];
}
if (isset($options['backend']['name'])) {
$current['backend']['name'] = $options['backend']['name'];
}
if (isset($options['frontend']['options'])) {
foreach ($options['frontend']['options'] as $key=>$value) {
$current['frontend']['options'][$key] = $value;
}
}
if (isset($options['backend']['options'])) {
foreach ($options['backend']['options'] as $key=>$value) {
$current['backend']['options'][$key] = $value;
}
}
return $current;
}
}

View File

@ -0,0 +1,484 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Config
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Config.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @category Zend
* @package Zend_Config
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Config implements Countable, Iterator
{
/**
* Whether in-memory modifications to configuration data are allowed
*
* @var boolean
*/
protected $_allowModifications;
/**
* Iteration index
*
* @var integer
*/
protected $_index;
/**
* Number of elements in configuration data
*
* @var integer
*/
protected $_count;
/**
* Contains array of configuration data
*
* @var array
*/
protected $_data;
/**
* Used when unsetting values during iteration to ensure we do not skip
* the next element
*
* @var boolean
*/
protected $_skipNextIteration;
/**
* Contains which config file sections were loaded. This is null
* if all sections were loaded, a string name if one section is loaded
* and an array of string names if multiple sections were loaded.
*
* @var mixed
*/
protected $_loadedSection;
/**
* This is used to track section inheritance. The keys are names of sections that
* extend other sections, and the values are the extended sections.
*
* @var array
*/
protected $_extends = array();
/**
* Load file error string.
*
* Is null if there was no error while file loading
*
* @var string
*/
protected $_loadFileErrorStr = null;
/**
* Zend_Config provides a property based interface to
* an array. The data are read-only unless $allowModifications
* is set to true on construction.
*
* Zend_Config also implements Countable and Iterator to
* facilitate easy access to the data.
*
* @param array $array
* @param boolean $allowModifications
* @return void
*/
public function __construct(array $array, $allowModifications = false)
{
$this->_allowModifications = (boolean) $allowModifications;
$this->_loadedSection = null;
$this->_index = 0;
$this->_data = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$this->_data[$key] = new self($value, $this->_allowModifications);
} else {
$this->_data[$key] = $value;
}
}
$this->_count = count($this->_data);
}
/**
* Retrieve a value and return $default if there is no element set.
*
* @param string $name
* @param mixed $default
* @return mixed
*/
public function get($name, $default = null)
{
$result = $default;
if (array_key_exists($name, $this->_data)) {
$result = $this->_data[$name];
}
return $result;
}
/**
* Magic function so that $obj->value will work.
*
* @param string $name
* @return mixed
*/
public function __get($name)
{
return $this->get($name);
}
/**
* Only allow setting of a property if $allowModifications
* was set to true on construction. Otherwise, throw an exception.
*
* @param string $name
* @param mixed $value
* @throws Zend_Config_Exception
* @return void
*/
public function __set($name, $value)
{
if ($this->_allowModifications) {
if (is_array($value)) {
$this->_data[$name] = new self($value, true);
} else {
$this->_data[$name] = $value;
}
$this->_count = count($this->_data);
} else {
/** @see Zend_Config_Exception */
// require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception('Zend_Config is read only');
}
}
/**
* Deep clone of this instance to ensure that nested Zend_Configs
* are also cloned.
*
* @return void
*/
public function __clone()
{
$array = array();
foreach ($this->_data as $key => $value) {
if ($value instanceof Zend_Config) {
$array[$key] = clone $value;
} else {
$array[$key] = $value;
}
}
$this->_data = $array;
}
/**
* Return an associative array of the stored data.
*
* @return array
*/
public function toArray()
{
$array = array();
$data = $this->_data;
foreach ($data as $key => $value) {
if ($value instanceof Zend_Config) {
$array[$key] = $value->toArray();
} else {
$array[$key] = $value;
}
}
return $array;
}
/**
* Support isset() overloading on PHP 5.1
*
* @param string $name
* @return boolean
*/
public function __isset($name)
{
return isset($this->_data[$name]);
}
/**
* Support unset() overloading on PHP 5.1
*
* @param string $name
* @throws Zend_Config_Exception
* @return void
*/
public function __unset($name)
{
if ($this->_allowModifications) {
unset($this->_data[$name]);
$this->_count = count($this->_data);
$this->_skipNextIteration = true;
} else {
/** @see Zend_Config_Exception */
// require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception('Zend_Config is read only');
}
}
/**
* Defined by Countable interface
*
* @return int
*/
public function count()
{
return $this->_count;
}
/**
* Defined by Iterator interface
*
* @return mixed
*/
public function current()
{
$this->_skipNextIteration = false;
return current($this->_data);
}
/**
* Defined by Iterator interface
*
* @return mixed
*/
public function key()
{
return key($this->_data);
}
/**
* Defined by Iterator interface
*
*/
public function next()
{
if ($this->_skipNextIteration) {
$this->_skipNextIteration = false;
return;
}
next($this->_data);
$this->_index++;
}
/**
* Defined by Iterator interface
*
*/
public function rewind()
{
$this->_skipNextIteration = false;
reset($this->_data);
$this->_index = 0;
}
/**
* Defined by Iterator interface
*
* @return boolean
*/
public function valid()
{
return $this->_index < $this->_count;
}
/**
* Returns the section name(s) loaded.
*
* @return mixed
*/
public function getSectionName()
{
if(is_array($this->_loadedSection) && count($this->_loadedSection) == 1) {
$this->_loadedSection = $this->_loadedSection[0];
}
return $this->_loadedSection;
}
/**
* Returns true if all sections were loaded
*
* @return boolean
*/
public function areAllSectionsLoaded()
{
return $this->_loadedSection === null;
}
/**
* Merge another Zend_Config with this one. The items
* in $merge will override the same named items in
* the current config.
*
* @param Zend_Config $merge
* @return Zend_Config
*/
public function merge(Zend_Config $merge)
{
foreach($merge as $key => $item) {
if(array_key_exists($key, $this->_data)) {
if($item instanceof Zend_Config && $this->$key instanceof Zend_Config) {
$this->$key = $this->$key->merge(new Zend_Config($item->toArray(), !$this->readOnly()));
} else {
$this->$key = $item;
}
} else {
if($item instanceof Zend_Config) {
$this->$key = new Zend_Config($item->toArray(), !$this->readOnly());
} else {
$this->$key = $item;
}
}
}
return $this;
}
/**
* Prevent any more modifications being made to this instance. Useful
* after merge() has been used to merge multiple Zend_Config objects
* into one object which should then not be modified again.
*
*/
public function setReadOnly()
{
$this->_allowModifications = false;
foreach ($this->_data as $key => $value) {
if ($value instanceof Zend_Config) {
$value->setReadOnly();
}
}
}
/**
* Returns if this Zend_Config object is read only or not.
*
* @return boolean
*/
public function readOnly()
{
return !$this->_allowModifications;
}
/**
* Get the current extends
*
* @return array
*/
public function getExtends()
{
return $this->_extends;
}
/**
* Set an extend for Zend_Config_Writer
*
* @param string $extendingSection
* @param string $extendedSection
* @return void
*/
public function setExtend($extendingSection, $extendedSection = null)
{
if ($extendedSection === null && isset($this->_extends[$extendingSection])) {
unset($this->_extends[$extendingSection]);
} else if ($extendedSection !== null) {
$this->_extends[$extendingSection] = $extendedSection;
}
}
/**
* Throws an exception if $extendingSection may not extend $extendedSection,
* and tracks the section extension if it is valid.
*
* @param string $extendingSection
* @param string $extendedSection
* @throws Zend_Config_Exception
* @return void
*/
protected function _assertValidExtend($extendingSection, $extendedSection)
{
// detect circular section inheritance
$extendedSectionCurrent = $extendedSection;
while (array_key_exists($extendedSectionCurrent, $this->_extends)) {
if ($this->_extends[$extendedSectionCurrent] == $extendingSection) {
/** @see Zend_Config_Exception */
// require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception('Illegal circular inheritance detected');
}
$extendedSectionCurrent = $this->_extends[$extendedSectionCurrent];
}
// remember that this section extends another section
$this->_extends[$extendingSection] = $extendedSection;
}
/**
* Handle any errors from simplexml_load_file or parse_ini_file
*
* @param integer $errno
* @param string $errstr
* @param string $errfile
* @param integer $errline
*/
protected function _loadFileErrorHandler($errno, $errstr, $errfile, $errline)
{
if ($this->_loadFileErrorStr === null) {
$this->_loadFileErrorStr = $errstr;
} else {
$this->_loadFileErrorStr .= (PHP_EOL . $errstr);
}
}
/**
* Merge two arrays recursively, overwriting keys of the same name
* in $firstArray with the value in $secondArray.
*
* @param mixed $firstArray First array
* @param mixed $secondArray Second array to merge into first array
* @return array
*/
protected function _arrayMergeRecursive($firstArray, $secondArray)
{
if (is_array($firstArray) && is_array($secondArray)) {
foreach ($secondArray as $key => $value) {
if (isset($firstArray[$key])) {
$firstArray[$key] = $this->_arrayMergeRecursive($firstArray[$key], $value);
} else {
if($key === 0) {
$firstArray= array(0=>$this->_arrayMergeRecursive($firstArray, $value));
} else {
$firstArray[$key] = $value;
}
}
}
} else {
$firstArray = $secondArray;
}
return $firstArray;
}
}

View File

@ -0,0 +1,33 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Config
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Exception.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Exception
*/
// require_once 'Zend/Exception.php';
/**
* @category Zend
* @package Zend_Config
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Config_Exception extends Zend_Exception {}

View File

@ -0,0 +1,309 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Config
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Ini.php 24045 2011-05-23 12:45:11Z rob $
*/
/**
* @see Zend_Config
*/
// require_once 'Zend/Config.php';
/**
* @category Zend
* @package Zend_Config
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Config_Ini extends Zend_Config
{
/**
* String that separates nesting levels of configuration data identifiers
*
* @var string
*/
protected $_nestSeparator = '.';
/**
* String that separates the parent section name
*
* @var string
*/
protected $_sectionSeparator = ':';
/**
* Whether to skip extends or not
*
* @var boolean
*/
protected $_skipExtends = false;
/**
* Loads the section $section from the config file $filename for
* access facilitated by nested object properties.
*
* If the section name contains a ":" then the section name to the right
* is loaded and included into the properties. Note that the keys in
* this $section will override any keys of the same
* name in the sections that have been included via ":".
*
* If the $section is null, then all sections in the ini file are loaded.
*
* If any key includes a ".", then this will act as a separator to
* create a sub-property.
*
* example ini file:
* [all]
* db.connection = database
* hostname = live
*
* [staging : all]
* hostname = staging
*
* after calling $data = new Zend_Config_Ini($file, 'staging'); then
* $data->hostname === "staging"
* $data->db->connection === "database"
*
* The $options parameter may be provided as either a boolean or an array.
* If provided as a boolean, this sets the $allowModifications option of
* Zend_Config. If provided as an array, there are three configuration
* directives that may be set. For example:
*
* $options = array(
* 'allowModifications' => false,
* 'nestSeparator' => ':',
* 'skipExtends' => false,
* );
*
* @param string $filename
* @param mixed $section
* @param boolean|array $options
* @throws Zend_Config_Exception
* @return void
*/
public function __construct($filename, $section = null, $options = false)
{
if (empty($filename)) {
/**
* @see Zend_Config_Exception
*/
// require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception('Filename is not set');
}
$allowModifications = false;
if (is_bool($options)) {
$allowModifications = $options;
} elseif (is_array($options)) {
if (isset($options['allowModifications'])) {
$allowModifications = (bool) $options['allowModifications'];
}
if (isset($options['nestSeparator'])) {
$this->_nestSeparator = (string) $options['nestSeparator'];
}
if (isset($options['skipExtends'])) {
$this->_skipExtends = (bool) $options['skipExtends'];
}
}
$iniArray = $this->_loadIniFile($filename);
if (null === $section) {
// Load entire file
$dataArray = array();
foreach ($iniArray as $sectionName => $sectionData) {
if(!is_array($sectionData)) {
$dataArray = $this->_arrayMergeRecursive($dataArray, $this->_processKey(array(), $sectionName, $sectionData));
} else {
$dataArray[$sectionName] = $this->_processSection($iniArray, $sectionName);
}
}
parent::__construct($dataArray, $allowModifications);
} else {
// Load one or more sections
if (!is_array($section)) {
$section = array($section);
}
$dataArray = array();
foreach ($section as $sectionName) {
if (!isset($iniArray[$sectionName])) {
/**
* @see Zend_Config_Exception
*/
// require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception("Section '$sectionName' cannot be found in $filename");
}
$dataArray = $this->_arrayMergeRecursive($this->_processSection($iniArray, $sectionName), $dataArray);
}
parent::__construct($dataArray, $allowModifications);
}
$this->_loadedSection = $section;
}
/**
* Load the INI file from disk using parse_ini_file(). Use a private error
* handler to convert any loading errors into a Zend_Config_Exception
*
* @param string $filename
* @throws Zend_Config_Exception
* @return array
*/
protected function _parseIniFile($filename)
{
set_error_handler(array($this, '_loadFileErrorHandler'));
$iniArray = parse_ini_file($filename, true); // Warnings and errors are suppressed
restore_error_handler();
// Check if there was a error while loading file
if ($this->_loadFileErrorStr !== null) {
/**
* @see Zend_Config_Exception
*/
// require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception($this->_loadFileErrorStr);
}
return $iniArray;
}
/**
* Load the ini file and preprocess the section separator (':' in the
* section name (that is used for section extension) so that the resultant
* array has the correct section names and the extension information is
* stored in a sub-key called ';extends'. We use ';extends' as this can
* never be a valid key name in an INI file that has been loaded using
* parse_ini_file().
*
* @param string $filename
* @throws Zend_Config_Exception
* @return array
*/
protected function _loadIniFile($filename)
{
$loaded = $this->_parseIniFile($filename);
$iniArray = array();
foreach ($loaded as $key => $data)
{
$pieces = explode($this->_sectionSeparator, $key);
$thisSection = trim($pieces[0]);
switch (count($pieces)) {
case 1:
$iniArray[$thisSection] = $data;
break;
case 2:
$extendedSection = trim($pieces[1]);
$iniArray[$thisSection] = array_merge(array(';extends'=>$extendedSection), $data);
break;
default:
/**
* @see Zend_Config_Exception
*/
// require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception("Section '$thisSection' may not extend multiple sections in $filename");
}
}
return $iniArray;
}
/**
* Process each element in the section and handle the ";extends" inheritance
* key. Passes control to _processKey() to handle the nest separator
* sub-property syntax that may be used within the key name.
*
* @param array $iniArray
* @param string $section
* @param array $config
* @throws Zend_Config_Exception
* @return array
*/
protected function _processSection($iniArray, $section, $config = array())
{
$thisSection = $iniArray[$section];
foreach ($thisSection as $key => $value) {
if (strtolower($key) == ';extends') {
if (isset($iniArray[$value])) {
$this->_assertValidExtend($section, $value);
if (!$this->_skipExtends) {
$config = $this->_processSection($iniArray, $value, $config);
}
} else {
/**
* @see Zend_Config_Exception
*/
// require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception("Parent section '$section' cannot be found");
}
} else {
$config = $this->_processKey($config, $key, $value);
}
}
return $config;
}
/**
* Assign the key's value to the property list. Handles the
* nest separator for sub-properties.
*
* @param array $config
* @param string $key
* @param string $value
* @throws Zend_Config_Exception
* @return array
*/
protected function _processKey($config, $key, $value)
{
if (strpos($key, $this->_nestSeparator) !== false) {
$pieces = explode($this->_nestSeparator, $key, 2);
if (strlen($pieces[0]) && strlen($pieces[1])) {
if (!isset($config[$pieces[0]])) {
if ($pieces[0] === '0' && !empty($config)) {
// convert the current values in $config into an array
$config = array($pieces[0] => $config);
} else {
$config[$pieces[0]] = array();
}
} elseif (!is_array($config[$pieces[0]])) {
/**
* @see Zend_Config_Exception
*/
// require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception("Cannot create sub-key for '{$pieces[0]}' as key already exists");
}
$config[$pieces[0]] = $this->_processKey($config[$pieces[0]], $pieces[1], $value);
} else {
/**
* @see Zend_Config_Exception
*/
// require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception("Invalid key '$key'");
}
} else {
$config[$key] = $value;
}
return $config;
}
}

View File

@ -0,0 +1,240 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Config
* @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Json.php 23294 2010-11-05 00:27:34Z ramon $
*/
/**
* @see Zend_Config
*/
// require_once 'Zend/Config.php';
/**
* @see Zend_Json
*/
// require_once 'Zend/Json.php';
/**
* JSON Adapter for Zend_Config
*
* @category Zend
* @package Zend_Config
* @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Config_Json extends Zend_Config
{
/**
* Name of object key indicating section current section extends
*/
const EXTENDS_NAME = "_extends";
/**
* Whether or not to ignore constants in the JSON string
*
* Note: if you do not have constant names in quotations in your JSON
* string, they may lead to syntax errors when parsing.
*
* @var bool
*/
protected $_ignoreConstants = false;
/**
* Whether to skip extends or not
*
* @var boolean
*/
protected $_skipExtends = false;
/**
* Loads the section $section from the config file encoded as JSON
*
* Sections are defined as properties of the main object
*
* In order to extend another section, a section defines the "_extends"
* property having a value of the section name from which the extending
* section inherits values.
*
* Note that the keys in $section will override any keys of the same
* name in the sections that have been included via "_extends".
*
* @param string $json JSON file or string to process
* @param mixed $section Section to process
* @param boolean $options Whether modifiacations are allowed at runtime
* @throws Zend_Config_Exception When JSON text is not set or cannot be loaded
* @throws Zend_Config_Exception When section $sectionName cannot be found in $json
*/
public function __construct($json, $section = null, $options = false)
{
if (empty($json)) {
// require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception('Filename is not set');
}
$allowModifications = false;
if (is_bool($options)) {
$allowModifications = $options;
} elseif (is_array($options)) {
foreach ($options as $key => $value) {
switch (strtolower($key)) {
case 'allow_modifications':
case 'allowmodifications':
$allowModifications = (bool) $value;
break;
case 'skip_extends':
case 'skipextends':
$this->_skipExtends = (bool) $value;
break;
case 'ignore_constants':
case 'ignoreconstants':
$this->_ignoreConstants = (bool) $value;
break;
default:
break;
}
}
}
set_error_handler(array($this, '_loadFileErrorHandler')); // Warnings and errors are suppressed
if ($json[0] != '{') {
$json = file_get_contents($json);
}
restore_error_handler();
// Check if there was a error while loading file
if ($this->_loadFileErrorStr !== null) {
// require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception($this->_loadFileErrorStr);
}
// Replace constants
if (!$this->_ignoreConstants) {
$json = $this->_replaceConstants($json);
}
// Parse/decode
$config = Zend_Json::decode($json);
if (null === $config) {
// decode failed
// require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception("Error parsing JSON data");
}
if ($section === null) {
$dataArray = array();
foreach ($config as $sectionName => $sectionData) {
$dataArray[$sectionName] = $this->_processExtends($config, $sectionName);
}
parent::__construct($dataArray, $allowModifications);
} elseif (is_array($section)) {
$dataArray = array();
foreach ($section as $sectionName) {
if (!isset($config[$sectionName])) {
// require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception(sprintf('Section "%s" cannot be found', $sectionName));
}
$dataArray = array_merge($this->_processExtends($config, $sectionName), $dataArray);
}
parent::__construct($dataArray, $allowModifications);
} else {
if (!isset($config[$section])) {
// require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception(sprintf('Section "%s" cannot be found', $section));
}
$dataArray = $this->_processExtends($config, $section);
if (!is_array($dataArray)) {
// Section in the JSON data contains just one top level string
$dataArray = array($section => $dataArray);
}
parent::__construct($dataArray, $allowModifications);
}
$this->_loadedSection = $section;
}
/**
* Helper function to process each element in the section and handle
* the "_extends" inheritance attribute.
*
* @param array $data Data array to process
* @param string $section Section to process
* @param array $config Configuration which was parsed yet
* @throws Zend_Config_Exception When $section cannot be found
* @return array
*/
protected function _processExtends(array $data, $section, array $config = array())
{
if (!isset($data[$section])) {
// require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception(sprintf('Section "%s" cannot be found', $section));
}
$thisSection = $data[$section];
if (is_array($thisSection) && isset($thisSection[self::EXTENDS_NAME])) {
if (is_array($thisSection[self::EXTENDS_NAME])) {
// require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception('Invalid extends clause: must be a string; array received');
}
$this->_assertValidExtend($section, $thisSection[self::EXTENDS_NAME]);
if (!$this->_skipExtends) {
$config = $this->_processExtends($data, $thisSection[self::EXTENDS_NAME], $config);
}
unset($thisSection[self::EXTENDS_NAME]);
}
$config = $this->_arrayMergeRecursive($config, $thisSection);
return $config;
}
/**
* Replace any constants referenced in a string with their values
*
* @param string $value
* @return string
*/
protected function _replaceConstants($value)
{
foreach ($this->_getConstants() as $constant) {
if (strstr($value, $constant)) {
$value = str_replace($constant, constant($constant), $value);
}
}
return $value;
}
/**
* Get (reverse) sorted list of defined constant names
*
* @return array
*/
protected function _getConstants()
{
$constants = array_keys(get_defined_constants());
rsort($constants, SORT_STRING);
return $constants;
}
}

View File

@ -0,0 +1,101 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Config
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Writer.php 23953 2011-05-03 05:47:39Z ralph $
*/
/**
* @category Zend
* @package Zend_Config
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
abstract class Zend_Config_Writer
{
/**
* Option keys to skip when calling setOptions()
*
* @var array
*/
protected $_skipOptions = array(
'options'
);
/**
* Config object to write
*
* @var Zend_Config
*/
protected $_config = null;
/**
* Create a new adapter
*
* $options can only be passed as array or be omitted
*
* @param null|array $options
*/
public function __construct(array $options = null)
{
if (is_array($options)) {
$this->setOptions($options);
}
}
/**
* Set options via a Zend_Config instance
*
* @param Zend_Config $config
* @return Zend_Config_Writer
*/
public function setConfig(Zend_Config $config)
{
$this->_config = $config;
return $this;
}
/**
* Set options via an array
*
* @param array $options
* @return Zend_Config_Writer
*/
public function setOptions(array $options)
{
foreach ($options as $key => $value) {
if (in_array(strtolower($key), $this->_skipOptions)) {
continue;
}
$method = 'set' . ucfirst($key);
if (method_exists($this, $method)) {
$this->$method($value);
}
}
return $this;
}
/**
* Write a Zend_Config object to it's target
*
* @return void
*/
abstract public function write();
}

View File

@ -0,0 +1,55 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Config
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Array.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Config_Writer
*/
// require_once 'Zend/Config/Writer/FileAbstract.php';
/**
* @category Zend
* @package Zend_Config
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Config_Writer_Array extends Zend_Config_Writer_FileAbstract
{
/**
* Render a Zend_Config into a PHP Array config string.
*
* @since 1.10
* @return string
*/
public function render()
{
$data = $this->_config->toArray();
$sectionName = $this->_config->getSectionName();
if (is_string($sectionName)) {
$data = array($sectionName => $data);
}
$arrayString = "<?php\n"
. "return " . var_export($data, true) . ";\n";
return $arrayString;
}
}

View File

@ -0,0 +1,134 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Config
* @package Writer
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
// require_once "Zend/Config/Writer.php";
/**
* Abstract File Writer
*
* @category Zend
* @package Zend_package
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: FileAbstract.php 23775 2011-03-01 17:25:24Z ralph $
*/
class Zend_Config_Writer_FileAbstract extends Zend_Config_Writer
{
/**
* Filename to write to
*
* @var string
*/
protected $_filename = null;
/**
* Wether to exclusively lock the file or not
*
* @var boolean
*/
protected $_exclusiveLock = false;
/**
* Set the target filename
*
* @param string $filename
* @return Zend_Config_Writer_Array
*/
public function setFilename($filename)
{
$this->_filename = $filename;
return $this;
}
/**
* Set wether to exclusively lock the file or not
*
* @param boolean $exclusiveLock
* @return Zend_Config_Writer_Array
*/
public function setExclusiveLock($exclusiveLock)
{
$this->_exclusiveLock = $exclusiveLock;
return $this;
}
/**
* Write configuration to file.
*
* @param string $filename
* @param Zend_Config $config
* @param bool $exclusiveLock
* @return void
*/
public function write($filename = null, Zend_Config $config = null, $exclusiveLock = null)
{
if ($filename !== null) {
$this->setFilename($filename);
}
if ($config !== null) {
$this->setConfig($config);
}
if ($exclusiveLock !== null) {
$this->setExclusiveLock($exclusiveLock);
}
if ($this->_filename === null) {
// require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception('No filename was set');
}
if ($this->_config === null) {
// require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception('No config was set');
}
$configString = $this->render();
$flags = 0;
if ($this->_exclusiveLock) {
$flags |= LOCK_EX;
}
$result = @file_put_contents($this->_filename, $configString, $flags);
if ($result === false) {
// require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception('Could not write to file "' . $this->_filename . '"');
}
}
/**
* Render a Zend_Config into a config file string.
*
* @since 1.10
* @todo For 2.0 this should be redone into an abstract method.
* @return string
*/
public function render()
{
return "";
}
}

View File

@ -0,0 +1,193 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Config
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Ini.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Config_Writer
*/
// require_once 'Zend/Config/Writer/FileAbstract.php';
/**
* @category Zend
* @package Zend_Config
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Config_Writer_Ini extends Zend_Config_Writer_FileAbstract
{
/**
* String that separates nesting levels of configuration data identifiers
*
* @var string
*/
protected $_nestSeparator = '.';
/**
* If true the ini string is rendered in the global namespace without sections.
*
* @var bool
*/
protected $_renderWithoutSections = false;
/**
* Set the nest separator
*
* @param string $filename
* @return Zend_Config_Writer_Ini
*/
public function setNestSeparator($separator)
{
$this->_nestSeparator = $separator;
return $this;
}
/**
* Set if rendering should occour without sections or not.
*
* If set to true, the INI file is rendered without sections completely
* into the global namespace of the INI file.
*
* @param bool $withoutSections
* @return Zend_Config_Writer_Ini
*/
public function setRenderWithoutSections($withoutSections=true)
{
$this->_renderWithoutSections = (bool)$withoutSections;
return $this;
}
/**
* Render a Zend_Config into a INI config string.
*
* @since 1.10
* @return string
*/
public function render()
{
$iniString = '';
$extends = $this->_config->getExtends();
$sectionName = $this->_config->getSectionName();
if($this->_renderWithoutSections == true) {
$iniString .= $this->_addBranch($this->_config);
} else if (is_string($sectionName)) {
$iniString .= '[' . $sectionName . ']' . "\n"
. $this->_addBranch($this->_config)
. "\n";
} else {
$config = $this->_sortRootElements($this->_config);
foreach ($config as $sectionName => $data) {
if (!($data instanceof Zend_Config)) {
$iniString .= $sectionName
. ' = '
. $this->_prepareValue($data)
. "\n";
} else {
if (isset($extends[$sectionName])) {
$sectionName .= ' : ' . $extends[$sectionName];
}
$iniString .= '[' . $sectionName . ']' . "\n"
. $this->_addBranch($data)
. "\n";
}
}
}
return $iniString;
}
/**
* Add a branch to an INI string recursively
*
* @param Zend_Config $config
* @return void
*/
protected function _addBranch(Zend_Config $config, $parents = array())
{
$iniString = '';
foreach ($config as $key => $value) {
$group = array_merge($parents, array($key));
if ($value instanceof Zend_Config) {
$iniString .= $this->_addBranch($value, $group);
} else {
$iniString .= implode($this->_nestSeparator, $group)
. ' = '
. $this->_prepareValue($value)
. "\n";
}
}
return $iniString;
}
/**
* Prepare a value for INI
*
* @param mixed $value
* @return string
*/
protected function _prepareValue($value)
{
if (is_integer($value) || is_float($value)) {
return $value;
} elseif (is_bool($value)) {
return ($value ? 'true' : 'false');
} elseif (strpos($value, '"') === false) {
return '"' . $value . '"';
} else {
/** @see Zend_Config_Exception */
// require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception('Value can not contain double quotes "');
}
}
/**
* Root elements that are not assigned to any section needs to be
* on the top of config.
*
* @see http://framework.zend.com/issues/browse/ZF-6289
* @param Zend_Config
* @return Zend_Config
*/
protected function _sortRootElements(Zend_Config $config)
{
$configArray = $config->toArray();
$sections = array();
// remove sections from config array
foreach ($configArray as $key => $value) {
if (is_array($value)) {
$sections[$key] = $value;
unset($configArray[$key]);
}
}
// readd sections to the end
foreach ($sections as $key => $value) {
$configArray[$key] = $value;
}
return new Zend_Config($configArray);
}
}

View File

@ -0,0 +1,106 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Config
* @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Json.php 23294 2010-11-05 00:27:34Z ramon $
*/
/**
* @see Zend_Config_Writer
*/
// require_once 'Zend/Config/Writer/FileAbstract.php';
/**
* @see Zend_Config_Json
*/
// require_once 'Zend/Config/Json.php';
/**
* @category Zend
* @package Zend_Config
* @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Config_Writer_Json extends Zend_Config_Writer_FileAbstract
{
/**
* If we need to pretty-print JSON data
*
* @var boolean
*/
protected $_prettyPrint = false;
/**
* Get prettyPrint flag
*
* @return the prettyPrint flag
*/
public function prettyPrint()
{
return $this->_prettyPrint;
}
/**
* Set prettyPrint flag
*
* @param bool $prettyPrint PrettyPrint flag
* @return Zend_Config_Writer_Json
*/
public function setPrettyPrint($flag)
{
$this->_prettyPrint = (bool) $flag;
return $this;
}
/**
* Render a Zend_Config into a JSON config string.
*
* @since 1.10
* @return string
*/
public function render()
{
$data = $this->_config->toArray();
$sectionName = $this->_config->getSectionName();
$extends = $this->_config->getExtends();
if (is_string($sectionName)) {
$data = array($sectionName => $data);
}
foreach ($extends as $section => $parentSection) {
$data[$section][Zend_Config_Json::EXTENDS_NAME] = $parentSection;
}
// Ensure that each "extends" section actually exists
foreach ($data as $section => $sectionData) {
if (is_array($sectionData) && isset($sectionData[Zend_Config_Json::EXTENDS_NAME])) {
$sectionExtends = $sectionData[Zend_Config_Json::EXTENDS_NAME];
if (!isset($data[$sectionExtends])) {
// Remove "extends" declaration if section does not exist
unset($data[$section][Zend_Config_Json::EXTENDS_NAME]);
}
}
}
$out = Zend_Json::encode($data);
if ($this->prettyPrint()) {
$out = Zend_Json::prettyPrint($out);
}
return $out;
}
}

View File

@ -0,0 +1,127 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Config
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Xml.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Config_Writer
*/
// require_once 'Zend/Config/Writer/FileAbstract.php';
/**
* @see Zend_Config_Xml
*/
// require_once 'Zend/Config/Xml.php';
/**
* @category Zend
* @package Zend_Config
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Config_Writer_Xml extends Zend_Config_Writer_FileAbstract
{
/**
* Render a Zend_Config into a XML config string.
*
* @since 1.10
* @return string
*/
public function render()
{
$xml = new SimpleXMLElement('<zend-config xmlns:zf="' . Zend_Config_Xml::XML_NAMESPACE . '"/>');
$extends = $this->_config->getExtends();
$sectionName = $this->_config->getSectionName();
if (is_string($sectionName)) {
$child = $xml->addChild($sectionName);
$this->_addBranch($this->_config, $child, $xml);
} else {
foreach ($this->_config as $sectionName => $data) {
if (!($data instanceof Zend_Config)) {
$xml->addChild($sectionName, (string) $data);
} else {
$child = $xml->addChild($sectionName);
if (isset($extends[$sectionName])) {
$child->addAttribute('zf:extends', $extends[$sectionName], Zend_Config_Xml::XML_NAMESPACE);
}
$this->_addBranch($data, $child, $xml);
}
}
}
$dom = dom_import_simplexml($xml)->ownerDocument;
$dom->formatOutput = true;
$xmlString = $dom->saveXML();
return $xmlString;
}
/**
* Add a branch to an XML object recursively
*
* @param Zend_Config $config
* @param SimpleXMLElement $xml
* @param SimpleXMLElement $parent
* @return void
*/
protected function _addBranch(Zend_Config $config, SimpleXMLElement $xml, SimpleXMLElement $parent)
{
$branchType = null;
foreach ($config as $key => $value) {
if ($branchType === null) {
if (is_numeric($key)) {
$branchType = 'numeric';
$branchName = $xml->getName();
$xml = $parent;
unset($parent->{$branchName});
} else {
$branchType = 'string';
}
} else if ($branchType !== (is_numeric($key) ? 'numeric' : 'string')) {
// require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception('Mixing of string and numeric keys is not allowed');
}
if ($branchType === 'numeric') {
if ($value instanceof Zend_Config) {
$child = $parent->addChild($branchName);
$this->_addBranch($value, $child, $parent);
} else {
$parent->addChild($branchName, (string) $value);
}
} else {
if ($value instanceof Zend_Config) {
$child = $xml->addChild($key);
$this->_addBranch($value, $child, $xml);
} else {
$xml->addChild($key, (string) $value);
}
}
}
}
}

View File

@ -0,0 +1,144 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Config
* @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Yaml.php 23651 2011-01-21 21:51:00Z mikaelkael $
*/
/**
* @see Zend_Config_Writer
*/
// require_once 'Zend/Config/Writer/FileAbstract.php';
/**
* @see Zend_Config_Yaml
*/
// require_once 'Zend/Config/Yaml.php';
/**
* @category Zend
* @package Zend_Config
* @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Config_Writer_Yaml extends Zend_Config_Writer_FileAbstract
{
/**
* What to call when we need to decode some YAML?
*
* @var callable
*/
protected $_yamlEncoder = array('Zend_Config_Writer_Yaml', 'encode');
/**
* Get callback for decoding YAML
*
* @return callable
*/
public function getYamlEncoder()
{
return $this->_yamlEncoder;
}
/**
* Set callback for decoding YAML
*
* @param callable $yamlEncoder the decoder to set
* @return Zend_Config_Yaml
*/
public function setYamlEncoder($yamlEncoder)
{
if (!is_callable($yamlEncoder)) {
// require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception('Invalid parameter to setYamlEncoder - must be callable');
}
$this->_yamlEncoder = $yamlEncoder;
return $this;
}
/**
* Render a Zend_Config into a YAML config string.
*
* @since 1.10
* @return string
*/
public function render()
{
$data = $this->_config->toArray();
$sectionName = $this->_config->getSectionName();
$extends = $this->_config->getExtends();
if (is_string($sectionName)) {
$data = array($sectionName => $data);
}
foreach ($extends as $section => $parentSection) {
$data[$section][Zend_Config_Yaml::EXTENDS_NAME] = $parentSection;
}
// Ensure that each "extends" section actually exists
foreach ($data as $section => $sectionData) {
if (is_array($sectionData) && isset($sectionData[Zend_Config_Yaml::EXTENDS_NAME])) {
$sectionExtends = $sectionData[Zend_Config_Yaml::EXTENDS_NAME];
if (!isset($data[$sectionExtends])) {
// Remove "extends" declaration if section does not exist
unset($data[$section][Zend_Config_Yaml::EXTENDS_NAME]);
}
}
}
return call_user_func($this->getYamlEncoder(), $data);
}
/**
* Very dumb YAML encoder
*
* Until we have Zend_Yaml...
*
* @param array $data YAML data
* @return string
*/
public static function encode($data)
{
return self::_encodeYaml(0, $data);
}
/**
* Service function for encoding YAML
*
* @param int $indent Current indent level
* @param array $data Data to encode
* @return string
*/
protected static function _encodeYaml($indent, $data)
{
reset($data);
$result = "";
$numeric = is_numeric(key($data));
foreach($data as $key => $value) {
if(is_array($value)) {
$encoded = "\n".self::_encodeYaml($indent+1, $value);
} else {
$encoded = (string)$value."\n";
}
$result .= str_repeat(" ", $indent).($numeric?"- ":"$key: ").$encoded;
}
return $result;
}
}

View File

@ -0,0 +1,296 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Config
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Xml.php 24045 2011-05-23 12:45:11Z rob $
*/
/**
* @see Zend_Config
*/
// require_once 'Zend/Config.php';
/**
* XML Adapter for Zend_Config
*
* @category Zend
* @package Zend_Config
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Config_Xml extends Zend_Config
{
/**
* XML namespace for ZF-related tags and attributes
*/
const XML_NAMESPACE = 'http://framework.zend.com/xml/zend-config-xml/1.0/';
/**
* Whether to skip extends or not
*
* @var boolean
*/
protected $_skipExtends = false;
/**
* Loads the section $section from the config file (or string $xml for
* access facilitated by nested object properties.
*
* Sections are defined in the XML as children of the root element.
*
* In order to extend another section, a section defines the "extends"
* attribute having a value of the section name from which the extending
* section inherits values.
*
* Note that the keys in $section will override any keys of the same
* name in the sections that have been included via "extends".
*
* The $options parameter may be provided as either a boolean or an array.
* If provided as a boolean, this sets the $allowModifications option of
* Zend_Config. If provided as an array, there are two configuration
* directives that may be set. For example:
*
* $options = array(
* 'allowModifications' => false,
* 'skipExtends' => false
* );
*
* @param string $xml XML file or string to process
* @param mixed $section Section to process
* @param array|boolean $options
* @throws Zend_Config_Exception When xml is not set or cannot be loaded
* @throws Zend_Config_Exception When section $sectionName cannot be found in $xml
*/
public function __construct($xml, $section = null, $options = false)
{
if (empty($xml)) {
// require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception('Filename is not set');
}
$allowModifications = false;
if (is_bool($options)) {
$allowModifications = $options;
} elseif (is_array($options)) {
if (isset($options['allowModifications'])) {
$allowModifications = (bool) $options['allowModifications'];
}
if (isset($options['skipExtends'])) {
$this->_skipExtends = (bool) $options['skipExtends'];
}
}
set_error_handler(array($this, '_loadFileErrorHandler')); // Warnings and errors are suppressed
if (strstr($xml, '<?xml')) {
$config = simplexml_load_string($xml);
} else {
$config = simplexml_load_file($xml);
}
restore_error_handler();
// Check if there was a error while loading file
if ($this->_loadFileErrorStr !== null) {
// require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception($this->_loadFileErrorStr);
}
if ($section === null) {
$dataArray = array();
foreach ($config as $sectionName => $sectionData) {
$dataArray[$sectionName] = $this->_processExtends($config, $sectionName);
}
parent::__construct($dataArray, $allowModifications);
} else if (is_array($section)) {
$dataArray = array();
foreach ($section as $sectionName) {
if (!isset($config->$sectionName)) {
// require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception("Section '$sectionName' cannot be found in $xml");
}
$dataArray = array_merge($this->_processExtends($config, $sectionName), $dataArray);
}
parent::__construct($dataArray, $allowModifications);
} else {
if (!isset($config->$section)) {
// require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception("Section '$section' cannot be found in $xml");
}
$dataArray = $this->_processExtends($config, $section);
if (!is_array($dataArray)) {
// Section in the XML file contains just one top level string
$dataArray = array($section => $dataArray);
}
parent::__construct($dataArray, $allowModifications);
}
$this->_loadedSection = $section;
}
/**
* Helper function to process each element in the section and handle
* the "extends" inheritance attribute.
*
* @param SimpleXMLElement $element XML Element to process
* @param string $section Section to process
* @param array $config Configuration which was parsed yet
* @throws Zend_Config_Exception When $section cannot be found
* @return array
*/
protected function _processExtends(SimpleXMLElement $element, $section, array $config = array())
{
if (!isset($element->$section)) {
// require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception("Section '$section' cannot be found");
}
$thisSection = $element->$section;
$nsAttributes = $thisSection->attributes(self::XML_NAMESPACE);
if (isset($thisSection['extends']) || isset($nsAttributes['extends'])) {
$extendedSection = (string) (isset($nsAttributes['extends']) ? $nsAttributes['extends'] : $thisSection['extends']);
$this->_assertValidExtend($section, $extendedSection);
if (!$this->_skipExtends) {
$config = $this->_processExtends($element, $extendedSection, $config);
}
}
$config = $this->_arrayMergeRecursive($config, $this->_toArray($thisSection));
return $config;
}
/**
* Returns a string or an associative and possibly multidimensional array from
* a SimpleXMLElement.
*
* @param SimpleXMLElement $xmlObject Convert a SimpleXMLElement into an array
* @return array|string
*/
protected function _toArray(SimpleXMLElement $xmlObject)
{
$config = array();
$nsAttributes = $xmlObject->attributes(self::XML_NAMESPACE);
// Search for parent node values
if (count($xmlObject->attributes()) > 0) {
foreach ($xmlObject->attributes() as $key => $value) {
if ($key === 'extends') {
continue;
}
$value = (string) $value;
if (array_key_exists($key, $config)) {
if (!is_array($config[$key])) {
$config[$key] = array($config[$key]);
}
$config[$key][] = $value;
} else {
$config[$key] = $value;
}
}
}
// Search for local 'const' nodes and replace them
if (count($xmlObject->children(self::XML_NAMESPACE)) > 0) {
if (count($xmlObject->children()) > 0) {
// require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception("A node with a 'const' childnode may not have any other children");
}
$dom = dom_import_simplexml($xmlObject);
$namespaceChildNodes = array();
// We have to store them in an array, as replacing nodes will
// confuse the DOMNodeList later
foreach ($dom->childNodes as $node) {
if ($node instanceof DOMElement && $node->namespaceURI === self::XML_NAMESPACE) {
$namespaceChildNodes[] = $node;
}
}
foreach ($namespaceChildNodes as $node) {
switch ($node->localName) {
case 'const':
if (!$node->hasAttributeNS(self::XML_NAMESPACE, 'name')) {
// require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception("Misssing 'name' attribute in 'const' node");
}
$constantName = $node->getAttributeNS(self::XML_NAMESPACE, 'name');
if (!defined($constantName)) {
// require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception("Constant with name '$constantName' was not defined");
}
$constantValue = constant($constantName);
$dom->replaceChild($dom->ownerDocument->createTextNode($constantValue), $node);
break;
default:
// require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception("Unknown node with name '$node->localName' found");
}
}
return (string) simplexml_import_dom($dom);
}
// Search for children
if (count($xmlObject->children()) > 0) {
foreach ($xmlObject->children() as $key => $value) {
if (count($value->children()) > 0 || count($value->children(self::XML_NAMESPACE)) > 0) {
$value = $this->_toArray($value);
} else if (count($value->attributes()) > 0) {
$attributes = $value->attributes();
if (isset($attributes['value'])) {
$value = (string) $attributes['value'];
} else {
$value = $this->_toArray($value);
}
} else {
$value = (string) $value;
}
if (array_key_exists($key, $config)) {
if (!is_array($config[$key]) || !array_key_exists(0, $config[$key])) {
$config[$key] = array($config[$key]);
}
$config[$key][] = $value;
} else {
$config[$key] = $value;
}
}
} else if (!isset($xmlObject['extends']) && !isset($nsAttributes['extends']) && (count($config) === 0)) {
// Object has no children nor attributes and doesn't use the extends
// attribute: it's a string
$config = (string) $xmlObject;
}
return $config;
}
}

View File

@ -0,0 +1,381 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Config
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Yaml.php 24092 2011-05-31 02:43:28Z adamlundrigan $
*/
/**
* @see Zend_Config
*/
// require_once 'Zend/Config.php';
/**
* YAML Adapter for Zend_Config
*
* @category Zend
* @package Zend_Config
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Config_Yaml extends Zend_Config
{
/**
* Attribute name that indicates what section a config extends from
*/
const EXTENDS_NAME = "_extends";
/**
* Whether to skip extends or not
*
* @var boolean
*/
protected $_skipExtends = false;
/**
* What to call when we need to decode some YAML?
*
* @var callable
*/
protected $_yamlDecoder = array(__CLASS__, 'decode');
/**
* Whether or not to ignore constants in parsed YAML
* @var bool
*/
protected static $_ignoreConstants = false;
/**
* Indicate whether parser should ignore constants or not
*
* @param bool $flag
* @return void
*/
public static function setIgnoreConstants($flag)
{
self::$_ignoreConstants = (bool) $flag;
}
/**
* Whether parser should ignore constants or not
*
* @return bool
*/
public static function ignoreConstants()
{
return self::$_ignoreConstants;
}
/**
* Get callback for decoding YAML
*
* @return callable
*/
public function getYamlDecoder()
{
return $this->_yamlDecoder;
}
/**
* Set callback for decoding YAML
*
* @param callable $yamlDecoder the decoder to set
* @return Zend_Config_Yaml
*/
public function setYamlDecoder($yamlDecoder)
{
if (!is_callable($yamlDecoder)) {
// require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception('Invalid parameter to setYamlDecoder() - must be callable');
}
$this->_yamlDecoder = $yamlDecoder;
return $this;
}
/**
* Loads the section $section from the config file encoded as YAML
*
* Sections are defined as properties of the main object
*
* In order to extend another section, a section defines the "_extends"
* property having a value of the section name from which the extending
* section inherits values.
*
* Note that the keys in $section will override any keys of the same
* name in the sections that have been included via "_extends".
*
* Options may include:
* - allow_modifications: whether or not the config object is mutable
* - skip_extends: whether or not to skip processing of parent configuration
* - yaml_decoder: a callback to use to decode the Yaml source
*
* @param string $yaml YAML file to process
* @param mixed $section Section to process
* @param array|boolean $options
*/
public function __construct($yaml, $section = null, $options = false)
{
if (empty($yaml)) {
// require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception('Filename is not set');
}
$ignoreConstants = $staticIgnoreConstants = self::ignoreConstants();
$allowModifications = false;
if (is_bool($options)) {
$allowModifications = $options;
} elseif (is_array($options)) {
foreach ($options as $key => $value) {
switch (strtolower($key)) {
case 'allow_modifications':
case 'allowmodifications':
$allowModifications = (bool) $value;
break;
case 'skip_extends':
case 'skipextends':
$this->_skipExtends = (bool) $value;
break;
case 'ignore_constants':
case 'ignoreconstants':
$ignoreConstants = (bool) $value;
break;
case 'yaml_decoder':
case 'yamldecoder':
$this->setYamlDecoder($value);
break;
default:
break;
}
}
}
// Suppress warnings and errors while loading file
set_error_handler(array($this, '_loadFileErrorHandler'));
$yaml = file_get_contents($yaml);
restore_error_handler();
// Check if there was a error while loading file
if ($this->_loadFileErrorStr !== null) {
// require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception($this->_loadFileErrorStr);
}
// Override static value for ignore_constants if provided in $options
self::setIgnoreConstants($ignoreConstants);
// Parse YAML
$config = call_user_func($this->getYamlDecoder(), $yaml);
// Reset original static state of ignore_constants
self::setIgnoreConstants($staticIgnoreConstants);
if (null === $config) {
// decode failed
// require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception("Error parsing YAML data");
}
if (null === $section) {
$dataArray = array();
foreach ($config as $sectionName => $sectionData) {
$dataArray[$sectionName] = $this->_processExtends($config, $sectionName);
}
parent::__construct($dataArray, $allowModifications);
} elseif (is_array($section)) {
$dataArray = array();
foreach ($section as $sectionName) {
if (!isset($config[$sectionName])) {
// require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception(sprintf('Section "%s" cannot be found', $section));
}
$dataArray = array_merge($this->_processExtends($config, $sectionName), $dataArray);
}
parent::__construct($dataArray, $allowModifications);
} else {
if (!isset($config[$section])) {
// require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception(sprintf('Section "%s" cannot be found', $section));
}
$dataArray = $this->_processExtends($config, $section);
if (!is_array($dataArray)) {
// Section in the yaml data contains just one top level string
$dataArray = array($section => $dataArray);
}
parent::__construct($dataArray, $allowModifications);
}
$this->_loadedSection = $section;
}
/**
* Helper function to process each element in the section and handle
* the "_extends" inheritance attribute.
*
* @param array $data Data array to process
* @param string $section Section to process
* @param array $config Configuration which was parsed yet
* @return array
* @throws Zend_Config_Exception When $section cannot be found
*/
protected function _processExtends(array $data, $section, array $config = array())
{
if (!isset($data[$section])) {
// require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception(sprintf('Section "%s" cannot be found', $section));
}
$thisSection = $data[$section];
if (is_array($thisSection) && isset($thisSection[self::EXTENDS_NAME])) {
$this->_assertValidExtend($section, $thisSection[self::EXTENDS_NAME]);
if (!$this->_skipExtends) {
$config = $this->_processExtends($data, $thisSection[self::EXTENDS_NAME], $config);
}
unset($thisSection[self::EXTENDS_NAME]);
}
$config = $this->_arrayMergeRecursive($config, $thisSection);
return $config;
}
/**
* Very dumb YAML parser
*
* Until we have Zend_Yaml...
*
* @param string $yaml YAML source
* @return array Decoded data
*/
public static function decode($yaml)
{
$lines = explode("\n", $yaml);
reset($lines);
return self::_decodeYaml(0, $lines);
}
/**
* Service function to decode YAML
*
* @param int $currentIndent Current indent level
* @param array $lines YAML lines
* @return array|string
*/
protected static function _decodeYaml($currentIndent, &$lines)
{
$config = array();
$inIndent = false;
while (list($n, $line) = each($lines)) {
$lineno = $n + 1;
$line = rtrim(preg_replace("/#.*$/", "", $line));
if (strlen($line) == 0) {
continue;
}
$indent = strspn($line, " ");
// line without the spaces
$line = trim($line);
if (strlen($line) == 0) {
continue;
}
if ($indent < $currentIndent) {
// this level is done
prev($lines);
return $config;
}
if (!$inIndent) {
$currentIndent = $indent;
$inIndent = true;
}
if (preg_match("/(\w+):\s*(.*)/", $line, $m)) {
// key: value
if (strlen($m[2])) {
// simple key: value
$value = rtrim(preg_replace("/#.*$/", "", $m[2]));
// Check for booleans and constants
if (preg_match('/^(t(rue)?|on|y(es)?)$/i', $value)) {
$value = true;
} elseif (preg_match('/^(f(alse)?|off|n(o)?)$/i', $value)) {
$value = false;
} elseif (!self::$_ignoreConstants) {
// test for constants
$value = self::_replaceConstants($value);
}
} else {
// key: and then values on new lines
$value = self::_decodeYaml($currentIndent + 1, $lines);
if (is_array($value) && !count($value)) {
$value = "";
}
}
$config[$m[1]] = $value;
} elseif ($line[0] == "-") {
// item in the list:
// - FOO
if (strlen($line) > 2) {
$config[] = substr($line, 2);
} else {
$config[] = self::_decodeYaml($currentIndent + 1, $lines);
}
} else {
// require_once 'Zend/Config/Exception.php';
throw new Zend_Config_Exception(sprintf(
'Error parsing YAML at line %d - unsupported syntax: "%s"',
$lineno, $line
));
}
}
return $config;
}
/**
* Replace any constants referenced in a string with their values
*
* @param string $value
* @return string
*/
protected static function _replaceConstants($value)
{
foreach (self::_getConstants() as $constant) {
if (strstr($value, $constant)) {
$value = str_replace($constant, constant($constant), $value);
}
}
return $value;
}
/**
* Get (reverse) sorted list of defined constant names
*
* @return array
*/
protected static function _getConstants()
{
$constants = array_keys(get_defined_constants());
rsort($constants, SORT_STRING);
return $constants;
}
}

View File

@ -0,0 +1,286 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Db.php 24417 2011-08-28 10:15:47Z padraic $
*/
/**
* Class for connecting to SQL databases and performing common operations.
*
* @category Zend
* @package Zend_Db
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db
{
/**
* Use the PROFILER constant in the config of a Zend_Db_Adapter.
*/
const PROFILER = 'profiler';
/**
* Use the CASE_FOLDING constant in the config of a Zend_Db_Adapter.
*/
const CASE_FOLDING = 'caseFolding';
/**
* Use the FETCH_MODE constant in the config of a Zend_Db_Adapter.
*/
const FETCH_MODE = 'fetchMode';
/**
* Use the AUTO_QUOTE_IDENTIFIERS constant in the config of a Zend_Db_Adapter.
*/
const AUTO_QUOTE_IDENTIFIERS = 'autoQuoteIdentifiers';
/**
* Use the ALLOW_SERIALIZATION constant in the config of a Zend_Db_Adapter.
*/
const ALLOW_SERIALIZATION = 'allowSerialization';
/**
* Use the AUTO_RECONNECT_ON_UNSERIALIZE constant in the config of a Zend_Db_Adapter.
*/
const AUTO_RECONNECT_ON_UNSERIALIZE = 'autoReconnectOnUnserialize';
/**
* Use the INT_TYPE, BIGINT_TYPE, and FLOAT_TYPE with the quote() method.
*/
const INT_TYPE = 0;
const BIGINT_TYPE = 1;
const FLOAT_TYPE = 2;
/**
* PDO constant values discovered by this script result:
*
* $list = array(
* 'PARAM_BOOL', 'PARAM_NULL', 'PARAM_INT', 'PARAM_STR', 'PARAM_LOB',
* 'PARAM_STMT', 'PARAM_INPUT_OUTPUT', 'FETCH_LAZY', 'FETCH_ASSOC',
* 'FETCH_NUM', 'FETCH_BOTH', 'FETCH_OBJ', 'FETCH_BOUND',
* 'FETCH_COLUMN', 'FETCH_CLASS', 'FETCH_INTO', 'FETCH_FUNC',
* 'FETCH_GROUP', 'FETCH_UNIQUE', 'FETCH_CLASSTYPE', 'FETCH_SERIALIZE',
* 'FETCH_NAMED', 'ATTR_AUTOCOMMIT', 'ATTR_PREFETCH', 'ATTR_TIMEOUT',
* 'ATTR_ERRMODE', 'ATTR_SERVER_VERSION', 'ATTR_CLIENT_VERSION',
* 'ATTR_SERVER_INFO', 'ATTR_CONNECTION_STATUS', 'ATTR_CASE',
* 'ATTR_CURSOR_NAME', 'ATTR_CURSOR', 'ATTR_ORACLE_NULLS',
* 'ATTR_PERSISTENT', 'ATTR_STATEMENT_CLASS', 'ATTR_FETCH_TABLE_NAMES',
* 'ATTR_FETCH_CATALOG_NAMES', 'ATTR_DRIVER_NAME',
* 'ATTR_STRINGIFY_FETCHES', 'ATTR_MAX_COLUMN_LEN', 'ERRMODE_SILENT',
* 'ERRMODE_WARNING', 'ERRMODE_EXCEPTION', 'CASE_NATURAL',
* 'CASE_LOWER', 'CASE_UPPER', 'NULL_NATURAL', 'NULL_EMPTY_STRING',
* 'NULL_TO_STRING', 'ERR_NONE', 'FETCH_ORI_NEXT',
* 'FETCH_ORI_PRIOR', 'FETCH_ORI_FIRST', 'FETCH_ORI_LAST',
* 'FETCH_ORI_ABS', 'FETCH_ORI_REL', 'CURSOR_FWDONLY', 'CURSOR_SCROLL',
* 'ERR_CANT_MAP', 'ERR_SYNTAX', 'ERR_CONSTRAINT', 'ERR_NOT_FOUND',
* 'ERR_ALREADY_EXISTS', 'ERR_NOT_IMPLEMENTED', 'ERR_MISMATCH',
* 'ERR_TRUNCATED', 'ERR_DISCONNECTED', 'ERR_NO_PERM',
* );
*
* $const = array();
* foreach ($list as $name) {
* $const[$name] = constant("PDO::$name");
* }
* var_export($const);
*/
const ATTR_AUTOCOMMIT = 0;
const ATTR_CASE = 8;
const ATTR_CLIENT_VERSION = 5;
const ATTR_CONNECTION_STATUS = 7;
const ATTR_CURSOR = 10;
const ATTR_CURSOR_NAME = 9;
const ATTR_DRIVER_NAME = 16;
const ATTR_ERRMODE = 3;
const ATTR_FETCH_CATALOG_NAMES = 15;
const ATTR_FETCH_TABLE_NAMES = 14;
const ATTR_MAX_COLUMN_LEN = 18;
const ATTR_ORACLE_NULLS = 11;
const ATTR_PERSISTENT = 12;
const ATTR_PREFETCH = 1;
const ATTR_SERVER_INFO = 6;
const ATTR_SERVER_VERSION = 4;
const ATTR_STATEMENT_CLASS = 13;
const ATTR_STRINGIFY_FETCHES = 17;
const ATTR_TIMEOUT = 2;
const CASE_LOWER = 2;
const CASE_NATURAL = 0;
const CASE_UPPER = 1;
const CURSOR_FWDONLY = 0;
const CURSOR_SCROLL = 1;
const ERR_ALREADY_EXISTS = NULL;
const ERR_CANT_MAP = NULL;
const ERR_CONSTRAINT = NULL;
const ERR_DISCONNECTED = NULL;
const ERR_MISMATCH = NULL;
const ERR_NO_PERM = NULL;
const ERR_NONE = '00000';
const ERR_NOT_FOUND = NULL;
const ERR_NOT_IMPLEMENTED = NULL;
const ERR_SYNTAX = NULL;
const ERR_TRUNCATED = NULL;
const ERRMODE_EXCEPTION = 2;
const ERRMODE_SILENT = 0;
const ERRMODE_WARNING = 1;
const FETCH_ASSOC = 2;
const FETCH_BOTH = 4;
const FETCH_BOUND = 6;
const FETCH_CLASS = 8;
const FETCH_CLASSTYPE = 262144;
const FETCH_COLUMN = 7;
const FETCH_FUNC = 10;
const FETCH_GROUP = 65536;
const FETCH_INTO = 9;
const FETCH_LAZY = 1;
const FETCH_NAMED = 11;
const FETCH_NUM = 3;
const FETCH_OBJ = 5;
const FETCH_ORI_ABS = 4;
const FETCH_ORI_FIRST = 2;
const FETCH_ORI_LAST = 3;
const FETCH_ORI_NEXT = 0;
const FETCH_ORI_PRIOR = 1;
const FETCH_ORI_REL = 5;
const FETCH_SERIALIZE = 524288;
const FETCH_UNIQUE = 196608;
const NULL_EMPTY_STRING = 1;
const NULL_NATURAL = 0;
const NULL_TO_STRING = NULL;
const PARAM_BOOL = 5;
const PARAM_INPUT_OUTPUT = -2147483648;
const PARAM_INT = 1;
const PARAM_LOB = 3;
const PARAM_NULL = 0;
const PARAM_STMT = 4;
const PARAM_STR = 2;
/**
* Factory for Zend_Db_Adapter_Abstract classes.
*
* First argument may be a string containing the base of the adapter class
* name, e.g. 'Mysqli' corresponds to class Zend_Db_Adapter_Mysqli. This
* name is currently case-insensitive, but is not ideal to rely on this behavior.
* If your class is named 'My_Company_Pdo_Mysql', where 'My_Company' is the namespace
* and 'Pdo_Mysql' is the adapter name, it is best to use the name exactly as it
* is defined in the class. This will ensure proper use of the factory API.
*
* First argument may alternatively be an object of type Zend_Config.
* The adapter class base name is read from the 'adapter' property.
* The adapter config parameters are read from the 'params' property.
*
* Second argument is optional and may be an associative array of key-value
* pairs. This is used as the argument to the adapter constructor.
*
* If the first argument is of type Zend_Config, it is assumed to contain
* all parameters, and the second argument is ignored.
*
* @param mixed $adapter String name of base adapter class, or Zend_Config object.
* @param mixed $config OPTIONAL; an array or Zend_Config object with adapter parameters.
* @return Zend_Db_Adapter_Abstract
* @throws Zend_Db_Exception
*/
public static function factory($adapter, $config = array())
{
if ($config instanceof Zend_Config) {
$config = $config->toArray();
}
/*
* Convert Zend_Config argument to plain string
* adapter name and separate config object.
*/
if ($adapter instanceof Zend_Config) {
if (isset($adapter->params)) {
$config = $adapter->params->toArray();
}
if (isset($adapter->adapter)) {
$adapter = (string) $adapter->adapter;
} else {
$adapter = null;
}
}
/*
* Verify that adapter parameters are in an array.
*/
if (!is_array($config)) {
/**
* @see Zend_Db_Exception
*/
// require_once 'Zend/Db/Exception.php';
throw new Zend_Db_Exception('Adapter parameters must be in an array or a Zend_Config object');
}
/*
* Verify that an adapter name has been specified.
*/
if (!is_string($adapter) || empty($adapter)) {
/**
* @see Zend_Db_Exception
*/
// require_once 'Zend/Db/Exception.php';
throw new Zend_Db_Exception('Adapter name must be specified in a string');
}
/*
* Form full adapter class name
*/
$adapterNamespace = 'Zend_Db_Adapter';
if (isset($config['adapterNamespace'])) {
if ($config['adapterNamespace'] != '') {
$adapterNamespace = $config['adapterNamespace'];
}
unset($config['adapterNamespace']);
}
// Adapter no longer normalized- see http://framework.zend.com/issues/browse/ZF-5606
$adapterName = $adapterNamespace . '_';
$adapterName .= str_replace(' ', '_', ucwords(str_replace('_', ' ', strtolower($adapter))));
/*
* Load the adapter class. This throws an exception
* if the specified class cannot be loaded.
*/
if (!class_exists($adapterName)) {
// require_once 'Zend/Loader.php';
Zend_Loader::loadClass($adapterName);
}
/*
* Create an instance of the adapter class.
* Pass the config to the adapter class constructor.
*/
$dbAdapter = new $adapterName($config);
/*
* Verify that the object created is a descendent of the abstract adapter type.
*/
if (! $dbAdapter instanceof Zend_Db_Adapter_Abstract) {
/**
* @see Zend_Db_Exception
*/
// require_once 'Zend/Db/Exception.php';
throw new Zend_Db_Exception("Adapter class '$adapterName' does not extend Zend_Db_Adapter_Abstract");
}
return $dbAdapter;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,840 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Adapter
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Db2.php 23775 2011-03-01 17:25:24Z ralph $
*
*/
/**
* @see Zend_Db
*/
// require_once 'Zend/Db.php';
/**
* @see Zend_Db_Adapter_Abstract
*/
// require_once 'Zend/Db/Adapter/Abstract.php';
/**
* @see Zend_Db_Statement_Db2
*/
// require_once 'Zend/Db/Statement/Db2.php';
/**
* @package Zend_Db
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Adapter_Db2 extends Zend_Db_Adapter_Abstract
{
/**
* User-provided configuration.
*
* Basic keys are:
*
* username => (string) Connect to the database as this username.
* password => (string) Password associated with the username.
* host => (string) What host to connect to (default 127.0.0.1)
* dbname => (string) The name of the database to user
* protocol => (string) Protocol to use, defaults to "TCPIP"
* port => (integer) Port number to use for TCP/IP if protocol is "TCPIP"
* persistent => (boolean) Set TRUE to use a persistent connection (db2_pconnect)
* os => (string) This should be set to 'i5' if the db is on an os400/i5
* schema => (string) The default schema the connection should use
*
* @var array
*/
protected $_config = array(
'dbname' => null,
'username' => null,
'password' => null,
'host' => 'localhost',
'port' => '50000',
'protocol' => 'TCPIP',
'persistent' => false,
'os' => null,
'schema' => null
);
/**
* Execution mode
*
* @var int execution flag (DB2_AUTOCOMMIT_ON or DB2_AUTOCOMMIT_OFF)
*/
protected $_execute_mode = DB2_AUTOCOMMIT_ON;
/**
* Default class name for a DB statement.
*
* @var string
*/
protected $_defaultStmtClass = 'Zend_Db_Statement_Db2';
protected $_isI5 = false;
/**
* Keys are UPPERCASE SQL datatypes or the constants
* Zend_Db::INT_TYPE, Zend_Db::BIGINT_TYPE, or Zend_Db::FLOAT_TYPE.
*
* Values are:
* 0 = 32-bit integer
* 1 = 64-bit integer
* 2 = float or decimal
*
* @var array Associative array of datatypes to values 0, 1, or 2.
*/
protected $_numericDataTypes = array(
Zend_Db::INT_TYPE => Zend_Db::INT_TYPE,
Zend_Db::BIGINT_TYPE => Zend_Db::BIGINT_TYPE,
Zend_Db::FLOAT_TYPE => Zend_Db::FLOAT_TYPE,
'INTEGER' => Zend_Db::INT_TYPE,
'SMALLINT' => Zend_Db::INT_TYPE,
'BIGINT' => Zend_Db::BIGINT_TYPE,
'DECIMAL' => Zend_Db::FLOAT_TYPE,
'NUMERIC' => Zend_Db::FLOAT_TYPE
);
/**
* Creates a connection resource.
*
* @return void
*/
protected function _connect()
{
if (is_resource($this->_connection)) {
// connection already exists
return;
}
if (!extension_loaded('ibm_db2')) {
/**
* @see Zend_Db_Adapter_Db2_Exception
*/
// require_once 'Zend/Db/Adapter/Db2/Exception.php';
throw new Zend_Db_Adapter_Db2_Exception('The IBM DB2 extension is required for this adapter but the extension is not loaded');
}
$this->_determineI5();
if ($this->_config['persistent']) {
// use persistent connection
$conn_func_name = 'db2_pconnect';
} else {
// use "normal" connection
$conn_func_name = 'db2_connect';
}
if (!isset($this->_config['driver_options']['autocommit'])) {
// set execution mode
$this->_config['driver_options']['autocommit'] = &$this->_execute_mode;
}
if (isset($this->_config['options'][Zend_Db::CASE_FOLDING])) {
$caseAttrMap = array(
Zend_Db::CASE_NATURAL => DB2_CASE_NATURAL,
Zend_Db::CASE_UPPER => DB2_CASE_UPPER,
Zend_Db::CASE_LOWER => DB2_CASE_LOWER
);
$this->_config['driver_options']['DB2_ATTR_CASE'] = $caseAttrMap[$this->_config['options'][Zend_Db::CASE_FOLDING]];
}
if ($this->_isI5 && isset($this->_config['driver_options']['i5_naming'])) {
if ($this->_config['driver_options']['i5_naming']) {
$this->_config['driver_options']['i5_naming'] = DB2_I5_NAMING_ON;
} else {
$this->_config['driver_options']['i5_naming'] = DB2_I5_NAMING_OFF;
}
}
if ($this->_config['host'] !== 'localhost' && !$this->_isI5) {
// if the host isn't localhost, use extended connection params
$dbname = 'DRIVER={IBM DB2 ODBC DRIVER}' .
';DATABASE=' . $this->_config['dbname'] .
';HOSTNAME=' . $this->_config['host'] .
';PORT=' . $this->_config['port'] .
';PROTOCOL=' . $this->_config['protocol'] .
';UID=' . $this->_config['username'] .
';PWD=' . $this->_config['password'] .';';
$this->_connection = $conn_func_name(
$dbname,
null,
null,
$this->_config['driver_options']
);
} else {
// host is localhost, so use standard connection params
$this->_connection = $conn_func_name(
$this->_config['dbname'],
$this->_config['username'],
$this->_config['password'],
$this->_config['driver_options']
);
}
// check the connection
if (!$this->_connection) {
/**
* @see Zend_Db_Adapter_Db2_Exception
*/
// require_once 'Zend/Db/Adapter/Db2/Exception.php';
throw new Zend_Db_Adapter_Db2_Exception(db2_conn_errormsg(), db2_conn_error());
}
}
/**
* Test if a connection is active
*
* @return boolean
*/
public function isConnected()
{
return ((bool) (is_resource($this->_connection)
&& get_resource_type($this->_connection) == 'DB2 Connection'));
}
/**
* Force the connection to close.
*
* @return void
*/
public function closeConnection()
{
if ($this->isConnected()) {
db2_close($this->_connection);
}
$this->_connection = null;
}
/**
* Returns an SQL statement for preparation.
*
* @param string $sql The SQL statement with placeholders.
* @return Zend_Db_Statement_Db2
*/
public function prepare($sql)
{
$this->_connect();
$stmtClass = $this->_defaultStmtClass;
if (!class_exists($stmtClass)) {
// require_once 'Zend/Loader.php';
Zend_Loader::loadClass($stmtClass);
}
$stmt = new $stmtClass($this, $sql);
$stmt->setFetchMode($this->_fetchMode);
return $stmt;
}
/**
* Gets the execution mode
*
* @return int the execution mode (DB2_AUTOCOMMIT_ON or DB2_AUTOCOMMIT_OFF)
*/
public function _getExecuteMode()
{
return $this->_execute_mode;
}
/**
* @param integer $mode
* @return void
*/
public function _setExecuteMode($mode)
{
switch ($mode) {
case DB2_AUTOCOMMIT_OFF:
case DB2_AUTOCOMMIT_ON:
$this->_execute_mode = $mode;
db2_autocommit($this->_connection, $mode);
break;
default:
/**
* @see Zend_Db_Adapter_Db2_Exception
*/
// require_once 'Zend/Db/Adapter/Db2/Exception.php';
throw new Zend_Db_Adapter_Db2_Exception("execution mode not supported");
break;
}
}
/**
* Quote a raw string.
*
* @param string $value Raw string
* @return string Quoted string
*/
protected function _quote($value)
{
if (is_int($value) || is_float($value)) {
return $value;
}
/**
* Use db2_escape_string() if it is present in the IBM DB2 extension.
* But some supported versions of PHP do not include this function,
* so fall back to default quoting in the parent class.
*/
if (function_exists('db2_escape_string')) {
return "'" . db2_escape_string($value) . "'";
}
return parent::_quote($value);
}
/**
* @return string
*/
public function getQuoteIdentifierSymbol()
{
$this->_connect();
$info = db2_server_info($this->_connection);
if ($info) {
$identQuote = $info->IDENTIFIER_QUOTE_CHAR;
} else {
// db2_server_info() does not return result on some i5 OS version
if ($this->_isI5) {
$identQuote ="'";
}
}
return $identQuote;
}
/**
* Returns a list of the tables in the database.
* @param string $schema OPTIONAL
* @return array
*/
public function listTables($schema = null)
{
$this->_connect();
if ($schema === null && $this->_config['schema'] != null) {
$schema = $this->_config['schema'];
}
$tables = array();
if (!$this->_isI5) {
if ($schema) {
$stmt = db2_tables($this->_connection, null, $schema);
} else {
$stmt = db2_tables($this->_connection);
}
while ($row = db2_fetch_assoc($stmt)) {
$tables[] = $row['TABLE_NAME'];
}
} else {
$tables = $this->_i5listTables($schema);
}
return $tables;
}
/**
* Returns the column descriptions for a table.
*
* The return value is an associative array keyed by the column name,
* as returned by the RDBMS.
*
* The value of each array element is an associative array
* with the following keys:
*
* SCHEMA_NAME => string; name of database or schema
* TABLE_NAME => string;
* COLUMN_NAME => string; column name
* COLUMN_POSITION => number; ordinal position of column in table
* DATA_TYPE => string; SQL datatype name of column
* DEFAULT => string; default expression of column, null if none
* NULLABLE => boolean; true if column can have nulls
* LENGTH => number; length of CHAR/VARCHAR
* SCALE => number; scale of NUMERIC/DECIMAL
* PRECISION => number; precision of NUMERIC/DECIMAL
* UNSIGNED => boolean; unsigned property of an integer type
* DB2 not supports UNSIGNED integer.
* PRIMARY => boolean; true if column is part of the primary key
* PRIMARY_POSITION => integer; position of column in primary key
* IDENTITY => integer; true if column is auto-generated with unique values
*
* @param string $tableName
* @param string $schemaName OPTIONAL
* @return array
*/
public function describeTable($tableName, $schemaName = null)
{
// Ensure the connection is made so that _isI5 is set
$this->_connect();
if ($schemaName === null && $this->_config['schema'] != null) {
$schemaName = $this->_config['schema'];
}
if (!$this->_isI5) {
$sql = "SELECT DISTINCT c.tabschema, c.tabname, c.colname, c.colno,
c.typename, c.default, c.nulls, c.length, c.scale,
c.identity, tc.type AS tabconsttype, k.colseq
FROM syscat.columns c
LEFT JOIN (syscat.keycoluse k JOIN syscat.tabconst tc
ON (k.tabschema = tc.tabschema
AND k.tabname = tc.tabname
AND tc.type = 'P'))
ON (c.tabschema = k.tabschema
AND c.tabname = k.tabname
AND c.colname = k.colname)
WHERE "
. $this->quoteInto('UPPER(c.tabname) = UPPER(?)', $tableName);
if ($schemaName) {
$sql .= $this->quoteInto(' AND UPPER(c.tabschema) = UPPER(?)', $schemaName);
}
$sql .= " ORDER BY c.colno";
} else {
// DB2 On I5 specific query
$sql = "SELECT DISTINCT C.TABLE_SCHEMA, C.TABLE_NAME, C.COLUMN_NAME, C.ORDINAL_POSITION,
C.DATA_TYPE, C.COLUMN_DEFAULT, C.NULLS ,C.LENGTH, C.SCALE, LEFT(C.IDENTITY,1),
LEFT(tc.TYPE, 1) AS tabconsttype, k.COLSEQ
FROM QSYS2.SYSCOLUMNS C
LEFT JOIN (QSYS2.syskeycst k JOIN QSYS2.SYSCST tc
ON (k.TABLE_SCHEMA = tc.TABLE_SCHEMA
AND k.TABLE_NAME = tc.TABLE_NAME
AND LEFT(tc.type,1) = 'P'))
ON (C.TABLE_SCHEMA = k.TABLE_SCHEMA
AND C.TABLE_NAME = k.TABLE_NAME
AND C.COLUMN_NAME = k.COLUMN_NAME)
WHERE "
. $this->quoteInto('UPPER(C.TABLE_NAME) = UPPER(?)', $tableName);
if ($schemaName) {
$sql .= $this->quoteInto(' AND UPPER(C.TABLE_SCHEMA) = UPPER(?)', $schemaName);
}
$sql .= " ORDER BY C.ORDINAL_POSITION FOR FETCH ONLY";
}
$desc = array();
$stmt = $this->query($sql);
/**
* To avoid case issues, fetch using FETCH_NUM
*/
$result = $stmt->fetchAll(Zend_Db::FETCH_NUM);
/**
* The ordering of columns is defined by the query so we can map
* to variables to improve readability
*/
$tabschema = 0;
$tabname = 1;
$colname = 2;
$colno = 3;
$typename = 4;
$default = 5;
$nulls = 6;
$length = 7;
$scale = 8;
$identityCol = 9;
$tabconstType = 10;
$colseq = 11;
foreach ($result as $key => $row) {
list ($primary, $primaryPosition, $identity) = array(false, null, false);
if ($row[$tabconstType] == 'P') {
$primary = true;
$primaryPosition = $row[$colseq];
}
/**
* In IBM DB2, an column can be IDENTITY
* even if it is not part of the PRIMARY KEY.
*/
if ($row[$identityCol] == 'Y') {
$identity = true;
}
// only colname needs to be case adjusted
$desc[$this->foldCase($row[$colname])] = array(
'SCHEMA_NAME' => $this->foldCase($row[$tabschema]),
'TABLE_NAME' => $this->foldCase($row[$tabname]),
'COLUMN_NAME' => $this->foldCase($row[$colname]),
'COLUMN_POSITION' => (!$this->_isI5) ? $row[$colno]+1 : $row[$colno],
'DATA_TYPE' => $row[$typename],
'DEFAULT' => $row[$default],
'NULLABLE' => (bool) ($row[$nulls] == 'Y'),
'LENGTH' => $row[$length],
'SCALE' => $row[$scale],
'PRECISION' => ($row[$typename] == 'DECIMAL' ? $row[$length] : 0),
'UNSIGNED' => false,
'PRIMARY' => $primary,
'PRIMARY_POSITION' => $primaryPosition,
'IDENTITY' => $identity
);
}
return $desc;
}
/**
* Return the most recent value from the specified sequence in the database.
* This is supported only on RDBMS brands that support sequences
* (e.g. Oracle, PostgreSQL, DB2). Other RDBMS brands return null.
*
* @param string $sequenceName
* @return string
*/
public function lastSequenceId($sequenceName)
{
$this->_connect();
if (!$this->_isI5) {
$quotedSequenceName = $this->quoteIdentifier($sequenceName, true);
$sql = 'SELECT PREVVAL FOR ' . $quotedSequenceName . ' AS VAL FROM SYSIBM.SYSDUMMY1';
} else {
$quotedSequenceName = $sequenceName;
$sql = 'SELECT PREVVAL FOR ' . $this->quoteIdentifier($sequenceName, true) . ' AS VAL FROM QSYS2.QSQPTABL';
}
$value = $this->fetchOne($sql);
return (string) $value;
}
/**
* Generate a new value from the specified sequence in the database, and return it.
* This is supported only on RDBMS brands that support sequences
* (e.g. Oracle, PostgreSQL, DB2). Other RDBMS brands return null.
*
* @param string $sequenceName
* @return string
*/
public function nextSequenceId($sequenceName)
{
$this->_connect();
$sql = 'SELECT NEXTVAL FOR '.$this->quoteIdentifier($sequenceName, true).' AS VAL FROM SYSIBM.SYSDUMMY1';
$value = $this->fetchOne($sql);
return (string) $value;
}
/**
* Gets the last ID generated automatically by an IDENTITY/AUTOINCREMENT column.
*
* As a convention, on RDBMS brands that support sequences
* (e.g. Oracle, PostgreSQL, DB2), this method forms the name of a sequence
* from the arguments and returns the last id generated by that sequence.
* On RDBMS brands that support IDENTITY/AUTOINCREMENT columns, this method
* returns the last value generated for such a column, and the table name
* argument is disregarded.
*
* The IDENTITY_VAL_LOCAL() function gives the last generated identity value
* in the current process, even if it was for a GENERATED column.
*
* @param string $tableName OPTIONAL
* @param string $primaryKey OPTIONAL
* @param string $idType OPTIONAL used for i5 platform to define sequence/idenity unique value
* @return string
*/
public function lastInsertId($tableName = null, $primaryKey = null, $idType = null)
{
$this->_connect();
if ($this->_isI5) {
return (string) $this->_i5LastInsertId($tableName, $idType);
}
if ($tableName !== null) {
$sequenceName = $tableName;
if ($primaryKey) {
$sequenceName .= "_$primaryKey";
}
$sequenceName .= '_seq';
return $this->lastSequenceId($sequenceName);
}
$sql = 'SELECT IDENTITY_VAL_LOCAL() AS VAL FROM SYSIBM.SYSDUMMY1';
$value = $this->fetchOne($sql);
return (string) $value;
}
/**
* Begin a transaction.
*
* @return void
*/
protected function _beginTransaction()
{
$this->_setExecuteMode(DB2_AUTOCOMMIT_OFF);
}
/**
* Commit a transaction.
*
* @return void
*/
protected function _commit()
{
if (!db2_commit($this->_connection)) {
/**
* @see Zend_Db_Adapter_Db2_Exception
*/
// require_once 'Zend/Db/Adapter/Db2/Exception.php';
throw new Zend_Db_Adapter_Db2_Exception(
db2_conn_errormsg($this->_connection),
db2_conn_error($this->_connection));
}
$this->_setExecuteMode(DB2_AUTOCOMMIT_ON);
}
/**
* Rollback a transaction.
*
* @return void
*/
protected function _rollBack()
{
if (!db2_rollback($this->_connection)) {
/**
* @see Zend_Db_Adapter_Db2_Exception
*/
// require_once 'Zend/Db/Adapter/Db2/Exception.php';
throw new Zend_Db_Adapter_Db2_Exception(
db2_conn_errormsg($this->_connection),
db2_conn_error($this->_connection));
}
$this->_setExecuteMode(DB2_AUTOCOMMIT_ON);
}
/**
* Set the fetch mode.
*
* @param integer $mode
* @return void
* @throws Zend_Db_Adapter_Db2_Exception
*/
public function setFetchMode($mode)
{
switch ($mode) {
case Zend_Db::FETCH_NUM: // seq array
case Zend_Db::FETCH_ASSOC: // assoc array
case Zend_Db::FETCH_BOTH: // seq+assoc array
case Zend_Db::FETCH_OBJ: // object
$this->_fetchMode = $mode;
break;
case Zend_Db::FETCH_BOUND: // bound to PHP variable
/**
* @see Zend_Db_Adapter_Db2_Exception
*/
// require_once 'Zend/Db/Adapter/Db2/Exception.php';
throw new Zend_Db_Adapter_Db2_Exception('FETCH_BOUND is not supported yet');
break;
default:
/**
* @see Zend_Db_Adapter_Db2_Exception
*/
// require_once 'Zend/Db/Adapter/Db2/Exception.php';
throw new Zend_Db_Adapter_Db2_Exception("Invalid fetch mode '$mode' specified");
break;
}
}
/**
* Adds an adapter-specific LIMIT clause to the SELECT statement.
*
* @param string $sql
* @param integer $count
* @param integer $offset OPTIONAL
* @return string
*/
public function limit($sql, $count, $offset = 0)
{
$count = intval($count);
if ($count <= 0) {
/**
* @see Zend_Db_Adapter_Db2_Exception
*/
// require_once 'Zend/Db/Adapter/Db2/Exception.php';
throw new Zend_Db_Adapter_Db2_Exception("LIMIT argument count=$count is not valid");
}
$offset = intval($offset);
if ($offset < 0) {
/**
* @see Zend_Db_Adapter_Db2_Exception
*/
// require_once 'Zend/Db/Adapter/Db2/Exception.php';
throw new Zend_Db_Adapter_Db2_Exception("LIMIT argument offset=$offset is not valid");
}
if ($offset == 0) {
$limit_sql = $sql . " FETCH FIRST $count ROWS ONLY";
return $limit_sql;
}
/**
* DB2 does not implement the LIMIT clause as some RDBMS do.
* We have to simulate it with subqueries and ROWNUM.
* Unfortunately because we use the column wildcard "*",
* this puts an extra column into the query result set.
*/
$limit_sql = "SELECT z2.*
FROM (
SELECT ROW_NUMBER() OVER() AS \"ZEND_DB_ROWNUM\", z1.*
FROM (
" . $sql . "
) z1
) z2
WHERE z2.zend_db_rownum BETWEEN " . ($offset+1) . " AND " . ($offset+$count);
return $limit_sql;
}
/**
* Check if the adapter supports real SQL parameters.
*
* @param string $type 'positional' or 'named'
* @return bool
*/
public function supportsParameters($type)
{
if ($type == 'positional') {
return true;
}
// if its 'named' or anything else
return false;
}
/**
* Retrieve server version in PHP style
*
* @return string
*/
public function getServerVersion()
{
$this->_connect();
$server_info = db2_server_info($this->_connection);
if ($server_info !== false) {
$version = $server_info->DBMS_VER;
if ($this->_isI5) {
$version = (int) substr($version, 0, 2) . '.' . (int) substr($version, 2, 2) . '.' . (int) substr($version, 4);
}
return $version;
} else {
return null;
}
}
/**
* Return whether or not this is running on i5
*
* @return bool
*/
public function isI5()
{
if ($this->_isI5 === null) {
$this->_determineI5();
}
return (bool) $this->_isI5;
}
/**
* Check the connection parameters according to verify
* type of used OS
*
* @return void
*/
protected function _determineI5()
{
// first us the compiled flag.
$this->_isI5 = (php_uname('s') == 'OS400') ? true : false;
// if this is set, then us it
if (isset($this->_config['os'])){
if (strtolower($this->_config['os']) === 'i5') {
$this->_isI5 = true;
} else {
// any other value passed in, its null
$this->_isI5 = false;
}
}
}
/**
* Db2 On I5 specific method
*
* Returns a list of the tables in the database .
* Used only for DB2/400.
*
* @return array
*/
protected function _i5listTables($schema = null)
{
//list of i5 libraries.
$tables = array();
if ($schema) {
$tablesStatement = db2_tables($this->_connection, null, $schema);
while ($rowTables = db2_fetch_assoc($tablesStatement) ) {
if ($rowTables['TABLE_NAME'] !== null) {
$tables[] = $rowTables['TABLE_NAME'];
}
}
} else {
$schemaStatement = db2_tables($this->_connection);
while ($schema = db2_fetch_assoc($schemaStatement)) {
if ($schema['TABLE_SCHEM'] !== null) {
// list of the tables which belongs to the selected library
$tablesStatement = db2_tables($this->_connection, NULL, $schema['TABLE_SCHEM']);
if (is_resource($tablesStatement)) {
while ($rowTables = db2_fetch_assoc($tablesStatement) ) {
if ($rowTables['TABLE_NAME'] !== null) {
$tables[] = $rowTables['TABLE_NAME'];
}
}
}
}
}
}
return $tables;
}
protected function _i5LastInsertId($objectName = null, $idType = null)
{
if ($objectName === null) {
$sql = 'SELECT IDENTITY_VAL_LOCAL() AS VAL FROM QSYS2.QSQPTABL';
$value = $this->fetchOne($sql);
return $value;
}
if (strtoupper($idType) === 'S'){
//check i5_lib option
$sequenceName = $objectName;
return $this->lastSequenceId($sequenceName);
}
//returns last identity value for the specified table
//if (strtoupper($idType) === 'I') {
$tableName = $objectName;
return $this->fetchOne('SELECT IDENTITY_VAL_LOCAL() from ' . $this->quoteIdentifier($tableName));
}
}

View File

@ -0,0 +1,45 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Adapter
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Exception.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* Zend_Db_Adapter_Exception
*/
// require_once 'Zend/Db/Adapter/Exception.php';
/**
* Zend_Db_Adapter_Db2_Exception
*
* @package Zend_Db
* @subpackage Adapter
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Adapter_Db2_Exception extends Zend_Db_Adapter_Exception
{
protected $code = '00000';
protected $message = 'unknown exception';
function __construct($message = 'unknown exception', $code = '00000', Exception $e = null)
{
parent::__construct($message, $code, $e);
}
}

View File

@ -0,0 +1,57 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Adapter
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Exception.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* Zend_Db_Exception
*/
// require_once 'Zend/Db/Exception.php';
/**
* @category Zend
* @package Zend_Db
* @subpackage Adapter
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Adapter_Exception extends Zend_Db_Exception
{
protected $_chainedException = null;
public function __construct($message = '', $code = 0, Exception $e = null)
{
if ($e && (0 === $code)) {
$code = $e->getCode();
}
parent::__construct($message, $code, $e);
}
public function hasChainedException()
{
return ($this->_previous !== null);
}
public function getChainedException()
{
return $this->getPrevious();
}
}

View File

@ -0,0 +1,585 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Adapter
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Mysqli.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Db_Adapter_Abstract
*/
// require_once 'Zend/Db/Adapter/Abstract.php';
/**
* @see Zend_Db_Profiler
*/
// require_once 'Zend/Db/Profiler.php';
/**
* @see Zend_Db_Select
*/
// require_once 'Zend/Db/Select.php';
/**
* @see Zend_Db_Statement_Mysqli
*/
// require_once 'Zend/Db/Statement/Mysqli.php';
/**
* @category Zend
* @package Zend_Db
* @subpackage Adapter
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Adapter_Mysqli extends Zend_Db_Adapter_Abstract
{
/**
* Keys are UPPERCASE SQL datatypes or the constants
* Zend_Db::INT_TYPE, Zend_Db::BIGINT_TYPE, or Zend_Db::FLOAT_TYPE.
*
* Values are:
* 0 = 32-bit integer
* 1 = 64-bit integer
* 2 = float or decimal
*
* @var array Associative array of datatypes to values 0, 1, or 2.
*/
protected $_numericDataTypes = array(
Zend_Db::INT_TYPE => Zend_Db::INT_TYPE,
Zend_Db::BIGINT_TYPE => Zend_Db::BIGINT_TYPE,
Zend_Db::FLOAT_TYPE => Zend_Db::FLOAT_TYPE,
'INT' => Zend_Db::INT_TYPE,
'INTEGER' => Zend_Db::INT_TYPE,
'MEDIUMINT' => Zend_Db::INT_TYPE,
'SMALLINT' => Zend_Db::INT_TYPE,
'TINYINT' => Zend_Db::INT_TYPE,
'BIGINT' => Zend_Db::BIGINT_TYPE,
'SERIAL' => Zend_Db::BIGINT_TYPE,
'DEC' => Zend_Db::FLOAT_TYPE,
'DECIMAL' => Zend_Db::FLOAT_TYPE,
'DOUBLE' => Zend_Db::FLOAT_TYPE,
'DOUBLE PRECISION' => Zend_Db::FLOAT_TYPE,
'FIXED' => Zend_Db::FLOAT_TYPE,
'FLOAT' => Zend_Db::FLOAT_TYPE
);
/**
* @var Zend_Db_Statement_Mysqli
*/
protected $_stmt = null;
/**
* Default class name for a DB statement.
*
* @var string
*/
protected $_defaultStmtClass = 'Zend_Db_Statement_Mysqli';
/**
* Quote a raw string.
*
* @param mixed $value Raw string
*
* @return string Quoted string
*/
protected function _quote($value)
{
if (is_int($value) || is_float($value)) {
return $value;
}
$this->_connect();
return "'" . $this->_connection->real_escape_string($value) . "'";
}
/**
* Returns the symbol the adapter uses for delimiting identifiers.
*
* @return string
*/
public function getQuoteIdentifierSymbol()
{
return "`";
}
/**
* Returns a list of the tables in the database.
*
* @return array
*/
public function listTables()
{
$result = array();
// Use mysqli extension API, because SHOW doesn't work
// well as a prepared statement on MySQL 4.1.
$sql = 'SHOW TABLES';
if ($queryResult = $this->getConnection()->query($sql)) {
while ($row = $queryResult->fetch_row()) {
$result[] = $row[0];
}
$queryResult->close();
} else {
/**
* @see Zend_Db_Adapter_Mysqli_Exception
*/
// require_once 'Zend/Db/Adapter/Mysqli/Exception.php';
throw new Zend_Db_Adapter_Mysqli_Exception($this->getConnection()->error);
}
return $result;
}
/**
* Returns the column descriptions for a table.
*
* The return value is an associative array keyed by the column name,
* as returned by the RDBMS.
*
* The value of each array element is an associative array
* with the following keys:
*
* SCHEMA_NAME => string; name of database or schema
* TABLE_NAME => string;
* COLUMN_NAME => string; column name
* COLUMN_POSITION => number; ordinal position of column in table
* DATA_TYPE => string; SQL datatype name of column
* DEFAULT => string; default expression of column, null if none
* NULLABLE => boolean; true if column can have nulls
* LENGTH => number; length of CHAR/VARCHAR
* SCALE => number; scale of NUMERIC/DECIMAL
* PRECISION => number; precision of NUMERIC/DECIMAL
* UNSIGNED => boolean; unsigned property of an integer type
* PRIMARY => boolean; true if column is part of the primary key
* PRIMARY_POSITION => integer; position of column in primary key
* IDENTITY => integer; true if column is auto-generated with unique values
*
* @param string $tableName
* @param string $schemaName OPTIONAL
* @return array
*/
public function describeTable($tableName, $schemaName = null)
{
/**
* @todo use INFORMATION_SCHEMA someday when
* MySQL's implementation isn't too slow.
*/
if ($schemaName) {
$sql = 'DESCRIBE ' . $this->quoteIdentifier("$schemaName.$tableName", true);
} else {
$sql = 'DESCRIBE ' . $this->quoteIdentifier($tableName, true);
}
/**
* Use mysqli extension API, because DESCRIBE doesn't work
* well as a prepared statement on MySQL 4.1.
*/
if ($queryResult = $this->getConnection()->query($sql)) {
while ($row = $queryResult->fetch_assoc()) {
$result[] = $row;
}
$queryResult->close();
} else {
/**
* @see Zend_Db_Adapter_Mysqli_Exception
*/
// require_once 'Zend/Db/Adapter/Mysqli/Exception.php';
throw new Zend_Db_Adapter_Mysqli_Exception($this->getConnection()->error);
}
$desc = array();
$row_defaults = array(
'Length' => null,
'Scale' => null,
'Precision' => null,
'Unsigned' => null,
'Primary' => false,
'PrimaryPosition' => null,
'Identity' => false
);
$i = 1;
$p = 1;
foreach ($result as $key => $row) {
$row = array_merge($row_defaults, $row);
if (preg_match('/unsigned/', $row['Type'])) {
$row['Unsigned'] = true;
}
if (preg_match('/^((?:var)?char)\((\d+)\)/', $row['Type'], $matches)) {
$row['Type'] = $matches[1];
$row['Length'] = $matches[2];
} else if (preg_match('/^decimal\((\d+),(\d+)\)/', $row['Type'], $matches)) {
$row['Type'] = 'decimal';
$row['Precision'] = $matches[1];
$row['Scale'] = $matches[2];
} else if (preg_match('/^float\((\d+),(\d+)\)/', $row['Type'], $matches)) {
$row['Type'] = 'float';
$row['Precision'] = $matches[1];
$row['Scale'] = $matches[2];
} else if (preg_match('/^((?:big|medium|small|tiny)?int)\((\d+)\)/', $row['Type'], $matches)) {
$row['Type'] = $matches[1];
/**
* The optional argument of a MySQL int type is not precision
* or length; it is only a hint for display width.
*/
}
if (strtoupper($row['Key']) == 'PRI') {
$row['Primary'] = true;
$row['PrimaryPosition'] = $p;
if ($row['Extra'] == 'auto_increment') {
$row['Identity'] = true;
} else {
$row['Identity'] = false;
}
++$p;
}
$desc[$this->foldCase($row['Field'])] = array(
'SCHEMA_NAME' => null, // @todo
'TABLE_NAME' => $this->foldCase($tableName),
'COLUMN_NAME' => $this->foldCase($row['Field']),
'COLUMN_POSITION' => $i,
'DATA_TYPE' => $row['Type'],
'DEFAULT' => $row['Default'],
'NULLABLE' => (bool) ($row['Null'] == 'YES'),
'LENGTH' => $row['Length'],
'SCALE' => $row['Scale'],
'PRECISION' => $row['Precision'],
'UNSIGNED' => $row['Unsigned'],
'PRIMARY' => $row['Primary'],
'PRIMARY_POSITION' => $row['PrimaryPosition'],
'IDENTITY' => $row['Identity']
);
++$i;
}
return $desc;
}
/**
* Creates a connection to the database.
*
* @return void
* @throws Zend_Db_Adapter_Mysqli_Exception
*/
protected function _connect()
{
if ($this->_connection) {
return;
}
if (!extension_loaded('mysqli')) {
/**
* @see Zend_Db_Adapter_Mysqli_Exception
*/
// require_once 'Zend/Db/Adapter/Mysqli/Exception.php';
throw new Zend_Db_Adapter_Mysqli_Exception('The Mysqli extension is required for this adapter but the extension is not loaded');
}
if (isset($this->_config['port'])) {
$port = (integer) $this->_config['port'];
} else {
$port = null;
}
$this->_connection = mysqli_init();
$enable_ssl = false;
$ssl_options = array (
'ssl_ca' => null,
'ssl_ca_path' => null,
'ssl_cert' => null,
'ssl_cipher' => null,
'ssl_key' => null,
);
if(!empty($this->_config['driver_options'])) {
foreach($this->_config['driver_options'] as $option=>$value) {
if(array_key_exists($option, $ssl_options)) {
$ssl_options[$option] = $value;
$enable_ssl = true;
} elseif(is_string($option)) {
// Suppress warnings here
// Ignore it if it's not a valid constant
$option = @constant(strtoupper($option));
if($option === null)
continue;
}
mysqli_options($this->_connection, $option, $value);
}
}
if ($enable_ssl) {
mysqli_ssl_set(
$this->_connection,
$ssl_options['ssl_key'],
$ssl_options['ssl_cert'],
$ssl_options['ssl_ca'],
$ssl_options['ssl_ca_path'],
$ssl_options['ssl_cipher']
);
}
$flags = null;
if ($enable_ssl) {
$flags = MYSQLI_CLIENT_SSL;
if (!empty($this->_config['driver_options']['ssl_no_verify'])
&& defined('MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT')
) {
$flags = MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT;
}
}
// Suppress connection warnings here.
// Throw an exception instead.
$_isConnected = @mysqli_real_connect(
$this->_connection,
$this->_config['host'],
$this->_config['username'],
$this->_config['password'],
$this->_config['dbname'],
$port,
$socket = null,
$enable_ssl ? $flags : null
);
if ($_isConnected === false || mysqli_connect_errno()) {
$this->closeConnection();
/**
* @see Zend_Db_Adapter_Mysqli_Exception
*/
// require_once 'Zend/Db/Adapter/Mysqli/Exception.php';
throw new Zend_Db_Adapter_Mysqli_Exception(mysqli_connect_error());
}
if (!empty($this->_config['charset'])) {
mysqli_set_charset($this->_connection, $this->_config['charset']);
}
}
/**
* Test if a connection is active
*
* @return boolean
*/
public function isConnected()
{
return ((bool) ($this->_connection instanceof mysqli));
}
/**
* Force the connection to close.
*
* @return void
*/
public function closeConnection()
{
if ($this->isConnected()) {
$this->_connection->close();
}
$this->_connection = null;
}
/**
* Prepare a statement and return a PDOStatement-like object.
*
* @param string $sql SQL query
* @return Zend_Db_Statement_Mysqli
*/
public function prepare($sql)
{
$this->_connect();
if ($this->_stmt) {
$this->_stmt->close();
}
$stmtClass = $this->_defaultStmtClass;
if (!class_exists($stmtClass)) {
// require_once 'Zend/Loader.php';
Zend_Loader::loadClass($stmtClass);
}
$stmt = new $stmtClass($this, $sql);
if ($stmt === false) {
return false;
}
$stmt->setFetchMode($this->_fetchMode);
$this->_stmt = $stmt;
return $stmt;
}
/**
* Gets the last ID generated automatically by an IDENTITY/AUTOINCREMENT column.
*
* As a convention, on RDBMS brands that support sequences
* (e.g. Oracle, PostgreSQL, DB2), this method forms the name of a sequence
* from the arguments and returns the last id generated by that sequence.
* On RDBMS brands that support IDENTITY/AUTOINCREMENT columns, this method
* returns the last value generated for such a column, and the table name
* argument is disregarded.
*
* MySQL does not support sequences, so $tableName and $primaryKey are ignored.
*
* @param string $tableName OPTIONAL Name of table.
* @param string $primaryKey OPTIONAL Name of primary key column.
* @return string
* @todo Return value should be int?
*/
public function lastInsertId($tableName = null, $primaryKey = null)
{
$mysqli = $this->_connection;
return (string) $mysqli->insert_id;
}
/**
* Begin a transaction.
*
* @return void
*/
protected function _beginTransaction()
{
$this->_connect();
$this->_connection->autocommit(false);
}
/**
* Commit a transaction.
*
* @return void
*/
protected function _commit()
{
$this->_connect();
$this->_connection->commit();
$this->_connection->autocommit(true);
}
/**
* Roll-back a transaction.
*
* @return void
*/
protected function _rollBack()
{
$this->_connect();
$this->_connection->rollback();
$this->_connection->autocommit(true);
}
/**
* Set the fetch mode.
*
* @param int $mode
* @return void
* @throws Zend_Db_Adapter_Mysqli_Exception
*/
public function setFetchMode($mode)
{
switch ($mode) {
case Zend_Db::FETCH_LAZY:
case Zend_Db::FETCH_ASSOC:
case Zend_Db::FETCH_NUM:
case Zend_Db::FETCH_BOTH:
case Zend_Db::FETCH_NAMED:
case Zend_Db::FETCH_OBJ:
$this->_fetchMode = $mode;
break;
case Zend_Db::FETCH_BOUND: // bound to PHP variable
/**
* @see Zend_Db_Adapter_Mysqli_Exception
*/
// require_once 'Zend/Db/Adapter/Mysqli/Exception.php';
throw new Zend_Db_Adapter_Mysqli_Exception('FETCH_BOUND is not supported yet');
break;
default:
/**
* @see Zend_Db_Adapter_Mysqli_Exception
*/
// require_once 'Zend/Db/Adapter/Mysqli/Exception.php';
throw new Zend_Db_Adapter_Mysqli_Exception("Invalid fetch mode '$mode' specified");
}
}
/**
* Adds an adapter-specific LIMIT clause to the SELECT statement.
*
* @param string $sql
* @param int $count
* @param int $offset OPTIONAL
* @return string
*/
public function limit($sql, $count, $offset = 0)
{
$count = intval($count);
if ($count <= 0) {
/**
* @see Zend_Db_Adapter_Mysqli_Exception
*/
// require_once 'Zend/Db/Adapter/Mysqli/Exception.php';
throw new Zend_Db_Adapter_Mysqli_Exception("LIMIT argument count=$count is not valid");
}
$offset = intval($offset);
if ($offset < 0) {
/**
* @see Zend_Db_Adapter_Mysqli_Exception
*/
// require_once 'Zend/Db/Adapter/Mysqli/Exception.php';
throw new Zend_Db_Adapter_Mysqli_Exception("LIMIT argument offset=$offset is not valid");
}
$sql .= " LIMIT $count";
if ($offset > 0) {
$sql .= " OFFSET $offset";
}
return $sql;
}
/**
* Check if the adapter supports real SQL parameters.
*
* @param string $type 'positional' or 'named'
* @return bool
*/
public function supportsParameters($type)
{
switch ($type) {
case 'positional':
return true;
case 'named':
default:
return false;
}
}
/**
* Retrieve server version in PHP style
*
*@return string
*/
public function getServerVersion()
{
$this->_connect();
$version = $this->_connection->server_version;
$major = (int) ($version / 10000);
$minor = (int) ($version % 10000 / 100);
$revision = (int) ($version % 100);
return $major . '.' . $minor . '.' . $revision;
}
}

View File

@ -0,0 +1,40 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Adapter
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Exception.php 23775 2011-03-01 17:25:24Z ralph $
*
*/
/**
* Zend
*/
// require_once 'Zend/Db/Adapter/Exception.php';
/**
* Zend_Db_Adapter_Mysqli_Exception
*
* @category Zend
* @package Zend_Db
* @subpackage Adapter
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Adapter_Mysqli_Exception extends Zend_Db_Adapter_Exception
{
}

View File

@ -0,0 +1,643 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Adapter
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Oracle.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Db_Adapter_Abstract
*/
// require_once 'Zend/Db/Adapter/Abstract.php';
/**
* @see Zend_Db_Statement_Oracle
*/
// require_once 'Zend/Db/Statement/Oracle.php';
/**
* @category Zend
* @package Zend_Db
* @subpackage Adapter
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Adapter_Oracle extends Zend_Db_Adapter_Abstract
{
/**
* User-provided configuration.
*
* Basic keys are:
*
* username => (string) Connect to the database as this username.
* password => (string) Password associated with the username.
* dbname => Either the name of the local Oracle instance, or the
* name of the entry in tnsnames.ora to which you want to connect.
* persistent => (boolean) Set TRUE to use a persistent connection
* @var array
*/
protected $_config = array(
'dbname' => null,
'username' => null,
'password' => null,
'persistent' => false
);
/**
* Keys are UPPERCASE SQL datatypes or the constants
* Zend_Db::INT_TYPE, Zend_Db::BIGINT_TYPE, or Zend_Db::FLOAT_TYPE.
*
* Values are:
* 0 = 32-bit integer
* 1 = 64-bit integer
* 2 = float or decimal
*
* @var array Associative array of datatypes to values 0, 1, or 2.
*/
protected $_numericDataTypes = array(
Zend_Db::INT_TYPE => Zend_Db::INT_TYPE,
Zend_Db::BIGINT_TYPE => Zend_Db::BIGINT_TYPE,
Zend_Db::FLOAT_TYPE => Zend_Db::FLOAT_TYPE,
'BINARY_DOUBLE' => Zend_Db::FLOAT_TYPE,
'BINARY_FLOAT' => Zend_Db::FLOAT_TYPE,
'NUMBER' => Zend_Db::FLOAT_TYPE,
);
/**
* @var integer
*/
protected $_execute_mode = null;
/**
* Default class name for a DB statement.
*
* @var string
*/
protected $_defaultStmtClass = 'Zend_Db_Statement_Oracle';
/**
* Check if LOB field are returned as string
* instead of OCI-Lob object
*
* @var boolean
*/
protected $_lobAsString = null;
/**
* Creates a connection resource.
*
* @return void
* @throws Zend_Db_Adapter_Oracle_Exception
*/
protected function _connect()
{
if (is_resource($this->_connection)) {
// connection already exists
return;
}
if (!extension_loaded('oci8')) {
/**
* @see Zend_Db_Adapter_Oracle_Exception
*/
// require_once 'Zend/Db/Adapter/Oracle/Exception.php';
throw new Zend_Db_Adapter_Oracle_Exception('The OCI8 extension is required for this adapter but the extension is not loaded');
}
$this->_setExecuteMode(OCI_COMMIT_ON_SUCCESS);
$connectionFuncName = ($this->_config['persistent'] == true) ? 'oci_pconnect' : 'oci_connect';
$this->_connection = @$connectionFuncName(
$this->_config['username'],
$this->_config['password'],
$this->_config['dbname'],
$this->_config['charset']);
// check the connection
if (!$this->_connection) {
/**
* @see Zend_Db_Adapter_Oracle_Exception
*/
// require_once 'Zend/Db/Adapter/Oracle/Exception.php';
throw new Zend_Db_Adapter_Oracle_Exception(oci_error());
}
}
/**
* Test if a connection is active
*
* @return boolean
*/
public function isConnected()
{
return ((bool) (is_resource($this->_connection)
&& (get_resource_type($this->_connection) == 'oci8 connection'
|| get_resource_type($this->_connection) == 'oci8 persistent connection')));
}
/**
* Force the connection to close.
*
* @return void
*/
public function closeConnection()
{
if ($this->isConnected()) {
oci_close($this->_connection);
}
$this->_connection = null;
}
/**
* Activate/deactivate return of LOB as string
*
* @param string $lob_as_string
* @return Zend_Db_Adapter_Oracle
*/
public function setLobAsString($lobAsString)
{
$this->_lobAsString = (bool) $lobAsString;
return $this;
}
/**
* Return whether or not LOB are returned as string
*
* @return boolean
*/
public function getLobAsString()
{
if ($this->_lobAsString === null) {
// if never set by user, we use driver option if it exists otherwise false
if (isset($this->_config['driver_options']) &&
isset($this->_config['driver_options']['lob_as_string'])) {
$this->_lobAsString = (bool) $this->_config['driver_options']['lob_as_string'];
} else {
$this->_lobAsString = false;
}
}
return $this->_lobAsString;
}
/**
* Returns an SQL statement for preparation.
*
* @param string $sql The SQL statement with placeholders.
* @return Zend_Db_Statement_Oracle
*/
public function prepare($sql)
{
$this->_connect();
$stmtClass = $this->_defaultStmtClass;
if (!class_exists($stmtClass)) {
// require_once 'Zend/Loader.php';
Zend_Loader::loadClass($stmtClass);
}
$stmt = new $stmtClass($this, $sql);
if ($stmt instanceof Zend_Db_Statement_Oracle) {
$stmt->setLobAsString($this->getLobAsString());
}
$stmt->setFetchMode($this->_fetchMode);
return $stmt;
}
/**
* Quote a raw string.
*
* @param string $value Raw string
* @return string Quoted string
*/
protected function _quote($value)
{
if (is_int($value) || is_float($value)) {
return $value;
}
$value = str_replace("'", "''", $value);
return "'" . addcslashes($value, "\000\n\r\\\032") . "'";
}
/**
* Quote a table identifier and alias.
*
* @param string|array|Zend_Db_Expr $ident The identifier or expression.
* @param string $alias An alias for the table.
* @param boolean $auto If true, heed the AUTO_QUOTE_IDENTIFIERS config option.
* @return string The quoted identifier and alias.
*/
public function quoteTableAs($ident, $alias = null, $auto = false)
{
// Oracle doesn't allow the 'AS' keyword between the table identifier/expression and alias.
return $this->_quoteIdentifierAs($ident, $alias, $auto, ' ');
}
/**
* Return the most recent value from the specified sequence in the database.
* This is supported only on RDBMS brands that support sequences
* (e.g. Oracle, PostgreSQL, DB2). Other RDBMS brands return null.
*
* @param string $sequenceName
* @return string
*/
public function lastSequenceId($sequenceName)
{
$this->_connect();
$sql = 'SELECT '.$this->quoteIdentifier($sequenceName, true).'.CURRVAL FROM dual';
$value = $this->fetchOne($sql);
return $value;
}
/**
* Generate a new value from the specified sequence in the database, and return it.
* This is supported only on RDBMS brands that support sequences
* (e.g. Oracle, PostgreSQL, DB2). Other RDBMS brands return null.
*
* @param string $sequenceName
* @return string
*/
public function nextSequenceId($sequenceName)
{
$this->_connect();
$sql = 'SELECT '.$this->quoteIdentifier($sequenceName, true).'.NEXTVAL FROM dual';
$value = $this->fetchOne($sql);
return $value;
}
/**
* Gets the last ID generated automatically by an IDENTITY/AUTOINCREMENT column.
*
* As a convention, on RDBMS brands that support sequences
* (e.g. Oracle, PostgreSQL, DB2), this method forms the name of a sequence
* from the arguments and returns the last id generated by that sequence.
* On RDBMS brands that support IDENTITY/AUTOINCREMENT columns, this method
* returns the last value generated for such a column, and the table name
* argument is disregarded.
*
* Oracle does not support IDENTITY columns, so if the sequence is not
* specified, this method returns null.
*
* @param string $tableName OPTIONAL Name of table.
* @param string $primaryKey OPTIONAL Name of primary key column.
* @return string
*/
public function lastInsertId($tableName = null, $primaryKey = null)
{
if ($tableName !== null) {
$sequenceName = $tableName;
if ($primaryKey) {
$sequenceName .= "_$primaryKey";
}
$sequenceName .= '_seq';
return $this->lastSequenceId($sequenceName);
}
// No support for IDENTITY columns; return null
return null;
}
/**
* Returns a list of the tables in the database.
*
* @return array
*/
public function listTables()
{
$this->_connect();
$data = $this->fetchCol('SELECT table_name FROM all_tables');
return $data;
}
/**
* Returns the column descriptions for a table.
*
* The return value is an associative array keyed by the column name,
* as returned by the RDBMS.
*
* The value of each array element is an associative array
* with the following keys:
*
* SCHEMA_NAME => string; name of schema
* TABLE_NAME => string;
* COLUMN_NAME => string; column name
* COLUMN_POSITION => number; ordinal position of column in table
* DATA_TYPE => string; SQL datatype name of column
* DEFAULT => string; default expression of column, null if none
* NULLABLE => boolean; true if column can have nulls
* LENGTH => number; length of CHAR/VARCHAR
* SCALE => number; scale of NUMERIC/DECIMAL
* PRECISION => number; precision of NUMERIC/DECIMAL
* UNSIGNED => boolean; unsigned property of an integer type
* PRIMARY => boolean; true if column is part of the primary key
* PRIMARY_POSITION => integer; position of column in primary key
* IDENTITY => integer; true if column is auto-generated with unique values
*
* @todo Discover integer unsigned property.
*
* @param string $tableName
* @param string $schemaName OPTIONAL
* @return array
*/
public function describeTable($tableName, $schemaName = null)
{
$version = $this->getServerVersion();
if (($version === null) || version_compare($version, '9.0.0', '>=')) {
$sql = "SELECT TC.TABLE_NAME, TC.OWNER, TC.COLUMN_NAME, TC.DATA_TYPE,
TC.DATA_DEFAULT, TC.NULLABLE, TC.COLUMN_ID, TC.DATA_LENGTH,
TC.DATA_SCALE, TC.DATA_PRECISION, C.CONSTRAINT_TYPE, CC.POSITION
FROM ALL_TAB_COLUMNS TC
LEFT JOIN (ALL_CONS_COLUMNS CC JOIN ALL_CONSTRAINTS C
ON (CC.CONSTRAINT_NAME = C.CONSTRAINT_NAME AND CC.TABLE_NAME = C.TABLE_NAME AND CC.OWNER = C.OWNER AND C.CONSTRAINT_TYPE = 'P'))
ON TC.TABLE_NAME = CC.TABLE_NAME AND TC.COLUMN_NAME = CC.COLUMN_NAME
WHERE UPPER(TC.TABLE_NAME) = UPPER(:TBNAME)";
$bind[':TBNAME'] = $tableName;
if ($schemaName) {
$sql .= ' AND UPPER(TC.OWNER) = UPPER(:SCNAME)';
$bind[':SCNAME'] = $schemaName;
}
$sql .= ' ORDER BY TC.COLUMN_ID';
} else {
$subSql="SELECT AC.OWNER, AC.TABLE_NAME, ACC.COLUMN_NAME, AC.CONSTRAINT_TYPE, ACC.POSITION
from ALL_CONSTRAINTS AC, ALL_CONS_COLUMNS ACC
WHERE ACC.CONSTRAINT_NAME = AC.CONSTRAINT_NAME
AND ACC.TABLE_NAME = AC.TABLE_NAME
AND ACC.OWNER = AC.OWNER
AND AC.CONSTRAINT_TYPE = 'P'
AND UPPER(AC.TABLE_NAME) = UPPER(:TBNAME)";
$bind[':TBNAME'] = $tableName;
if ($schemaName) {
$subSql .= ' AND UPPER(ACC.OWNER) = UPPER(:SCNAME)';
$bind[':SCNAME'] = $schemaName;
}
$sql="SELECT TC.TABLE_NAME, TC.OWNER, TC.COLUMN_NAME, TC.DATA_TYPE,
TC.DATA_DEFAULT, TC.NULLABLE, TC.COLUMN_ID, TC.DATA_LENGTH,
TC.DATA_SCALE, TC.DATA_PRECISION, CC.CONSTRAINT_TYPE, CC.POSITION
FROM ALL_TAB_COLUMNS TC, ($subSql) CC
WHERE UPPER(TC.TABLE_NAME) = UPPER(:TBNAME)
AND TC.OWNER = CC.OWNER(+) AND TC.TABLE_NAME = CC.TABLE_NAME(+) AND TC.COLUMN_NAME = CC.COLUMN_NAME(+)";
if ($schemaName) {
$sql .= ' AND UPPER(TC.OWNER) = UPPER(:SCNAME)';
}
$sql .= ' ORDER BY TC.COLUMN_ID';
}
$stmt = $this->query($sql, $bind);
/**
* Use FETCH_NUM so we are not dependent on the CASE attribute of the PDO connection
*/
$result = $stmt->fetchAll(Zend_Db::FETCH_NUM);
$table_name = 0;
$owner = 1;
$column_name = 2;
$data_type = 3;
$data_default = 4;
$nullable = 5;
$column_id = 6;
$data_length = 7;
$data_scale = 8;
$data_precision = 9;
$constraint_type = 10;
$position = 11;
$desc = array();
foreach ($result as $key => $row) {
list ($primary, $primaryPosition, $identity) = array(false, null, false);
if ($row[$constraint_type] == 'P') {
$primary = true;
$primaryPosition = $row[$position];
/**
* Oracle does not support auto-increment keys.
*/
$identity = false;
}
$desc[$this->foldCase($row[$column_name])] = array(
'SCHEMA_NAME' => $this->foldCase($row[$owner]),
'TABLE_NAME' => $this->foldCase($row[$table_name]),
'COLUMN_NAME' => $this->foldCase($row[$column_name]),
'COLUMN_POSITION' => $row[$column_id],
'DATA_TYPE' => $row[$data_type],
'DEFAULT' => $row[$data_default],
'NULLABLE' => (bool) ($row[$nullable] == 'Y'),
'LENGTH' => $row[$data_length],
'SCALE' => $row[$data_scale],
'PRECISION' => $row[$data_precision],
'UNSIGNED' => null, // @todo
'PRIMARY' => $primary,
'PRIMARY_POSITION' => $primaryPosition,
'IDENTITY' => $identity
);
}
return $desc;
}
/**
* Leave autocommit mode and begin a transaction.
*
* @return void
*/
protected function _beginTransaction()
{
$this->_setExecuteMode(OCI_DEFAULT);
}
/**
* Commit a transaction and return to autocommit mode.
*
* @return void
* @throws Zend_Db_Adapter_Oracle_Exception
*/
protected function _commit()
{
if (!oci_commit($this->_connection)) {
/**
* @see Zend_Db_Adapter_Oracle_Exception
*/
// require_once 'Zend/Db/Adapter/Oracle/Exception.php';
throw new Zend_Db_Adapter_Oracle_Exception(oci_error($this->_connection));
}
$this->_setExecuteMode(OCI_COMMIT_ON_SUCCESS);
}
/**
* Roll back a transaction and return to autocommit mode.
*
* @return void
* @throws Zend_Db_Adapter_Oracle_Exception
*/
protected function _rollBack()
{
if (!oci_rollback($this->_connection)) {
/**
* @see Zend_Db_Adapter_Oracle_Exception
*/
// require_once 'Zend/Db/Adapter/Oracle/Exception.php';
throw new Zend_Db_Adapter_Oracle_Exception(oci_error($this->_connection));
}
$this->_setExecuteMode(OCI_COMMIT_ON_SUCCESS);
}
/**
* Set the fetch mode.
*
* @todo Support FETCH_CLASS and FETCH_INTO.
*
* @param integer $mode A fetch mode.
* @return void
* @throws Zend_Db_Adapter_Oracle_Exception
*/
public function setFetchMode($mode)
{
switch ($mode) {
case Zend_Db::FETCH_NUM: // seq array
case Zend_Db::FETCH_ASSOC: // assoc array
case Zend_Db::FETCH_BOTH: // seq+assoc array
case Zend_Db::FETCH_OBJ: // object
$this->_fetchMode = $mode;
break;
case Zend_Db::FETCH_BOUND: // bound to PHP variable
/**
* @see Zend_Db_Adapter_Oracle_Exception
*/
// require_once 'Zend/Db/Adapter/Oracle/Exception.php';
throw new Zend_Db_Adapter_Oracle_Exception('FETCH_BOUND is not supported yet');
break;
default:
/**
* @see Zend_Db_Adapter_Oracle_Exception
*/
// require_once 'Zend/Db/Adapter/Oracle/Exception.php';
throw new Zend_Db_Adapter_Oracle_Exception("Invalid fetch mode '$mode' specified");
break;
}
}
/**
* Adds an adapter-specific LIMIT clause to the SELECT statement.
*
* @param string $sql
* @param integer $count
* @param integer $offset OPTIONAL
* @return string
* @throws Zend_Db_Adapter_Oracle_Exception
*/
public function limit($sql, $count, $offset = 0)
{
$count = intval($count);
if ($count <= 0) {
/**
* @see Zend_Db_Adapter_Oracle_Exception
*/
// require_once 'Zend/Db/Adapter/Oracle/Exception.php';
throw new Zend_Db_Adapter_Oracle_Exception("LIMIT argument count=$count is not valid");
}
$offset = intval($offset);
if ($offset < 0) {
/**
* @see Zend_Db_Adapter_Oracle_Exception
*/
// require_once 'Zend/Db/Adapter/Oracle/Exception.php';
throw new Zend_Db_Adapter_Oracle_Exception("LIMIT argument offset=$offset is not valid");
}
/**
* Oracle does not implement the LIMIT clause as some RDBMS do.
* We have to simulate it with subqueries and ROWNUM.
* Unfortunately because we use the column wildcard "*",
* this puts an extra column into the query result set.
*/
$limit_sql = "SELECT z2.*
FROM (
SELECT z1.*, ROWNUM AS \"zend_db_rownum\"
FROM (
" . $sql . "
) z1
) z2
WHERE z2.\"zend_db_rownum\" BETWEEN " . ($offset+1) . " AND " . ($offset+$count);
return $limit_sql;
}
/**
* @param integer $mode
* @throws Zend_Db_Adapter_Oracle_Exception
*/
private function _setExecuteMode($mode)
{
switch($mode) {
case OCI_COMMIT_ON_SUCCESS:
case OCI_DEFAULT:
case OCI_DESCRIBE_ONLY:
$this->_execute_mode = $mode;
break;
default:
/**
* @see Zend_Db_Adapter_Oracle_Exception
*/
// require_once 'Zend/Db/Adapter/Oracle/Exception.php';
throw new Zend_Db_Adapter_Oracle_Exception("Invalid execution mode '$mode' specified");
break;
}
}
/**
* @return int
*/
public function _getExecuteMode()
{
return $this->_execute_mode;
}
/**
* Check if the adapter supports real SQL parameters.
*
* @param string $type 'positional' or 'named'
* @return bool
*/
public function supportsParameters($type)
{
switch ($type) {
case 'named':
return true;
case 'positional':
default:
return false;
}
}
/**
* Retrieve server version in PHP style
*
* @return string
*/
public function getServerVersion()
{
$this->_connect();
$version = oci_server_version($this->_connection);
if ($version !== false) {
$matches = null;
if (preg_match('/((?:[0-9]{1,2}\.){1,3}[0-9]{1,2})/', $version, $matches)) {
return $matches[1];
} else {
return null;
}
} else {
return null;
}
}
}

View File

@ -0,0 +1,60 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Adapter
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Exception.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* Zend_Db_Adapter_Exception
*/
// require_once 'Zend/Db/Adapter/Exception.php';
/**
* Zend_Db_Adapter_Oracle_Exception
*
* @category Zend
* @package Zend_Db
* @subpackage Adapter
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Adapter_Oracle_Exception extends Zend_Db_Adapter_Exception
{
protected $message = 'Unknown exception';
protected $code = 0;
function __construct($error = null, $code = 0) {
if (is_array($error)) {
if (!isset($error['offset'])) {
$this->message = $error['code'] .' '. $error['message'];
} else {
$this->message = $error['code'] .' '. $error['message']." "
. substr($error['sqltext'], 0, $error['offset'])
. "*"
. substr($error['sqltext'], $error['offset']);
}
$this->code = $error['code'];
} else if (is_string($error)) {
$this->message = $error;
}
if (!$this->code && $code) {
$this->code = $code;
}
}
}

View File

@ -0,0 +1,401 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Adapter
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Abstract.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Db_Adapter_Abstract
*/
// require_once 'Zend/Db/Adapter/Abstract.php';
/**
* @see Zend_Db_Statement_Pdo
*/
// require_once 'Zend/Db/Statement/Pdo.php';
/**
* Class for connecting to SQL databases and performing common operations using PDO.
*
* @category Zend
* @package Zend_Db
* @subpackage Adapter
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
abstract class Zend_Db_Adapter_Pdo_Abstract extends Zend_Db_Adapter_Abstract
{
/**
* Default class name for a DB statement.
*
* @var string
*/
protected $_defaultStmtClass = 'Zend_Db_Statement_Pdo';
/**
* Creates a PDO DSN for the adapter from $this->_config settings.
*
* @return string
*/
protected function _dsn()
{
// baseline of DSN parts
$dsn = $this->_config;
// don't pass the username, password, charset, persistent and driver_options in the DSN
unset($dsn['username']);
unset($dsn['password']);
unset($dsn['options']);
unset($dsn['charset']);
unset($dsn['persistent']);
unset($dsn['driver_options']);
// use all remaining parts in the DSN
foreach ($dsn as $key => $val) {
$dsn[$key] = "$key=$val";
}
return $this->_pdoType . ':' . implode(';', $dsn);
}
/**
* Creates a PDO object and connects to the database.
*
* @return void
* @throws Zend_Db_Adapter_Exception
*/
protected function _connect()
{
// if we already have a PDO object, no need to re-connect.
if ($this->_connection) {
return;
}
// get the dsn first, because some adapters alter the $_pdoType
$dsn = $this->_dsn();
// check for PDO extension
if (!extension_loaded('pdo')) {
/**
* @see Zend_Db_Adapter_Exception
*/
// require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception('The PDO extension is required for this adapter but the extension is not loaded');
}
// check the PDO driver is available
if (!in_array($this->_pdoType, PDO::getAvailableDrivers())) {
/**
* @see Zend_Db_Adapter_Exception
*/
// require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception('The ' . $this->_pdoType . ' driver is not currently installed');
}
// create PDO connection
$q = $this->_profiler->queryStart('connect', Zend_Db_Profiler::CONNECT);
// add the persistence flag if we find it in our config array
if (isset($this->_config['persistent']) && ($this->_config['persistent'] == true)) {
$this->_config['driver_options'][PDO::ATTR_PERSISTENT] = true;
}
try {
$this->_connection = new PDO(
$dsn,
$this->_config['username'],
$this->_config['password'],
$this->_config['driver_options']
);
$this->_profiler->queryEnd($q);
// set the PDO connection to perform case-folding on array keys, or not
$this->_connection->setAttribute(PDO::ATTR_CASE, $this->_caseFolding);
// always use exceptions.
$this->_connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
/**
* @see Zend_Db_Adapter_Exception
*/
// require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception($e->getMessage(), $e->getCode(), $e);
}
}
/**
* Test if a connection is active
*
* @return boolean
*/
public function isConnected()
{
return ((bool) ($this->_connection instanceof PDO));
}
/**
* Force the connection to close.
*
* @return void
*/
public function closeConnection()
{
$this->_connection = null;
}
/**
* Prepares an SQL statement.
*
* @param string $sql The SQL statement with placeholders.
* @param array $bind An array of data to bind to the placeholders.
* @return PDOStatement
*/
public function prepare($sql)
{
$this->_connect();
$stmtClass = $this->_defaultStmtClass;
if (!class_exists($stmtClass)) {
// require_once 'Zend/Loader.php';
Zend_Loader::loadClass($stmtClass);
}
$stmt = new $stmtClass($this, $sql);
$stmt->setFetchMode($this->_fetchMode);
return $stmt;
}
/**
* Gets the last ID generated automatically by an IDENTITY/AUTOINCREMENT column.
*
* As a convention, on RDBMS brands that support sequences
* (e.g. Oracle, PostgreSQL, DB2), this method forms the name of a sequence
* from the arguments and returns the last id generated by that sequence.
* On RDBMS brands that support IDENTITY/AUTOINCREMENT columns, this method
* returns the last value generated for such a column, and the table name
* argument is disregarded.
*
* On RDBMS brands that don't support sequences, $tableName and $primaryKey
* are ignored.
*
* @param string $tableName OPTIONAL Name of table.
* @param string $primaryKey OPTIONAL Name of primary key column.
* @return string
*/
public function lastInsertId($tableName = null, $primaryKey = null)
{
$this->_connect();
return $this->_connection->lastInsertId();
}
/**
* Special handling for PDO query().
* All bind parameter names must begin with ':'
*
* @param string|Zend_Db_Select $sql The SQL statement with placeholders.
* @param array $bind An array of data to bind to the placeholders.
* @return Zend_Db_Statement_Pdo
* @throws Zend_Db_Adapter_Exception To re-throw PDOException.
*/
public function query($sql, $bind = array())
{
if (empty($bind) && $sql instanceof Zend_Db_Select) {
$bind = $sql->getBind();
}
if (is_array($bind)) {
foreach ($bind as $name => $value) {
if (!is_int($name) && !preg_match('/^:/', $name)) {
$newName = ":$name";
unset($bind[$name]);
$bind[$newName] = $value;
}
}
}
try {
return parent::query($sql, $bind);
} catch (PDOException $e) {
/**
* @see Zend_Db_Statement_Exception
*/
// require_once 'Zend/Db/Statement/Exception.php';
throw new Zend_Db_Statement_Exception($e->getMessage(), $e->getCode(), $e);
}
}
/**
* Executes an SQL statement and return the number of affected rows
*
* @param mixed $sql The SQL statement with placeholders.
* May be a string or Zend_Db_Select.
* @return integer Number of rows that were modified
* or deleted by the SQL statement
*/
public function exec($sql)
{
if ($sql instanceof Zend_Db_Select) {
$sql = $sql->assemble();
}
try {
$affected = $this->getConnection()->exec($sql);
if ($affected === false) {
$errorInfo = $this->getConnection()->errorInfo();
/**
* @see Zend_Db_Adapter_Exception
*/
// require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception($errorInfo[2]);
}
return $affected;
} catch (PDOException $e) {
/**
* @see Zend_Db_Adapter_Exception
*/
// require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception($e->getMessage(), $e->getCode(), $e);
}
}
/**
* Quote a raw string.
*
* @param string $value Raw string
* @return string Quoted string
*/
protected function _quote($value)
{
if (is_int($value) || is_float($value)) {
return $value;
}
$this->_connect();
return $this->_connection->quote($value);
}
/**
* Begin a transaction.
*/
protected function _beginTransaction()
{
$this->_connect();
$this->_connection->beginTransaction();
}
/**
* Commit a transaction.
*/
protected function _commit()
{
$this->_connect();
$this->_connection->commit();
}
/**
* Roll-back a transaction.
*/
protected function _rollBack() {
$this->_connect();
$this->_connection->rollBack();
}
/**
* Set the PDO fetch mode.
*
* @todo Support FETCH_CLASS and FETCH_INTO.
*
* @param int $mode A PDO fetch mode.
* @return void
* @throws Zend_Db_Adapter_Exception
*/
public function setFetchMode($mode)
{
//check for PDO extension
if (!extension_loaded('pdo')) {
/**
* @see Zend_Db_Adapter_Exception
*/
// require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception('The PDO extension is required for this adapter but the extension is not loaded');
}
switch ($mode) {
case PDO::FETCH_LAZY:
case PDO::FETCH_ASSOC:
case PDO::FETCH_NUM:
case PDO::FETCH_BOTH:
case PDO::FETCH_NAMED:
case PDO::FETCH_OBJ:
$this->_fetchMode = $mode;
break;
default:
/**
* @see Zend_Db_Adapter_Exception
*/
// require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception("Invalid fetch mode '$mode' specified");
break;
}
}
/**
* Check if the adapter supports real SQL parameters.
*
* @param string $type 'positional' or 'named'
* @return bool
*/
public function supportsParameters($type)
{
switch ($type) {
case 'positional':
case 'named':
default:
return true;
}
}
/**
* Retrieve server version in PHP style
*
* @return string
*/
public function getServerVersion()
{
$this->_connect();
try {
$version = $this->_connection->getAttribute(PDO::ATTR_SERVER_VERSION);
} catch (PDOException $e) {
// In case of the driver doesn't support getting attributes
return null;
}
$matches = null;
if (preg_match('/((?:[0-9]{1,2}\.){1,3}[0-9]{1,2})/', $version, $matches)) {
return $matches[1];
} else {
return null;
}
}
}

View File

@ -0,0 +1,360 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Adapter
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Ibm.php 23775 2011-03-01 17:25:24Z ralph $
*/
/** @see Zend_Db_Adapter_Pdo_Abstract */
// require_once 'Zend/Db/Adapter/Pdo/Abstract.php';
/** @see Zend_Db_Abstract_Pdo_Ibm_Db2 */
// require_once 'Zend/Db/Adapter/Pdo/Ibm/Db2.php';
/** @see Zend_Db_Abstract_Pdo_Ibm_Ids */
// require_once 'Zend/Db/Adapter/Pdo/Ibm/Ids.php';
/** @see Zend_Db_Statement_Pdo_Ibm */
// require_once 'Zend/Db/Statement/Pdo/Ibm.php';
/**
* @category Zend
* @package Zend_Db
* @subpackage Adapter
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Adapter_Pdo_Ibm extends Zend_Db_Adapter_Pdo_Abstract
{
/**
* PDO type.
*
* @var string
*/
protected $_pdoType = 'ibm';
/**
* The IBM data server connected to
*
* @var string
*/
protected $_serverType = null;
/**
* Keys are UPPERCASE SQL datatypes or the constants
* Zend_Db::INT_TYPE, Zend_Db::BIGINT_TYPE, or Zend_Db::FLOAT_TYPE.
*
* Values are:
* 0 = 32-bit integer
* 1 = 64-bit integer
* 2 = float or decimal
*
* @var array Associative array of datatypes to values 0, 1, or 2.
*/
protected $_numericDataTypes = array(
Zend_Db::INT_TYPE => Zend_Db::INT_TYPE,
Zend_Db::BIGINT_TYPE => Zend_Db::BIGINT_TYPE,
Zend_Db::FLOAT_TYPE => Zend_Db::FLOAT_TYPE,
'INTEGER' => Zend_Db::INT_TYPE,
'SMALLINT' => Zend_Db::INT_TYPE,
'BIGINT' => Zend_Db::BIGINT_TYPE,
'DECIMAL' => Zend_Db::FLOAT_TYPE,
'DEC' => Zend_Db::FLOAT_TYPE,
'REAL' => Zend_Db::FLOAT_TYPE,
'NUMERIC' => Zend_Db::FLOAT_TYPE,
'DOUBLE PRECISION' => Zend_Db::FLOAT_TYPE,
'FLOAT' => Zend_Db::FLOAT_TYPE
);
/**
* Creates a PDO object and connects to the database.
*
* The IBM data server is set.
* Current options are DB2 or IDS
* @todo also differentiate between z/OS and i/5
*
* @return void
* @throws Zend_Db_Adapter_Exception
*/
public function _connect()
{
if ($this->_connection) {
return;
}
parent::_connect();
$this->getConnection()->setAttribute(Zend_Db::ATTR_STRINGIFY_FETCHES, true);
try {
if ($this->_serverType === null) {
$server = substr($this->getConnection()->getAttribute(PDO::ATTR_SERVER_INFO), 0, 3);
switch ($server) {
case 'DB2':
$this->_serverType = new Zend_Db_Adapter_Pdo_Ibm_Db2($this);
// Add DB2-specific numeric types
$this->_numericDataTypes['DECFLOAT'] = Zend_Db::FLOAT_TYPE;
$this->_numericDataTypes['DOUBLE'] = Zend_Db::FLOAT_TYPE;
$this->_numericDataTypes['NUM'] = Zend_Db::FLOAT_TYPE;
break;
case 'IDS':
$this->_serverType = new Zend_Db_Adapter_Pdo_Ibm_Ids($this);
// Add IDS-specific numeric types
$this->_numericDataTypes['SERIAL'] = Zend_Db::INT_TYPE;
$this->_numericDataTypes['SERIAL8'] = Zend_Db::BIGINT_TYPE;
$this->_numericDataTypes['INT8'] = Zend_Db::BIGINT_TYPE;
$this->_numericDataTypes['SMALLFLOAT'] = Zend_Db::FLOAT_TYPE;
$this->_numericDataTypes['MONEY'] = Zend_Db::FLOAT_TYPE;
break;
}
}
} catch (PDOException $e) {
/** @see Zend_Db_Adapter_Exception */
// require_once 'Zend/Db/Adapter/Exception.php';
$error = strpos($e->getMessage(), 'driver does not support that attribute');
if ($error) {
throw new Zend_Db_Adapter_Exception("PDO_IBM driver extension is downlevel. Please use driver release version 1.2.1 or later", 0, $e);
} else {
throw new Zend_Db_Adapter_Exception($e->getMessage(), $e->getCode(), $e);
}
}
}
/**
* Creates a PDO DSN for the adapter from $this->_config settings.
*
* @return string
*/
protected function _dsn()
{
$this->_checkRequiredOptions($this->_config);
// check if using full connection string
if (array_key_exists('host', $this->_config)) {
$dsn = ';DATABASE=' . $this->_config['dbname']
. ';HOSTNAME=' . $this->_config['host']
. ';PORT=' . $this->_config['port']
// PDO_IBM supports only DB2 TCPIP protocol
. ';PROTOCOL=' . 'TCPIP;';
} else {
// catalogued connection
$dsn = $this->_config['dbname'];
}
return $this->_pdoType . ': ' . $dsn;
}
/**
* Checks required options
*
* @param array $config
* @throws Zend_Db_Adapter_Exception
* @return void
*/
protected function _checkRequiredOptions(array $config)
{
parent::_checkRequiredOptions($config);
if (array_key_exists('host', $this->_config) &&
!array_key_exists('port', $config)) {
/** @see Zend_Db_Adapter_Exception */
// require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception("Configuration must have a key for 'port' when 'host' is specified");
}
}
/**
* Prepares an SQL statement.
*
* @param string $sql The SQL statement with placeholders.
* @param array $bind An array of data to bind to the placeholders.
* @return PDOStatement
*/
public function prepare($sql)
{
$this->_connect();
$stmtClass = $this->_defaultStmtClass;
$stmt = new $stmtClass($this, $sql);
$stmt->setFetchMode($this->_fetchMode);
return $stmt;
}
/**
* Returns a list of the tables in the database.
*
* @return array
*/
public function listTables()
{
$this->_connect();
return $this->_serverType->listTables();
}
/**
* Returns the column descriptions for a table.
*
* The return value is an associative array keyed by the column name,
* as returned by the RDBMS.
*
* The value of each array element is an associative array
* with the following keys:
*
* SCHEMA_NAME => string; name of database or schema
* TABLE_NAME => string;
* COLUMN_NAME => string; column name
* COLUMN_POSITION => number; ordinal position of column in table
* DATA_TYPE => string; SQL datatype name of column
* DEFAULT => string; default expression of column, null if none
* NULLABLE => boolean; true if column can have nulls
* LENGTH => number; length of CHAR/VARCHAR
* SCALE => number; scale of NUMERIC/DECIMAL
* PRECISION => number; precision of NUMERIC/DECIMAL
* UNSIGNED => boolean; unsigned property of an integer type
* PRIMARY => boolean; true if column is part of the primary key
* PRIMARY_POSITION => integer; position of column in primary key
*
* @todo Discover integer unsigned property.
*
* @param string $tableName
* @param string $schemaName OPTIONAL
* @return array
*/
public function describeTable($tableName, $schemaName = null)
{
$this->_connect();
return $this->_serverType->describeTable($tableName, $schemaName);
}
/**
* Inserts a table row with specified data.
* Special handling for PDO_IBM
* remove empty slots
*
* @param mixed $table The table to insert data into.
* @param array $bind Column-value pairs.
* @return int The number of affected rows.
*/
public function insert($table, array $bind)
{
$this->_connect();
$newbind = array();
if (is_array($bind)) {
foreach ($bind as $name => $value) {
if($value !== null) {
$newbind[$name] = $value;
}
}
}
return parent::insert($table, $newbind);
}
/**
* Adds an adapter-specific LIMIT clause to the SELECT statement.
*
* @param string $sql
* @param integer $count
* @param integer $offset OPTIONAL
* @return string
*/
public function limit($sql, $count, $offset = 0)
{
$this->_connect();
return $this->_serverType->limit($sql, $count, $offset);
}
/**
* Gets the last ID generated automatically by an IDENTITY/AUTOINCREMENT
* column.
*
* @param string $tableName OPTIONAL
* @param string $primaryKey OPTIONAL
* @return integer
*/
public function lastInsertId($tableName = null, $primaryKey = null)
{
$this->_connect();
if ($tableName !== null) {
$sequenceName = $tableName;
if ($primaryKey) {
$sequenceName .= "_$primaryKey";
}
$sequenceName .= '_seq';
return $this->lastSequenceId($sequenceName);
}
$id = $this->getConnection()->lastInsertId();
return $id;
}
/**
* Return the most recent value from the specified sequence in the database.
*
* @param string $sequenceName
* @return integer
*/
public function lastSequenceId($sequenceName)
{
$this->_connect();
return $this->_serverType->lastSequenceId($sequenceName);
}
/**
* Generate a new value from the specified sequence in the database,
* and return it.
*
* @param string $sequenceName
* @return integer
*/
public function nextSequenceId($sequenceName)
{
$this->_connect();
return $this->_serverType->nextSequenceId($sequenceName);
}
/**
* Retrieve server version in PHP style
* Pdo_Idm doesn't support getAttribute(PDO::ATTR_SERVER_VERSION)
* @return string
*/
public function getServerVersion()
{
try {
$stmt = $this->query('SELECT service_level, fixpack_num FROM TABLE (sysproc.env_get_inst_info()) as INSTANCEINFO');
$result = $stmt->fetchAll(Zend_Db::FETCH_NUM);
if (count($result)) {
$matches = null;
if (preg_match('/((?:[0-9]{1,2}\.){1,3}[0-9]{1,2})/', $result[0][0], $matches)) {
return $matches[1];
} else {
return null;
}
}
return null;
} catch (PDOException $e) {
return null;
}
}
}

View File

@ -0,0 +1,228 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Adapter
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Db2.php 23775 2011-03-01 17:25:24Z ralph $
*/
/** @see Zend_Db_Adapter_Pdo_Ibm */
// require_once 'Zend/Db/Adapter/Pdo/Ibm.php';
/** @see Zend_Db_Statement_Pdo_Ibm */
// require_once 'Zend/Db/Statement/Pdo/Ibm.php';
/**
* @category Zend
* @package Zend_Db
* @subpackage Adapter
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Adapter_Pdo_Ibm_Db2
{
/**
* @var Zend_Db_Adapter_Abstract
*/
protected $_adapter = null;
/**
* Construct the data server class.
*
* It will be used to generate non-generic SQL
* for a particular data server
*
* @param Zend_Db_Adapter_Abstract $adapter
*/
public function __construct($adapter)
{
$this->_adapter = $adapter;
}
/**
* Returns a list of the tables in the database.
*
* @return array
*/
public function listTables()
{
$sql = "SELECT tabname "
. "FROM SYSCAT.TABLES ";
return $this->_adapter->fetchCol($sql);
}
/**
* DB2 catalog lookup for describe table
*
* @param string $tableName
* @param string $schemaName OPTIONAL
* @return array
*/
public function describeTable($tableName, $schemaName = null)
{
$sql = "SELECT DISTINCT c.tabschema, c.tabname, c.colname, c.colno,
c.typename, c.default, c.nulls, c.length, c.scale,
c.identity, tc.type AS tabconsttype, k.colseq
FROM syscat.columns c
LEFT JOIN (syscat.keycoluse k JOIN syscat.tabconst tc
ON (k.tabschema = tc.tabschema
AND k.tabname = tc.tabname
AND tc.type = 'P'))
ON (c.tabschema = k.tabschema
AND c.tabname = k.tabname
AND c.colname = k.colname)
WHERE "
. $this->_adapter->quoteInto('UPPER(c.tabname) = UPPER(?)', $tableName);
if ($schemaName) {
$sql .= $this->_adapter->quoteInto(' AND UPPER(c.tabschema) = UPPER(?)', $schemaName);
}
$sql .= " ORDER BY c.colno";
$desc = array();
$stmt = $this->_adapter->query($sql);
/**
* To avoid case issues, fetch using FETCH_NUM
*/
$result = $stmt->fetchAll(Zend_Db::FETCH_NUM);
/**
* The ordering of columns is defined by the query so we can map
* to variables to improve readability
*/
$tabschema = 0;
$tabname = 1;
$colname = 2;
$colno = 3;
$typename = 4;
$default = 5;
$nulls = 6;
$length = 7;
$scale = 8;
$identityCol = 9;
$tabconstype = 10;
$colseq = 11;
foreach ($result as $key => $row) {
list ($primary, $primaryPosition, $identity) = array(false, null, false);
if ($row[$tabconstype] == 'P') {
$primary = true;
$primaryPosition = $row[$colseq];
}
/**
* In IBM DB2, an column can be IDENTITY
* even if it is not part of the PRIMARY KEY.
*/
if ($row[$identityCol] == 'Y') {
$identity = true;
}
$desc[$this->_adapter->foldCase($row[$colname])] = array(
'SCHEMA_NAME' => $this->_adapter->foldCase($row[$tabschema]),
'TABLE_NAME' => $this->_adapter->foldCase($row[$tabname]),
'COLUMN_NAME' => $this->_adapter->foldCase($row[$colname]),
'COLUMN_POSITION' => $row[$colno]+1,
'DATA_TYPE' => $row[$typename],
'DEFAULT' => $row[$default],
'NULLABLE' => (bool) ($row[$nulls] == 'Y'),
'LENGTH' => $row[$length],
'SCALE' => $row[$scale],
'PRECISION' => ($row[$typename] == 'DECIMAL' ? $row[$length] : 0),
'UNSIGNED' => false,
'PRIMARY' => $primary,
'PRIMARY_POSITION' => $primaryPosition,
'IDENTITY' => $identity
);
}
return $desc;
}
/**
* Adds a DB2-specific LIMIT clause to the SELECT statement.
*
* @param string $sql
* @param integer $count
* @param integer $offset OPTIONAL
* @throws Zend_Db_Adapter_Exception
* @return string
*/
public function limit($sql, $count, $offset = 0)
{
$count = intval($count);
if ($count < 0) {
/** @see Zend_Db_Adapter_Exception */
// require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception("LIMIT argument count=$count is not valid");
} else {
$offset = intval($offset);
if ($offset < 0) {
/** @see Zend_Db_Adapter_Exception */
// require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception("LIMIT argument offset=$offset is not valid");
}
if ($offset == 0 && $count > 0) {
$limit_sql = $sql . " FETCH FIRST $count ROWS ONLY";
return $limit_sql;
}
/**
* DB2 does not implement the LIMIT clause as some RDBMS do.
* We have to simulate it with subqueries and ROWNUM.
* Unfortunately because we use the column wildcard "*",
* this puts an extra column into the query result set.
*/
$limit_sql = "SELECT z2.*
FROM (
SELECT ROW_NUMBER() OVER() AS \"ZEND_DB_ROWNUM\", z1.*
FROM (
" . $sql . "
) z1
) z2
WHERE z2.zend_db_rownum BETWEEN " . ($offset+1) . " AND " . ($offset+$count);
}
return $limit_sql;
}
/**
* DB2-specific last sequence id
*
* @param string $sequenceName
* @return integer
*/
public function lastSequenceId($sequenceName)
{
$sql = 'SELECT PREVVAL FOR '.$this->_adapter->quoteIdentifier($sequenceName).' AS VAL FROM SYSIBM.SYSDUMMY1';
$value = $this->_adapter->fetchOne($sql);
return $value;
}
/**
* DB2-specific sequence id value
*
* @param string $sequenceName
* @return integer
*/
public function nextSequenceId($sequenceName)
{
$sql = 'SELECT NEXTVAL FOR '.$this->_adapter->quoteIdentifier($sequenceName).' AS VAL FROM SYSIBM.SYSDUMMY1';
$value = $this->_adapter->fetchOne($sql);
return $value;
}
}

View File

@ -0,0 +1,301 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Adapter
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Ids.php 23775 2011-03-01 17:25:24Z ralph $
*/
/** @see Zend_Db_Adapter_Pdo_Ibm */
// require_once 'Zend/Db/Adapter/Pdo/Ibm.php';
/** @see Zend_Db_Statement_Pdo_Ibm */
// require_once 'Zend/Db/Statement/Pdo/Ibm.php';
/**
* @category Zend
* @package Zend_Db
* @subpackage Adapter
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Adapter_Pdo_Ibm_Ids
{
/**
* @var Zend_Db_Adapter_Abstract
*/
protected $_adapter = null;
/**
* Construct the data server class.
*
* It will be used to generate non-generic SQL
* for a particular data server
*
* @param Zend_Db_Adapter_Abstract $adapter
*/
public function __construct($adapter)
{
$this->_adapter = $adapter;
}
/**
* Returns a list of the tables in the database.
*
* @return array
*/
public function listTables()
{
$sql = "SELECT tabname "
. "FROM systables ";
return $this->_adapter->fetchCol($sql);
}
/**
* IDS catalog lookup for describe table
*
* @param string $tableName
* @param string $schemaName OPTIONAL
* @return array
*/
public function describeTable($tableName, $schemaName = null)
{
// this is still a work in progress
$sql= "SELECT DISTINCT t.owner, t.tabname, c.colname, c.colno, c.coltype,
d.default, c.collength, t.tabid
FROM syscolumns c
JOIN systables t ON c.tabid = t.tabid
LEFT JOIN sysdefaults d ON c.tabid = d.tabid AND c.colno = d.colno
WHERE "
. $this->_adapter->quoteInto('UPPER(t.tabname) = UPPER(?)', $tableName);
if ($schemaName) {
$sql .= $this->_adapter->quoteInto(' AND UPPER(t.owner) = UPPER(?)', $schemaName);
}
$sql .= " ORDER BY c.colno";
$desc = array();
$stmt = $this->_adapter->query($sql);
$result = $stmt->fetchAll(Zend_Db::FETCH_NUM);
/**
* The ordering of columns is defined by the query so we can map
* to variables to improve readability
*/
$tabschema = 0;
$tabname = 1;
$colname = 2;
$colno = 3;
$typename = 4;
$default = 5;
$length = 6;
$tabid = 7;
$primaryCols = null;
foreach ($result as $key => $row) {
$primary = false;
$primaryPosition = null;
if (!$primaryCols) {
$primaryCols = $this->_getPrimaryInfo($row[$tabid]);
}
if (array_key_exists($row[$colno], $primaryCols)) {
$primary = true;
$primaryPosition = $primaryCols[$row[$colno]];
}
$identity = false;
if ($row[$typename] == 6 + 256 ||
$row[$typename] == 18 + 256) {
$identity = true;
}
$desc[$this->_adapter->foldCase($row[$colname])] = array (
'SCHEMA_NAME' => $this->_adapter->foldCase($row[$tabschema]),
'TABLE_NAME' => $this->_adapter->foldCase($row[$tabname]),
'COLUMN_NAME' => $this->_adapter->foldCase($row[$colname]),
'COLUMN_POSITION' => $row[$colno],
'DATA_TYPE' => $this->_getDataType($row[$typename]),
'DEFAULT' => $row[$default],
'NULLABLE' => (bool) !($row[$typename] - 256 >= 0),
'LENGTH' => $row[$length],
'SCALE' => ($row[$typename] == 5 ? $row[$length]&255 : 0),
'PRECISION' => ($row[$typename] == 5 ? (int)($row[$length]/256) : 0),
'UNSIGNED' => false,
'PRIMARY' => $primary,
'PRIMARY_POSITION' => $primaryPosition,
'IDENTITY' => $identity
);
}
return $desc;
}
/**
* Map number representation of a data type
* to a string
*
* @param int $typeNo
* @return string
*/
protected function _getDataType($typeNo)
{
$typemap = array(
0 => "CHAR",
1 => "SMALLINT",
2 => "INTEGER",
3 => "FLOAT",
4 => "SMALLFLOAT",
5 => "DECIMAL",
6 => "SERIAL",
7 => "DATE",
8 => "MONEY",
9 => "NULL",
10 => "DATETIME",
11 => "BYTE",
12 => "TEXT",
13 => "VARCHAR",
14 => "INTERVAL",
15 => "NCHAR",
16 => "NVARCHAR",
17 => "INT8",
18 => "SERIAL8",
19 => "SET",
20 => "MULTISET",
21 => "LIST",
22 => "Unnamed ROW",
40 => "Variable-length opaque type",
4118 => "Named ROW"
);
if ($typeNo - 256 >= 0) {
$typeNo = $typeNo - 256;
}
return $typemap[$typeNo];
}
/**
* Helper method to retrieve primary key column
* and column location
*
* @param int $tabid
* @return array
*/
protected function _getPrimaryInfo($tabid)
{
$sql = "SELECT i.part1, i.part2, i.part3, i.part4, i.part5, i.part6,
i.part7, i.part8, i.part9, i.part10, i.part11, i.part12,
i.part13, i.part14, i.part15, i.part16
FROM sysindexes i
JOIN sysconstraints c ON c.idxname = i.idxname
WHERE i.tabid = " . $tabid . " AND c.constrtype = 'P'";
$stmt = $this->_adapter->query($sql);
$results = $stmt->fetchAll();
$cols = array();
// this should return only 1 row
// unless there is no primary key,
// in which case, the empty array is returned
if ($results) {
$row = $results[0];
} else {
return $cols;
}
$position = 0;
foreach ($row as $key => $colno) {
$position++;
if ($colno == 0) {
return $cols;
} else {
$cols[$colno] = $position;
}
}
}
/**
* Adds an IDS-specific LIMIT clause to the SELECT statement.
*
* @param string $sql
* @param integer $count
* @param integer $offset OPTIONAL
* @throws Zend_Db_Adapter_Exception
* @return string
*/
public function limit($sql, $count, $offset = 0)
{
$count = intval($count);
if ($count < 0) {
/** @see Zend_Db_Adapter_Exception */
// require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception("LIMIT argument count=$count is not valid");
} else if ($count == 0) {
$limit_sql = str_ireplace("SELECT", "SELECT * FROM (SELECT", $sql);
$limit_sql .= ") WHERE 0 = 1";
} else {
$offset = intval($offset);
if ($offset < 0) {
/** @see Zend_Db_Adapter_Exception */
// require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception("LIMIT argument offset=$offset is not valid");
}
if ($offset == 0) {
$limit_sql = str_ireplace("SELECT", "SELECT FIRST $count", $sql);
} else {
$limit_sql = str_ireplace("SELECT", "SELECT SKIP $offset LIMIT $count", $sql);
}
}
return $limit_sql;
}
/**
* IDS-specific last sequence id
*
* @param string $sequenceName
* @return integer
*/
public function lastSequenceId($sequenceName)
{
$sql = 'SELECT '.$this->_adapter->quoteIdentifier($sequenceName).'.CURRVAL FROM '
.'systables WHERE tabid = 1';
$value = $this->_adapter->fetchOne($sql);
return $value;
}
/**
* IDS-specific sequence id value
*
* @param string $sequenceName
* @return integer
*/
public function nextSequenceId($sequenceName)
{
$sql = 'SELECT '.$this->_adapter->quoteIdentifier($sequenceName).'.NEXTVAL FROM '
.'systables WHERE tabid = 1';
$value = $this->_adapter->fetchOne($sql);
return $value;
}
}

View File

@ -0,0 +1,423 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Adapter
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Mssql.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Db_Adapter_Pdo_Abstract
*/
// require_once 'Zend/Db/Adapter/Pdo/Abstract.php';
/**
* Class for connecting to Microsoft SQL Server databases and performing common operations.
*
* @category Zend
* @package Zend_Db
* @subpackage Adapter
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Adapter_Pdo_Mssql extends Zend_Db_Adapter_Pdo_Abstract
{
/**
* PDO type.
*
* @var string
*/
protected $_pdoType = 'mssql';
/**
* Keys are UPPERCASE SQL datatypes or the constants
* Zend_Db::INT_TYPE, Zend_Db::BIGINT_TYPE, or Zend_Db::FLOAT_TYPE.
*
* Values are:
* 0 = 32-bit integer
* 1 = 64-bit integer
* 2 = float or decimal
*
* @var array Associative array of datatypes to values 0, 1, or 2.
*/
protected $_numericDataTypes = array(
Zend_Db::INT_TYPE => Zend_Db::INT_TYPE,
Zend_Db::BIGINT_TYPE => Zend_Db::BIGINT_TYPE,
Zend_Db::FLOAT_TYPE => Zend_Db::FLOAT_TYPE,
'INT' => Zend_Db::INT_TYPE,
'SMALLINT' => Zend_Db::INT_TYPE,
'TINYINT' => Zend_Db::INT_TYPE,
'BIGINT' => Zend_Db::BIGINT_TYPE,
'DECIMAL' => Zend_Db::FLOAT_TYPE,
'FLOAT' => Zend_Db::FLOAT_TYPE,
'MONEY' => Zend_Db::FLOAT_TYPE,
'NUMERIC' => Zend_Db::FLOAT_TYPE,
'REAL' => Zend_Db::FLOAT_TYPE,
'SMALLMONEY' => Zend_Db::FLOAT_TYPE
);
/**
* Creates a PDO DSN for the adapter from $this->_config settings.
*
* @return string
*/
protected function _dsn()
{
// baseline of DSN parts
$dsn = $this->_config;
// don't pass the username and password in the DSN
unset($dsn['username']);
unset($dsn['password']);
unset($dsn['options']);
unset($dsn['persistent']);
unset($dsn['driver_options']);
if (isset($dsn['port'])) {
$seperator = ':';
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
$seperator = ',';
}
$dsn['host'] .= $seperator . $dsn['port'];
unset($dsn['port']);
}
// this driver supports multiple DSN prefixes
// @see http://www.php.net/manual/en/ref.pdo-dblib.connection.php
if (isset($dsn['pdoType'])) {
switch (strtolower($dsn['pdoType'])) {
case 'freetds':
case 'sybase':
$this->_pdoType = 'sybase';
break;
case 'mssql':
$this->_pdoType = 'mssql';
break;
case 'dblib':
default:
$this->_pdoType = 'dblib';
break;
}
unset($dsn['pdoType']);
}
// use all remaining parts in the DSN
foreach ($dsn as $key => $val) {
$dsn[$key] = "$key=$val";
}
$dsn = $this->_pdoType . ':' . implode(';', $dsn);
return $dsn;
}
/**
* @return void
*/
protected function _connect()
{
if ($this->_connection) {
return;
}
parent::_connect();
$this->_connection->exec('SET QUOTED_IDENTIFIER ON');
}
/**
* Begin a transaction.
*
* It is necessary to override the abstract PDO transaction functions here, as
* the PDO driver for MSSQL does not support transactions.
*/
protected function _beginTransaction()
{
$this->_connect();
$this->_connection->exec('BEGIN TRANSACTION');
return true;
}
/**
* Commit a transaction.
*
* It is necessary to override the abstract PDO transaction functions here, as
* the PDO driver for MSSQL does not support transactions.
*/
protected function _commit()
{
$this->_connect();
$this->_connection->exec('COMMIT TRANSACTION');
return true;
}
/**
* Roll-back a transaction.
*
* It is necessary to override the abstract PDO transaction functions here, as
* the PDO driver for MSSQL does not support transactions.
*/
protected function _rollBack() {
$this->_connect();
$this->_connection->exec('ROLLBACK TRANSACTION');
return true;
}
/**
* Returns a list of the tables in the database.
*
* @return array
*/
public function listTables()
{
$sql = "SELECT name FROM sysobjects WHERE type = 'U' ORDER BY name";
return $this->fetchCol($sql);
}
/**
* Returns the column descriptions for a table.
*
* The return value is an associative array keyed by the column name,
* as returned by the RDBMS.
*
* The value of each array element is an associative array
* with the following keys:
*
* SCHEMA_NAME => string; name of database or schema
* TABLE_NAME => string;
* COLUMN_NAME => string; column name
* COLUMN_POSITION => number; ordinal position of column in table
* DATA_TYPE => string; SQL datatype name of column
* DEFAULT => string; default expression of column, null if none
* NULLABLE => boolean; true if column can have nulls
* LENGTH => number; length of CHAR/VARCHAR
* SCALE => number; scale of NUMERIC/DECIMAL
* PRECISION => number; precision of NUMERIC/DECIMAL
* UNSIGNED => boolean; unsigned property of an integer type
* PRIMARY => boolean; true if column is part of the primary key
* PRIMARY_POSITION => integer; position of column in primary key
* PRIMARY_AUTO => integer; position of auto-generated column in primary key
*
* @todo Discover column primary key position.
* @todo Discover integer unsigned property.
*
* @param string $tableName
* @param string $schemaName OPTIONAL
* @return array
*/
public function describeTable($tableName, $schemaName = null)
{
if ($schemaName != null) {
if (strpos($schemaName, '.') !== false) {
$result = explode('.', $schemaName);
$schemaName = $result[1];
}
}
/**
* Discover metadata information about this table.
*/
$sql = "exec sp_columns @table_name = " . $this->quoteIdentifier($tableName, true);
if ($schemaName != null) {
$sql .= ", @table_owner = " . $this->quoteIdentifier($schemaName, true);
}
$stmt = $this->query($sql);
$result = $stmt->fetchAll(Zend_Db::FETCH_NUM);
$table_name = 2;
$column_name = 3;
$type_name = 5;
$precision = 6;
$length = 7;
$scale = 8;
$nullable = 10;
$column_def = 12;
$column_position = 16;
/**
* Discover primary key column(s) for this table.
*/
$sql = "exec sp_pkeys @table_name = " . $this->quoteIdentifier($tableName, true);
if ($schemaName != null) {
$sql .= ", @table_owner = " . $this->quoteIdentifier($schemaName, true);
}
$stmt = $this->query($sql);
$primaryKeysResult = $stmt->fetchAll(Zend_Db::FETCH_NUM);
$primaryKeyColumn = array();
$pkey_column_name = 3;
$pkey_key_seq = 4;
foreach ($primaryKeysResult as $pkeysRow) {
$primaryKeyColumn[$pkeysRow[$pkey_column_name]] = $pkeysRow[$pkey_key_seq];
}
$desc = array();
$p = 1;
foreach ($result as $key => $row) {
$identity = false;
$words = explode(' ', $row[$type_name], 2);
if (isset($words[0])) {
$type = $words[0];
if (isset($words[1])) {
$identity = (bool) preg_match('/identity/', $words[1]);
}
}
$isPrimary = array_key_exists($row[$column_name], $primaryKeyColumn);
if ($isPrimary) {
$primaryPosition = $primaryKeyColumn[$row[$column_name]];
} else {
$primaryPosition = null;
}
$desc[$this->foldCase($row[$column_name])] = array(
'SCHEMA_NAME' => null, // @todo
'TABLE_NAME' => $this->foldCase($row[$table_name]),
'COLUMN_NAME' => $this->foldCase($row[$column_name]),
'COLUMN_POSITION' => (int) $row[$column_position],
'DATA_TYPE' => $type,
'DEFAULT' => $row[$column_def],
'NULLABLE' => (bool) $row[$nullable],
'LENGTH' => $row[$length],
'SCALE' => $row[$scale],
'PRECISION' => $row[$precision],
'UNSIGNED' => null, // @todo
'PRIMARY' => $isPrimary,
'PRIMARY_POSITION' => $primaryPosition,
'IDENTITY' => $identity
);
}
return $desc;
}
/**
* Adds an adapter-specific LIMIT clause to the SELECT statement.
*
* @link http://lists.bestpractical.com/pipermail/rt-devel/2005-June/007339.html
*
* @param string $sql
* @param integer $count
* @param integer $offset OPTIONAL
* @throws Zend_Db_Adapter_Exception
* @return string
*/
public function limit($sql, $count, $offset = 0)
{
$count = intval($count);
if ($count <= 0) {
/** @see Zend_Db_Adapter_Exception */
// require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception("LIMIT argument count=$count is not valid");
}
$offset = intval($offset);
if ($offset < 0) {
/** @see Zend_Db_Adapter_Exception */
// require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception("LIMIT argument offset=$offset is not valid");
}
$sql = preg_replace(
'/^SELECT\s+(DISTINCT\s)?/i',
'SELECT $1TOP ' . ($count+$offset) . ' ',
$sql
);
if ($offset > 0) {
$orderby = stristr($sql, 'ORDER BY');
if ($orderby !== false) {
$orderParts = explode(',', substr($orderby, 8));
$pregReplaceCount = null;
$orderbyInverseParts = array();
foreach ($orderParts as $orderPart) {
$orderPart = rtrim($orderPart);
$inv = preg_replace('/\s+desc$/i', ' ASC', $orderPart, 1, $pregReplaceCount);
if ($pregReplaceCount) {
$orderbyInverseParts[] = $inv;
continue;
}
$inv = preg_replace('/\s+asc$/i', ' DESC', $orderPart, 1, $pregReplaceCount);
if ($pregReplaceCount) {
$orderbyInverseParts[] = $inv;
continue;
} else {
$orderbyInverseParts[] = $orderPart . ' DESC';
}
}
$orderbyInverse = 'ORDER BY ' . implode(', ', $orderbyInverseParts);
}
$sql = 'SELECT * FROM (SELECT TOP ' . $count . ' * FROM (' . $sql . ') AS inner_tbl';
if ($orderby !== false) {
$sql .= ' ' . $orderbyInverse . ' ';
}
$sql .= ') AS outer_tbl';
if ($orderby !== false) {
$sql .= ' ' . $orderby;
}
}
return $sql;
}
/**
* Gets the last ID generated automatically by an IDENTITY/AUTOINCREMENT column.
*
* As a convention, on RDBMS brands that support sequences
* (e.g. Oracle, PostgreSQL, DB2), this method forms the name of a sequence
* from the arguments and returns the last id generated by that sequence.
* On RDBMS brands that support IDENTITY/AUTOINCREMENT columns, this method
* returns the last value generated for such a column, and the table name
* argument is disregarded.
*
* Microsoft SQL Server does not support sequences, so the arguments to
* this method are ignored.
*
* @param string $tableName OPTIONAL Name of table.
* @param string $primaryKey OPTIONAL Name of primary key column.
* @return string
* @throws Zend_Db_Adapter_Exception
*/
public function lastInsertId($tableName = null, $primaryKey = null)
{
$sql = 'SELECT SCOPE_IDENTITY()';
return (int)$this->fetchOne($sql);
}
/**
* Retrieve server version in PHP style
* Pdo_Mssql doesn't support getAttribute(PDO::ATTR_SERVER_VERSION)
* @return string
*/
public function getServerVersion()
{
try {
$stmt = $this->query("SELECT SERVERPROPERTY('productversion')");
$result = $stmt->fetchAll(Zend_Db::FETCH_NUM);
if (count($result)) {
return $result[0][0];
}
return null;
} catch (PDOException $e) {
return null;
}
}
}

View File

@ -0,0 +1,270 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Adapter
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Mysql.php 23986 2011-05-03 20:10:42Z ralph $
*/
/**
* @see Zend_Db_Adapter_Pdo_Abstract
*/
// require_once 'Zend/Db/Adapter/Pdo/Abstract.php';
/**
* Class for connecting to MySQL databases and performing common operations.
*
* @category Zend
* @package Zend_Db
* @subpackage Adapter
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Adapter_Pdo_Mysql extends Zend_Db_Adapter_Pdo_Abstract
{
/**
* PDO type.
*
* @var string
*/
protected $_pdoType = 'mysql';
/**
* Keys are UPPERCASE SQL datatypes or the constants
* Zend_Db::INT_TYPE, Zend_Db::BIGINT_TYPE, or Zend_Db::FLOAT_TYPE.
*
* Values are:
* 0 = 32-bit integer
* 1 = 64-bit integer
* 2 = float or decimal
*
* @var array Associative array of datatypes to values 0, 1, or 2.
*/
protected $_numericDataTypes = array(
Zend_Db::INT_TYPE => Zend_Db::INT_TYPE,
Zend_Db::BIGINT_TYPE => Zend_Db::BIGINT_TYPE,
Zend_Db::FLOAT_TYPE => Zend_Db::FLOAT_TYPE,
'INT' => Zend_Db::INT_TYPE,
'INTEGER' => Zend_Db::INT_TYPE,
'MEDIUMINT' => Zend_Db::INT_TYPE,
'SMALLINT' => Zend_Db::INT_TYPE,
'TINYINT' => Zend_Db::INT_TYPE,
'BIGINT' => Zend_Db::BIGINT_TYPE,
'SERIAL' => Zend_Db::BIGINT_TYPE,
'DEC' => Zend_Db::FLOAT_TYPE,
'DECIMAL' => Zend_Db::FLOAT_TYPE,
'DOUBLE' => Zend_Db::FLOAT_TYPE,
'DOUBLE PRECISION' => Zend_Db::FLOAT_TYPE,
'FIXED' => Zend_Db::FLOAT_TYPE,
'FLOAT' => Zend_Db::FLOAT_TYPE
);
/**
* Override _dsn() and ensure that charset is incorporated in mysql
* @see Zend_Db_Adapter_Pdo_Abstract::_dsn()
*/
protected function _dsn()
{
$dsn = parent::_dsn();
if (isset($this->_config['charset'])) {
$dsn .= ';charset=' . $this->_config['charset'];
}
return $dsn;
}
/**
* Creates a PDO object and connects to the database.
*
* @return void
* @throws Zend_Db_Adapter_Exception
*/
protected function _connect()
{
if ($this->_connection) {
return;
}
if (!empty($this->_config['charset'])) {
$initCommand = "SET NAMES '" . $this->_config['charset'] . "'";
$this->_config['driver_options'][1002] = $initCommand; // 1002 = PDO::MYSQL_ATTR_INIT_COMMAND
}
parent::_connect();
}
/**
* @return string
*/
public function getQuoteIdentifierSymbol()
{
return "`";
}
/**
* Returns a list of the tables in the database.
*
* @return array
*/
public function listTables()
{
return $this->fetchCol('SHOW TABLES');
}
/**
* Returns the column descriptions for a table.
*
* The return value is an associative array keyed by the column name,
* as returned by the RDBMS.
*
* The value of each array element is an associative array
* with the following keys:
*
* SCHEMA_NAME => string; name of database or schema
* TABLE_NAME => string;
* COLUMN_NAME => string; column name
* COLUMN_POSITION => number; ordinal position of column in table
* DATA_TYPE => string; SQL datatype name of column
* DEFAULT => string; default expression of column, null if none
* NULLABLE => boolean; true if column can have nulls
* LENGTH => number; length of CHAR/VARCHAR
* SCALE => number; scale of NUMERIC/DECIMAL
* PRECISION => number; precision of NUMERIC/DECIMAL
* UNSIGNED => boolean; unsigned property of an integer type
* PRIMARY => boolean; true if column is part of the primary key
* PRIMARY_POSITION => integer; position of column in primary key
* IDENTITY => integer; true if column is auto-generated with unique values
*
* @param string $tableName
* @param string $schemaName OPTIONAL
* @return array
*/
public function describeTable($tableName, $schemaName = null)
{
// @todo use INFORMATION_SCHEMA someday when MySQL's
// implementation has reasonably good performance and
// the version with this improvement is in wide use.
if ($schemaName) {
$sql = 'DESCRIBE ' . $this->quoteIdentifier("$schemaName.$tableName", true);
} else {
$sql = 'DESCRIBE ' . $this->quoteIdentifier($tableName, true);
}
$stmt = $this->query($sql);
// Use FETCH_NUM so we are not dependent on the CASE attribute of the PDO connection
$result = $stmt->fetchAll(Zend_Db::FETCH_NUM);
$field = 0;
$type = 1;
$null = 2;
$key = 3;
$default = 4;
$extra = 5;
$desc = array();
$i = 1;
$p = 1;
foreach ($result as $row) {
list($length, $scale, $precision, $unsigned, $primary, $primaryPosition, $identity)
= array(null, null, null, null, false, null, false);
if (preg_match('/unsigned/', $row[$type])) {
$unsigned = true;
}
if (preg_match('/^((?:var)?char)\((\d+)\)/', $row[$type], $matches)) {
$row[$type] = $matches[1];
$length = $matches[2];
} else if (preg_match('/^decimal\((\d+),(\d+)\)/', $row[$type], $matches)) {
$row[$type] = 'decimal';
$precision = $matches[1];
$scale = $matches[2];
} else if (preg_match('/^float\((\d+),(\d+)\)/', $row[$type], $matches)) {
$row[$type] = 'float';
$precision = $matches[1];
$scale = $matches[2];
} else if (preg_match('/^((?:big|medium|small|tiny)?int)\((\d+)\)/', $row[$type], $matches)) {
$row[$type] = $matches[1];
// The optional argument of a MySQL int type is not precision
// or length; it is only a hint for display width.
}
if (strtoupper($row[$key]) == 'PRI') {
$primary = true;
$primaryPosition = $p;
if ($row[$extra] == 'auto_increment') {
$identity = true;
} else {
$identity = false;
}
++$p;
}
$desc[$this->foldCase($row[$field])] = array(
'SCHEMA_NAME' => null, // @todo
'TABLE_NAME' => $this->foldCase($tableName),
'COLUMN_NAME' => $this->foldCase($row[$field]),
'COLUMN_POSITION' => $i,
'DATA_TYPE' => $row[$type],
'DEFAULT' => $row[$default],
'NULLABLE' => (bool) ($row[$null] == 'YES'),
'LENGTH' => $length,
'SCALE' => $scale,
'PRECISION' => $precision,
'UNSIGNED' => $unsigned,
'PRIMARY' => $primary,
'PRIMARY_POSITION' => $primaryPosition,
'IDENTITY' => $identity
);
++$i;
}
return $desc;
}
/**
* Adds an adapter-specific LIMIT clause to the SELECT statement.
*
* @param string $sql
* @param integer $count
* @param integer $offset OPTIONAL
* @throws Zend_Db_Adapter_Exception
* @return string
*/
public function limit($sql, $count, $offset = 0)
{
$count = intval($count);
if ($count <= 0) {
/** @see Zend_Db_Adapter_Exception */
// require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception("LIMIT argument count=$count is not valid");
}
$offset = intval($offset);
if ($offset < 0) {
/** @see Zend_Db_Adapter_Exception */
// require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception("LIMIT argument offset=$offset is not valid");
}
$sql .= " LIMIT $count";
if ($offset > 0) {
$sql .= " OFFSET $offset";
}
return $sql;
}
}

View File

@ -0,0 +1,378 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Adapter
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Oci.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Db_Adapter_Pdo_Abstract
*/
// require_once 'Zend/Db/Adapter/Pdo/Abstract.php';
/**
* Class for connecting to Oracle databases and performing common operations.
*
* @category Zend
* @package Zend_Db
* @subpackage Adapter
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Adapter_Pdo_Oci extends Zend_Db_Adapter_Pdo_Abstract
{
/**
* PDO type.
*
* @var string
*/
protected $_pdoType = 'oci';
/**
* Default class name for a DB statement.
*
* @var string
*/
protected $_defaultStmtClass = 'Zend_Db_Statement_Pdo_Oci';
/**
* Keys are UPPERCASE SQL datatypes or the constants
* Zend_Db::INT_TYPE, Zend_Db::BIGINT_TYPE, or Zend_Db::FLOAT_TYPE.
*
* Values are:
* 0 = 32-bit integer
* 1 = 64-bit integer
* 2 = float or decimal
*
* @var array Associative array of datatypes to values 0, 1, or 2.
*/
protected $_numericDataTypes = array(
Zend_Db::INT_TYPE => Zend_Db::INT_TYPE,
Zend_Db::BIGINT_TYPE => Zend_Db::BIGINT_TYPE,
Zend_Db::FLOAT_TYPE => Zend_Db::FLOAT_TYPE,
'BINARY_DOUBLE' => Zend_Db::FLOAT_TYPE,
'BINARY_FLOAT' => Zend_Db::FLOAT_TYPE,
'NUMBER' => Zend_Db::FLOAT_TYPE
);
/**
* Creates a PDO DSN for the adapter from $this->_config settings.
*
* @return string
*/
protected function _dsn()
{
// baseline of DSN parts
$dsn = $this->_config;
if (isset($dsn['host'])) {
$tns = 'dbname=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)' .
'(HOST=' . $dsn['host'] . ')';
if (isset($dsn['port'])) {
$tns .= '(PORT=' . $dsn['port'] . ')';
} else {
$tns .= '(PORT=1521)';
}
$tns .= '))(CONNECT_DATA=(SID=' . $dsn['dbname'] . ')))';
} else {
$tns = 'dbname=' . $dsn['dbname'];
}
if (isset($dsn['charset'])) {
$tns .= ';charset=' . $dsn['charset'];
}
return $this->_pdoType . ':' . $tns;
}
/**
* Quote a raw string.
* Most PDO drivers have an implementation for the quote() method,
* but the Oracle OCI driver must use the same implementation as the
* Zend_Db_Adapter_Abstract class.
*
* @param string $value Raw string
* @return string Quoted string
*/
protected function _quote($value)
{
if (is_int($value) || is_float($value)) {
return $value;
}
$value = str_replace("'", "''", $value);
return "'" . addcslashes($value, "\000\n\r\\\032") . "'";
}
/**
* Quote a table identifier and alias.
*
* @param string|array|Zend_Db_Expr $ident The identifier or expression.
* @param string $alias An alias for the table.
* @return string The quoted identifier and alias.
*/
public function quoteTableAs($ident, $alias = null, $auto = false)
{
// Oracle doesn't allow the 'AS' keyword between the table identifier/expression and alias.
return $this->_quoteIdentifierAs($ident, $alias, $auto, ' ');
}
/**
* Returns a list of the tables in the database.
*
* @return array
*/
public function listTables()
{
$data = $this->fetchCol('SELECT table_name FROM all_tables');
return $data;
}
/**
* Returns the column descriptions for a table.
*
* The return value is an associative array keyed by the column name,
* as returned by the RDBMS.
*
* The value of each array element is an associative array
* with the following keys:
*
* SCHEMA_NAME => string; name of schema
* TABLE_NAME => string;
* COLUMN_NAME => string; column name
* COLUMN_POSITION => number; ordinal position of column in table
* DATA_TYPE => string; SQL datatype name of column
* DEFAULT => string; default expression of column, null if none
* NULLABLE => boolean; true if column can have nulls
* LENGTH => number; length of CHAR/VARCHAR
* SCALE => number; scale of NUMERIC/DECIMAL
* PRECISION => number; precision of NUMERIC/DECIMAL
* UNSIGNED => boolean; unsigned property of an integer type
* PRIMARY => boolean; true if column is part of the primary key
* PRIMARY_POSITION => integer; position of column in primary key
* IDENTITY => integer; true if column is auto-generated with unique values
*
* @todo Discover integer unsigned property.
*
* @param string $tableName
* @param string $schemaName OPTIONAL
* @return array
*/
public function describeTable($tableName, $schemaName = null)
{
$version = $this->getServerVersion();
if (($version === null) || version_compare($version, '9.0.0', '>=')) {
$sql = "SELECT TC.TABLE_NAME, TC.OWNER, TC.COLUMN_NAME, TC.DATA_TYPE,
TC.DATA_DEFAULT, TC.NULLABLE, TC.COLUMN_ID, TC.DATA_LENGTH,
TC.DATA_SCALE, TC.DATA_PRECISION, C.CONSTRAINT_TYPE, CC.POSITION
FROM ALL_TAB_COLUMNS TC
LEFT JOIN (ALL_CONS_COLUMNS CC JOIN ALL_CONSTRAINTS C
ON (CC.CONSTRAINT_NAME = C.CONSTRAINT_NAME AND CC.TABLE_NAME = C.TABLE_NAME AND CC.OWNER = C.OWNER AND C.CONSTRAINT_TYPE = 'P'))
ON TC.TABLE_NAME = CC.TABLE_NAME AND TC.COLUMN_NAME = CC.COLUMN_NAME
WHERE UPPER(TC.TABLE_NAME) = UPPER(:TBNAME)";
$bind[':TBNAME'] = $tableName;
if ($schemaName) {
$sql .= ' AND UPPER(TC.OWNER) = UPPER(:SCNAME)';
$bind[':SCNAME'] = $schemaName;
}
$sql .= ' ORDER BY TC.COLUMN_ID';
} else {
$subSql="SELECT AC.OWNER, AC.TABLE_NAME, ACC.COLUMN_NAME, AC.CONSTRAINT_TYPE, ACC.POSITION
from ALL_CONSTRAINTS AC, ALL_CONS_COLUMNS ACC
WHERE ACC.CONSTRAINT_NAME = AC.CONSTRAINT_NAME
AND ACC.TABLE_NAME = AC.TABLE_NAME
AND ACC.OWNER = AC.OWNER
AND AC.CONSTRAINT_TYPE = 'P'
AND UPPER(AC.TABLE_NAME) = UPPER(:TBNAME)";
$bind[':TBNAME'] = $tableName;
if ($schemaName) {
$subSql .= ' AND UPPER(ACC.OWNER) = UPPER(:SCNAME)';
$bind[':SCNAME'] = $schemaName;
}
$sql="SELECT TC.TABLE_NAME, TC.OWNER, TC.COLUMN_NAME, TC.DATA_TYPE,
TC.DATA_DEFAULT, TC.NULLABLE, TC.COLUMN_ID, TC.DATA_LENGTH,
TC.DATA_SCALE, TC.DATA_PRECISION, CC.CONSTRAINT_TYPE, CC.POSITION
FROM ALL_TAB_COLUMNS TC, ($subSql) CC
WHERE UPPER(TC.TABLE_NAME) = UPPER(:TBNAME)
AND TC.OWNER = CC.OWNER(+) AND TC.TABLE_NAME = CC.TABLE_NAME(+) AND TC.COLUMN_NAME = CC.COLUMN_NAME(+)";
if ($schemaName) {
$sql .= ' AND UPPER(TC.OWNER) = UPPER(:SCNAME)';
}
$sql .= ' ORDER BY TC.COLUMN_ID';
}
$stmt = $this->query($sql, $bind);
/**
* Use FETCH_NUM so we are not dependent on the CASE attribute of the PDO connection
*/
$result = $stmt->fetchAll(Zend_Db::FETCH_NUM);
$table_name = 0;
$owner = 1;
$column_name = 2;
$data_type = 3;
$data_default = 4;
$nullable = 5;
$column_id = 6;
$data_length = 7;
$data_scale = 8;
$data_precision = 9;
$constraint_type = 10;
$position = 11;
$desc = array();
foreach ($result as $key => $row) {
list ($primary, $primaryPosition, $identity) = array(false, null, false);
if ($row[$constraint_type] == 'P') {
$primary = true;
$primaryPosition = $row[$position];
/**
* Oracle does not support auto-increment keys.
*/
$identity = false;
}
$desc[$this->foldCase($row[$column_name])] = array(
'SCHEMA_NAME' => $this->foldCase($row[$owner]),
'TABLE_NAME' => $this->foldCase($row[$table_name]),
'COLUMN_NAME' => $this->foldCase($row[$column_name]),
'COLUMN_POSITION' => $row[$column_id],
'DATA_TYPE' => $row[$data_type],
'DEFAULT' => $row[$data_default],
'NULLABLE' => (bool) ($row[$nullable] == 'Y'),
'LENGTH' => $row[$data_length],
'SCALE' => $row[$data_scale],
'PRECISION' => $row[$data_precision],
'UNSIGNED' => null, // @todo
'PRIMARY' => $primary,
'PRIMARY_POSITION' => $primaryPosition,
'IDENTITY' => $identity
);
}
return $desc;
}
/**
* Return the most recent value from the specified sequence in the database.
* This is supported only on RDBMS brands that support sequences
* (e.g. Oracle, PostgreSQL, DB2). Other RDBMS brands return null.
*
* @param string $sequenceName
* @return integer
*/
public function lastSequenceId($sequenceName)
{
$this->_connect();
$value = $this->fetchOne('SELECT '.$this->quoteIdentifier($sequenceName, true).'.CURRVAL FROM dual');
return $value;
}
/**
* Generate a new value from the specified sequence in the database, and return it.
* This is supported only on RDBMS brands that support sequences
* (e.g. Oracle, PostgreSQL, DB2). Other RDBMS brands return null.
*
* @param string $sequenceName
* @return integer
*/
public function nextSequenceId($sequenceName)
{
$this->_connect();
$value = $this->fetchOne('SELECT '.$this->quoteIdentifier($sequenceName, true).'.NEXTVAL FROM dual');
return $value;
}
/**
* Gets the last ID generated automatically by an IDENTITY/AUTOINCREMENT column.
*
* As a convention, on RDBMS brands that support sequences
* (e.g. Oracle, PostgreSQL, DB2), this method forms the name of a sequence
* from the arguments and returns the last id generated by that sequence.
* On RDBMS brands that support IDENTITY/AUTOINCREMENT columns, this method
* returns the last value generated for such a column, and the table name
* argument is disregarded.
*
* Oracle does not support IDENTITY columns, so if the sequence is not
* specified, this method returns null.
*
* @param string $tableName OPTIONAL Name of table.
* @param string $primaryKey OPTIONAL Name of primary key column.
* @return string
* @throws Zend_Db_Adapter_Oracle_Exception
*/
public function lastInsertId($tableName = null, $primaryKey = null)
{
if ($tableName !== null) {
$sequenceName = $tableName;
if ($primaryKey) {
$sequenceName .= $this->foldCase("_$primaryKey");
}
$sequenceName .= $this->foldCase('_seq');
return $this->lastSequenceId($sequenceName);
}
// No support for IDENTITY columns; return null
return null;
}
/**
* Adds an adapter-specific LIMIT clause to the SELECT statement.
*
* @param string $sql
* @param integer $count
* @param integer $offset
* @throws Zend_Db_Adapter_Exception
* @return string
*/
public function limit($sql, $count, $offset = 0)
{
$count = intval($count);
if ($count <= 0) {
/** @see Zend_Db_Adapter_Exception */
// require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception("LIMIT argument count=$count is not valid");
}
$offset = intval($offset);
if ($offset < 0) {
/** @see Zend_Db_Adapter_Exception */
// require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception("LIMIT argument offset=$offset is not valid");
}
/**
* Oracle does not implement the LIMIT clause as some RDBMS do.
* We have to simulate it with subqueries and ROWNUM.
* Unfortunately because we use the column wildcard "*",
* this puts an extra column into the query result set.
*/
$limit_sql = "SELECT z2.*
FROM (
SELECT z1.*, ROWNUM AS \"zend_db_rownum\"
FROM (
" . $sql . "
) z1
) z2
WHERE z2.\"zend_db_rownum\" BETWEEN " . ($offset+1) . " AND " . ($offset+$count);
return $limit_sql;
}
}

View File

@ -0,0 +1,336 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Adapter
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Pgsql.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Db_Adapter_Pdo_Abstract
*/
// require_once 'Zend/Db/Adapter/Pdo/Abstract.php';
/**
* Class for connecting to PostgreSQL databases and performing common operations.
*
* @category Zend
* @package Zend_Db
* @subpackage Adapter
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Adapter_Pdo_Pgsql extends Zend_Db_Adapter_Pdo_Abstract
{
/**
* PDO type.
*
* @var string
*/
protected $_pdoType = 'pgsql';
/**
* Keys are UPPERCASE SQL datatypes or the constants
* Zend_Db::INT_TYPE, Zend_Db::BIGINT_TYPE, or Zend_Db::FLOAT_TYPE.
*
* Values are:
* 0 = 32-bit integer
* 1 = 64-bit integer
* 2 = float or decimal
*
* @var array Associative array of datatypes to values 0, 1, or 2.
*/
protected $_numericDataTypes = array(
Zend_Db::INT_TYPE => Zend_Db::INT_TYPE,
Zend_Db::BIGINT_TYPE => Zend_Db::BIGINT_TYPE,
Zend_Db::FLOAT_TYPE => Zend_Db::FLOAT_TYPE,
'INTEGER' => Zend_Db::INT_TYPE,
'SERIAL' => Zend_Db::INT_TYPE,
'SMALLINT' => Zend_Db::INT_TYPE,
'BIGINT' => Zend_Db::BIGINT_TYPE,
'BIGSERIAL' => Zend_Db::BIGINT_TYPE,
'DECIMAL' => Zend_Db::FLOAT_TYPE,
'DOUBLE PRECISION' => Zend_Db::FLOAT_TYPE,
'NUMERIC' => Zend_Db::FLOAT_TYPE,
'REAL' => Zend_Db::FLOAT_TYPE
);
/**
* Creates a PDO object and connects to the database.
*
* @return void
* @throws Zend_Db_Adapter_Exception
*/
protected function _connect()
{
if ($this->_connection) {
return;
}
parent::_connect();
if (!empty($this->_config['charset'])) {
$sql = "SET NAMES '" . $this->_config['charset'] . "'";
$this->_connection->exec($sql);
}
}
/**
* Returns a list of the tables in the database.
*
* @return array
*/
public function listTables()
{
// @todo use a better query with joins instead of subqueries
$sql = "SELECT c.relname AS table_name "
. "FROM pg_class c, pg_user u "
. "WHERE c.relowner = u.usesysid AND c.relkind = 'r' "
. "AND NOT EXISTS (SELECT 1 FROM pg_views WHERE viewname = c.relname) "
. "AND c.relname !~ '^(pg_|sql_)' "
. "UNION "
. "SELECT c.relname AS table_name "
. "FROM pg_class c "
. "WHERE c.relkind = 'r' "
. "AND NOT EXISTS (SELECT 1 FROM pg_views WHERE viewname = c.relname) "
. "AND NOT EXISTS (SELECT 1 FROM pg_user WHERE usesysid = c.relowner) "
. "AND c.relname !~ '^pg_'";
return $this->fetchCol($sql);
}
/**
* Returns the column descriptions for a table.
*
* The return value is an associative array keyed by the column name,
* as returned by the RDBMS.
*
* The value of each array element is an associative array
* with the following keys:
*
* SCHEMA_NAME => string; name of database or schema
* TABLE_NAME => string;
* COLUMN_NAME => string; column name
* COLUMN_POSITION => number; ordinal position of column in table
* DATA_TYPE => string; SQL datatype name of column
* DEFAULT => string; default expression of column, null if none
* NULLABLE => boolean; true if column can have nulls
* LENGTH => number; length of CHAR/VARCHAR
* SCALE => number; scale of NUMERIC/DECIMAL
* PRECISION => number; precision of NUMERIC/DECIMAL
* UNSIGNED => boolean; unsigned property of an integer type
* PRIMARY => boolean; true if column is part of the primary key
* PRIMARY_POSITION => integer; position of column in primary key
* IDENTITY => integer; true if column is auto-generated with unique values
*
* @todo Discover integer unsigned property.
*
* @param string $tableName
* @param string $schemaName OPTIONAL
* @return array
*/
public function describeTable($tableName, $schemaName = null)
{
$sql = "SELECT
a.attnum,
n.nspname,
c.relname,
a.attname AS colname,
t.typname AS type,
a.atttypmod,
FORMAT_TYPE(a.atttypid, a.atttypmod) AS complete_type,
d.adsrc AS default_value,
a.attnotnull AS notnull,
a.attlen AS length,
co.contype,
ARRAY_TO_STRING(co.conkey, ',') AS conkey
FROM pg_attribute AS a
JOIN pg_class AS c ON a.attrelid = c.oid
JOIN pg_namespace AS n ON c.relnamespace = n.oid
JOIN pg_type AS t ON a.atttypid = t.oid
LEFT OUTER JOIN pg_constraint AS co ON (co.conrelid = c.oid
AND a.attnum = ANY(co.conkey) AND co.contype = 'p')
LEFT OUTER JOIN pg_attrdef AS d ON d.adrelid = c.oid AND d.adnum = a.attnum
WHERE a.attnum > 0 AND c.relname = ".$this->quote($tableName);
if ($schemaName) {
$sql .= " AND n.nspname = ".$this->quote($schemaName);
}
$sql .= ' ORDER BY a.attnum';
$stmt = $this->query($sql);
// Use FETCH_NUM so we are not dependent on the CASE attribute of the PDO connection
$result = $stmt->fetchAll(Zend_Db::FETCH_NUM);
$attnum = 0;
$nspname = 1;
$relname = 2;
$colname = 3;
$type = 4;
$atttypemod = 5;
$complete_type = 6;
$default_value = 7;
$notnull = 8;
$length = 9;
$contype = 10;
$conkey = 11;
$desc = array();
foreach ($result as $key => $row) {
$defaultValue = $row[$default_value];
if ($row[$type] == 'varchar' || $row[$type] == 'bpchar' ) {
if (preg_match('/character(?: varying)?(?:\((\d+)\))?/', $row[$complete_type], $matches)) {
if (isset($matches[1])) {
$row[$length] = $matches[1];
} else {
$row[$length] = null; // unlimited
}
}
if (preg_match("/^'(.*?)'::(?:character varying|bpchar)$/", $defaultValue, $matches)) {
$defaultValue = $matches[1];
}
}
list($primary, $primaryPosition, $identity) = array(false, null, false);
if ($row[$contype] == 'p') {
$primary = true;
$primaryPosition = array_search($row[$attnum], explode(',', $row[$conkey])) + 1;
$identity = (bool) (preg_match('/^nextval/', $row[$default_value]));
}
$desc[$this->foldCase($row[$colname])] = array(
'SCHEMA_NAME' => $this->foldCase($row[$nspname]),
'TABLE_NAME' => $this->foldCase($row[$relname]),
'COLUMN_NAME' => $this->foldCase($row[$colname]),
'COLUMN_POSITION' => $row[$attnum],
'DATA_TYPE' => $row[$type],
'DEFAULT' => $defaultValue,
'NULLABLE' => (bool) ($row[$notnull] != 't'),
'LENGTH' => $row[$length],
'SCALE' => null, // @todo
'PRECISION' => null, // @todo
'UNSIGNED' => null, // @todo
'PRIMARY' => $primary,
'PRIMARY_POSITION' => $primaryPosition,
'IDENTITY' => $identity
);
}
return $desc;
}
/**
* Adds an adapter-specific LIMIT clause to the SELECT statement.
*
* @param string $sql
* @param integer $count
* @param integer $offset OPTIONAL
* @return string
*/
public function limit($sql, $count, $offset = 0)
{
$count = intval($count);
if ($count <= 0) {
/**
* @see Zend_Db_Adapter_Exception
*/
// require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception("LIMIT argument count=$count is not valid");
}
$offset = intval($offset);
if ($offset < 0) {
/**
* @see Zend_Db_Adapter_Exception
*/
// require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception("LIMIT argument offset=$offset is not valid");
}
$sql .= " LIMIT $count";
if ($offset > 0) {
$sql .= " OFFSET $offset";
}
return $sql;
}
/**
* Return the most recent value from the specified sequence in the database.
* This is supported only on RDBMS brands that support sequences
* (e.g. Oracle, PostgreSQL, DB2). Other RDBMS brands return null.
*
* @param string $sequenceName
* @return string
*/
public function lastSequenceId($sequenceName)
{
$this->_connect();
$sequenceName = str_replace($this->getQuoteIdentifierSymbol(), '', (string) $sequenceName);
$value = $this->fetchOne("SELECT CURRVAL("
. $this->quote($this->quoteIdentifier($sequenceName, true))
. ")");
return $value;
}
/**
* Generate a new value from the specified sequence in the database, and return it.
* This is supported only on RDBMS brands that support sequences
* (e.g. Oracle, PostgreSQL, DB2). Other RDBMS brands return null.
*
* @param string $sequenceName
* @return string
*/
public function nextSequenceId($sequenceName)
{
$this->_connect();
$sequenceName = str_replace($this->getQuoteIdentifierSymbol(), '', (string) $sequenceName);
$value = $this->fetchOne("SELECT NEXTVAL("
. $this->quote($this->quoteIdentifier($sequenceName, true))
. ")");
return $value;
}
/**
* Gets the last ID generated automatically by an IDENTITY/AUTOINCREMENT column.
*
* As a convention, on RDBMS brands that support sequences
* (e.g. Oracle, PostgreSQL, DB2), this method forms the name of a sequence
* from the arguments and returns the last id generated by that sequence.
* On RDBMS brands that support IDENTITY/AUTOINCREMENT columns, this method
* returns the last value generated for such a column, and the table name
* argument is disregarded.
*
* @param string $tableName OPTIONAL Name of table.
* @param string $primaryKey OPTIONAL Name of primary key column.
* @return string
*/
public function lastInsertId($tableName = null, $primaryKey = null)
{
if ($tableName !== null) {
$sequenceName = $tableName;
if ($primaryKey) {
$sequenceName .= "_$primaryKey";
}
$sequenceName .= '_seq';
return $this->lastSequenceId($sequenceName);
}
return $this->_connection->lastInsertId($tableName);
}
}

View File

@ -0,0 +1,297 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Adapter
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Sqlite.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Db_Adapter_Pdo_Abstract
*/
// require_once 'Zend/Db/Adapter/Pdo/Abstract.php';
/**
* Class for connecting to SQLite2 and SQLite3 databases and performing common operations.
*
* @category Zend
* @package Zend_Db
* @subpackage Adapter
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Adapter_Pdo_Sqlite extends Zend_Db_Adapter_Pdo_Abstract
{
/**
* PDO type
*
* @var string
*/
protected $_pdoType = 'sqlite';
/**
* Keys are UPPERCASE SQL datatypes or the constants
* Zend_Db::INT_TYPE, Zend_Db::BIGINT_TYPE, or Zend_Db::FLOAT_TYPE.
*
* Values are:
* 0 = 32-bit integer
* 1 = 64-bit integer
* 2 = float or decimal
*
* @var array Associative array of datatypes to values 0, 1, or 2.
*/
protected $_numericDataTypes = array(
Zend_Db::INT_TYPE => Zend_Db::INT_TYPE,
Zend_Db::BIGINT_TYPE => Zend_Db::BIGINT_TYPE,
Zend_Db::FLOAT_TYPE => Zend_Db::FLOAT_TYPE,
'INTEGER' => Zend_Db::BIGINT_TYPE,
'REAL' => Zend_Db::FLOAT_TYPE
);
/**
* Constructor.
*
* $config is an array of key/value pairs containing configuration
* options. Note that the SQLite options are different than most of
* the other PDO adapters in that no username or password are needed.
* Also, an extra config key "sqlite2" specifies compatibility mode.
*
* dbname => (string) The name of the database to user (required,
* use :memory: for memory-based database)
*
* sqlite2 => (boolean) PDO_SQLITE defaults to SQLite 3. For compatibility
* with an older SQLite 2 database, set this to TRUE.
*
* @param array $config An array of configuration keys.
*/
public function __construct(array $config = array())
{
if (isset($config['sqlite2']) && $config['sqlite2']) {
$this->_pdoType = 'sqlite2';
}
// SQLite uses no username/password. Stub to satisfy parent::_connect()
$this->_config['username'] = null;
$this->_config['password'] = null;
return parent::__construct($config);
}
/**
* Check for config options that are mandatory.
* Throw exceptions if any are missing.
*
* @param array $config
* @throws Zend_Db_Adapter_Exception
*/
protected function _checkRequiredOptions(array $config)
{
// we need at least a dbname
if (! array_key_exists('dbname', $config)) {
/** @see Zend_Db_Adapter_Exception */
// require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception("Configuration array must have a key for 'dbname' that names the database instance");
}
}
/**
* DSN builder
*/
protected function _dsn()
{
return $this->_pdoType .':'. $this->_config['dbname'];
}
/**
* Special configuration for SQLite behavior: make sure that result sets
* contain keys like 'column' instead of 'table.column'.
*
* @throws Zend_Db_Adapter_Exception
*/
protected function _connect()
{
/**
* if we already have a PDO object, no need to re-connect.
*/
if ($this->_connection) {
return;
}
parent::_connect();
$retval = $this->_connection->exec('PRAGMA full_column_names=0');
if ($retval === false) {
$error = $this->_connection->errorInfo();
/** @see Zend_Db_Adapter_Exception */
// require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception($error[2]);
}
$retval = $this->_connection->exec('PRAGMA short_column_names=1');
if ($retval === false) {
$error = $this->_connection->errorInfo();
/** @see Zend_Db_Adapter_Exception */
// require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception($error[2]);
}
}
/**
* Returns a list of the tables in the database.
*
* @return array
*/
public function listTables()
{
$sql = "SELECT name FROM sqlite_master WHERE type='table' "
. "UNION ALL SELECT name FROM sqlite_temp_master "
. "WHERE type='table' ORDER BY name";
return $this->fetchCol($sql);
}
/**
* Returns the column descriptions for a table.
*
* The return value is an associative array keyed by the column name,
* as returned by the RDBMS.
*
* The value of each array element is an associative array
* with the following keys:
*
* SCHEMA_NAME => string; name of database or schema
* TABLE_NAME => string;
* COLUMN_NAME => string; column name
* COLUMN_POSITION => number; ordinal position of column in table
* DATA_TYPE => string; SQL datatype name of column
* DEFAULT => string; default expression of column, null if none
* NULLABLE => boolean; true if column can have nulls
* LENGTH => number; length of CHAR/VARCHAR
* SCALE => number; scale of NUMERIC/DECIMAL
* PRECISION => number; precision of NUMERIC/DECIMAL
* UNSIGNED => boolean; unsigned property of an integer type
* PRIMARY => boolean; true if column is part of the primary key
* PRIMARY_POSITION => integer; position of column in primary key
* IDENTITY => integer; true if column is auto-generated with unique values
*
* @param string $tableName
* @param string $schemaName OPTIONAL
* @return array
*/
public function describeTable($tableName, $schemaName = null)
{
$sql = 'PRAGMA ';
if ($schemaName) {
$sql .= $this->quoteIdentifier($schemaName) . '.';
}
$sql .= 'table_info('.$this->quoteIdentifier($tableName).')';
$stmt = $this->query($sql);
/**
* Use FETCH_NUM so we are not dependent on the CASE attribute of the PDO connection
*/
$result = $stmt->fetchAll(Zend_Db::FETCH_NUM);
$cid = 0;
$name = 1;
$type = 2;
$notnull = 3;
$dflt_value = 4;
$pk = 5;
$desc = array();
$p = 1;
foreach ($result as $key => $row) {
list($length, $scale, $precision, $primary, $primaryPosition, $identity) =
array(null, null, null, false, null, false);
if (preg_match('/^((?:var)?char)\((\d+)\)/i', $row[$type], $matches)) {
$row[$type] = $matches[1];
$length = $matches[2];
} else if (preg_match('/^decimal\((\d+),(\d+)\)/i', $row[$type], $matches)) {
$row[$type] = 'DECIMAL';
$precision = $matches[1];
$scale = $matches[2];
}
if ((bool) $row[$pk]) {
$primary = true;
$primaryPosition = $p;
/**
* SQLite INTEGER primary key is always auto-increment.
*/
$identity = (bool) ($row[$type] == 'INTEGER');
++$p;
}
$desc[$this->foldCase($row[$name])] = array(
'SCHEMA_NAME' => $this->foldCase($schemaName),
'TABLE_NAME' => $this->foldCase($tableName),
'COLUMN_NAME' => $this->foldCase($row[$name]),
'COLUMN_POSITION' => $row[$cid]+1,
'DATA_TYPE' => $row[$type],
'DEFAULT' => $row[$dflt_value],
'NULLABLE' => ! (bool) $row[$notnull],
'LENGTH' => $length,
'SCALE' => $scale,
'PRECISION' => $precision,
'UNSIGNED' => null, // Sqlite3 does not support unsigned data
'PRIMARY' => $primary,
'PRIMARY_POSITION' => $primaryPosition,
'IDENTITY' => $identity
);
}
return $desc;
}
/**
* Adds an adapter-specific LIMIT clause to the SELECT statement.
*
* @param string $sql
* @param integer $count
* @param integer $offset OPTIONAL
* @return string
*/
public function limit($sql, $count, $offset = 0)
{
$count = intval($count);
if ($count <= 0) {
/** @see Zend_Db_Adapter_Exception */
// require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception("LIMIT argument count=$count is not valid");
}
$offset = intval($offset);
if ($offset < 0) {
/** @see Zend_Db_Adapter_Exception */
// require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception("LIMIT argument offset=$offset is not valid");
}
$sql .= " LIMIT $count";
if ($offset > 0) {
$sql .= " OFFSET $offset";
}
return $sql;
}
}

View File

@ -0,0 +1,673 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Adapter
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Sqlsrv.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Db_Adapter_Abstract
*/
// require_once 'Zend/Db/Adapter/Abstract.php';
/**
* @see Zend_Db_Statement_Sqlsrv
*/
// require_once 'Zend/Db/Statement/Sqlsrv.php';
/**
* @category Zend
* @package Zend_Db
* @subpackage Adapter
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Adapter_Sqlsrv extends Zend_Db_Adapter_Abstract
{
/**
* User-provided configuration.
*
* Basic keys are:
*
* username => (string) Connect to the database as this username.
* password => (string) Password associated with the username.
* dbname => The name of the local SQL Server instance
*
* @var array
*/
protected $_config = array(
'dbname' => null,
'username' => null,
'password' => null,
);
/**
* Last insert id from INSERT query
*
* @var int
*/
protected $_lastInsertId;
/**
* Query used to fetch last insert id
*
* @var string
*/
protected $_lastInsertSQL = 'SELECT SCOPE_IDENTITY() as Current_Identity';
/**
* Keys are UPPERCASE SQL datatypes or the constants
* Zend_Db::INT_TYPE, Zend_Db::BIGINT_TYPE, or Zend_Db::FLOAT_TYPE.
*
* Values are:
* 0 = 32-bit integer
* 1 = 64-bit integer
* 2 = float or decimal
*
* @var array Associative array of datatypes to values 0, 1, or 2.
*/
protected $_numericDataTypes = array(
Zend_Db::INT_TYPE => Zend_Db::INT_TYPE,
Zend_Db::BIGINT_TYPE => Zend_Db::BIGINT_TYPE,
Zend_Db::FLOAT_TYPE => Zend_Db::FLOAT_TYPE,
'INT' => Zend_Db::INT_TYPE,
'SMALLINT' => Zend_Db::INT_TYPE,
'TINYINT' => Zend_Db::INT_TYPE,
'BIGINT' => Zend_Db::BIGINT_TYPE,
'DECIMAL' => Zend_Db::FLOAT_TYPE,
'FLOAT' => Zend_Db::FLOAT_TYPE,
'MONEY' => Zend_Db::FLOAT_TYPE,
'NUMERIC' => Zend_Db::FLOAT_TYPE,
'REAL' => Zend_Db::FLOAT_TYPE,
'SMALLMONEY' => Zend_Db::FLOAT_TYPE,
);
/**
* Default class name for a DB statement.
*
* @var string
*/
protected $_defaultStmtClass = 'Zend_Db_Statement_Sqlsrv';
/**
* Creates a connection resource.
*
* @return void
* @throws Zend_Db_Adapter_Sqlsrv_Exception
*/
protected function _connect()
{
if (is_resource($this->_connection)) {
// connection already exists
return;
}
if (!extension_loaded('sqlsrv')) {
/**
* @see Zend_Db_Adapter_Sqlsrv_Exception
*/
// require_once 'Zend/Db/Adapter/Sqlsrv/Exception.php';
throw new Zend_Db_Adapter_Sqlsrv_Exception('The Sqlsrv extension is required for this adapter but the extension is not loaded');
}
$serverName = $this->_config['host'];
if (isset($this->_config['port'])) {
$port = (integer) $this->_config['port'];
$serverName .= ', ' . $port;
}
$connectionInfo = array(
'Database' => $this->_config['dbname'],
);
if (isset($this->_config['username']) && isset($this->_config['password']))
{
$connectionInfo += array(
'UID' => $this->_config['username'],
'PWD' => $this->_config['password'],
);
}
// else - windows authentication
if (!empty($this->_config['driver_options'])) {
foreach ($this->_config['driver_options'] as $option => $value) {
// A value may be a constant.
if (is_string($value)) {
$constantName = strtoupper($value);
if (defined($constantName)) {
$connectionInfo[$option] = constant($constantName);
} else {
$connectionInfo[$option] = $value;
}
}
}
}
$this->_connection = sqlsrv_connect($serverName, $connectionInfo);
if (!$this->_connection) {
/**
* @see Zend_Db_Adapter_Sqlsrv_Exception
*/
// require_once 'Zend/Db/Adapter/Sqlsrv/Exception.php';
throw new Zend_Db_Adapter_Sqlsrv_Exception(sqlsrv_errors());
}
}
/**
* Check for config options that are mandatory.
* Throw exceptions if any are missing.
*
* @param array $config
* @throws Zend_Db_Adapter_Exception
*/
protected function _checkRequiredOptions(array $config)
{
// we need at least a dbname
if (! array_key_exists('dbname', $config)) {
/** @see Zend_Db_Adapter_Exception */
// require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception("Configuration array must have a key for 'dbname' that names the database instance");
}
if (! array_key_exists('password', $config) && array_key_exists('username', $config)) {
/**
* @see Zend_Db_Adapter_Exception
*/
// require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception("Configuration array must have a key for 'password' for login credentials.
If Windows Authentication is desired, both keys 'username' and 'password' should be ommited from config.");
}
if (array_key_exists('password', $config) && !array_key_exists('username', $config)) {
/**
* @see Zend_Db_Adapter_Exception
*/
// require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception("Configuration array must have a key for 'username' for login credentials.
If Windows Authentication is desired, both keys 'username' and 'password' should be ommited from config.");
}
}
/**
* Set the transaction isoltion level.
*
* @param integer|null $level A fetch mode from SQLSRV_TXN_*.
* @return true
* @throws Zend_Db_Adapter_Sqlsrv_Exception
*/
public function setTransactionIsolationLevel($level = null)
{
$this->_connect();
$sql = null;
// Default transaction level in sql server
if ($level === null)
{
$level = SQLSRV_TXN_READ_COMMITTED;
}
switch ($level) {
case SQLSRV_TXN_READ_UNCOMMITTED:
$sql = "READ UNCOMMITTED";
break;
case SQLSRV_TXN_READ_COMMITTED:
$sql = "READ COMMITTED";
break;
case SQLSRV_TXN_REPEATABLE_READ:
$sql = "REPEATABLE READ";
break;
case SQLSRV_TXN_SNAPSHOT:
$sql = "SNAPSHOT";
break;
case SQLSRV_TXN_SERIALIZABLE:
$sql = "SERIALIZABLE";
break;
default:
// require_once 'Zend/Db/Adapter/Sqlsrv/Exception.php';
throw new Zend_Db_Adapter_Sqlsrv_Exception("Invalid transaction isolation level mode '$level' specified");
}
if (!sqlsrv_query($this->_connection, "SET TRANSACTION ISOLATION LEVEL $sql;")) {
// require_once 'Zend/Db/Adapter/Sqlsrv/Exception.php';
throw new Zend_Db_Adapter_Sqlsrv_Exception("Transaction cannot be changed to '$level'");
}
return true;
}
/**
* Test if a connection is active
*
* @return boolean
*/
public function isConnected()
{
return (is_resource($this->_connection)
&& (get_resource_type($this->_connection) == 'SQL Server Connection')
);
}
/**
* Force the connection to close.
*
* @return void
*/
public function closeConnection()
{
if ($this->isConnected()) {
sqlsrv_close($this->_connection);
}
$this->_connection = null;
}
/**
* Returns an SQL statement for preparation.
*
* @param string $sql The SQL statement with placeholders.
* @return Zend_Db_Statement_Sqlsrv
*/
public function prepare($sql)
{
$this->_connect();
$stmtClass = $this->_defaultStmtClass;
if (!class_exists($stmtClass)) {
/**
* @see Zend_Loader
*/
// require_once 'Zend/Loader.php';
Zend_Loader::loadClass($stmtClass);
}
$stmt = new $stmtClass($this, $sql);
$stmt->setFetchMode($this->_fetchMode);
return $stmt;
}
/**
* Quote a raw string.
*
* @param string $value Raw string
* @return string Quoted string
*/
protected function _quote($value)
{
if (is_int($value)) {
return $value;
} elseif (is_float($value)) {
return sprintf('%F', $value);
}
return "'" . str_replace("'", "''", $value) . "'";
}
/**
* Gets the last ID generated automatically by an IDENTITY/AUTOINCREMENT column.
*
* As a convention, on RDBMS brands that support sequences
* (e.g. Oracle, PostgreSQL, DB2), this method forms the name of a sequence
* from the arguments and returns the last id generated by that sequence.
* On RDBMS brands that support IDENTITY/AUTOINCREMENT columns, this method
* returns the last value generated for such a column, and the table name
* argument is disregarded.
*
* @param string $tableName OPTIONAL Name of table.
* @param string $primaryKey OPTIONAL Name of primary key column.
* @return string
*/
public function lastInsertId($tableName = null, $primaryKey = null)
{
if ($tableName) {
$tableName = $this->quote($tableName);
$sql = 'SELECT IDENT_CURRENT (' . $tableName . ') as Current_Identity';
return (string) $this->fetchOne($sql);
}
if ($this->_lastInsertId > 0) {
return (string) $this->_lastInsertId;
}
$sql = $this->_lastInsertSQL;
return (string) $this->fetchOne($sql);
}
/**
* Inserts a table row with specified data.
*
* @param mixed $table The table to insert data into.
* @param array $bind Column-value pairs.
* @return int The number of affected rows.
*/
public function insert($table, array $bind)
{
// extract and quote col names from the array keys
$cols = array();
$vals = array();
foreach ($bind as $col => $val) {
$cols[] = $this->quoteIdentifier($col, true);
if ($val instanceof Zend_Db_Expr) {
$vals[] = $val->__toString();
unset($bind[$col]);
} else {
$vals[] = '?';
}
}
// build the statement
$sql = "INSERT INTO "
. $this->quoteIdentifier($table, true)
. ' (' . implode(', ', $cols) . ') '
. 'VALUES (' . implode(', ', $vals) . ')'
. ' ' . $this->_lastInsertSQL;
// execute the statement and return the number of affected rows
$stmt = $this->query($sql, array_values($bind));
$result = $stmt->rowCount();
$stmt->nextRowset();
$this->_lastInsertId = $stmt->fetchColumn();
return $result;
}
/**
* Returns a list of the tables in the database.
*
* @return array
*/
public function listTables()
{
$this->_connect();
$sql = "SELECT name FROM sysobjects WHERE type = 'U' ORDER BY name";
return $this->fetchCol($sql);
}
/**
* Returns the column descriptions for a table.
*
* The return value is an associative array keyed by the column name,
* as returned by the RDBMS.
*
* The value of each array element is an associative array
* with the following keys:
*
* SCHEMA_NAME => string; name of schema
* TABLE_NAME => string;
* COLUMN_NAME => string; column name
* COLUMN_POSITION => number; ordinal position of column in table
* DATA_TYPE => string; SQL datatype name of column
* DEFAULT => string; default expression of column, null if none
* NULLABLE => boolean; true if column can have nulls
* LENGTH => number; length of CHAR/VARCHAR
* SCALE => number; scale of NUMERIC/DECIMAL
* PRECISION => number; precision of NUMERIC/DECIMAL
* UNSIGNED => boolean; unsigned property of an integer type
* PRIMARY => boolean; true if column is part of the primary key
* PRIMARY_POSITION => integer; position of column in primary key
* IDENTITY => integer; true if column is auto-generated with unique values
*
* @todo Discover integer unsigned property.
*
* @param string $tableName
* @param string $schemaName OPTIONAL
* @return array
*/
public function describeTable($tableName, $schemaName = null)
{
/**
* Discover metadata information about this table.
*/
$sql = "exec sp_columns @table_name = " . $this->quoteIdentifier($tableName, true);
$stmt = $this->query($sql);
$result = $stmt->fetchAll(Zend_Db::FETCH_NUM);
// ZF-7698
$stmt->closeCursor();
if (count($result) == 0) {
return array();
}
$owner = 1;
$table_name = 2;
$column_name = 3;
$type_name = 5;
$precision = 6;
$length = 7;
$scale = 8;
$nullable = 10;
$column_def = 12;
$column_position = 16;
/**
* Discover primary key column(s) for this table.
*/
$tableOwner = $result[0][$owner];
$sql = "exec sp_pkeys @table_owner = " . $tableOwner
. ", @table_name = " . $this->quoteIdentifier($tableName, true);
$stmt = $this->query($sql);
$primaryKeysResult = $stmt->fetchAll(Zend_Db::FETCH_NUM);
$primaryKeyColumn = array();
// Per http://msdn.microsoft.com/en-us/library/ms189813.aspx,
// results from sp_keys stored procedure are:
// 0=TABLE_QUALIFIER 1=TABLE_OWNER 2=TABLE_NAME 3=COLUMN_NAME 4=KEY_SEQ 5=PK_NAME
$pkey_column_name = 3;
$pkey_key_seq = 4;
foreach ($primaryKeysResult as $pkeysRow) {
$primaryKeyColumn[$pkeysRow[$pkey_column_name]] = $pkeysRow[$pkey_key_seq];
}
$desc = array();
$p = 1;
foreach ($result as $key => $row) {
$identity = false;
$words = explode(' ', $row[$type_name], 2);
if (isset($words[0])) {
$type = $words[0];
if (isset($words[1])) {
$identity = (bool) preg_match('/identity/', $words[1]);
}
}
$isPrimary = array_key_exists($row[$column_name], $primaryKeyColumn);
if ($isPrimary) {
$primaryPosition = $primaryKeyColumn[$row[$column_name]];
} else {
$primaryPosition = null;
}
$desc[$this->foldCase($row[$column_name])] = array(
'SCHEMA_NAME' => null, // @todo
'TABLE_NAME' => $this->foldCase($row[$table_name]),
'COLUMN_NAME' => $this->foldCase($row[$column_name]),
'COLUMN_POSITION' => (int) $row[$column_position],
'DATA_TYPE' => $type,
'DEFAULT' => $row[$column_def],
'NULLABLE' => (bool) $row[$nullable],
'LENGTH' => $row[$length],
'SCALE' => $row[$scale],
'PRECISION' => $row[$precision],
'UNSIGNED' => null, // @todo
'PRIMARY' => $isPrimary,
'PRIMARY_POSITION' => $primaryPosition,
'IDENTITY' => $identity,
);
}
return $desc;
}
/**
* Leave autocommit mode and begin a transaction.
*
* @return void
* @throws Zend_Db_Adapter_Sqlsrv_Exception
*/
protected function _beginTransaction()
{
if (!sqlsrv_begin_transaction($this->_connection)) {
// require_once 'Zend/Db/Adapter/Sqlsrv/Exception.php';
throw new Zend_Db_Adapter_Sqlsrv_Exception(sqlsrv_errors());
}
}
/**
* Commit a transaction and return to autocommit mode.
*
* @return void
* @throws Zend_Db_Adapter_Sqlsrv_Exception
*/
protected function _commit()
{
if (!sqlsrv_commit($this->_connection)) {
// require_once 'Zend/Db/Adapter/Sqlsrv/Exception.php';
throw new Zend_Db_Adapter_Sqlsrv_Exception(sqlsrv_errors());
}
}
/**
* Roll back a transaction and return to autocommit mode.
*
* @return void
* @throws Zend_Db_Adapter_Sqlsrv_Exception
*/
protected function _rollBack()
{
if (!sqlsrv_rollback($this->_connection)) {
// require_once 'Zend/Db/Adapter/Sqlsrv/Exception.php';
throw new Zend_Db_Adapter_Sqlsrv_Exception(sqlsrv_errors());
}
}
/**
* Set the fetch mode.
*
* @todo Support FETCH_CLASS and FETCH_INTO.
*
* @param integer $mode A fetch mode.
* @return void
* @throws Zend_Db_Adapter_Sqlsrv_Exception
*/
public function setFetchMode($mode)
{
switch ($mode) {
case Zend_Db::FETCH_NUM: // seq array
case Zend_Db::FETCH_ASSOC: // assoc array
case Zend_Db::FETCH_BOTH: // seq+assoc array
case Zend_Db::FETCH_OBJ: // object
$this->_fetchMode = $mode;
break;
case Zend_Db::FETCH_BOUND: // bound to PHP variable
// require_once 'Zend/Db/Adapter/Sqlsrv/Exception.php';
throw new Zend_Db_Adapter_Sqlsrv_Exception('FETCH_BOUND is not supported yet');
break;
default:
// require_once 'Zend/Db/Adapter/Sqlsrv/Exception.php';
throw new Zend_Db_Adapter_Sqlsrv_Exception("Invalid fetch mode '$mode' specified");
break;
}
}
/**
* Adds an adapter-specific LIMIT clause to the SELECT statement.
*
* @param string $sql
* @param integer $count
* @param integer $offset OPTIONAL
* @return string
* @throws Zend_Db_Adapter_Sqlsrv_Exception
*/
public function limit($sql, $count, $offset = 0)
{
$count = intval($count);
if ($count <= 0) {
// require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception("LIMIT argument count=$count is not valid");
}
$offset = intval($offset);
if ($offset < 0) {
/** @see Zend_Db_Adapter_Exception */
// require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception("LIMIT argument offset=$offset is not valid");
}
if ($offset == 0) {
$sql = preg_replace('/^SELECT\s/i', 'SELECT TOP ' . $count . ' ', $sql);
} else {
$orderby = stristr($sql, 'ORDER BY');
if (!$orderby) {
$over = 'ORDER BY (SELECT 0)';
} else {
$over = preg_replace('/\"[^,]*\".\"([^,]*)\"/i', '"inner_tbl"."$1"', $orderby);
}
// Remove ORDER BY clause from $sql
$sql = preg_replace('/\s+ORDER BY(.*)/', '', $sql);
// Add ORDER BY clause as an argument for ROW_NUMBER()
$sql = "SELECT ROW_NUMBER() OVER ($over) AS \"ZEND_DB_ROWNUM\", * FROM ($sql) AS inner_tbl";
$start = $offset + 1;
$end = $offset + $count;
$sql = "WITH outer_tbl AS ($sql) SELECT * FROM outer_tbl WHERE \"ZEND_DB_ROWNUM\" BETWEEN $start AND $end";
}
return $sql;
}
/**
* Check if the adapter supports real SQL parameters.
*
* @param string $type 'positional' or 'named'
* @return bool
*/
public function supportsParameters($type)
{
if ($type == 'positional') {
return true;
}
// if its 'named' or anything else
return false;
}
/**
* Retrieve server version in PHP style
*
* @return string
*/
public function getServerVersion()
{
$this->_connect();
$serverInfo = sqlsrv_server_info($this->_connection);
if ($serverInfo !== false) {
return $serverInfo['SQLServerVersion'];
}
return null;
}
}

View File

@ -0,0 +1,63 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Adapter
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Exception.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Db_Adapter_Exception
*/
// require_once 'Zend/Db/Adapter/Exception.php';
/**
* Zend_Db_Adapter_Sqlsrv_Exception
*
* @category Zend
* @package Zend_Db
* @subpackage Adapter
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Adapter_Sqlsrv_Exception extends Zend_Db_Adapter_Exception
{
/**
* Constructor
*
* If $message is an array, the assumption is that the return value of
* sqlsrv_errors() was provided. If so, it then retrieves the most recent
* error from that stack, and sets the message and code based on it.
*
* @param null|array|string $message
* @param null|int $code
*/
public function __construct($message = null, $code = 0)
{
if (is_array($message)) {
// Error should be array of errors
// We only need first one (?)
if (isset($message[0])) {
$message = $message[0];
}
$code = (int) $message['code'];
$message = (string) $message['message'];
}
parent::__construct($message, $code, new Exception($message, $code));
}
}

View File

@ -0,0 +1,35 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Exception.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* Zend_Exception
*/
// require_once 'Zend/Exception.php';
/**
* @category Zend
* @package Zend_Db
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Exception extends Zend_Exception
{
}

View File

@ -0,0 +1,77 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Expr
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Expr.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* Class for SQL SELECT fragments.
*
* This class simply holds a string, so that fragments of SQL statements can be
* distinguished from identifiers and values that should be implicitly quoted
* when interpolated into SQL statements.
*
* For example, when specifying a primary key value when inserting into a new
* row, some RDBMS brands may require you to use an expression to generate the
* new value of a sequence. If this expression is treated as an identifier,
* it will be quoted and the expression will not be evaluated. Another example
* is that you can use Zend_Db_Expr in the Zend_Db_Select::order() method to
* order by an expression instead of simply a column name.
*
* The way this works is that in each context in which a column name can be
* specified to methods of Zend_Db classes, if the value is an instance of
* Zend_Db_Expr instead of a plain string, then the expression is not quoted.
* If it is a plain string, it is assumed to be a plain column name.
*
* @category Zend
* @package Zend_Db
* @subpackage Expr
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Expr
{
/**
* Storage for the SQL expression.
*
* @var string
*/
protected $_expression;
/**
* Instantiate an expression, which is just a string stored as
* an instance member variable.
*
* @param string $expression The string containing a SQL expression.
*/
public function __construct($expression)
{
$this->_expression = (string) $expression;
}
/**
* @return string The string of the SQL expression stored in this object.
*/
public function __toString()
{
return $this->_expression;
}
}

View File

@ -0,0 +1,471 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Profiler
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Profiler.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @category Zend
* @package Zend_Db
* @subpackage Profiler
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Profiler
{
/**
* A connection operation or selecting a database.
*/
const CONNECT = 1;
/**
* Any general database query that does not fit into the other constants.
*/
const QUERY = 2;
/**
* Adding new data to the database, such as SQL's INSERT.
*/
const INSERT = 4;
/**
* Updating existing information in the database, such as SQL's UPDATE.
*
*/
const UPDATE = 8;
/**
* An operation related to deleting data in the database,
* such as SQL's DELETE.
*/
const DELETE = 16;
/**
* Retrieving information from the database, such as SQL's SELECT.
*/
const SELECT = 32;
/**
* Transactional operation, such as start transaction, commit, or rollback.
*/
const TRANSACTION = 64;
/**
* Inform that a query is stored (in case of filtering)
*/
const STORED = 'stored';
/**
* Inform that a query is ignored (in case of filtering)
*/
const IGNORED = 'ignored';
/**
* Array of Zend_Db_Profiler_Query objects.
*
* @var array
*/
protected $_queryProfiles = array();
/**
* Stores enabled state of the profiler. If set to False, calls to
* queryStart() will simply be ignored.
*
* @var boolean
*/
protected $_enabled = false;
/**
* Stores the number of seconds to filter. NULL if filtering by time is
* disabled. If an integer is stored here, profiles whose elapsed time
* is less than this value in seconds will be unset from
* the self::$_queryProfiles array.
*
* @var integer
*/
protected $_filterElapsedSecs = null;
/**
* Logical OR of any of the filter constants. NULL if filtering by query
* type is disable. If an integer is stored here, it is the logical OR of
* any of the query type constants. When the query ends, if it is not
* one of the types specified, it will be unset from the
* self::$_queryProfiles array.
*
* @var integer
*/
protected $_filterTypes = null;
/**
* Class constructor. The profiler is disabled by default unless it is
* specifically enabled by passing in $enabled here or calling setEnabled().
*
* @param boolean $enabled
* @return void
*/
public function __construct($enabled = false)
{
$this->setEnabled($enabled);
}
/**
* Enable or disable the profiler. If $enable is false, the profiler
* is disabled and will not log any queries sent to it.
*
* @param boolean $enable
* @return Zend_Db_Profiler Provides a fluent interface
*/
public function setEnabled($enable)
{
$this->_enabled = (boolean) $enable;
return $this;
}
/**
* Get the current state of enable. If True is returned,
* the profiler is enabled.
*
* @return boolean
*/
public function getEnabled()
{
return $this->_enabled;
}
/**
* Sets a minimum number of seconds for saving query profiles. If this
* is set, only those queries whose elapsed time is equal or greater than
* $minimumSeconds will be saved. To save all queries regardless of
* elapsed time, set $minimumSeconds to null.
*
* @param integer $minimumSeconds OPTIONAL
* @return Zend_Db_Profiler Provides a fluent interface
*/
public function setFilterElapsedSecs($minimumSeconds = null)
{
if (null === $minimumSeconds) {
$this->_filterElapsedSecs = null;
} else {
$this->_filterElapsedSecs = (integer) $minimumSeconds;
}
return $this;
}
/**
* Returns the minimum number of seconds for saving query profiles, or null if
* query profiles are saved regardless of elapsed time.
*
* @return integer|null
*/
public function getFilterElapsedSecs()
{
return $this->_filterElapsedSecs;
}
/**
* Sets the types of query profiles to save. Set $queryType to one of
* the Zend_Db_Profiler::* constants to only save profiles for that type of
* query. To save more than one type, logical OR them together. To
* save all queries regardless of type, set $queryType to null.
*
* @param integer $queryTypes OPTIONAL
* @return Zend_Db_Profiler Provides a fluent interface
*/
public function setFilterQueryType($queryTypes = null)
{
$this->_filterTypes = $queryTypes;
return $this;
}
/**
* Returns the types of query profiles saved, or null if queries are saved regardless
* of their types.
*
* @return integer|null
* @see Zend_Db_Profiler::setFilterQueryType()
*/
public function getFilterQueryType()
{
return $this->_filterTypes;
}
/**
* Clears the history of any past query profiles. This is relentless
* and will even clear queries that were started and may not have
* been marked as ended.
*
* @return Zend_Db_Profiler Provides a fluent interface
*/
public function clear()
{
$this->_queryProfiles = array();
return $this;
}
/**
* @param integer $queryId
* @return integer or null
*/
public function queryClone(Zend_Db_Profiler_Query $query)
{
$this->_queryProfiles[] = clone $query;
end($this->_queryProfiles);
return key($this->_queryProfiles);
}
/**
* Starts a query. Creates a new query profile object (Zend_Db_Profiler_Query)
* and returns the "query profiler handle". Run the query, then call
* queryEnd() and pass it this handle to make the query as ended and
* record the time. If the profiler is not enabled, this takes no
* action and immediately returns null.
*
* @param string $queryText SQL statement
* @param integer $queryType OPTIONAL Type of query, one of the Zend_Db_Profiler::* constants
* @return integer|null
*/
public function queryStart($queryText, $queryType = null)
{
if (!$this->_enabled) {
return null;
}
// make sure we have a query type
if (null === $queryType) {
switch (strtolower(substr(ltrim($queryText), 0, 6))) {
case 'insert':
$queryType = self::INSERT;
break;
case 'update':
$queryType = self::UPDATE;
break;
case 'delete':
$queryType = self::DELETE;
break;
case 'select':
$queryType = self::SELECT;
break;
default:
$queryType = self::QUERY;
break;
}
}
/**
* @see Zend_Db_Profiler_Query
*/
// require_once 'Zend/Db/Profiler/Query.php';
$this->_queryProfiles[] = new Zend_Db_Profiler_Query($queryText, $queryType);
end($this->_queryProfiles);
return key($this->_queryProfiles);
}
/**
* Ends a query. Pass it the handle that was returned by queryStart().
* This will mark the query as ended and save the time.
*
* @param integer $queryId
* @throws Zend_Db_Profiler_Exception
* @return void
*/
public function queryEnd($queryId)
{
// Don't do anything if the Zend_Db_Profiler is not enabled.
if (!$this->_enabled) {
return self::IGNORED;
}
// Check for a valid query handle.
if (!isset($this->_queryProfiles[$queryId])) {
/**
* @see Zend_Db_Profiler_Exception
*/
// require_once 'Zend/Db/Profiler/Exception.php';
throw new Zend_Db_Profiler_Exception("Profiler has no query with handle '$queryId'.");
}
$qp = $this->_queryProfiles[$queryId];
// Ensure that the query profile has not already ended
if ($qp->hasEnded()) {
/**
* @see Zend_Db_Profiler_Exception
*/
// require_once 'Zend/Db/Profiler/Exception.php';
throw new Zend_Db_Profiler_Exception("Query with profiler handle '$queryId' has already ended.");
}
// End the query profile so that the elapsed time can be calculated.
$qp->end();
/**
* If filtering by elapsed time is enabled, only keep the profile if
* it ran for the minimum time.
*/
if (null !== $this->_filterElapsedSecs && $qp->getElapsedSecs() < $this->_filterElapsedSecs) {
unset($this->_queryProfiles[$queryId]);
return self::IGNORED;
}
/**
* If filtering by query type is enabled, only keep the query if
* it was one of the allowed types.
*/
if (null !== $this->_filterTypes && !($qp->getQueryType() & $this->_filterTypes)) {
unset($this->_queryProfiles[$queryId]);
return self::IGNORED;
}
return self::STORED;
}
/**
* Get a profile for a query. Pass it the same handle that was returned
* by queryStart() and it will return a Zend_Db_Profiler_Query object.
*
* @param integer $queryId
* @throws Zend_Db_Profiler_Exception
* @return Zend_Db_Profiler_Query
*/
public function getQueryProfile($queryId)
{
if (!array_key_exists($queryId, $this->_queryProfiles)) {
/**
* @see Zend_Db_Profiler_Exception
*/
// require_once 'Zend/Db/Profiler/Exception.php';
throw new Zend_Db_Profiler_Exception("Query handle '$queryId' not found in profiler log.");
}
return $this->_queryProfiles[$queryId];
}
/**
* Get an array of query profiles (Zend_Db_Profiler_Query objects). If $queryType
* is set to one of the Zend_Db_Profiler::* constants then only queries of that
* type will be returned. Normally, queries that have not yet ended will
* not be returned unless $showUnfinished is set to True. If no
* queries were found, False is returned. The returned array is indexed by the query
* profile handles.
*
* @param integer $queryType
* @param boolean $showUnfinished
* @return array|false
*/
public function getQueryProfiles($queryType = null, $showUnfinished = false)
{
$queryProfiles = array();
foreach ($this->_queryProfiles as $key => $qp) {
if ($queryType === null) {
$condition = true;
} else {
$condition = ($qp->getQueryType() & $queryType);
}
if (($qp->hasEnded() || $showUnfinished) && $condition) {
$queryProfiles[$key] = $qp;
}
}
if (empty($queryProfiles)) {
$queryProfiles = false;
}
return $queryProfiles;
}
/**
* Get the total elapsed time (in seconds) of all of the profiled queries.
* Only queries that have ended will be counted. If $queryType is set to
* one or more of the Zend_Db_Profiler::* constants, the elapsed time will be calculated
* only for queries of the given type(s).
*
* @param integer $queryType OPTIONAL
* @return float
*/
public function getTotalElapsedSecs($queryType = null)
{
$elapsedSecs = 0;
foreach ($this->_queryProfiles as $key => $qp) {
if (null === $queryType) {
$condition = true;
} else {
$condition = ($qp->getQueryType() & $queryType);
}
if (($qp->hasEnded()) && $condition) {
$elapsedSecs += $qp->getElapsedSecs();
}
}
return $elapsedSecs;
}
/**
* Get the total number of queries that have been profiled. Only queries that have ended will
* be counted. If $queryType is set to one of the Zend_Db_Profiler::* constants, only queries of
* that type will be counted.
*
* @param integer $queryType OPTIONAL
* @return integer
*/
public function getTotalNumQueries($queryType = null)
{
if (null === $queryType) {
return count($this->_queryProfiles);
}
$numQueries = 0;
foreach ($this->_queryProfiles as $qp) {
if ($qp->hasEnded() && ($qp->getQueryType() & $queryType)) {
$numQueries++;
}
}
return $numQueries;
}
/**
* Get the Zend_Db_Profiler_Query object for the last query that was run, regardless if it has
* ended or not. If the query has not ended, its end time will be null. If no queries have
* been profiled, false is returned.
*
* @return Zend_Db_Profiler_Query|false
*/
public function getLastQueryProfile()
{
if (empty($this->_queryProfiles)) {
return false;
}
end($this->_queryProfiles);
return current($this->_queryProfiles);
}
}

View File

@ -0,0 +1,40 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Profiler
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Exception.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Db_Exception
*/
// require_once 'Zend/Db/Exception.php';
/**
* @category Zend
* @package Zend_Db
* @subpackage Profiler
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Profiler_Exception extends Zend_Db_Exception
{
}

View File

@ -0,0 +1,161 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Profiler
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Firebug.php 23775 2011-03-01 17:25:24Z ralph $
*/
/** Zend_Db_Profiler */
// require_once 'Zend/Db/Profiler.php';
/** Zend_Wildfire_Plugin_FirePhp */
// require_once 'Zend/Wildfire/Plugin/FirePhp.php';
/** Zend_Wildfire_Plugin_FirePhp_TableMessage */
// require_once 'Zend/Wildfire/Plugin/FirePhp/TableMessage.php';
/**
* Writes DB events as log messages to the Firebug Console via FirePHP.
*
* @category Zend
* @package Zend_Db
* @subpackage Profiler
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Profiler_Firebug extends Zend_Db_Profiler
{
/**
* The original label for this profiler.
* @var string
*/
protected $_label = null;
/**
* The label template for this profiler
* @var string
*/
protected $_label_template = '%label% (%totalCount% @ %totalDuration% sec)';
/**
* The message envelope holding the profiling summary
* @var Zend_Wildfire_Plugin_FirePhp_TableMessage
*/
protected $_message = null;
/**
* The total time taken for all profiled queries.
* @var float
*/
protected $_totalElapsedTime = 0;
/**
* Constructor
*
* @param string $label OPTIONAL Label for the profiling info.
* @return void
*/
public function __construct($label = null)
{
$this->_label = $label;
if(!$this->_label) {
$this->_label = 'Zend_Db_Profiler_Firebug';
}
}
/**
* Enable or disable the profiler. If $enable is false, the profiler
* is disabled and will not log any queries sent to it.
*
* @param boolean $enable
* @return Zend_Db_Profiler Provides a fluent interface
*/
public function setEnabled($enable)
{
parent::setEnabled($enable);
if ($this->getEnabled()) {
if (!$this->_message) {
$this->_message = new Zend_Wildfire_Plugin_FirePhp_TableMessage($this->_label);
$this->_message->setBuffered(true);
$this->_message->setHeader(array('Time','Event','Parameters'));
$this->_message->setDestroy(true);
$this->_message->setOption('includeLineNumbers', false);
Zend_Wildfire_Plugin_FirePhp::getInstance()->send($this->_message);
}
} else {
if ($this->_message) {
$this->_message->setDestroy(true);
$this->_message = null;
}
}
return $this;
}
/**
* Intercept the query end and log the profiling data.
*
* @param integer $queryId
* @throws Zend_Db_Profiler_Exception
* @return void
*/
public function queryEnd($queryId)
{
$state = parent::queryEnd($queryId);
if (!$this->getEnabled() || $state == self::IGNORED) {
return;
}
$this->_message->setDestroy(false);
$profile = $this->getQueryProfile($queryId);
$this->_totalElapsedTime += $profile->getElapsedSecs();
$this->_message->addRow(array((string)round($profile->getElapsedSecs(),5),
$profile->getQuery(),
($params=$profile->getQueryParams())?$params:null));
$this->updateMessageLabel();
}
/**
* Update the label of the message holding the profile info.
*
* @return void
*/
protected function updateMessageLabel()
{
if (!$this->_message) {
return;
}
$this->_message->setLabel(str_replace(array('%label%',
'%totalCount%',
'%totalDuration%'),
array($this->_label,
$this->getTotalNumQueries(),
(string)round($this->_totalElapsedTime,5)),
$this->_label_template));
}
}

View File

@ -0,0 +1,213 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Profiler
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Query.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @category Zend
* @package Zend_Db
* @subpackage Profiler
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Profiler_Query
{
/**
* SQL query string or user comment, set by $query argument in constructor.
*
* @var string
*/
protected $_query = '';
/**
* One of the Zend_Db_Profiler constants for query type, set by $queryType argument in constructor.
*
* @var integer
*/
protected $_queryType = 0;
/**
* Unix timestamp with microseconds when instantiated.
*
* @var float
*/
protected $_startedMicrotime = null;
/**
* Unix timestamp with microseconds when self::queryEnd() was called.
*
* @var integer
*/
protected $_endedMicrotime = null;
/**
* @var array
*/
protected $_boundParams = array();
/**
* @var array
*/
/**
* Class constructor. A query is about to be started, save the query text ($query) and its
* type (one of the Zend_Db_Profiler::* constants).
*
* @param string $query
* @param integer $queryType
* @return void
*/
public function __construct($query, $queryType)
{
$this->_query = $query;
$this->_queryType = $queryType;
// by default, and for backward-compatibility, start the click ticking
$this->start();
}
/**
* Clone handler for the query object.
* @return void
*/
public function __clone()
{
$this->_boundParams = array();
$this->_endedMicrotime = null;
$this->start();
}
/**
* Starts the elapsed time click ticking.
* This can be called subsequent to object creation,
* to restart the clock. For instance, this is useful
* right before executing a prepared query.
*
* @return void
*/
public function start()
{
$this->_startedMicrotime = microtime(true);
}
/**
* Ends the query and records the time so that the elapsed time can be determined later.
*
* @return void
*/
public function end()
{
$this->_endedMicrotime = microtime(true);
}
/**
* Returns true if and only if the query has ended.
*
* @return boolean
*/
public function hasEnded()
{
return $this->_endedMicrotime !== null;
}
/**
* Get the original SQL text of the query.
*
* @return string
*/
public function getQuery()
{
return $this->_query;
}
/**
* Get the type of this query (one of the Zend_Db_Profiler::* constants)
*
* @return integer
*/
public function getQueryType()
{
return $this->_queryType;
}
/**
* @param string $param
* @param mixed $variable
* @return void
*/
public function bindParam($param, $variable)
{
$this->_boundParams[$param] = $variable;
}
/**
* @param array $param
* @return void
*/
public function bindParams(array $params)
{
if (array_key_exists(0, $params)) {
array_unshift($params, null);
unset($params[0]);
}
foreach ($params as $param => $value) {
$this->bindParam($param, $value);
}
}
/**
* @return array
*/
public function getQueryParams()
{
return $this->_boundParams;
}
/**
* Get the elapsed time (in seconds) that the query ran.
* If the query has not yet ended, false is returned.
*
* @return float|false
*/
public function getElapsedSecs()
{
if (null === $this->_endedMicrotime) {
return false;
}
return $this->_endedMicrotime - $this->_startedMicrotime;
}
/**
* Get the time (in seconds) when the profiler started running.
*
* @return bool|float
*/
public function getStartedMicrotime()
{
if(null === $this->_startedMicrotime) {
return false;
}
return $this->_startedMicrotime;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,39 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Select
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Exception.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* Zend_Db_Exception
*/
// require_once 'Zend/Db/Exception.php';
/**
* @category Zend
* @package Zend_Db
* @subpackage Select
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Select_Exception extends Zend_Db_Exception
{
}

View File

@ -0,0 +1,485 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Statement
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Statement.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Db
*/
// require_once 'Zend/Db.php';
/**
* @see Zend_Db_Statement_Interface
*/
// require_once 'Zend/Db/Statement/Interface.php';
/**
* Abstract class to emulate a PDOStatement for native database adapters.
*
* @category Zend
* @package Zend_Db
* @subpackage Statement
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
abstract class Zend_Db_Statement implements Zend_Db_Statement_Interface
{
/**
* @var resource|object The driver level statement object/resource
*/
protected $_stmt = null;
/**
* @var Zend_Db_Adapter_Abstract
*/
protected $_adapter = null;
/**
* The current fetch mode.
*
* @var integer
*/
protected $_fetchMode = Zend_Db::FETCH_ASSOC;
/**
* Attributes.
*
* @var array
*/
protected $_attribute = array();
/**
* Column result bindings.
*
* @var array
*/
protected $_bindColumn = array();
/**
* Query parameter bindings; covers bindParam() and bindValue().
*
* @var array
*/
protected $_bindParam = array();
/**
* SQL string split into an array at placeholders.
*
* @var array
*/
protected $_sqlSplit = array();
/**
* Parameter placeholders in the SQL string by position in the split array.
*
* @var array
*/
protected $_sqlParam = array();
/**
* @var Zend_Db_Profiler_Query
*/
protected $_queryId = null;
/**
* Constructor for a statement.
*
* @param Zend_Db_Adapter_Abstract $adapter
* @param mixed $sql Either a string or Zend_Db_Select.
*/
public function __construct($adapter, $sql)
{
$this->_adapter = $adapter;
if ($sql instanceof Zend_Db_Select) {
$sql = $sql->assemble();
}
$this->_parseParameters($sql);
$this->_prepare($sql);
$this->_queryId = $this->_adapter->getProfiler()->queryStart($sql);
}
/**
* Internal method called by abstract statment constructor to setup
* the driver level statement
*
* @return void
*/
protected function _prepare($sql)
{
return;
}
/**
* @param string $sql
* @return void
*/
protected function _parseParameters($sql)
{
$sql = $this->_stripQuoted($sql);
// split into text and params
$this->_sqlSplit = preg_split('/(\?|\:[a-zA-Z0-9_]+)/',
$sql, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
// map params
$this->_sqlParam = array();
foreach ($this->_sqlSplit as $key => $val) {
if ($val == '?') {
if ($this->_adapter->supportsParameters('positional') === false) {
/**
* @see Zend_Db_Statement_Exception
*/
// require_once 'Zend/Db/Statement/Exception.php';
throw new Zend_Db_Statement_Exception("Invalid bind-variable position '$val'");
}
} else if ($val[0] == ':') {
if ($this->_adapter->supportsParameters('named') === false) {
/**
* @see Zend_Db_Statement_Exception
*/
// require_once 'Zend/Db/Statement/Exception.php';
throw new Zend_Db_Statement_Exception("Invalid bind-variable name '$val'");
}
}
$this->_sqlParam[] = $val;
}
// set up for binding
$this->_bindParam = array();
}
/**
* Remove parts of a SQL string that contain quoted strings
* of values or identifiers.
*
* @param string $sql
* @return string
*/
protected function _stripQuoted($sql)
{
// get the character for delimited id quotes,
// this is usually " but in MySQL is `
$d = $this->_adapter->quoteIdentifier('a');
$d = $d[0];
// get the value used as an escaped delimited id quote,
// e.g. \" or "" or \`
$de = $this->_adapter->quoteIdentifier($d);
$de = substr($de, 1, 2);
$de = str_replace('\\', '\\\\', $de);
// get the character for value quoting
// this should be '
$q = $this->_adapter->quote('a');
$q = $q[0];
// get the value used as an escaped quote,
// e.g. \' or ''
$qe = $this->_adapter->quote($q);
$qe = substr($qe, 1, 2);
$qe = str_replace('\\', '\\\\', $qe);
// get a version of the SQL statement with all quoted
// values and delimited identifiers stripped out
// remove "foo\"bar"
$sql = preg_replace("/$q($qe|\\\\{2}|[^$q])*$q/", '', $sql);
// remove 'foo\'bar'
if (!empty($q)) {
$sql = preg_replace("/$q($qe|[^$q])*$q/", '', $sql);
}
return $sql;
}
/**
* Bind a column of the statement result set to a PHP variable.
*
* @param string $column Name the column in the result set, either by
* position or by name.
* @param mixed $param Reference to the PHP variable containing the value.
* @param mixed $type OPTIONAL
* @return bool
*/
public function bindColumn($column, &$param, $type = null)
{
$this->_bindColumn[$column] =& $param;
return true;
}
/**
* Binds a parameter to the specified variable name.
*
* @param mixed $parameter Name the parameter, either integer or string.
* @param mixed $variable Reference to PHP variable containing the value.
* @param mixed $type OPTIONAL Datatype of SQL parameter.
* @param mixed $length OPTIONAL Length of SQL parameter.
* @param mixed $options OPTIONAL Other options.
* @return bool
*/
public function bindParam($parameter, &$variable, $type = null, $length = null, $options = null)
{
if (!is_int($parameter) && !is_string($parameter)) {
/**
* @see Zend_Db_Statement_Exception
*/
// require_once 'Zend/Db/Statement/Exception.php';
throw new Zend_Db_Statement_Exception('Invalid bind-variable position');
}
$position = null;
if (($intval = (int) $parameter) > 0 && $this->_adapter->supportsParameters('positional')) {
if ($intval >= 1 || $intval <= count($this->_sqlParam)) {
$position = $intval;
}
} else if ($this->_adapter->supportsParameters('named')) {
if ($parameter[0] != ':') {
$parameter = ':' . $parameter;
}
if (in_array($parameter, $this->_sqlParam) !== false) {
$position = $parameter;
}
}
if ($position === null) {
/**
* @see Zend_Db_Statement_Exception
*/
// require_once 'Zend/Db/Statement/Exception.php';
throw new Zend_Db_Statement_Exception("Invalid bind-variable position '$parameter'");
}
// Finally we are assured that $position is valid
$this->_bindParam[$position] =& $variable;
return $this->_bindParam($position, $variable, $type, $length, $options);
}
/**
* Binds a value to a parameter.
*
* @param mixed $parameter Name the parameter, either integer or string.
* @param mixed $value Scalar value to bind to the parameter.
* @param mixed $type OPTIONAL Datatype of the parameter.
* @return bool
*/
public function bindValue($parameter, $value, $type = null)
{
return $this->bindParam($parameter, $value, $type);
}
/**
* Executes a prepared statement.
*
* @param array $params OPTIONAL Values to bind to parameter placeholders.
* @return bool
*/
public function execute(array $params = null)
{
/*
* Simple case - no query profiler to manage.
*/
if ($this->_queryId === null) {
return $this->_execute($params);
}
/*
* Do the same thing, but with query profiler
* management before and after the execute.
*/
$prof = $this->_adapter->getProfiler();
$qp = $prof->getQueryProfile($this->_queryId);
if ($qp->hasEnded()) {
$this->_queryId = $prof->queryClone($qp);
$qp = $prof->getQueryProfile($this->_queryId);
}
if ($params !== null) {
$qp->bindParams($params);
} else {
$qp->bindParams($this->_bindParam);
}
$qp->start($this->_queryId);
$retval = $this->_execute($params);
$prof->queryEnd($this->_queryId);
return $retval;
}
/**
* Returns an array containing all of the result set rows.
*
* @param int $style OPTIONAL Fetch mode.
* @param int $col OPTIONAL Column number, if fetch mode is by column.
* @return array Collection of rows, each in a format by the fetch mode.
*/
public function fetchAll($style = null, $col = null)
{
$data = array();
if ($style === Zend_Db::FETCH_COLUMN && $col === null) {
$col = 0;
}
if ($col === null) {
while ($row = $this->fetch($style)) {
$data[] = $row;
}
} else {
while (false !== ($val = $this->fetchColumn($col))) {
$data[] = $val;
}
}
return $data;
}
/**
* Returns a single column from the next row of a result set.
*
* @param int $col OPTIONAL Position of the column to fetch.
* @return string One value from the next row of result set, or false.
*/
public function fetchColumn($col = 0)
{
$data = array();
$col = (int) $col;
$row = $this->fetch(Zend_Db::FETCH_NUM);
if (!is_array($row)) {
return false;
}
return $row[$col];
}
/**
* Fetches the next row and returns it as an object.
*
* @param string $class OPTIONAL Name of the class to create.
* @param array $config OPTIONAL Constructor arguments for the class.
* @return mixed One object instance of the specified class, or false.
*/
public function fetchObject($class = 'stdClass', array $config = array())
{
$obj = new $class($config);
$row = $this->fetch(Zend_Db::FETCH_ASSOC);
if (!is_array($row)) {
return false;
}
foreach ($row as $key => $val) {
$obj->$key = $val;
}
return $obj;
}
/**
* Retrieve a statement attribute.
*
* @param string $key Attribute name.
* @return mixed Attribute value.
*/
public function getAttribute($key)
{
if (array_key_exists($key, $this->_attribute)) {
return $this->_attribute[$key];
}
}
/**
* Set a statement attribute.
*
* @param string $key Attribute name.
* @param mixed $val Attribute value.
* @return bool
*/
public function setAttribute($key, $val)
{
$this->_attribute[$key] = $val;
}
/**
* Set the default fetch mode for this statement.
*
* @param int $mode The fetch mode.
* @return bool
* @throws Zend_Db_Statement_Exception
*/
public function setFetchMode($mode)
{
switch ($mode) {
case Zend_Db::FETCH_NUM:
case Zend_Db::FETCH_ASSOC:
case Zend_Db::FETCH_BOTH:
case Zend_Db::FETCH_OBJ:
$this->_fetchMode = $mode;
break;
case Zend_Db::FETCH_BOUND:
default:
$this->closeCursor();
/**
* @see Zend_Db_Statement_Exception
*/
// require_once 'Zend/Db/Statement/Exception.php';
throw new Zend_Db_Statement_Exception('invalid fetch mode');
break;
}
}
/**
* Helper function to map retrieved row
* to bound column variables
*
* @param array $row
* @return bool True
*/
public function _fetchBound($row)
{
foreach ($row as $key => $value) {
// bindColumn() takes 1-based integer positions
// but fetch() returns 0-based integer indexes
if (is_int($key)) {
$key++;
}
// set results only to variables that were bound previously
if (isset($this->_bindColumn[$key])) {
$this->_bindColumn[$key] = $value;
}
}
return true;
}
/**
* Gets the Zend_Db_Adapter_Abstract for this
* particular Zend_Db_Statement object.
*
* @return Zend_Db_Adapter_Abstract
*/
public function getAdapter()
{
return $this->_adapter;
}
/**
* Gets the resource or object setup by the
* _parse
* @return unknown_type
*/
public function getDriverStatement()
{
return $this->_stmt;
}
}

View File

@ -0,0 +1,360 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Statement
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Db2.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Db_Statement
*/
// require_once 'Zend/Db/Statement.php';
/**
* Extends for DB2 native adapter.
*
* @package Zend_Db
* @subpackage Statement
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Statement_Db2 extends Zend_Db_Statement
{
/**
* Column names.
*/
protected $_keys;
/**
* Fetched result values.
*/
protected $_values;
/**
* Prepare a statement handle.
*
* @param string $sql
* @return void
* @throws Zend_Db_Statement_Db2_Exception
*/
public function _prepare($sql)
{
$connection = $this->_adapter->getConnection();
// db2_prepare on i5 emits errors, these need to be
// suppressed so that proper exceptions can be thrown
$this->_stmt = @db2_prepare($connection, $sql);
if (!$this->_stmt) {
/**
* @see Zend_Db_Statement_Db2_Exception
*/
// require_once 'Zend/Db/Statement/Db2/Exception.php';
throw new Zend_Db_Statement_Db2_Exception(
db2_stmt_errormsg(),
db2_stmt_error()
);
}
}
/**
* Binds a parameter to the specified variable name.
*
* @param mixed $parameter Name the parameter, either integer or string.
* @param mixed $variable Reference to PHP variable containing the value.
* @param mixed $type OPTIONAL Datatype of SQL parameter.
* @param mixed $length OPTIONAL Length of SQL parameter.
* @param mixed $options OPTIONAL Other options.
* @return bool
* @throws Zend_Db_Statement_Db2_Exception
*/
public function _bindParam($parameter, &$variable, $type = null, $length = null, $options = null)
{
if ($type === null) {
$type = DB2_PARAM_IN;
}
if (isset($options['data-type'])) {
$datatype = $options['data-type'];
} else {
$datatype = DB2_CHAR;
}
if (!db2_bind_param($this->_stmt, $position, "variable", $type, $datatype)) {
/**
* @see Zend_Db_Statement_Db2_Exception
*/
// require_once 'Zend/Db/Statement/Db2/Exception.php';
throw new Zend_Db_Statement_Db2_Exception(
db2_stmt_errormsg(),
db2_stmt_error()
);
}
return true;
}
/**
* Closes the cursor, allowing the statement to be executed again.
*
* @return bool
*/
public function closeCursor()
{
if (!$this->_stmt) {
return false;
}
db2_free_stmt($this->_stmt);
$this->_stmt = false;
return true;
}
/**
* Returns the number of columns in the result set.
* Returns null if the statement has no result set metadata.
*
* @return int The number of columns.
*/
public function columnCount()
{
if (!$this->_stmt) {
return false;
}
return db2_num_fields($this->_stmt);
}
/**
* Retrieves the error code, if any, associated with the last operation on
* the statement handle.
*
* @return string error code.
*/
public function errorCode()
{
if (!$this->_stmt) {
return false;
}
$error = db2_stmt_error();
if ($error === '') {
return false;
}
return $error;
}
/**
* Retrieves an array of error information, if any, associated with the
* last operation on the statement handle.
*
* @return array
*/
public function errorInfo()
{
$error = $this->errorCode();
if ($error === false){
return false;
}
/*
* Return three-valued array like PDO. But DB2 does not distinguish
* between SQLCODE and native RDBMS error code, so repeat the SQLCODE.
*/
return array(
$error,
$error,
db2_stmt_errormsg()
);
}
/**
* Executes a prepared statement.
*
* @param array $params OPTIONAL Values to bind to parameter placeholders.
* @return bool
* @throws Zend_Db_Statement_Db2_Exception
*/
public function _execute(array $params = null)
{
if (!$this->_stmt) {
return false;
}
$retval = true;
if ($params !== null) {
$retval = @db2_execute($this->_stmt, $params);
} else {
$retval = @db2_execute($this->_stmt);
}
if ($retval === false) {
/**
* @see Zend_Db_Statement_Db2_Exception
*/
// require_once 'Zend/Db/Statement/Db2/Exception.php';
throw new Zend_Db_Statement_Db2_Exception(
db2_stmt_errormsg(),
db2_stmt_error());
}
$this->_keys = array();
if ($field_num = $this->columnCount()) {
for ($i = 0; $i < $field_num; $i++) {
$name = db2_field_name($this->_stmt, $i);
$this->_keys[] = $name;
}
}
$this->_values = array();
if ($this->_keys) {
$this->_values = array_fill(0, count($this->_keys), null);
}
return $retval;
}
/**
* Fetches a row from the result set.
*
* @param int $style OPTIONAL Fetch mode for this fetch operation.
* @param int $cursor OPTIONAL Absolute, relative, or other.
* @param int $offset OPTIONAL Number for absolute or relative cursors.
* @return mixed Array, object, or scalar depending on fetch mode.
* @throws Zend_Db_Statement_Db2_Exception
*/
public function fetch($style = null, $cursor = null, $offset = null)
{
if (!$this->_stmt) {
return false;
}
if ($style === null) {
$style = $this->_fetchMode;
}
switch ($style) {
case Zend_Db::FETCH_NUM :
$row = db2_fetch_array($this->_stmt);
break;
case Zend_Db::FETCH_ASSOC :
$row = db2_fetch_assoc($this->_stmt);
break;
case Zend_Db::FETCH_BOTH :
$row = db2_fetch_both($this->_stmt);
break;
case Zend_Db::FETCH_OBJ :
$row = db2_fetch_object($this->_stmt);
break;
case Zend_Db::FETCH_BOUND:
$row = db2_fetch_both($this->_stmt);
if ($row !== false) {
return $this->_fetchBound($row);
}
break;
default:
/**
* @see Zend_Db_Statement_Db2_Exception
*/
// require_once 'Zend/Db/Statement/Db2/Exception.php';
throw new Zend_Db_Statement_Db2_Exception("Invalid fetch mode '$style' specified");
break;
}
return $row;
}
/**
* Fetches the next row and returns it as an object.
*
* @param string $class OPTIONAL Name of the class to create.
* @param array $config OPTIONAL Constructor arguments for the class.
* @return mixed One object instance of the specified class.
*/
public function fetchObject($class = 'stdClass', array $config = array())
{
$obj = $this->fetch(Zend_Db::FETCH_OBJ);
return $obj;
}
/**
* Retrieves the next rowset (result set) for a SQL statement that has
* multiple result sets. An example is a stored procedure that returns
* the results of multiple queries.
*
* @return bool
* @throws Zend_Db_Statement_Db2_Exception
*/
public function nextRowset()
{
/**
* @see Zend_Db_Statement_Db2_Exception
*/
// require_once 'Zend/Db/Statement/Db2/Exception.php';
throw new Zend_Db_Statement_Db2_Exception(__FUNCTION__ . '() is not implemented');
}
/**
* Returns the number of rows affected by the execution of the
* last INSERT, DELETE, or UPDATE statement executed by this
* statement object.
*
* @return int The number of rows affected.
*/
public function rowCount()
{
if (!$this->_stmt) {
return false;
}
$num = @db2_num_rows($this->_stmt);
if ($num === false) {
return 0;
}
return $num;
}
/**
* Returns an array containing all of the result set rows.
*
* @param int $style OPTIONAL Fetch mode.
* @param int $col OPTIONAL Column number, if fetch mode is by column.
* @return array Collection of rows, each in a format by the fetch mode.
*
* Behaves like parent, but if limit()
* is used, the final result removes the extra column
* 'zend_db_rownum'
*/
public function fetchAll($style = null, $col = null)
{
$data = parent::fetchAll($style, $col);
$results = array();
$remove = $this->_adapter->foldCase('ZEND_DB_ROWNUM');
foreach ($data as $row) {
if (is_array($row) && array_key_exists($remove, $row)) {
unset($row[$remove]);
}
$results[] = $row;
}
return $results;
}
}

View File

@ -0,0 +1,58 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Statement
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Exception.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* Zend_Db_Statement_Exception
*/
// require_once 'Zend/Db/Statement/Exception.php';
/**
* @package Zend_Db
* @subpackage Statement
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Statement_Db2_Exception extends Zend_Db_Statement_Exception
{
/**
* @var string
*/
protected $code = '00000';
/**
* @var string
*/
protected $message = 'unknown exception';
/**
* @param string $msg
* @param string $state
*/
function __construct($msg = 'unknown exception', $state = '00000')
{
$this->message = $msg;
$this->code = $state;
}
}

View File

@ -0,0 +1,56 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Statement
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Exception.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Db_Exception
*/
// require_once 'Zend/Db/Exception.php';
/**
* Zend_Db_Statement_Exception
*
* @category Zend
* @package Zend_Db
* @subpackage Statement
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Statement_Exception extends Zend_Db_Exception
{
/**
* Check if this general exception has a specific database driver specific exception nested inside.
*
* @return bool
*/
public function hasChainedException()
{
return ($this->getPrevious() !== null);
}
/**
* @return Exception|null
*/
public function getChainedException()
{
return $this->getPrevious();
}
}

View File

@ -0,0 +1,203 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Statement
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Interface.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* Emulates a PDOStatement for native database adapters.
*
* @category Zend
* @package Zend_Db
* @subpackage Statement
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
interface Zend_Db_Statement_Interface
{
/**
* Bind a column of the statement result set to a PHP variable.
*
* @param string $column Name the column in the result set, either by
* position or by name.
* @param mixed $param Reference to the PHP variable containing the value.
* @param mixed $type OPTIONAL
* @return bool
* @throws Zend_Db_Statement_Exception
*/
public function bindColumn($column, &$param, $type = null);
/**
* Binds a parameter to the specified variable name.
*
* @param mixed $parameter Name the parameter, either integer or string.
* @param mixed $variable Reference to PHP variable containing the value.
* @param mixed $type OPTIONAL Datatype of SQL parameter.
* @param mixed $length OPTIONAL Length of SQL parameter.
* @param mixed $options OPTIONAL Other options.
* @return bool
* @throws Zend_Db_Statement_Exception
*/
public function bindParam($parameter, &$variable, $type = null, $length = null, $options = null);
/**
* Binds a value to a parameter.
*
* @param mixed $parameter Name the parameter, either integer or string.
* @param mixed $value Scalar value to bind to the parameter.
* @param mixed $type OPTIONAL Datatype of the parameter.
* @return bool
* @throws Zend_Db_Statement_Exception
*/
public function bindValue($parameter, $value, $type = null);
/**
* Closes the cursor, allowing the statement to be executed again.
*
* @return bool
* @throws Zend_Db_Statement_Exception
*/
public function closeCursor();
/**
* Returns the number of columns in the result set.
* Returns null if the statement has no result set metadata.
*
* @return int The number of columns.
* @throws Zend_Db_Statement_Exception
*/
public function columnCount();
/**
* Retrieves the error code, if any, associated with the last operation on
* the statement handle.
*
* @return string error code.
* @throws Zend_Db_Statement_Exception
*/
public function errorCode();
/**
* Retrieves an array of error information, if any, associated with the
* last operation on the statement handle.
*
* @return array
* @throws Zend_Db_Statement_Exception
*/
public function errorInfo();
/**
* Executes a prepared statement.
*
* @param array $params OPTIONAL Values to bind to parameter placeholders.
* @return bool
* @throws Zend_Db_Statement_Exception
*/
public function execute(array $params = array());
/**
* Fetches a row from the result set.
*
* @param int $style OPTIONAL Fetch mode for this fetch operation.
* @param int $cursor OPTIONAL Absolute, relative, or other.
* @param int $offset OPTIONAL Number for absolute or relative cursors.
* @return mixed Array, object, or scalar depending on fetch mode.
* @throws Zend_Db_Statement_Exception
*/
public function fetch($style = null, $cursor = null, $offset = null);
/**
* Returns an array containing all of the result set rows.
*
* @param int $style OPTIONAL Fetch mode.
* @param int $col OPTIONAL Column number, if fetch mode is by column.
* @return array Collection of rows, each in a format by the fetch mode.
* @throws Zend_Db_Statement_Exception
*/
public function fetchAll($style = null, $col = null);
/**
* Returns a single column from the next row of a result set.
*
* @param int $col OPTIONAL Position of the column to fetch.
* @return string
* @throws Zend_Db_Statement_Exception
*/
public function fetchColumn($col = 0);
/**
* Fetches the next row and returns it as an object.
*
* @param string $class OPTIONAL Name of the class to create.
* @param array $config OPTIONAL Constructor arguments for the class.
* @return mixed One object instance of the specified class.
* @throws Zend_Db_Statement_Exception
*/
public function fetchObject($class = 'stdClass', array $config = array());
/**
* Retrieve a statement attribute.
*
* @param string $key Attribute name.
* @return mixed Attribute value.
* @throws Zend_Db_Statement_Exception
*/
public function getAttribute($key);
/**
* Retrieves the next rowset (result set) for a SQL statement that has
* multiple result sets. An example is a stored procedure that returns
* the results of multiple queries.
*
* @return bool
* @throws Zend_Db_Statement_Exception
*/
public function nextRowset();
/**
* Returns the number of rows affected by the execution of the
* last INSERT, DELETE, or UPDATE statement executed by this
* statement object.
*
* @return int The number of rows affected.
* @throws Zend_Db_Statement_Exception
*/
public function rowCount();
/**
* Set a statement attribute.
*
* @param string $key Attribute name.
* @param mixed $val Attribute value.
* @return bool
* @throws Zend_Db_Statement_Exception
*/
public function setAttribute($key, $val);
/**
* Set the default fetch mode for this statement.
*
* @param int $mode The fetch mode.
* @return bool
* @throws Zend_Db_Statement_Exception
*/
public function setFetchMode($mode);
}

View File

@ -0,0 +1,362 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Statement
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Mysqli.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Db_Statement
*/
// require_once 'Zend/Db/Statement.php';
/**
* Extends for Mysqli
*
* @category Zend
* @package Zend_Db
* @subpackage Statement
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Statement_Mysqli extends Zend_Db_Statement
{
/**
* Column names.
*
* @var array
*/
protected $_keys;
/**
* Fetched result values.
*
* @var array
*/
protected $_values;
/**
* @var array
*/
protected $_meta = null;
/**
* @param string $sql
* @return void
* @throws Zend_Db_Statement_Mysqli_Exception
*/
public function _prepare($sql)
{
$mysqli = $this->_adapter->getConnection();
$this->_stmt = $mysqli->prepare($sql);
if ($this->_stmt === false || $mysqli->errno) {
/**
* @see Zend_Db_Statement_Mysqli_Exception
*/
// require_once 'Zend/Db/Statement/Mysqli/Exception.php';
throw new Zend_Db_Statement_Mysqli_Exception("Mysqli prepare error: " . $mysqli->error, $mysqli->errno);
}
}
/**
* Binds a parameter to the specified variable name.
*
* @param mixed $parameter Name the parameter, either integer or string.
* @param mixed $variable Reference to PHP variable containing the value.
* @param mixed $type OPTIONAL Datatype of SQL parameter.
* @param mixed $length OPTIONAL Length of SQL parameter.
* @param mixed $options OPTIONAL Other options.
* @return bool
* @throws Zend_Db_Statement_Mysqli_Exception
*/
protected function _bindParam($parameter, &$variable, $type = null, $length = null, $options = null)
{
return true;
}
/**
* Closes the cursor and the statement.
*
* @return bool
*/
public function close()
{
if ($this->_stmt) {
$r = $this->_stmt->close();
$this->_stmt = null;
return $r;
}
return false;
}
/**
* Closes the cursor, allowing the statement to be executed again.
*
* @return bool
*/
public function closeCursor()
{
if ($stmt = $this->_stmt) {
$mysqli = $this->_adapter->getConnection();
while ($mysqli->more_results()) {
$mysqli->next_result();
}
$this->_stmt->free_result();
return $this->_stmt->reset();
}
return false;
}
/**
* Returns the number of columns in the result set.
* Returns null if the statement has no result set metadata.
*
* @return int The number of columns.
*/
public function columnCount()
{
if (isset($this->_meta) && $this->_meta) {
return $this->_meta->field_count;
}
return 0;
}
/**
* Retrieves the error code, if any, associated with the last operation on
* the statement handle.
*
* @return string error code.
*/
public function errorCode()
{
if (!$this->_stmt) {
return false;
}
return substr($this->_stmt->sqlstate, 0, 5);
}
/**
* Retrieves an array of error information, if any, associated with the
* last operation on the statement handle.
*
* @return array
*/
public function errorInfo()
{
if (!$this->_stmt) {
return false;
}
return array(
substr($this->_stmt->sqlstate, 0, 5),
$this->_stmt->errno,
$this->_stmt->error,
);
}
/**
* Executes a prepared statement.
*
* @param array $params OPTIONAL Values to bind to parameter placeholders.
* @return bool
* @throws Zend_Db_Statement_Mysqli_Exception
*/
public function _execute(array $params = null)
{
if (!$this->_stmt) {
return false;
}
// if no params were given as an argument to execute(),
// then default to the _bindParam array
if ($params === null) {
$params = $this->_bindParam;
}
// send $params as input parameters to the statement
if ($params) {
array_unshift($params, str_repeat('s', count($params)));
$stmtParams = array();
foreach ($params as $k => &$value) {
$stmtParams[$k] = &$value;
}
call_user_func_array(
array($this->_stmt, 'bind_param'),
$stmtParams
);
}
// execute the statement
$retval = $this->_stmt->execute();
if ($retval === false) {
/**
* @see Zend_Db_Statement_Mysqli_Exception
*/
// require_once 'Zend/Db/Statement/Mysqli/Exception.php';
throw new Zend_Db_Statement_Mysqli_Exception("Mysqli statement execute error : " . $this->_stmt->error, $this->_stmt->errno);
}
// retain metadata
if ($this->_meta === null) {
$this->_meta = $this->_stmt->result_metadata();
if ($this->_stmt->errno) {
/**
* @see Zend_Db_Statement_Mysqli_Exception
*/
// require_once 'Zend/Db/Statement/Mysqli/Exception.php';
throw new Zend_Db_Statement_Mysqli_Exception("Mysqli statement metadata error: " . $this->_stmt->error, $this->_stmt->errno);
}
}
// statements that have no result set do not return metadata
if ($this->_meta !== false) {
// get the column names that will result
$this->_keys = array();
foreach ($this->_meta->fetch_fields() as $col) {
$this->_keys[] = $this->_adapter->foldCase($col->name);
}
// set up a binding space for result variables
$this->_values = array_fill(0, count($this->_keys), null);
// set up references to the result binding space.
// just passing $this->_values in the call_user_func_array()
// below won't work, you need references.
$refs = array();
foreach ($this->_values as $i => &$f) {
$refs[$i] = &$f;
}
$this->_stmt->store_result();
// bind to the result variables
call_user_func_array(
array($this->_stmt, 'bind_result'),
$this->_values
);
}
return $retval;
}
/**
* Fetches a row from the result set.
*
* @param int $style OPTIONAL Fetch mode for this fetch operation.
* @param int $cursor OPTIONAL Absolute, relative, or other.
* @param int $offset OPTIONAL Number for absolute or relative cursors.
* @return mixed Array, object, or scalar depending on fetch mode.
* @throws Zend_Db_Statement_Mysqli_Exception
*/
public function fetch($style = null, $cursor = null, $offset = null)
{
if (!$this->_stmt) {
return false;
}
// fetch the next result
$retval = $this->_stmt->fetch();
switch ($retval) {
case null: // end of data
case false: // error occurred
$this->_stmt->reset();
return false;
default:
// fallthrough
}
// make sure we have a fetch mode
if ($style === null) {
$style = $this->_fetchMode;
}
// dereference the result values, otherwise things like fetchAll()
// return the same values for every entry (because of the reference).
$values = array();
foreach ($this->_values as $key => $val) {
$values[] = $val;
}
$row = false;
switch ($style) {
case Zend_Db::FETCH_NUM:
$row = $values;
break;
case Zend_Db::FETCH_ASSOC:
$row = array_combine($this->_keys, $values);
break;
case Zend_Db::FETCH_BOTH:
$assoc = array_combine($this->_keys, $values);
$row = array_merge($values, $assoc);
break;
case Zend_Db::FETCH_OBJ:
$row = (object) array_combine($this->_keys, $values);
break;
case Zend_Db::FETCH_BOUND:
$assoc = array_combine($this->_keys, $values);
$row = array_merge($values, $assoc);
return $this->_fetchBound($row);
break;
default:
/**
* @see Zend_Db_Statement_Mysqli_Exception
*/
// require_once 'Zend/Db/Statement/Mysqli/Exception.php';
throw new Zend_Db_Statement_Mysqli_Exception("Invalid fetch mode '$style' specified");
break;
}
return $row;
}
/**
* Retrieves the next rowset (result set) for a SQL statement that has
* multiple result sets. An example is a stored procedure that returns
* the results of multiple queries.
*
* @return bool
* @throws Zend_Db_Statement_Mysqli_Exception
*/
public function nextRowset()
{
/**
* @see Zend_Db_Statement_Mysqli_Exception
*/
// require_once 'Zend/Db/Statement/Mysqli/Exception.php';
throw new Zend_Db_Statement_Mysqli_Exception(__FUNCTION__.'() is not implemented');
}
/**
* Returns the number of rows affected by the execution of the
* last INSERT, DELETE, or UPDATE statement executed by this
* statement object.
*
* @return int The number of rows affected.
*/
public function rowCount()
{
if (!$this->_adapter) {
return false;
}
$mysqli = $this->_adapter->getConnection();
return $mysqli->affected_rows;
}
}

View File

@ -0,0 +1,38 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Statement
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Exception.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* Zend_Db_Statement_Exception
*/
// require_once 'Zend/Db/Statement/Exception.php';
/**
* @package Zend_Db
* @subpackage Statement
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Statement_Mysqli_Exception extends Zend_Db_Statement_Exception
{
}

View File

@ -0,0 +1,577 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Statement
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Oracle.php 23959 2011-05-03 10:45:47Z yoshida@zend.co.jp $
*/
/**
* @see Zend_Db_Statement
*/
// require_once 'Zend/Db/Statement.php';
/**
* Extends for Oracle.
*
* @category Zend
* @package Zend_Db
* @subpackage Statement
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Statement_Oracle extends Zend_Db_Statement
{
/**
* Column names.
*/
protected $_keys;
/**
* Fetched result values.
*/
protected $_values;
/**
* Check if LOB field are returned as string
* instead of OCI-Lob object
*
* @var boolean
*/
protected $_lobAsString = false;
/**
* Activate/deactivate return of LOB as string
*
* @param string $lob_as_string
* @return Zend_Db_Statement_Oracle
*/
public function setLobAsString($lob_as_string)
{
$this->_lobAsString = (bool) $lob_as_string;
return $this;
}
/**
* Return whether or not LOB are returned as string
*
* @return boolean
*/
public function getLobAsString()
{
return $this->_lobAsString;
}
/**
* Prepares statement handle
*
* @param string $sql
* @return void
* @throws Zend_Db_Statement_Oracle_Exception
*/
protected function _prepare($sql)
{
$connection = $this->_adapter->getConnection();
$this->_stmt = @oci_parse($connection, $sql);
if (!$this->_stmt) {
/**
* @see Zend_Db_Statement_Oracle_Exception
*/
// require_once 'Zend/Db/Statement/Oracle/Exception.php';
throw new Zend_Db_Statement_Oracle_Exception(oci_error($connection));
}
}
/**
* Binds a parameter to the specified variable name.
*
* @param mixed $parameter Name the parameter, either integer or string.
* @param mixed $variable Reference to PHP variable containing the value.
* @param mixed $type OPTIONAL Datatype of SQL parameter.
* @param mixed $length OPTIONAL Length of SQL parameter.
* @param mixed $options OPTIONAL Other options.
* @return bool
* @throws Zend_Db_Statement_Exception
*/
protected function _bindParam($parameter, &$variable, $type = null, $length = null, $options = null)
{
// default value
if ($type === NULL) {
$type = SQLT_CHR;
}
// default value
if ($length === NULL) {
$length = -1;
}
$retval = @oci_bind_by_name($this->_stmt, $parameter, $variable, $length, $type);
if ($retval === false) {
/**
* @see Zend_Db_Adapter_Oracle_Exception
*/
// require_once 'Zend/Db/Statement/Oracle/Exception.php';
throw new Zend_Db_Statement_Oracle_Exception(oci_error($this->_stmt));
}
return true;
}
/**
* Closes the cursor, allowing the statement to be executed again.
*
* @return bool
*/
public function closeCursor()
{
if (!$this->_stmt) {
return false;
}
oci_free_statement($this->_stmt);
$this->_stmt = false;
return true;
}
/**
* Returns the number of columns in the result set.
* Returns null if the statement has no result set metadata.
*
* @return int The number of columns.
*/
public function columnCount()
{
if (!$this->_stmt) {
return false;
}
return oci_num_fields($this->_stmt);
}
/**
* Retrieves the error code, if any, associated with the last operation on
* the statement handle.
*
* @return string error code.
*/
public function errorCode()
{
if (!$this->_stmt) {
return false;
}
$error = oci_error($this->_stmt);
if (!$error) {
return false;
}
return $error['code'];
}
/**
* Retrieves an array of error information, if any, associated with the
* last operation on the statement handle.
*
* @return array
*/
public function errorInfo()
{
if (!$this->_stmt) {
return false;
}
$error = oci_error($this->_stmt);
if (!$error) {
return false;
}
if (isset($error['sqltext'])) {
return array(
$error['code'],
$error['message'],
$error['offset'],
$error['sqltext'],
);
} else {
return array(
$error['code'],
$error['message'],
);
}
}
/**
* Executes a prepared statement.
*
* @param array $params OPTIONAL Values to bind to parameter placeholders.
* @return bool
* @throws Zend_Db_Statement_Exception
*/
public function _execute(array $params = null)
{
$connection = $this->_adapter->getConnection();
if (!$this->_stmt) {
return false;
}
if ($params !== null) {
if (!is_array($params)) {
$params = array($params);
}
$error = false;
foreach (array_keys($params) as $name) {
if (!@oci_bind_by_name($this->_stmt, $name, $params[$name], -1)) {
$error = true;
break;
}
}
if ($error) {
/**
* @see Zend_Db_Adapter_Oracle_Exception
*/
// require_once 'Zend/Db/Statement/Oracle/Exception.php';
throw new Zend_Db_Statement_Oracle_Exception(oci_error($this->_stmt));
}
}
$retval = @oci_execute($this->_stmt, $this->_adapter->_getExecuteMode());
if ($retval === false) {
/**
* @see Zend_Db_Adapter_Oracle_Exception
*/
// require_once 'Zend/Db/Statement/Oracle/Exception.php';
throw new Zend_Db_Statement_Oracle_Exception(oci_error($this->_stmt));
}
$this->_keys = Array();
if ($field_num = oci_num_fields($this->_stmt)) {
for ($i = 1; $i <= $field_num; $i++) {
$name = oci_field_name($this->_stmt, $i);
$this->_keys[] = $name;
}
}
$this->_values = Array();
if ($this->_keys) {
$this->_values = array_fill(0, count($this->_keys), null);
}
return $retval;
}
/**
* Fetches a row from the result set.
*
* @param int $style OPTIONAL Fetch mode for this fetch operation.
* @param int $cursor OPTIONAL Absolute, relative, or other.
* @param int $offset OPTIONAL Number for absolute or relative cursors.
* @return mixed Array, object, or scalar depending on fetch mode.
* @throws Zend_Db_Statement_Exception
*/
public function fetch($style = null, $cursor = null, $offset = null)
{
if (!$this->_stmt) {
return false;
}
if ($style === null) {
$style = $this->_fetchMode;
}
$lob_as_string = $this->getLobAsString() ? OCI_RETURN_LOBS : 0;
switch ($style) {
case Zend_Db::FETCH_NUM:
$row = oci_fetch_array($this->_stmt, OCI_NUM | OCI_RETURN_NULLS | $lob_as_string);
break;
case Zend_Db::FETCH_ASSOC:
$row = oci_fetch_array($this->_stmt, OCI_ASSOC | OCI_RETURN_NULLS | $lob_as_string);
break;
case Zend_Db::FETCH_BOTH:
$row = oci_fetch_array($this->_stmt, OCI_BOTH | OCI_RETURN_NULLS | $lob_as_string);
break;
case Zend_Db::FETCH_OBJ:
$row = oci_fetch_object($this->_stmt);
break;
case Zend_Db::FETCH_BOUND:
$row = oci_fetch_array($this->_stmt, OCI_BOTH | OCI_RETURN_NULLS | $lob_as_string);
if ($row !== false) {
return $this->_fetchBound($row);
}
break;
default:
/**
* @see Zend_Db_Adapter_Oracle_Exception
*/
// require_once 'Zend/Db/Statement/Oracle/Exception.php';
throw new Zend_Db_Statement_Oracle_Exception(
array(
'code' => 'HYC00',
'message' => "Invalid fetch mode '$style' specified"
)
);
break;
}
if (! $row && $error = oci_error($this->_stmt)) {
/**
* @see Zend_Db_Adapter_Oracle_Exception
*/
// require_once 'Zend/Db/Statement/Oracle/Exception.php';
throw new Zend_Db_Statement_Oracle_Exception($error);
}
if (is_array($row) && array_key_exists('zend_db_rownum', $row)) {
unset($row['zend_db_rownum']);
}
return $row;
}
/**
* Returns an array containing all of the result set rows.
*
* @param int $style OPTIONAL Fetch mode.
* @param int $col OPTIONAL Column number, if fetch mode is by column.
* @return array Collection of rows, each in a format by the fetch mode.
* @throws Zend_Db_Statement_Exception
*/
public function fetchAll($style = null, $col = 0)
{
if (!$this->_stmt) {
return false;
}
// make sure we have a fetch mode
if ($style === null) {
$style = $this->_fetchMode;
}
$flags = OCI_FETCHSTATEMENT_BY_ROW;
switch ($style) {
case Zend_Db::FETCH_BOTH:
/**
* @see Zend_Db_Adapter_Oracle_Exception
*/
// require_once 'Zend/Db/Statement/Oracle/Exception.php';
throw new Zend_Db_Statement_Oracle_Exception(
array(
'code' => 'HYC00',
'message' => "OCI8 driver does not support fetchAll(FETCH_BOTH), use fetch() in a loop instead"
)
);
// notreached
$flags |= OCI_NUM;
$flags |= OCI_ASSOC;
break;
case Zend_Db::FETCH_NUM:
$flags |= OCI_NUM;
break;
case Zend_Db::FETCH_ASSOC:
$flags |= OCI_ASSOC;
break;
case Zend_Db::FETCH_OBJ:
break;
case Zend_Db::FETCH_COLUMN:
$flags = $flags &~ OCI_FETCHSTATEMENT_BY_ROW;
$flags |= OCI_FETCHSTATEMENT_BY_COLUMN;
$flags |= OCI_NUM;
break;
default:
/**
* @see Zend_Db_Adapter_Oracle_Exception
*/
// require_once 'Zend/Db/Statement/Oracle/Exception.php';
throw new Zend_Db_Statement_Oracle_Exception(
array(
'code' => 'HYC00',
'message' => "Invalid fetch mode '$style' specified"
)
);
break;
}
$result = Array();
if ($flags != OCI_FETCHSTATEMENT_BY_ROW) { /* not Zend_Db::FETCH_OBJ */
if (! ($rows = oci_fetch_all($this->_stmt, $result, 0, -1, $flags) )) {
if ($error = oci_error($this->_stmt)) {
/**
* @see Zend_Db_Adapter_Oracle_Exception
*/
// require_once 'Zend/Db/Statement/Oracle/Exception.php';
throw new Zend_Db_Statement_Oracle_Exception($error);
}
if (!$rows) {
return array();
}
}
if ($style == Zend_Db::FETCH_COLUMN) {
$result = $result[$col];
}
foreach ($result as &$row) {
if (is_array($row) && array_key_exists('zend_db_rownum', $row)) {
unset($row['zend_db_rownum']);
}
}
} else {
while (($row = oci_fetch_object($this->_stmt)) !== false) {
$result [] = $row;
}
if ($error = oci_error($this->_stmt)) {
/**
* @see Zend_Db_Adapter_Oracle_Exception
*/
// require_once 'Zend/Db/Statement/Oracle/Exception.php';
throw new Zend_Db_Statement_Oracle_Exception($error);
}
}
return $result;
}
/**
* Returns a single column from the next row of a result set.
*
* @param int $col OPTIONAL Position of the column to fetch.
* @return string
* @throws Zend_Db_Statement_Exception
*/
public function fetchColumn($col = 0)
{
if (!$this->_stmt) {
return false;
}
if (!oci_fetch($this->_stmt)) {
// if no error, there is simply no record
if (!$error = oci_error($this->_stmt)) {
return false;
}
/**
* @see Zend_Db_Adapter_Oracle_Exception
*/
// require_once 'Zend/Db/Statement/Oracle/Exception.php';
throw new Zend_Db_Statement_Oracle_Exception($error);
}
$data = oci_result($this->_stmt, $col+1); //1-based
if ($data === false) {
/**
* @see Zend_Db_Adapter_Oracle_Exception
*/
// require_once 'Zend/Db/Statement/Oracle/Exception.php';
throw new Zend_Db_Statement_Oracle_Exception(oci_error($this->_stmt));
}
if ($this->getLobAsString()) {
// instanceof doesn't allow '-', we must use a temporary string
$type = 'OCI-Lob';
if ($data instanceof $type) {
$data = $data->read($data->size());
}
}
return $data;
}
/**
* Fetches the next row and returns it as an object.
*
* @param string $class OPTIONAL Name of the class to create.
* @param array $config OPTIONAL Constructor arguments for the class.
* @return mixed One object instance of the specified class.
* @throws Zend_Db_Statement_Exception
*/
public function fetchObject($class = 'stdClass', array $config = array())
{
if (!$this->_stmt) {
return false;
}
$obj = oci_fetch_object($this->_stmt);
if ($error = oci_error($this->_stmt)) {
/**
* @see Zend_Db_Adapter_Oracle_Exception
*/
// require_once 'Zend/Db/Statement/Oracle/Exception.php';
throw new Zend_Db_Statement_Oracle_Exception($error);
}
/* @todo XXX handle parameters */
return $obj;
}
/**
* Retrieves the next rowset (result set) for a SQL statement that has
* multiple result sets. An example is a stored procedure that returns
* the results of multiple queries.
*
* @return bool
* @throws Zend_Db_Statement_Exception
*/
public function nextRowset()
{
/**
* @see Zend_Db_Statement_Oracle_Exception
*/
// require_once 'Zend/Db/Statement/Oracle/Exception.php';
throw new Zend_Db_Statement_Oracle_Exception(
array(
'code' => 'HYC00',
'message' => 'Optional feature not implemented'
)
);
}
/**
* Returns the number of rows affected by the execution of the
* last INSERT, DELETE, or UPDATE statement executed by this
* statement object.
*
* @return int The number of rows affected.
* @throws Zend_Db_Statement_Exception
*/
public function rowCount()
{
if (!$this->_stmt) {
return false;
}
$num_rows = oci_num_rows($this->_stmt);
if ($num_rows === false) {
/**
* @see Zend_Db_Adapter_Oracle_Exception
*/
// require_once 'Zend/Db/Statement/Oracle/Exception.php';
throw new Zend_Db_Statement_Oracle_Exception(oci_error($this->_stmt));
}
return $num_rows;
}
}

View File

@ -0,0 +1,59 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Statement
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Exception.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* Zend_Db_Statement_Exception
*/
// require_once 'Zend/Db/Statement/Exception.php';
/**
* @category Zend
* @package Zend_Db
* @subpackage Statement
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Statement_Oracle_Exception extends Zend_Db_Statement_Exception
{
protected $message = 'Unknown exception';
protected $code = 0;
function __construct($error = null, $code = 0)
{
if (is_array($error)) {
if (!isset($error['offset'])) {
$this->message = $error['code']." ".$error['message'];
} else {
$this->message = $error['code']." ".$error['message']." ";
$this->message .= substr($error['sqltext'], 0, $error['offset']);
$this->message .= "*";
$this->message .= substr($error['sqltext'], $error['offset']);
}
$this->code = $error['code'];
}
if (!$this->code && $code) {
$this->code = $code;
}
}
}

View File

@ -0,0 +1,439 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Statement
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Pdo.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Db_Statement
*/
// require_once 'Zend/Db/Statement.php';
/**
* Proxy class to wrap a PDOStatement object.
* Matches the interface of PDOStatement. All methods simply proxy to the
* matching method in PDOStatement. PDOExceptions thrown by PDOStatement
* are re-thrown as Zend_Db_Statement_Exception.
*
* @category Zend
* @package Zend_Db
* @subpackage Statement
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Statement_Pdo extends Zend_Db_Statement implements IteratorAggregate
{
/**
* @var int
*/
protected $_fetchMode = PDO::FETCH_ASSOC;
/**
* Prepare a string SQL statement and create a statement object.
*
* @param string $sql
* @return void
* @throws Zend_Db_Statement_Exception
*/
protected function _prepare($sql)
{
try {
$this->_stmt = $this->_adapter->getConnection()->prepare($sql);
} catch (PDOException $e) {
// require_once 'Zend/Db/Statement/Exception.php';
throw new Zend_Db_Statement_Exception($e->getMessage(), $e->getCode(), $e);
}
}
/**
* Bind a column of the statement result set to a PHP variable.
*
* @param string $column Name the column in the result set, either by
* position or by name.
* @param mixed $param Reference to the PHP variable containing the value.
* @param mixed $type OPTIONAL
* @return bool
* @throws Zend_Db_Statement_Exception
*/
public function bindColumn($column, &$param, $type = null)
{
try {
if ($type === null) {
return $this->_stmt->bindColumn($column, $param);
} else {
return $this->_stmt->bindColumn($column, $param, $type);
}
} catch (PDOException $e) {
// require_once 'Zend/Db/Statement/Exception.php';
throw new Zend_Db_Statement_Exception($e->getMessage(), $e->getCode(), $e);
}
}
/**
* Binds a parameter to the specified variable name.
*
* @param mixed $parameter Name the parameter, either integer or string.
* @param mixed $variable Reference to PHP variable containing the value.
* @param mixed $type OPTIONAL Datatype of SQL parameter.
* @param mixed $length OPTIONAL Length of SQL parameter.
* @param mixed $options OPTIONAL Other options.
* @return bool
* @throws Zend_Db_Statement_Exception
*/
protected function _bindParam($parameter, &$variable, $type = null, $length = null, $options = null)
{
try {
if ($type === null) {
if (is_bool($variable)) {
$type = PDO::PARAM_BOOL;
} elseif ($variable === null) {
$type = PDO::PARAM_NULL;
} elseif (is_integer($variable)) {
$type = PDO::PARAM_INT;
} else {
$type = PDO::PARAM_STR;
}
}
return $this->_stmt->bindParam($parameter, $variable, $type, $length, $options);
} catch (PDOException $e) {
// require_once 'Zend/Db/Statement/Exception.php';
throw new Zend_Db_Statement_Exception($e->getMessage(), $e->getCode(), $e);
}
}
/**
* Binds a value to a parameter.
*
* @param mixed $parameter Name the parameter, either integer or string.
* @param mixed $value Scalar value to bind to the parameter.
* @param mixed $type OPTIONAL Datatype of the parameter.
* @return bool
* @throws Zend_Db_Statement_Exception
*/
public function bindValue($parameter, $value, $type = null)
{
if (is_string($parameter) && $parameter[0] != ':') {
$parameter = ":$parameter";
}
$this->_bindParam[$parameter] = $value;
try {
if ($type === null) {
return $this->_stmt->bindValue($parameter, $value);
} else {
return $this->_stmt->bindValue($parameter, $value, $type);
}
} catch (PDOException $e) {
// require_once 'Zend/Db/Statement/Exception.php';
throw new Zend_Db_Statement_Exception($e->getMessage(), $e->getCode(), $e);
}
}
/**
* Closes the cursor, allowing the statement to be executed again.
*
* @return bool
* @throws Zend_Db_Statement_Exception
*/
public function closeCursor()
{
try {
return $this->_stmt->closeCursor();
} catch (PDOException $e) {
// require_once 'Zend/Db/Statement/Exception.php';
throw new Zend_Db_Statement_Exception($e->getMessage(), $e->getCode(), $e);
}
}
/**
* Returns the number of columns in the result set.
* Returns null if the statement has no result set metadata.
*
* @return int The number of columns.
* @throws Zend_Db_Statement_Exception
*/
public function columnCount()
{
try {
return $this->_stmt->columnCount();
} catch (PDOException $e) {
// require_once 'Zend/Db/Statement/Exception.php';
throw new Zend_Db_Statement_Exception($e->getMessage(), $e->getCode(), $e);
}
}
/**
* Retrieves the error code, if any, associated with the last operation on
* the statement handle.
*
* @return string error code.
* @throws Zend_Db_Statement_Exception
*/
public function errorCode()
{
try {
return $this->_stmt->errorCode();
} catch (PDOException $e) {
// require_once 'Zend/Db/Statement/Exception.php';
throw new Zend_Db_Statement_Exception($e->getMessage(), $e->getCode(), $e);
}
}
/**
* Retrieves an array of error information, if any, associated with the
* last operation on the statement handle.
*
* @return array
* @throws Zend_Db_Statement_Exception
*/
public function errorInfo()
{
try {
return $this->_stmt->errorInfo();
} catch (PDOException $e) {
// require_once 'Zend/Db/Statement/Exception.php';
throw new Zend_Db_Statement_Exception($e->getMessage(), $e->getCode(), $e);
}
}
/**
* Executes a prepared statement.
*
* @param array $params OPTIONAL Values to bind to parameter placeholders.
* @return bool
* @throws Zend_Db_Statement_Exception
*/
public function _execute(array $params = null)
{
try {
if ($params !== null) {
return $this->_stmt->execute($params);
} else {
return $this->_stmt->execute();
}
} catch (PDOException $e) {
// require_once 'Zend/Db/Statement/Exception.php';
throw new Zend_Db_Statement_Exception($e->getMessage(), (int) $e->getCode(), $e);
}
}
/**
* Fetches a row from the result set.
*
* @param int $style OPTIONAL Fetch mode for this fetch operation.
* @param int $cursor OPTIONAL Absolute, relative, or other.
* @param int $offset OPTIONAL Number for absolute or relative cursors.
* @return mixed Array, object, or scalar depending on fetch mode.
* @throws Zend_Db_Statement_Exception
*/
public function fetch($style = null, $cursor = null, $offset = null)
{
if ($style === null) {
$style = $this->_fetchMode;
}
try {
return $this->_stmt->fetch($style, $cursor, $offset);
} catch (PDOException $e) {
// require_once 'Zend/Db/Statement/Exception.php';
throw new Zend_Db_Statement_Exception($e->getMessage(), $e->getCode(), $e);
}
}
/**
* Required by IteratorAggregate interface
*
* @return IteratorIterator
*/
public function getIterator()
{
return new IteratorIterator($this->_stmt);
}
/**
* Returns an array containing all of the result set rows.
*
* @param int $style OPTIONAL Fetch mode.
* @param int $col OPTIONAL Column number, if fetch mode is by column.
* @return array Collection of rows, each in a format by the fetch mode.
* @throws Zend_Db_Statement_Exception
*/
public function fetchAll($style = null, $col = null)
{
if ($style === null) {
$style = $this->_fetchMode;
}
try {
if ($style == PDO::FETCH_COLUMN) {
if ($col === null) {
$col = 0;
}
return $this->_stmt->fetchAll($style, $col);
} else {
return $this->_stmt->fetchAll($style);
}
} catch (PDOException $e) {
// require_once 'Zend/Db/Statement/Exception.php';
throw new Zend_Db_Statement_Exception($e->getMessage(), $e->getCode(), $e);
}
}
/**
* Returns a single column from the next row of a result set.
*
* @param int $col OPTIONAL Position of the column to fetch.
* @return string
* @throws Zend_Db_Statement_Exception
*/
public function fetchColumn($col = 0)
{
try {
return $this->_stmt->fetchColumn($col);
} catch (PDOException $e) {
// require_once 'Zend/Db/Statement/Exception.php';
throw new Zend_Db_Statement_Exception($e->getMessage(), $e->getCode(), $e);
}
}
/**
* Fetches the next row and returns it as an object.
*
* @param string $class OPTIONAL Name of the class to create.
* @param array $config OPTIONAL Constructor arguments for the class.
* @return mixed One object instance of the specified class.
* @throws Zend_Db_Statement_Exception
*/
public function fetchObject($class = 'stdClass', array $config = array())
{
try {
return $this->_stmt->fetchObject($class, $config);
} catch (PDOException $e) {
// require_once 'Zend/Db/Statement/Exception.php';
throw new Zend_Db_Statement_Exception($e->getMessage(), $e->getCode(), $e);
}
}
/**
* Retrieve a statement attribute.
*
* @param integer $key Attribute name.
* @return mixed Attribute value.
* @throws Zend_Db_Statement_Exception
*/
public function getAttribute($key)
{
try {
return $this->_stmt->getAttribute($key);
} catch (PDOException $e) {
// require_once 'Zend/Db/Statement/Exception.php';
throw new Zend_Db_Statement_Exception($e->getMessage(), $e->getCode(), $e);
}
}
/**
* Returns metadata for a column in a result set.
*
* @param int $column
* @return mixed
* @throws Zend_Db_Statement_Exception
*/
public function getColumnMeta($column)
{
try {
return $this->_stmt->getColumnMeta($column);
} catch (PDOException $e) {
// require_once 'Zend/Db/Statement/Exception.php';
throw new Zend_Db_Statement_Exception($e->getMessage(), $e->getCode(), $e);
}
}
/**
* Retrieves the next rowset (result set) for a SQL statement that has
* multiple result sets. An example is a stored procedure that returns
* the results of multiple queries.
*
* @return bool
* @throws Zend_Db_Statement_Exception
*/
public function nextRowset()
{
try {
return $this->_stmt->nextRowset();
} catch (PDOException $e) {
// require_once 'Zend/Db/Statement/Exception.php';
throw new Zend_Db_Statement_Exception($e->getMessage(), $e->getCode(), $e);
}
}
/**
* Returns the number of rows affected by the execution of the
* last INSERT, DELETE, or UPDATE statement executed by this
* statement object.
*
* @return int The number of rows affected.
* @throws Zend_Db_Statement_Exception
*/
public function rowCount()
{
try {
return $this->_stmt->rowCount();
} catch (PDOException $e) {
// require_once 'Zend/Db/Statement/Exception.php';
throw new Zend_Db_Statement_Exception($e->getMessage(), $e->getCode(), $e);
}
}
/**
* Set a statement attribute.
*
* @param string $key Attribute name.
* @param mixed $val Attribute value.
* @return bool
* @throws Zend_Db_Statement_Exception
*/
public function setAttribute($key, $val)
{
try {
return $this->_stmt->setAttribute($key, $val);
} catch (PDOException $e) {
// require_once 'Zend/Db/Statement/Exception.php';
throw new Zend_Db_Statement_Exception($e->getMessage(), $e->getCode(), $e);
}
}
/**
* Set the default fetch mode for this statement.
*
* @param int $mode The fetch mode.
* @return bool
* @throws Zend_Db_Statement_Exception
*/
public function setFetchMode($mode)
{
$this->_fetchMode = $mode;
try {
return $this->_stmt->setFetchMode($mode);
} catch (PDOException $e) {
// require_once 'Zend/Db/Statement/Exception.php';
throw new Zend_Db_Statement_Exception($e->getMessage(), $e->getCode(), $e);
}
}
}

View File

@ -0,0 +1,94 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Statement
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Ibm.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Db_Statement_Pdo
*/
// require_once 'Zend/Db/Statement/Pdo.php';
/**
* Proxy class to wrap a PDOStatement object for IBM Databases.
* Matches the interface of PDOStatement. All methods simply proxy to the
* matching method in PDOStatement. PDOExceptions thrown by PDOStatement
* are re-thrown as Zend_Db_Statement_Exception.
*
* @category Zend
* @package Zend_Db
* @subpackage Statement
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Statement_Pdo_Ibm extends Zend_Db_Statement_Pdo
{
/**
* Returns an array containing all of the result set rows.
*
* Behaves like parent, but if limit()
* is used, the final result removes the extra column
* 'zend_db_rownum'
*
* @param int $style OPTIONAL Fetch mode.
* @param int $col OPTIONAL Column number, if fetch mode is by column.
* @return array Collection of rows, each in a format by the fetch mode.
* @throws Zend_Db_Statement_Exception
*/
public function fetchAll($style = null, $col = null)
{
$data = parent::fetchAll($style, $col);
$results = array();
$remove = $this->_adapter->foldCase('ZEND_DB_ROWNUM');
foreach ($data as $row) {
if (is_array($row) && array_key_exists($remove, $row)) {
unset($row[$remove]);
}
$results[] = $row;
}
return $results;
}
/**
* Binds a parameter to the specified variable name.
*
* @param mixed $parameter Name the parameter, either integer or string.
* @param mixed $variable Reference to PHP variable containing the value.
* @param mixed $type OPTIONAL Datatype of SQL parameter.
* @param mixed $length OPTIONAL Length of SQL parameter.
* @param mixed $options OPTIONAL Other options.
* @return bool
* @throws Zend_Db_Statement_Exception
*/
public function _bindParam($parameter, &$variable, $type = null, $length = null, $options = null)
{
try {
if (($type === null) && ($length === null) && ($options === null)) {
return $this->_stmt->bindParam($parameter, $variable);
} else {
return $this->_stmt->bindParam($parameter, $variable, $type, $length, $options);
}
} catch (PDOException $e) {
// require_once 'Zend/Db/Statement/Exception.php';
throw new Zend_Db_Statement_Exception($e->getMessage(), $e->getCode(), $e);
}
}
}

View File

@ -0,0 +1,91 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Statement
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Oci.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Db_Statement_Pdo
*/
// require_once 'Zend/Db/Statement/Pdo.php';
/**
* Proxy class to wrap a PDOStatement object for IBM Databases.
* Matches the interface of PDOStatement. All methods simply proxy to the
* matching method in PDOStatement. PDOExceptions thrown by PDOStatement
* are re-thrown as Zend_Db_Statement_Exception.
*
* @category Zend
* @package Zend_Db
* @subpackage Statement
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Statement_Pdo_Oci extends Zend_Db_Statement_Pdo
{
/**
* Returns an array containing all of the result set rows.
*
* Behaves like parent, but if limit()
* is used, the final result removes the extra column
* 'zend_db_rownum'
*
* @param int $style OPTIONAL Fetch mode.
* @param int $col OPTIONAL Column number, if fetch mode is by column.
* @return array Collection of rows, each in a format by the fetch mode.
* @throws Zend_Db_Statement_Exception
*/
public function fetchAll($style = null, $col = null)
{
$data = parent::fetchAll($style, $col);
$results = array();
$remove = $this->_adapter->foldCase('zend_db_rownum');
foreach ($data as $row) {
if (is_array($row) && array_key_exists($remove, $row)) {
unset($row[$remove]);
}
$results[] = $row;
}
return $results;
}
/**
* Fetches a row from the result set.
*
* @param int $style OPTIONAL Fetch mode for this fetch operation.
* @param int $cursor OPTIONAL Absolute, relative, or other.
* @param int $offset OPTIONAL Number for absolute or relative cursors.
* @return mixed Array, object, or scalar depending on fetch mode.
* @throws Zend_Db_Statement_Exception
*/
public function fetch($style = null, $cursor = null, $offset = null)
{
$row = parent::fetch($style, $cursor, $offset);
$remove = $this->_adapter->foldCase('zend_db_rownum');
if (is_array($row) && array_key_exists($remove, $row)) {
unset($row[$remove]);
}
return $row;
}
}

View File

@ -0,0 +1,440 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Statement
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Sqlsrv.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Db_Statement
*/
// require_once 'Zend/Db/Statement.php';
/**
* Extends for Microsoft SQL Server Driver for PHP
*
* @category Zend
* @package Zend_Db
* @subpackage Statement
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Statement_Sqlsrv extends Zend_Db_Statement
{
/**
* The connection_stmt object original string.
*/
protected $_originalSQL;
/**
* Column names.
*/
protected $_keys;
/**
* Query executed
*/
protected $_executed = false;
/**
* Prepares statement handle
*
* @param string $sql
* @return void
* @throws Zend_Db_Statement_Sqlsrv_Exception
*/
protected function _prepare($sql)
{
$connection = $this->_adapter->getConnection();
$this->_stmt = sqlsrv_prepare($connection, $sql);
if (!$this->_stmt) {
// require_once 'Zend/Db/Statement/Sqlsrv/Exception.php';
throw new Zend_Db_Statement_Sqlsrv_Exception(sqlsrv_errors());
}
$this->_originalSQL = $sql;
}
/**
* Binds a parameter to the specified variable name.
*
* @param mixed $parameter Name the parameter, either integer or string.
* @param mixed $variable Reference to PHP variable containing the value.
* @param mixed $type OPTIONAL Datatype of SQL parameter.
* @param mixed $length OPTIONAL Length of SQL parameter.
* @param mixed $options OPTIONAL Other options.
* @return bool
* @throws Zend_Db_Statement_Exception
*/
protected function _bindParam($parameter, &$variable, $type = null, $length = null, $options = null)
{
//Db server doesn't support bind by name
return true;
}
/**
* Closes the cursor, allowing the statement to be executed again.
*
* @return bool
*/
public function closeCursor()
{
if (!$this->_stmt) {
return false;
}
sqlsrv_free_stmt($this->_stmt);
$this->_stmt = false;
return true;
}
/**
* Returns the number of columns in the result set.
* Returns null if the statement has no result set metadata.
*
* @return int The number of columns.
*/
public function columnCount()
{
if ($this->_stmt && $this->_executed) {
return sqlsrv_num_fields($this->_stmt);
}
return 0;
}
/**
* Retrieves the error code, if any, associated with the last operation on
* the statement handle.
*
* @return string error code.
*/
public function errorCode()
{
if (!$this->_stmt) {
return false;
}
$error = sqlsrv_errors();
if (!$error) {
return false;
}
return $error[0]['code'];
}
/**
* Retrieves an array of error information, if any, associated with the
* last operation on the statement handle.
*
* @return array
*/
public function errorInfo()
{
if (!$this->_stmt) {
return false;
}
$error = sqlsrv_errors();
if (!$error) {
return false;
}
return array(
$error[0]['code'],
$error[0]['message'],
);
}
/**
* Executes a prepared statement.
*
* @param array $params OPTIONAL Values to bind to parameter placeholders.
* @return bool
* @throws Zend_Db_Statement_Exception
*/
public function _execute(array $params = null)
{
$connection = $this->_adapter->getConnection();
if (!$this->_stmt) {
return false;
}
if ($params !== null) {
if (!is_array($params)) {
$params = array($params);
}
$error = false;
// make all params passed by reference
$params_ = array();
$temp = array();
$i = 1;
foreach ($params as $param) {
$temp[$i] = $param;
$params_[] = &$temp[$i];
$i++;
}
$params = $params_;
}
$this->_stmt = sqlsrv_query($connection, $this->_originalSQL, $params);
if (!$this->_stmt) {
// require_once 'Zend/Db/Statement/Sqlsrv/Exception.php';
throw new Zend_Db_Statement_Sqlsrv_Exception(sqlsrv_errors());
}
$this->_executed = true;
return (!$this->_stmt);
}
/**
* Fetches a row from the result set.
*
* @param int $style OPTIONAL Fetch mode for this fetch operation.
* @param int $cursor OPTIONAL Absolute, relative, or other.
* @param int $offset OPTIONAL Number for absolute or relative cursors.
* @return mixed Array, object, or scalar depending on fetch mode.
* @throws Zend_Db_Statement_Exception
*/
public function fetch($style = null, $cursor = null, $offset = null)
{
if (!$this->_stmt) {
return false;
}
if (null === $style) {
$style = $this->_fetchMode;
}
$values = sqlsrv_fetch_array($this->_stmt, SQLSRV_FETCH_ASSOC);
if (!$values && (null !== $error = sqlsrv_errors())) {
// require_once 'Zend/Db/Statement/Sqlsrv/Exception.php';
throw new Zend_Db_Statement_Sqlsrv_Exception($error);
}
if (null === $values) {
return null;
}
if (!$this->_keys) {
foreach ($values as $key => $value) {
$this->_keys[] = $this->_adapter->foldCase($key);
}
}
$values = array_values($values);
$row = false;
switch ($style) {
case Zend_Db::FETCH_NUM:
$row = $values;
break;
case Zend_Db::FETCH_ASSOC:
$row = array_combine($this->_keys, $values);
break;
case Zend_Db::FETCH_BOTH:
$assoc = array_combine($this->_keys, $values);
$row = array_merge($values, $assoc);
break;
case Zend_Db::FETCH_OBJ:
$row = (object) array_combine($this->_keys, $values);
break;
case Zend_Db::FETCH_BOUND:
$assoc = array_combine($this->_keys, $values);
$row = array_merge($values, $assoc);
$row = $this->_fetchBound($row);
break;
default:
// require_once 'Zend/Db/Statement/Sqlsrv/Exception.php';
throw new Zend_Db_Statement_Sqlsrv_Exception("Invalid fetch mode '$style' specified");
break;
}
return $row;
}
/**
* Returns a single column from the next row of a result set.
*
* @param int $col OPTIONAL Position of the column to fetch.
* @return string
* @throws Zend_Db_Statement_Exception
*/
public function fetchColumn($col = 0)
{
if (!$this->_stmt) {
return false;
}
if (!sqlsrv_fetch($this->_stmt)) {
if (null !== $error = sqlsrv_errors()) {
// require_once 'Zend/Db/Statement/Sqlsrv/Exception.php';
throw new Zend_Db_Statement_Sqlsrv_Exception($error);
}
// If no error, there is simply no record
return false;
}
$data = sqlsrv_get_field($this->_stmt, $col); //0-based
if ($data === false) {
// require_once 'Zend/Db/Statement/Sqlsrv/Exception.php';
throw new Zend_Db_Statement_Sqlsrv_Exception(sqlsrv_errors());
}
return $data;
}
/**
* Fetches the next row and returns it as an object.
*
* @param string $class OPTIONAL Name of the class to create.
* @param array $config OPTIONAL Constructor arguments for the class.
* @return mixed One object instance of the specified class.
* @throws Zend_Db_Statement_Exception
*/
public function fetchObject($class = 'stdClass', array $config = array())
{
if (!$this->_stmt) {
return false;
}
$obj = sqlsrv_fetch_object($this->_stmt);
if ($error = sqlsrv_errors()) {
// require_once 'Zend/Db/Statement/Sqlsrv/Exception.php';
throw new Zend_Db_Statement_Sqlsrv_Exception($error);
}
/* @todo XXX handle parameters */
if (null === $obj) {
return false;
}
return $obj;
}
/**
* Returns metadata for a column in a result set.
*
* @param int $column
* @return mixed
* @throws Zend_Db_Statement_Sqlsrv_Exception
*/
public function getColumnMeta($column)
{
$fields = sqlsrv_field_metadata($this->_stmt);
if (!$fields) {
throw new Zend_Db_Statement_Sqlsrv_Exception('Column metadata can not be fetched');
}
if (!isset($fields[$column])) {
throw new Zend_Db_Statement_Sqlsrv_Exception('Column index does not exist in statement');
}
return $fields[$column];
}
/**
* Retrieves the next rowset (result set) for a SQL statement that has
* multiple result sets. An example is a stored procedure that returns
* the results of multiple queries.
*
* @return bool
* @throws Zend_Db_Statement_Exception
*/
public function nextRowset()
{
if (sqlsrv_next_result($this->_stmt) === false) {
// require_once 'Zend/Db/Statement/Sqlsrv/Exception.php';
throw new Zend_Db_Statement_Sqlsrv_Exception(sqlsrv_errors());
}
// reset column keys
$this->_keys = null;
return true;
}
/**
* Returns the number of rows affected by the execution of the
* last INSERT, DELETE, or UPDATE statement executed by this
* statement object.
*
* @return int The number of rows affected.
* @throws Zend_Db_Statement_Exception
*/
public function rowCount()
{
if (!$this->_stmt) {
return false;
}
if (!$this->_executed) {
return 0;
}
$num_rows = sqlsrv_rows_affected($this->_stmt);
// Strict check is necessary; 0 is a valid return value
if ($num_rows === false) {
// require_once 'Zend/Db/Statement/Sqlsrv/Exception.php';
throw new Zend_Db_Statement_Sqlsrv_Exception(sqlsrv_errors());
}
return $num_rows;
}
/**
* Returns an array containing all of the result set rows.
*
* @param int $style OPTIONAL Fetch mode.
* @param int $col OPTIONAL Column number, if fetch mode is by column.
* @return array Collection of rows, each in a format by the fetch mode.
*
* Behaves like parent, but if limit()
* is used, the final result removes the extra column
* 'zend_db_rownum'
*/
public function fetchAll($style = null, $col = null)
{
$data = parent::fetchAll($style, $col);
$results = array();
$remove = $this->_adapter->foldCase('ZEND_DB_ROWNUM');
foreach ($data as $row) {
if (is_array($row) && array_key_exists($remove, $row)) {
unset($row[$remove]);
}
$results[] = $row;
}
return $results;
}
}

View File

@ -0,0 +1,61 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Statement
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Exception.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Db_Statement_Exception
*/
// require_once 'Zend/Db/Statement/Exception.php';
/**
* @package Zend_Db
* @subpackage Statement
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Statement_Sqlsrv_Exception extends Zend_Db_Statement_Exception
{
/**
* Constructor
*
* If $message is an array, the assumption is that the return value of
* sqlsrv_errors() was provided. If so, it then retrieves the most recent
* error from that stack, and sets the message and code based on it.
*
* @param null|array|string $message
* @param null|int $code
*/
public function __construct($message = null, $code = 0)
{
if (is_array($message)) {
// Error should be array of errors
// We only need first one (?)
if (isset($message[0])) {
$message = $message[0];
}
$code = (int) $message['code'];
$message = (string) $message['message'];
}
parent::__construct($message, $code);
}
}

View File

@ -0,0 +1,79 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Table
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Table.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Db_Table_Abstract
*/
// require_once 'Zend/Db/Table/Abstract.php';
/**
* @see Zend_Db_Table_Definition
*/
// require_once 'Zend/Db/Table/Definition.php';
/**
* Class for SQL table interface.
*
* @category Zend
* @package Zend_Db
* @subpackage Table
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Table extends Zend_Db_Table_Abstract
{
/**
* __construct() - For concrete implementation of Zend_Db_Table
*
* @param string|array $config string can reference a Zend_Registry key for a db adapter
* OR it can reference the name of a table
* @param array|Zend_Db_Table_Definition $definition
*/
public function __construct($config = array(), $definition = null)
{
if ($definition !== null && is_array($definition)) {
$definition = new Zend_Db_Table_Definition($definition);
}
if (is_string($config)) {
if (Zend_Registry::isRegistered($config)) {
trigger_error(__CLASS__ . '::' . __METHOD__ . '(\'registryName\') is not valid usage of Zend_Db_Table, '
. 'try extending Zend_Db_Table_Abstract in your extending classes.',
E_USER_NOTICE
);
$config = array(self::ADAPTER => $config);
} else {
// process this as table with or without a definition
if ($definition instanceof Zend_Db_Table_Definition
&& $definition->hasTableConfig($config)) {
// this will have DEFINITION_CONFIG_NAME & DEFINITION
$config = $definition->getTableConfig($config);
} else {
$config = array(self::NAME => $config);
}
}
}
parent::__construct($config);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,131 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Table
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Definition.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* Class for SQL table interface.
*
* @category Zend
* @package Zend_Db
* @subpackage Table
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Table_Definition
{
/**
* @var array
*/
protected $_tableConfigs = array();
/**
* __construct()
*
* @param array|Zend_Config $options
*/
public function __construct($options = null)
{
if ($options instanceof Zend_Config) {
$this->setConfig($options);
} elseif (is_array($options)) {
$this->setOptions($options);
}
}
/**
* setConfig()
*
* @param Zend_Config $config
* @return Zend_Db_Table_Definition
*/
public function setConfig(Zend_Config $config)
{
$this->setOptions($config->toArray());
return $this;
}
/**
* setOptions()
*
* @param array $options
* @return Zend_Db_Table_Definition
*/
public function setOptions(Array $options)
{
foreach ($options as $optionName => $optionValue) {
$this->setTableConfig($optionName, $optionValue);
}
return $this;
}
/**
* @param string $tableName
* @param array $tableConfig
* @return Zend_Db_Table_Definition
*/
public function setTableConfig($tableName, array $tableConfig)
{
// @todo logic here
$tableConfig[Zend_Db_Table::DEFINITION_CONFIG_NAME] = $tableName;
$tableConfig[Zend_Db_Table::DEFINITION] = $this;
if (!isset($tableConfig[Zend_Db_Table::NAME])) {
$tableConfig[Zend_Db_Table::NAME] = $tableName;
}
$this->_tableConfigs[$tableName] = $tableConfig;
return $this;
}
/**
* getTableConfig()
*
* @param string $tableName
* @return array
*/
public function getTableConfig($tableName)
{
return $this->_tableConfigs[$tableName];
}
/**
* removeTableConfig()
*
* @param string $tableName
*/
public function removeTableConfig($tableName)
{
unset($this->_tableConfigs[$tableName]);
}
/**
* hasTableConfig()
*
* @param string $tableName
* @return bool
*/
public function hasTableConfig($tableName)
{
return (isset($this->_tableConfigs[$tableName]));
}
}

View File

@ -0,0 +1,38 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Table
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Exception.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* Zend_Db_Exception
*/
// require_once 'Zend/Db/Exception.php';
/**
* @category Zend
* @package Zend_Db
* @subpackage Table
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Table_Exception extends Zend_Db_Exception
{
}

View File

@ -0,0 +1,42 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Table
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Row.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Db_Table_Row_Abstract
*/
// require_once 'Zend/Db/Table/Row/Abstract.php';
/**
* Reference concrete class that extends Zend_Db_Table_Row_Abstract.
* Developers may also create their own classes that extend the abstract class.
*
* @category Zend
* @package Zend_Db
* @subpackage Table
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Table_Row extends Zend_Db_Table_Row_Abstract
{
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,38 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Table
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Exception.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* Zend_Db_Table_Exception
*/
// require_once 'Zend/Db/Table/Exception.php';
/**
* @category Zend
* @package Zend_Db
* @subpackage Table
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Table_Row_Exception extends Zend_Db_Table_Exception
{
}

View File

@ -0,0 +1,43 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Table
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Rowset.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Db_Table_Rowset_Abstract
*/
// require_once 'Zend/Db/Table/Rowset/Abstract.php';
/**
* Reference concrete class that extends Zend_Db_Table_Rowset_Abstract.
* Developers may also create their own classes that extend the abstract class.
*
* @category Zend
* @package Zend_Db
* @subpackage Table
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Table_Rowset extends Zend_Db_Table_Rowset_Abstract
{
}

View File

@ -0,0 +1,435 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Table
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Abstract.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @category Zend
* @package Zend_Db
* @subpackage Table
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
abstract class Zend_Db_Table_Rowset_Abstract implements SeekableIterator, Countable, ArrayAccess
{
/**
* The original data for each row.
*
* @var array
*/
protected $_data = array();
/**
* Zend_Db_Table_Abstract object.
*
* @var Zend_Db_Table_Abstract
*/
protected $_table;
/**
* Connected is true if we have a reference to a live
* Zend_Db_Table_Abstract object.
* This is false after the Rowset has been deserialized.
*
* @var boolean
*/
protected $_connected = true;
/**
* Zend_Db_Table_Abstract class name.
*
* @var string
*/
protected $_tableClass;
/**
* Zend_Db_Table_Row_Abstract class name.
*
* @var string
*/
protected $_rowClass = 'Zend_Db_Table_Row';
/**
* Iterator pointer.
*
* @var integer
*/
protected $_pointer = 0;
/**
* How many data rows there are.
*
* @var integer
*/
protected $_count;
/**
* Collection of instantiated Zend_Db_Table_Row objects.
*
* @var array
*/
protected $_rows = array();
/**
* @var boolean
*/
protected $_stored = false;
/**
* @var boolean
*/
protected $_readOnly = false;
/**
* Constructor.
*
* @param array $config
*/
public function __construct(array $config)
{
if (isset($config['table'])) {
$this->_table = $config['table'];
$this->_tableClass = get_class($this->_table);
}
if (isset($config['rowClass'])) {
$this->_rowClass = $config['rowClass'];
}
if (!class_exists($this->_rowClass)) {
// require_once 'Zend/Loader.php';
Zend_Loader::loadClass($this->_rowClass);
}
if (isset($config['data'])) {
$this->_data = $config['data'];
}
if (isset($config['readOnly'])) {
$this->_readOnly = $config['readOnly'];
}
if (isset($config['stored'])) {
$this->_stored = $config['stored'];
}
// set the count of rows
$this->_count = count($this->_data);
$this->init();
}
/**
* Store data, class names, and state in serialized object
*
* @return array
*/
public function __sleep()
{
return array('_data', '_tableClass', '_rowClass', '_pointer', '_count', '_rows', '_stored',
'_readOnly');
}
/**
* Setup to do on wakeup.
* A de-serialized Rowset should not be assumed to have access to a live
* database connection, so set _connected = false.
*
* @return void
*/
public function __wakeup()
{
$this->_connected = false;
}
/**
* Initialize object
*
* Called from {@link __construct()} as final step of object instantiation.
*
* @return void
*/
public function init()
{
}
/**
* Return the connected state of the rowset.
*
* @return boolean
*/
public function isConnected()
{
return $this->_connected;
}
/**
* Returns the table object, or null if this is disconnected rowset
*
* @return Zend_Db_Table_Abstract
*/
public function getTable()
{
return $this->_table;
}
/**
* Set the table object, to re-establish a live connection
* to the database for a Rowset that has been de-serialized.
*
* @param Zend_Db_Table_Abstract $table
* @return boolean
* @throws Zend_Db_Table_Row_Exception
*/
public function setTable(Zend_Db_Table_Abstract $table)
{
$this->_table = $table;
$this->_connected = false;
// @todo This works only if we have iterated through
// the result set once to instantiate the rows.
foreach ($this as $row) {
$connected = $row->setTable($table);
if ($connected == true) {
$this->_connected = true;
}
}
return $this->_connected;
}
/**
* Query the class name of the Table object for which this
* Rowset was created.
*
* @return string
*/
public function getTableClass()
{
return $this->_tableClass;
}
/**
* Rewind the Iterator to the first element.
* Similar to the reset() function for arrays in PHP.
* Required by interface Iterator.
*
* @return Zend_Db_Table_Rowset_Abstract Fluent interface.
*/
public function rewind()
{
$this->_pointer = 0;
return $this;
}
/**
* Return the current element.
* Similar to the current() function for arrays in PHP
* Required by interface Iterator.
*
* @return Zend_Db_Table_Row_Abstract current element from the collection
*/
public function current()
{
if ($this->valid() === false) {
return null;
}
// return the row object
return $this->_loadAndReturnRow($this->_pointer);
}
/**
* Return the identifying key of the current element.
* Similar to the key() function for arrays in PHP.
* Required by interface Iterator.
*
* @return int
*/
public function key()
{
return $this->_pointer;
}
/**
* Move forward to next element.
* Similar to the next() function for arrays in PHP.
* Required by interface Iterator.
*
* @return void
*/
public function next()
{
++$this->_pointer;
}
/**
* Check if there is a current element after calls to rewind() or next().
* Used to check if we've iterated to the end of the collection.
* Required by interface Iterator.
*
* @return bool False if there's nothing more to iterate over
*/
public function valid()
{
return $this->_pointer >= 0 && $this->_pointer < $this->_count;
}
/**
* Returns the number of elements in the collection.
*
* Implements Countable::count()
*
* @return int
*/
public function count()
{
return $this->_count;
}
/**
* Take the Iterator to position $position
* Required by interface SeekableIterator.
*
* @param int $position the position to seek to
* @return Zend_Db_Table_Rowset_Abstract
* @throws Zend_Db_Table_Rowset_Exception
*/
public function seek($position)
{
$position = (int) $position;
if ($position < 0 || $position >= $this->_count) {
// require_once 'Zend/Db/Table/Rowset/Exception.php';
throw new Zend_Db_Table_Rowset_Exception("Illegal index $position");
}
$this->_pointer = $position;
return $this;
}
/**
* Check if an offset exists
* Required by the ArrayAccess implementation
*
* @param string $offset
* @return boolean
*/
public function offsetExists($offset)
{
return isset($this->_data[(int) $offset]);
}
/**
* Get the row for the given offset
* Required by the ArrayAccess implementation
*
* @param string $offset
* @return Zend_Db_Table_Row_Abstract
*/
public function offsetGet($offset)
{
$offset = (int) $offset;
if ($offset < 0 || $offset >= $this->_count) {
// require_once 'Zend/Db/Table/Rowset/Exception.php';
throw new Zend_Db_Table_Rowset_Exception("Illegal index $offset");
}
$this->_pointer = $offset;
return $this->current();
}
/**
* Does nothing
* Required by the ArrayAccess implementation
*
* @param string $offset
* @param mixed $value
*/
public function offsetSet($offset, $value)
{
}
/**
* Does nothing
* Required by the ArrayAccess implementation
*
* @param string $offset
*/
public function offsetUnset($offset)
{
}
/**
* Returns a Zend_Db_Table_Row from a known position into the Iterator
*
* @param int $position the position of the row expected
* @param bool $seek wether or not seek the iterator to that position after
* @return Zend_Db_Table_Row
* @throws Zend_Db_Table_Rowset_Exception
*/
public function getRow($position, $seek = false)
{
try {
$row = $this->_loadAndReturnRow($position);
} catch (Zend_Db_Table_Rowset_Exception $e) {
// require_once 'Zend/Db/Table/Rowset/Exception.php';
throw new Zend_Db_Table_Rowset_Exception('No row could be found at position ' . (int) $position, 0, $e);
}
if ($seek == true) {
$this->seek($position);
}
return $row;
}
/**
* Returns all data as an array.
*
* Updates the $_data property with current row object values.
*
* @return array
*/
public function toArray()
{
// @todo This works only if we have iterated through
// the result set once to instantiate the rows.
foreach ($this->_rows as $i => $row) {
$this->_data[$i] = $row->toArray();
}
return $this->_data;
}
protected function _loadAndReturnRow($position)
{
if (!isset($this->_data[$position])) {
// require_once 'Zend/Db/Table/Rowset/Exception.php';
throw new Zend_Db_Table_Rowset_Exception("Data for provided position does not exist");
}
// do we already have a row object for this position?
if (empty($this->_rows[$position])) {
$this->_rows[$position] = new $this->_rowClass(
array(
'table' => $this->_table,
'data' => $this->_data[$position],
'stored' => $this->_stored,
'readOnly' => $this->_readOnly
)
);
}
// return the row object
return $this->_rows[$position];
}
}

View File

@ -0,0 +1,37 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Table
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Exception.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* Zend_Db_Table_Exception
*/
// require_once 'Zend/Db/Table/Exception.php';
/**
* @category Zend
* @package Zend_Db
* @subpackage Table
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Table_Rowset_Exception extends Zend_Db_Table_Exception
{
}

View File

@ -0,0 +1,224 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Select
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Select.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Db_Select
*/
// require_once 'Zend/Db/Select.php';
/**
* @see Zend_Db_Table_Abstract
*/
// require_once 'Zend/Db/Table/Abstract.php';
/**
* Class for SQL SELECT query manipulation for the Zend_Db_Table component.
*
* @category Zend
* @package Zend_Db
* @subpackage Table
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Table_Select extends Zend_Db_Select
{
/**
* Table schema for parent Zend_Db_Table.
*
* @var array
*/
protected $_info;
/**
* Table integrity override.
*
* @var array
*/
protected $_integrityCheck = true;
/**
* Table instance that created this select object
*
* @var Zend_Db_Table_Abstract
*/
protected $_table;
/**
* Class constructor
*
* @param Zend_Db_Table_Abstract $adapter
*/
public function __construct(Zend_Db_Table_Abstract $table)
{
parent::__construct($table->getAdapter());
$this->setTable($table);
}
/**
* Return the table that created this select object
*
* @return Zend_Db_Table_Abstract
*/
public function getTable()
{
return $this->_table;
}
/**
* Sets the primary table name and retrieves the table schema.
*
* @param Zend_Db_Table_Abstract $adapter
* @return Zend_Db_Select This Zend_Db_Select object.
*/
public function setTable(Zend_Db_Table_Abstract $table)
{
$this->_adapter = $table->getAdapter();
$this->_info = $table->info();
$this->_table = $table;
return $this;
}
/**
* Sets the integrity check flag.
*
* Setting this flag to false skips the checks for table joins, allowing
* 'hybrid' table rows to be created.
*
* @param Zend_Db_Table_Abstract $adapter
* @return Zend_Db_Select This Zend_Db_Select object.
*/
public function setIntegrityCheck($flag = true)
{
$this->_integrityCheck = $flag;
return $this;
}
/**
* Tests query to determine if expressions or aliases columns exist.
*
* @return boolean
*/
public function isReadOnly()
{
$readOnly = false;
$fields = $this->getPart(Zend_Db_Table_Select::COLUMNS);
$cols = $this->_info[Zend_Db_Table_Abstract::COLS];
if (!count($fields)) {
return $readOnly;
}
foreach ($fields as $columnEntry) {
$column = $columnEntry[1];
$alias = $columnEntry[2];
if ($alias !== null) {
$column = $alias;
}
switch (true) {
case ($column == self::SQL_WILDCARD):
break;
case ($column instanceof Zend_Db_Expr):
case (!in_array($column, $cols)):
$readOnly = true;
break 2;
}
}
return $readOnly;
}
/**
* Adds a FROM table and optional columns to the query.
*
* The table name can be expressed
*
* @param array|string|Zend_Db_Expr|Zend_Db_Table_Abstract $name The table name or an
associative array relating
table name to correlation
name.
* @param array|string|Zend_Db_Expr $cols The columns to select from this table.
* @param string $schema The schema name to specify, if any.
* @return Zend_Db_Table_Select This Zend_Db_Table_Select object.
*/
public function from($name, $cols = self::SQL_WILDCARD, $schema = null)
{
if ($name instanceof Zend_Db_Table_Abstract) {
$info = $name->info();
$name = $info[Zend_Db_Table_Abstract::NAME];
if (isset($info[Zend_Db_Table_Abstract::SCHEMA])) {
$schema = $info[Zend_Db_Table_Abstract::SCHEMA];
}
}
return $this->joinInner($name, null, $cols, $schema);
}
/**
* Performs a validation on the select query before passing back to the parent class.
* Ensures that only columns from the primary Zend_Db_Table are returned in the result.
*
* @return string|null This object as a SELECT string (or null if a string cannot be produced)
*/
public function assemble()
{
$fields = $this->getPart(Zend_Db_Table_Select::COLUMNS);
$primary = $this->_info[Zend_Db_Table_Abstract::NAME];
$schema = $this->_info[Zend_Db_Table_Abstract::SCHEMA];
if (count($this->_parts[self::UNION]) == 0) {
// If no fields are specified we assume all fields from primary table
if (!count($fields)) {
$this->from($primary, self::SQL_WILDCARD, $schema);
$fields = $this->getPart(Zend_Db_Table_Select::COLUMNS);
}
$from = $this->getPart(Zend_Db_Table_Select::FROM);
if ($this->_integrityCheck !== false) {
foreach ($fields as $columnEntry) {
list($table, $column) = $columnEntry;
// Check each column to ensure it only references the primary table
if ($column) {
if (!isset($from[$table]) || $from[$table]['tableName'] != $primary) {
// require_once 'Zend/Db/Table/Select/Exception.php';
throw new Zend_Db_Table_Select_Exception('Select query cannot join with another table');
}
}
}
}
}
return parent::assemble();
}
}

View File

@ -0,0 +1,39 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Select
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Exception.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* Zend_Db_Exception
*/
// require_once 'Zend/Db/Select/Exception.php';
/**
* @category Zend
* @package Zend_Db
* @subpackage Table
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Table_Select_Exception extends Zend_Db_Select_Exception
{
}

View File

@ -0,0 +1,96 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Exception.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @category Zend
* @package Zend
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Exception extends Exception
{
/**
* @var null|Exception
*/
private $_previous = null;
/**
* Construct the exception
*
* @param string $msg
* @param int $code
* @param Exception $previous
* @return void
*/
public function __construct($msg = '', $code = 0, Exception $previous = null)
{
if (version_compare(PHP_VERSION, '5.3.0', '<')) {
parent::__construct($msg, (int) $code);
$this->_previous = $previous;
} else {
parent::__construct($msg, (int) $code, $previous);
}
}
/**
* Overloading
*
* For PHP < 5.3.0, provides access to the getPrevious() method.
*
* @param string $method
* @param array $args
* @return mixed
*/
public function __call($method, array $args)
{
if ('getprevious' == strtolower($method)) {
return $this->_getPrevious();
}
return null;
}
/**
* String representation of the exception
*
* @return string
*/
public function __toString()
{
if (version_compare(PHP_VERSION, '5.3.0', '<')) {
if (null !== ($e = $this->getPrevious())) {
return $e->__toString()
. "\n\nNext "
. parent::__toString();
}
}
return parent::__toString();
}
/**
* Returns previous Exception
*
* @return Exception|null
*/
protected function _getPrevious()
{
return $this->_previous;
}
}

View File

@ -0,0 +1,27 @@
Copyright (c) 2005-2010, Zend Technologies USA, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Zend Technologies USA, Inc. nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,37 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Mail
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Exception.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* @see Zend_Exception
*/
// require_once 'Zend/Exception.php';
/**
* @category Zend
* @package Zend_Mail
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Mail_Exception extends Zend_Exception
{}

View File

@ -0,0 +1,112 @@
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Mail
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Message.php 24163 2011-06-29 15:24:10Z adamlundrigan $
*/
/**
* Zend_Mail_Part
*/
// require_once 'Zend/Mail/Part.php';
/**
* Zend_Mail_Message_Interface
*/
// require_once 'Zend/Mail/Message/Interface.php';
/**
* @category Zend
* @package Zend_Mail
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Mail_Message extends Zend_Mail_Part implements Zend_Mail_Message_Interface
{
/**
* flags for this message
* @var array
*/
protected $_flags = array();
/**
* Public constructor
*
* In addition to the parameters of Zend_Mail_Part::__construct() this constructor supports:
* - file filename or file handle of a file with raw message content
* - flags array with flags for message, keys are ignored, use constants defined in Zend_Mail_Storage
*
* @param string $rawMessage full message with or without headers
* @throws Zend_Mail_Exception
*/
public function __construct(array $params)
{
if (isset($params['file'])) {
if (!is_resource($params['file'])) {
$params['raw'] = @file_get_contents($params['file']);
if ($params['raw'] === false) {
/**
* @see Zend_Mail_Exception
*/
// require_once 'Zend/Mail/Exception.php';
throw new Zend_Mail_Exception('could not open file');
}
} else {
$params['raw'] = stream_get_contents($params['file']);
}
}
if (!empty($params['flags'])) {
// set key and value to the same value for easy lookup
$this->_flags = array_merge($this->_flags, array_combine($params['flags'],$params['flags']));
}
parent::__construct($params);
}
/**
* return toplines as found after headers
*
* @return string toplines
*/
public function getTopLines()
{
return $this->_topLines;
}
/**
* check if flag is set
*
* @param mixed $flag a flag name, use constants defined in Zend_Mail_Storage
* @return bool true if set, otherwise false
*/
public function hasFlag($flag)
{
return isset($this->_flags[$flag]);
}
/**
* get all set flags
*
* @return array array with flags, key and value are the same for easy lookup
*/
public function getFlags()
{
return $this->_flags;
}
}

Some files were not shown because too many files have changed in this diff Show More