- Fixed usage of DbSimple.

- Fixed map view template.

Signed-off-by: TheLuda <theluda@getmangos.com>
This commit is contained in:
TheLuda 2012-09-19 17:07:02 +02:00
parent 947f95fb20
commit 4639f81ae4
4 changed files with 133 additions and 130 deletions

View File

@ -11,7 +11,7 @@
* *
* Use static DbSimple_Generic::connect($dsn) call if you don't know * Use static DbSimple_Generic::connect($dsn) call if you don't know
* database type and parameters, but have its DSN. * database type and parameters, but have its DSN.
* *
* Additional keys can be added by appending a URI query string to the * Additional keys can be added by appending a URI query string to the
* end of the DSN. * end of the DSN.
* *
@ -30,13 +30,13 @@
* *
* Parsing code is partially grabbed from PEAR DB class, * Parsing code is partially grabbed from PEAR DB class,
* initial author: Tomas V.V.Cox <cox@idecnet.com>. * initial author: Tomas V.V.Cox <cox@idecnet.com>.
* *
* Contains 3 classes: * Contains 3 classes:
* - DbSimple_Generic: database factory class * - DbSimple_Generic: database factory class
* - DbSimple_Generic_Database: common database methods * - DbSimple_Generic_Database: common database methods
* - DbSimple_Generic_Blob: common BLOB support * - DbSimple_Generic_Blob: common BLOB support
* - DbSimple_Generic_LastError: error reporting and tracking * - DbSimple_Generic_LastError: error reporting and tracking
* *
* Special result-set fields: * Special result-set fields:
* - ARRAY_KEY* ("*" means "anything") * - ARRAY_KEY* ("*" means "anything")
* - PARENT_KEY * - PARENT_KEY
@ -46,14 +46,14 @@
* - CALC_TOTAL * - CALC_TOTAL
* - GET_TOTAL * - GET_TOTAL
* - UNIQ_KEY * - UNIQ_KEY
* *
* Query attributes: * Query attributes:
* - BLOB_OBJ * - BLOB_OBJ
* - CACHE * - CACHE
* *
* @author Dmitry Koterov, http://forum.dklab.ru/users/DmitryKoterov/ * @author Dmitry Koterov, http://forum.dklab.ru/users/DmitryKoterov/
* @author Konstantin Zhinko, http://forum.dklab.ru/users/KonstantinGinkoTit/ * @author Konstantin Zhinko, http://forum.dklab.ru/users/KonstantinGinkoTit/
* *
* @version 2.x $Id$ * @version 2.x $Id$
*/ */
@ -64,7 +64,7 @@ define('DBSIMPLE_SKIP', log(0));
/** /**
* Names of special columns in result-set which is used * Names of special columns in result-set which is used
* as array key (or karent key in forest-based resultsets) in * as array key (or karent key in forest-based resultsets) in
* resulting hash. * resulting hash.
*/ */
define('DBSIMPLE_ARRAY_KEY', 'ARRAY_KEY'); // hash-based resultset support define('DBSIMPLE_ARRAY_KEY', 'ARRAY_KEY'); // hash-based resultset support
@ -78,7 +78,7 @@ class DbSimple_Generic
{ {
/** /**
* DbSimple_Generic connect(mixed $dsn) * DbSimple_Generic connect(mixed $dsn)
* *
* Universal static function to connect ANY database using DSN syntax. * Universal static function to connect ANY database using DSN syntax.
* Choose database driver according to DSN. Return new instance * Choose database driver according to DSN. Return new instance
* of this driver. * of this driver.
@ -86,7 +86,7 @@ class DbSimple_Generic
function& connect($dsn) function& connect($dsn)
{ {
// Load database driver and create its instance. // Load database driver and create its instance.
$parsed = DbSimple_Generic::parseDSN($dsn); $parsed = $this->parseDSN($dsn);
if (!$parsed) { if (!$parsed) {
$dummy = null; $dummy = null;
return $dummy; return $dummy;
@ -110,7 +110,7 @@ class DbSimple_Generic
} }
} }
} }
$object =& new $class($parsed); $object =new $class($parsed);
if (isset($parsed['ident_prefix'])) { if (isset($parsed['ident_prefix'])) {
$object->setIdentPrefix($parsed['ident_prefix']); $object->setIdentPrefix($parsed['ident_prefix']);
} }
@ -128,9 +128,9 @@ class DbSimple_Generic
$fp = @fopen($testFile = $dir . '/DbSimple_' . md5(getmypid() . microtime()), 'w'); $fp = @fopen($testFile = $dir . '/DbSimple_' . md5(getmypid() . microtime()), 'w');
if ($fp) { if ($fp) {
fclose($fp); fclose($fp);
unlink($testFile); unlink($testFile);
require_once 'Cache' . '/Lite.php'; // "." -> no phpEclipse notice require_once 'Cache' . '/Lite.php'; // "." -> no phpEclipse notice
$t =& new Cache_Lite(array('cacheDir' => $dir.'/', 'lifeTime' => null, 'automaticSerialization' => true)); $t =new Cache_Lite(array('cacheDir' => $dir.'/', 'lifeTime' => null, 'automaticSerialization' => true));
$object->_cacher =& $t; $object->_cacher =& $t;
break; break;
} }
@ -139,12 +139,12 @@ class DbSimple_Generic
} }
return $object; return $object;
} }
/** /**
* array parseDSN(mixed $dsn) * array parseDSN(mixed $dsn)
* Parse a data source name. * Parse a data source name.
* See parse_url() for details. * See parse_url() for details.
*/ */
function parseDSN($dsn) function parseDSN($dsn)
{ {
@ -158,14 +158,14 @@ class DbSimple_Generic
} }
$parsed['dsn'] = $dsn; $parsed['dsn'] = $dsn;
return $parsed; return $parsed;
} }
} }
/** /**
* Base class for all databases. * Base class for all databases.
* Can create transactions and new BLOBs, parse DSNs. * Can create transactions and new BLOBs, parse DSNs.
* *
* Logger is COMMON for multiple transactions. * Logger is COMMON for multiple transactions.
* Error handler is private for each transaction and database. * Error handler is private for each transaction and database.
*/ */
@ -184,7 +184,7 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
$this->_resetLastError(); $this->_resetLastError();
return $this->_performNewBlob($blob_id); return $this->_performNewBlob($blob_id);
} }
/** /**
* void transaction($mode) * void transaction($mode)
* Create new transaction. * Create new transaction.
@ -228,7 +228,7 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
$total = false; $total = false;
return $this->_query($args, $total); return $this->_query($args, $total);
} }
/** /**
* mixed selectPage(int &$total, string $query [, $arg1] [,$arg2] ...) * mixed selectPage(int &$total, string $query [, $arg1] [,$arg2] ...)
* Execute query and return the result. * Execute query and return the result.
@ -305,18 +305,18 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
$total = false; $total = false;
return $this->_query($args, $total); return $this->_query($args, $total);
} }
/** /**
* string escape(mixed $s, bool $isIdent=false) * string escape(mixed $s, bool $isIdent=false)
* Enclose the string into database quotes correctly escaping * Enclose the string into database quotes correctly escaping
* special characters. If $isIdent is true, value quoted as identifier * special characters. If $isIdent is true, value quoted as identifier
* (e.g.: `value` in MySQL, "value" in Firebird, [value] in MSSQL). * (e.g.: `value` in MySQL, "value" in Firebird, [value] in MSSQL).
*/ */
function escape($s, $isIdent=false) function escape($s, $isIdent=false)
{ {
return $this->_performEscape($s, $isIdent); return $this->_performEscape($s, $isIdent);
} }
/** /**
* callback setLogger(callback $logger) * callback setLogger(callback $logger)
@ -329,7 +329,7 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
$this->_logger = $logger; $this->_logger = $logger;
return $prev; return $prev;
} }
/** /**
* callback setCacher(callback $cacher) * callback setCacher(callback $cacher)
* Set cache mechanism called during each query if specified. * Set cache mechanism called during each query if specified.
@ -341,7 +341,7 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
$this->_cacher = $cacher; $this->_cacher = $cacher;
return $prev; return $prev;
} }
/** /**
* string setIdentPrefix($prx) * string setIdentPrefix($prx)
* Set identifier prefix used for $_ placeholder. * Set identifier prefix used for $_ placeholder.
@ -363,7 +363,7 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
if ($prx !== null) $this->_cachePrefix = $prx; if ($prx !== null) $this->_cachePrefix = $prx;
return $old; return $old;
} }
/** /**
* array getStatistics() * array getStatistics()
* Returns various statistical information. * Returns various statistical information.
@ -390,7 +390,7 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
/** /**
* object _performNewBlob($id) * object _performNewBlob($id)
* *
* Returns new blob object. * Returns new blob object.
*/ */
function& _performNewBlob($id) function& _performNewBlob($id)
@ -406,10 +406,10 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
{ {
die("Method must be defined in derived class. Abstract function called at ".__FILE__." line ".__LINE__); die("Method must be defined in derived class. Abstract function called at ".__FILE__." line ".__LINE__);
} }
/** /**
* mixed _performTransformQuery(array &$query, string $how) * mixed _performTransformQuery(array &$query, string $how)
* *
* Transform query different way specified by $how. * Transform query different way specified by $how.
* May return some information about performed transform. * May return some information about performed transform.
*/ */
@ -417,8 +417,8 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
{ {
die("Method must be defined in derived class. Abstract function called at ".__FILE__." line ".__LINE__); die("Method must be defined in derived class. Abstract function called at ".__FILE__." line ".__LINE__);
} }
/** /**
* resource _performQuery($arrayQuery) * resource _performQuery($arrayQuery)
* Must return: * Must return:
@ -430,7 +430,7 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
{ {
die("Method must be defined in derived class. Abstract function called at ".__FILE__." line ".__LINE__); die("Method must be defined in derived class. Abstract function called at ".__FILE__." line ".__LINE__);
} }
/** /**
* mixed _performFetch($resultResource) * mixed _performFetch($resultResource)
* Fetch ONE NEXT row from result-set. * Fetch ONE NEXT row from result-set.
@ -462,7 +462,7 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
{ {
die("Method must be defined in derived class. Abstract function called at ".__FILE__." line ".__LINE__); die("Method must be defined in derived class. Abstract function called at ".__FILE__." line ".__LINE__);
} }
/** /**
* mixed _performCommit() * mixed _performCommit()
* Commit the transaction. * Commit the transaction.
@ -480,7 +480,7 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
{ {
die("Method must be defined in derived class. Abstract function called at ".__FILE__." line ".__LINE__); die("Method must be defined in derived class. Abstract function called at ".__FILE__." line ".__LINE__);
} }
/** /**
* string _performGetPlaceholderIgnoreRe() * string _performGetPlaceholderIgnoreRe()
* Return regular expression which matches ignored query parts. * Return regular expression which matches ignored query parts.
@ -489,25 +489,25 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
function _performGetPlaceholderIgnoreRe() function _performGetPlaceholderIgnoreRe()
{ {
return ''; return '';
} }
/** /**
* Returns marker for native database placeholder. E.g. in FireBird it is '?', * Returns marker for native database placeholder. E.g. in FireBird it is '?',
* in PostgreSQL - '$1', '$2' etc. * in PostgreSQL - '$1', '$2' etc.
* *
* @param int $n Number of native placeholder from the beginning of the query (begins from 0!). * @param int $n Number of native placeholder from the beginning of the query (begins from 0!).
* @return string String representation of native placeholder marker (by default - '?'). * @return string String representation of native placeholder marker (by default - '?').
*/ */
function _performGetNativePlaceholderMarker($n) function _performGetNativePlaceholderMarker($n)
{ {
return '?'; return '?';
} }
/** /**
* Private methods. * Private methods.
*/ */
function ____________PRIVATE() {} // for phpEclipse outline function ____________PRIVATE() {} // for phpEclipse outline
/** /**
@ -517,7 +517,7 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
function _query($query, &$total) function _query($query, &$total)
{ {
$this->_resetLastError(); $this->_resetLastError();
// Fetch query attributes. // Fetch query attributes.
$this->attributes = $this->_transformQuery($query, 'GET_ATTRIBUTES'); $this->attributes = $this->_transformQuery($query, 'GET_ATTRIBUTES');
@ -539,8 +539,8 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
$storeTime = isset($cacheData['storeTime']) ? $cacheData['storeTime'] : null; $storeTime = isset($cacheData['storeTime']) ? $cacheData['storeTime'] : null;
$invalCache = isset($cacheData['invalCache']) ? $cacheData['invalCache'] : null; $invalCache = isset($cacheData['invalCache']) ? $cacheData['invalCache'] : null;
$result = isset($cacheData['result']) ? $cacheData['result'] : null; $result = isset($cacheData['result']) ? $cacheData['result'] : null;
$rows = isset($cacheData['rows']) ? $cacheData['rows'] : null; $rows = isset($cacheData['rows']) ? $cacheData['rows'] : null;
$cache_params = $this->attributes['CACHE']; $cache_params = $this->attributes['CACHE'];
@ -549,10 +549,10 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
$re = '/ $re = '/
( (
([0-9]+) #2 - hours ([0-9]+) #2 - hours
h)? [ \t]* h)? [ \t]*
( (
([0-9]+) #4 - minutes ([0-9]+) #4 - minutes
m)? [ \t]* m)? [ \t]*
( (
([0-9]+) #6 - seconds ([0-9]+) #6 - seconds
s?)? (,)? s?)? (,)?
@ -560,7 +560,7 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
$m = null; $m = null;
preg_match($re, $cache_params, $m); preg_match($re, $cache_params, $m);
$ttl = @$m[6] + @$m[4] * 60 + @$m[2] * 3600; $ttl = @$m[6] + @$m[4] * 60 + @$m[2] * 3600;
// Cutting out time param - now there are just fields for uniqKey or nothing // Cutting out time param - now there are just fields for uniqKey or nothing
$cache_params = trim(preg_replace($re, '', $cache_params, 1)); $cache_params = trim(preg_replace($re, '', $cache_params, 1));
$uniq_key = null; $uniq_key = null;
@ -583,13 +583,13 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
} }
else $cache_it = true; else $cache_it = true;
} }
if (null === $rows || true === $cache_it) { if (null === $rows || true === $cache_it) {
$this->_logQuery($query); $this->_logQuery($query);
// Run the query (counting time). // Run the query (counting time).
$qStart = $this->_microtime(); $qStart = $this->_microtime();
$result = $this->_performQuery($query); $result = $this->_performQuery($query);
$fetchTime = $firstFetchTime = 0; $fetchTime = $firstFetchTime = 0;
@ -613,7 +613,7 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
// Log query statistics. // Log query statistics.
$this->_logQueryStat($queryTime, $fetchTime, $firstFetchTime, $rows); $this->_logQueryStat($queryTime, $fetchTime, $firstFetchTime, $rows);
// Prepare BLOB objects if needed. // Prepare BLOB objects if needed.
if (is_array($rows) && !empty($this->attributes['BLOB_OBJ'])) { if (is_array($rows) && !empty($this->attributes['BLOB_OBJ'])) {
$blobFieldNames = $this->_performGetBlobFieldNames($result); $blobFieldNames = $this->_performGetBlobFieldNames($result);
@ -623,7 +623,7 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
} }
} }
} }
// Transform resulting rows. // Transform resulting rows.
$result = $this->_transformResult($rows); $result = $this->_transformResult($rows);
@ -649,11 +649,11 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
return $result; return $result;
} }
/** /**
* mixed _transformQuery(array &$query, string $how) * mixed _transformQuery(array &$query, string $how)
* *
* Transform query different way specified by $how. * Transform query different way specified by $how.
* May return some information about performed transform. * May return some information about performed transform.
*/ */
@ -689,8 +689,8 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
// No such transform. // No such transform.
$this->_setLastError(-1, "No such transform type: $how", $query); $this->_setLastError(-1, "No such transform type: $how", $query);
} }
/** /**
* void _expandPlaceholders(array &$queryAndArgs, bool $useNative=false) * void _expandPlaceholders(array &$queryAndArgs, bool $useNative=false)
* Replace placeholders by quoted values. * Replace placeholders by quoted values.
@ -707,7 +707,7 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
return; return;
} }
} }
if (!is_array($queryAndArgs)) { if (!is_array($queryAndArgs)) {
$queryAndArgs = array($queryAndArgs); $queryAndArgs = array($queryAndArgs);
} }
@ -727,13 +727,13 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
} else { } else {
$queryAndArgs = array($query); $queryAndArgs = array($query);
} }
if ($cacheCode) { if ($cacheCode) {
$this->_placeholderCache[$cacheCode] = $queryAndArgs; $this->_placeholderCache[$cacheCode] = $queryAndArgs;
} }
} }
/** /**
* Do real placeholder processing. * Do real placeholder processing.
* Imply that all interval variables (_placeholder_*) already prepared. * Imply that all interval variables (_placeholder_*) already prepared.
@ -745,17 +745,17 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
(?> (?>
# Ignored chunks. # Ignored chunks.
(?> (?>
# Comment. # Comment.
-- [^\r\n]* -- [^\r\n]*
) )
| |
(?> (?>
# DB-specifics. # DB-specifics.
' . trim($this->_performGetPlaceholderIgnoreRe()) . ' ' . trim($this->_performGetPlaceholderIgnoreRe()) . '
) )
) )
| |
(?> (?>
# Optional blocks # Optional blocks
\{ \{
# Use "+" here, not "*"! Else nested blocks are not processed well. # Use "+" here, not "*"! Else nested blocks are not processed well.
@ -770,12 +770,12 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
}sx'; }sx';
$query = preg_replace_callback( $query = preg_replace_callback(
$re, $re,
array(&$this, '_expandPlaceholdersCallback'), array(&$this, '_expandPlaceholdersCallback'),
$query $query
); );
return $query; return $query;
} }
/** /**
* string _expandPlaceholdersCallback(list $m) * string _expandPlaceholdersCallback(list $m)
@ -786,12 +786,12 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
// Placeholder. // Placeholder.
if (!empty($m[2])) { if (!empty($m[2])) {
$type = $m[3]; $type = $m[3];
// Idenifier prefix. // Idenifier prefix.
if ($type == '_') { if ($type == '_') {
return $this->_identPrefix; return $this->_identPrefix;
} }
// Value-based placeholder. // Value-based placeholder.
if (!$this->_placeholderArgs) return 'DBSIMPLE_ERROR_NO_VALUE'; if (!$this->_placeholderArgs) return 'DBSIMPLE_ERROR_NO_VALUE';
$value = array_pop($this->_placeholderArgs); $value = array_pop($this->_placeholderArgs);
@ -801,7 +801,7 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
$this->_placeholderNoValueFound = true; $this->_placeholderNoValueFound = true;
return ''; return '';
} }
// First process guaranteed non-native placeholders. // First process guaranteed non-native placeholders.
switch ($type) { switch ($type) {
case 'a': case 'a':
@ -836,15 +836,15 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
if ($this->_placeholderNativeArgs !== null) { if ($this->_placeholderNativeArgs !== null) {
$this->_placeholderNativeArgs[] = $value; $this->_placeholderNativeArgs[] = $value;
return $this->_performGetNativePlaceholderMarker(count($this->_placeholderNativeArgs) - 1); return $this->_performGetNativePlaceholderMarker(count($this->_placeholderNativeArgs) - 1);
} }
// In non-native mode arguments are quoted. // In non-native mode arguments are quoted.
if ($value === null) return 'NULL'; if ($value === null) return 'NULL';
switch ($type) { switch ($type) {
case '': case '':
if (!is_scalar($value)) return 'DBSIMPLE_ERROR_VALUE_NOT_SCALAR'; if (!is_scalar($value)) return 'DBSIMPLE_ERROR_VALUE_NOT_SCALAR';
return $this->escape($value); return $this->escape($value);
case 'd': case 'd':
return intval($value); return intval($value);
case 'f': case 'f':
return str_replace(',', '.', floatval($value)); return str_replace(',', '.', floatval($value));
@ -852,21 +852,21 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
// By default - escape as string. // By default - escape as string.
return $this->escape($value); return $this->escape($value);
} }
// Optional block. // Optional block.
if (isset($m[1]) && strlen($block=$m[1])) { if (isset($m[1]) && strlen($block=$m[1])) {
$prev = @$this->_placeholderNoValueFound; $prev = @$this->_placeholderNoValueFound;
$block = $this->_expandPlaceholdersFlow($block); $block = $this->_expandPlaceholdersFlow($block);
$block = $this->_placeholderNoValueFound? '' : ' ' . $block . ' '; $block = $this->_placeholderNoValueFound? '' : ' ' . $block . ' ';
$this->_placeholderNoValueFound = $prev; // recurrent-safe $this->_placeholderNoValueFound = $prev; // recurrent-safe
return $block; return $block;
} }
// Default: skipped part of the string. // Default: skipped part of the string.
return $m[0]; return $m[0];
} }
/** /**
* void _setLastError($code, $msg, $query) * void _setLastError($code, $msg, $query)
* Set last database error context. * Set last database error context.
@ -880,8 +880,8 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
} }
return DbSimple_Generic_LastError::_setLastError($code, $msg, $query); return DbSimple_Generic_LastError::_setLastError($code, $msg, $query);
} }
/** /**
* Return microtime as float value. * Return microtime as float value.
*/ */
@ -890,8 +890,8 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
$t = explode(" ", microtime()); $t = explode(" ", microtime());
return $t[0] + $t[1]; return $t[0] + $t[1];
} }
/** /**
* Convert SQL field-list to COUNT(...) clause * Convert SQL field-list to COUNT(...) clause
* (e.g. 'DISTINCT a AS aa, b AS bb' -> 'COUNT(DISTINCT a, b)'). * (e.g. 'DISTINCT a AS aa, b AS bb' -> 'COUNT(DISTINCT a, b)').
@ -928,7 +928,7 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
} }
} }
natsort($ak); // sort ARRAY_KEY* using natural comparision natsort($ak); // sort ARRAY_KEY* using natural comparision
if ($ak) { if ($ak) {
// Tree-based array? Fields: ARRAY_KEY, PARENT_KEY // Tree-based array? Fields: ARRAY_KEY, PARENT_KEY
if ($pk !== null) { if ($pk !== null) {
@ -944,7 +944,7 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
/** /**
* Converts rowset to key-based array. * Converts rowset to key-based array.
* *
* @param array $rows Two-dimensional array of resulting rows. * @param array $rows Two-dimensional array of resulting rows.
* @param array $ak List of ARRAY_KEY* field names. * @param array $ak List of ARRAY_KEY* field names.
* @return array Transformed array. * @return array Transformed array.
@ -977,7 +977,7 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
/** /**
* Converts rowset to the forest. * Converts rowset to the forest.
* *
* @param array $rows Two-dimensional array of resulting rows. * @param array $rows Two-dimensional array of resulting rows.
* @param string $idName Name of ID field. * @param string $idName Name of ID field.
* @param string $pidName Name of PARENT_ID field. * @param string $pidName Name of PARENT_ID field.
@ -992,8 +992,8 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
$row =& $rows[$i]; $row =& $rows[$i];
$id = $row[$idName]; $id = $row[$idName];
if ($id === null) { if ($id === null) {
// Rows without an ID are totally invalid and makes the result tree to // Rows without an ID are totally invalid and makes the result tree to
// be empty (because PARENT_ID = null means "a root of the tree"). So // be empty (because PARENT_ID = null means "a root of the tree"). So
// skip them totally. // skip them totally.
continue; continue;
} }
@ -1014,7 +1014,7 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
if (!isset($ids[$pid])) { if (!isset($ids[$pid])) {
$forest[$row[$idName]] =& $row; $forest[$row[$idName]] =& $row;
} }
unset($row[$idName]); unset($row[$idName]);
unset($row[$pidName]); unset($row[$pidName]);
} }
return $forest; return $forest;
@ -1036,7 +1036,7 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
array_walk($v, array(&$this, '_shrinkLastArrayDimensionCallback')); array_walk($v, array(&$this, '_shrinkLastArrayDimensionCallback'));
} }
} }
/** /**
* void _logQuery($query, $noTrace=false) * void _logQuery($query, $noTrace=false)
@ -1053,8 +1053,8 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
$args[] = $noTrace? null : $this->findLibraryCaller(); $args[] = $noTrace? null : $this->findLibraryCaller();
return call_user_func_array($this->_logger, $args); return call_user_func_array($this->_logger, $args);
} }
/** /**
* void _logQueryStat($queryTime, $fetchTime, $firstFetchTime, $rows) * void _logQueryStat($queryTime, $fetchTime, $firstFetchTime, $rows)
* Log information about performed query statistics. * Log information about performed query statistics.
@ -1064,10 +1064,10 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
// Always increment counters. // Always increment counters.
$this->_statistics['time'] += $queryTime; $this->_statistics['time'] += $queryTime;
$this->_statistics['count']++; $this->_statistics['count']++;
// If no logger, economize CPU resources and actually log nothing. // If no logger, economize CPU resources and actually log nothing.
if (!$this->_logger) return; if (!$this->_logger) return;
$dt = round($queryTime * 1000); $dt = round($queryTime * 1000);
$firstFetchTime = round($firstFetchTime*1000); $firstFetchTime = round($firstFetchTime*1000);
$tailFetchTime = round($fetchTime * 1000) - $firstFetchTime; $tailFetchTime = round($fetchTime * 1000) - $firstFetchTime;
@ -1080,7 +1080,7 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
$log .= "; returned "; $log .= "; returned ";
if (!is_array($rows)) { if (!is_array($rows)) {
$log .= $this->escape($rows); $log .= $this->escape($rows);
} else { } else {
$detailed = null; $detailed = null;
if (count($rows) == 1) { if (count($rows) == 1) {
@ -1103,10 +1103,10 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
$log .= count($rows). " row(s)"; $log .= count($rows). " row(s)";
} }
} }
$this->_logQuery($log, true); $this->_logQuery($log, true);
} }
/** /**
* mixed _cache($hash, $result=null) * mixed _cache($hash, $result=null)
* Calls cache mechanism if possible. * Calls cache mechanism if possible.
@ -1123,18 +1123,18 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
} }
else return false; else return false;
} }
/** /**
* protected constructor(string $dsn) * protected constructor(string $dsn)
* *
* Prevent from direct creation of this object. * Prevent from direct creation of this object.
*/ */
function DbSimple_Generic_Database() function DbSimple_Generic_Database()
{ {
die("This is protected constructor! Do not instantiate directly at ".__FILE__." line ".__LINE__); die("This is protected constructor! Do not instantiate directly at ".__FILE__." line ".__LINE__);
} }
// Identifiers prefix (used for ?_ placeholder). // Identifiers prefix (used for ?_ placeholder).
var $_identPrefix = ''; var $_identPrefix = '';
@ -1143,14 +1143,14 @@ class DbSimple_Generic_Database extends DbSimple_Generic_LastError
'time' => 0, 'time' => 0,
'count' => 0, 'count' => 0,
); );
var $_cachePrefix = ''; var $_cachePrefix = '';
var $_logger = null; var $_logger = null;
var $_cacher = null; var $_cacher = null;
var $_placeholderArgs, $_placeholderNativeArgs, $_placeholderCache=array(); var $_placeholderArgs, $_placeholderNativeArgs, $_placeholderCache=array();
var $_placeholderNoValueFound; var $_placeholderNoValueFound;
/** /**
* When string representation of row (in characters) is greater than this, * When string representation of row (in characters) is greater than this,
* row data will not be logged. * row data will not be logged.
@ -1283,13 +1283,13 @@ class DbSimple_Generic_LastError
/** /**
* void addIgnoreInTrace($reName) * void addIgnoreInTrace($reName)
* Add regular expression matching ClassName::functionName or functionName. * Add regular expression matching ClassName::functionName or functionName.
* Matched stack frames will be ignored in stack traces passed to query logger. * Matched stack frames will be ignored in stack traces passed to query logger.
*/ */
function addIgnoreInTrace($name) function addIgnoreInTrace($name)
{ {
$this->ignoresInTraceRe .= "|" . $name; $this->ignoresInTraceRe .= "|" . $name;
} }
/** /**
* array of array findLibraryCaller() * array of array findLibraryCaller()
* Return part of stacktrace before calling first library method. * Return part of stacktrace before calling first library method.
@ -1304,39 +1304,39 @@ class DbSimple_Generic_LastError
); );
return $caller; return $caller;
} }
/** /**
* array debug_backtrace_smart($ignoresRe=null, $returnCaller=false) * array debug_backtrace_smart($ignoresRe=null, $returnCaller=false)
* *
* Return stacktrace. Correctly work with call_user_func* * Return stacktrace. Correctly work with call_user_func*
* (totally skip them correcting caller references). * (totally skip them correcting caller references).
* If $returnCaller is true, return only first matched caller, * If $returnCaller is true, return only first matched caller,
* not all stacktrace. * not all stacktrace.
* *
* @version 2.03 * @version 2.03
*/ */
function debug_backtrace_smart($ignoresRe=null, $returnCaller=false) function debug_backtrace_smart($ignoresRe=null, $returnCaller=false)
{ {
if (!is_callable($tracer='debug_backtrace')) return array(); if (!is_callable($tracer='debug_backtrace')) return array();
$trace = $tracer(); $trace = $tracer();
if ($ignoresRe !== null) $ignoresRe = "/^(?>{$ignoresRe})$/six"; if ($ignoresRe !== null) $ignoresRe = "/^(?>{$ignoresRe})$/six";
$smart = array(); $smart = array();
$framesSeen = 0; $framesSeen = 0;
for ($i=0, $n=count($trace); $i<$n; $i++) { for ($i=0, $n=count($trace); $i<$n; $i++) {
$t = $trace[$i]; $t = $trace[$i];
if (!$t) continue; if (!$t) continue;
// Next frame. // Next frame.
$next = isset($trace[$i+1])? $trace[$i+1] : null; $next = isset($trace[$i+1])? $trace[$i+1] : null;
// Dummy frame before call_user_func* frames. // Dummy frame before call_user_func* frames.
if (!isset($t['file'])) { if (!isset($t['file'])) {
$t['over_function'] = $trace[$i+1]['function']; $t['over_function'] = $trace[$i+1]['function'];
$t = $t + $trace[$i+1]; $t = $t + $trace[$i+1];
$trace[$i+1] = null; // skip call_user_func on next iteration $trace[$i+1] = null; // skip call_user_func on next iteration
} }
// Skip myself frame. // Skip myself frame.
if (++$framesSeen < 2) continue; if (++$framesSeen < 2) continue;
@ -1348,7 +1348,7 @@ class DbSimple_Generic_LastError
$frameCaller = (isset($next['class'])? $next['class'].'::' : '') . (isset($next['function'])? $next['function'] : ''); $frameCaller = (isset($next['class'])? $next['class'].'::' : '') . (isset($next['function'])? $next['function'] : '');
if (preg_match($ignoresRe, $frameCaller)) continue; if (preg_match($ignoresRe, $frameCaller)) continue;
} }
// On each iteration we consider ability to add PREVIOUS frame // On each iteration we consider ability to add PREVIOUS frame
// to $smart stack. // to $smart stack.
if ($returnCaller) return $t; if ($returnCaller) return $t;
@ -1356,6 +1356,6 @@ class DbSimple_Generic_LastError
} }
return $smart; return $smart;
} }
} }
?> ?>

View File

@ -32,7 +32,8 @@ class DbSimple_Mysql extends DbSimple_Generic_Database
*/ */
function DbSimple_Mysql($dsn) function DbSimple_Mysql($dsn)
{ {
$p = DbSimple_Generic::parseDSN($dsn); $DbSimple = new DbSimple_Generic();
$p = $DbSimple->parseDSN($dsn);
if (!is_callable('mysql_connect')) { if (!is_callable('mysql_connect')) {
return $this->_setLastError("-1", "MySQL extension is not loaded", "mysql_connect"); return $this->_setLastError("-1", "MySQL extension is not loaded", "mysql_connect");
} }
@ -70,7 +71,7 @@ class DbSimple_Mysql extends DbSimple_Generic_Database
function& _performNewBlob($blobid=null) function& _performNewBlob($blobid=null)
{ {
$obj =& new DbSimple_Mysql_Blob($this, $blobid); $obj =new DbSimple_Mysql_Blob($this, $blobid);
return $obj; return $obj;
} }
@ -231,4 +232,4 @@ class DbSimple_Mysql_Blob extends DbSimple_Generic_Blob
return strlen($this->blobdata); return strlen($this->blobdata);
} }
} }
?> ?>

View File

@ -18,15 +18,16 @@ require_once 'includes/DbSimple/Generic.php';
// Configuration array // Configuration array
global $UDWBaseconf; global $UDWBaseconf;
// Connect to world DB // Connect to world DB
$DB = DbSimple_Generic::connect("mysql://" . $UDWBaseconf['world']['user'] . ":" . $UDWBaseconf['world']['pass'] . "@" . $UDWBaseconf['world']['host'] . "/" . $UDWBaseconf['world']['db']); $DBSimple = new DbSimple_Generic();
$DB = $DBSimple->connect("mysql://" . $UDWBaseconf['world']['user'] . ":" . $UDWBaseconf['world']['pass'] . "@" . $UDWBaseconf['world']['host'] . "/" . $UDWBaseconf['world']['db']);
$DB->setErrorHandler('databaseErrorHandler'); $DB->setErrorHandler('databaseErrorHandler');
$DB->setIdentPrefix($UDWBaseconf['world']['table_prefix']); $DB->setIdentPrefix($UDWBaseconf['world']['table_prefix']);
$DB->query('SET NAMES ?', 'utf8'); $DB->query('SET NAMES ?', 'utf8');
// Connect to the realm DB // Connect to the realm DB
if ($UDWBaseconf['realmd']) { if ($UDWBaseconf['realmd']) {
$rDB = DbSimple_Generic::connect("mysql://" . $UDWBaseconf['realmd']['user'] . ":" . $UDWBaseconf['realmd']['pass'] . "@" . $UDWBaseconf['realmd']['host'] . "/" . $UDWBaseconf['realmd']['db']); $rDB = $DBSimple->connect("mysql://" . $UDWBaseconf['realmd']['user'] . ":" . $UDWBaseconf['realmd']['pass'] . "@" . $UDWBaseconf['realmd']['host'] . "/" . $UDWBaseconf['realmd']['db']);
$rDB->setErrorHandler('databaseErrorHandler'); $rDB->setErrorHandler('databaseErrorHandler');
$rDB->setIdentPrefix($UDWBaseconf['realmd']['table_prefix']); $rDB->setIdentPrefix($UDWBaseconf['realmd']['table_prefix']);
$rDB->query('SET NAMES ?', 'utf8'); $rDB->query('SET NAMES ?', 'utf8');
@ -34,10 +35,10 @@ if ($UDWBaseconf['realmd']) {
/** /**
* Error handling * Error handling
* *
* @param type $message * @param type $message
* @param type $info * @param type $info
* @return type * @return type
*/ */
function databaseErrorHandler($message, $info) { function databaseErrorHandler($message, $info) {
// If @ has been used, do nothing. // If @ has been used, do nothing.
@ -58,7 +59,7 @@ if ($UDWBaseconf['debug'])
* *
* @global type $smarty * @global type $smarty
* @param type $db * @param type $db
* @param type $sql * @param type $sql
*/ */
function myLogger($db, $sql) { function myLogger($db, $sql) {
global $smarty; global $smarty;
@ -67,16 +68,16 @@ function myLogger($db, $sql) {
/** /**
* PRECACHING * PRECACHING
* *
* Contents of the file: * Contents of the file:
* *
* - cache_delete_timestamp * - cache_delete_timestamp
* - serialized data * - serialized data
* - serialized allitems * - serialized allitems
* - serialized allspells * - serialized allspells
* - serialized exdata * - serialized exdata
* - serialized zonedata * - serialized zonedata
* *
*/ */
$cache_types = array( $cache_types = array(
1 => 'npc_page', 1 => 'npc_page',
@ -112,7 +113,7 @@ $cache_types = array(
* @param type $type_id * @param type $type_id
* @param type $data * @param type $data
* @param type $prefix * @param type $prefix
* @return type * @return type
*/ */
function save_cache($type, $type_id, $data, $prefix = '') { function save_cache($type, $type_id, $data, $prefix = '') {
global $cache_types, $allitems, $allspells, $UDWBaseconf, $exdata, $zonedata; global $cache_types, $allitems, $allspells, $UDWBaseconf, $exdata, $zonedata;
@ -160,7 +161,7 @@ function save_cache($type, $type_id, $data, $prefix = '') {
* @global type $zonedata * @global type $zonedata
* @param type $type * @param type $type
* @param type $type_id * @param type $type_id
* @return type * @return type
*/ */
function load_cache($type, $type_id) { function load_cache($type, $type_id) {
global $cache_types, $smarty, $allitems, $allspells, $exdata, $zonedata; global $cache_types, $smarty, $allitems, $allspells, $exdata, $zonedata;
@ -189,4 +190,4 @@ function load_cache($type, $type_id) {
$smarty->assign('zonedata', unserialize($data[5])); $smarty->assign('zonedata', unserialize($data[5]));
return unserialize($data[1]); return unserialize($data[1]);
} }

View File

@ -60,13 +60,13 @@
<option value="440">Tanaris</option> <option value="440">Tanaris</option>
<option value="141">Teldrassil</option> <option value="141">Teldrassil</option>
<option value="17">The Barrens</option> <option value="17">The Barrens</option>
<option value="3557">The Exodar</option>
<option value="400">Thousand Needles</option> <option value="400">Thousand Needles</option>
<option value="1638">Thunder Bluff</option> <option value="1638">Thunder Bluff</option>
<option value="490">Un'Goro Crater</option> <option value="490">Un'Goro Crater</option>
<option value="618">Winterspring</option> <option value="618">Winterspring</option>
</select>
<div style="padding-bottom: 4px"></div> <div style="padding-bottom: 4px"></div>
<select onchange="mapperChooseZone(this)" class="zone-picker"> <select onchange="mapperChooseZone(this)" class="zone-picker">
<option value="0">Instances</option> <option value="0">Instances</option>
<optgroup label="Dungeons"> <optgroup label="Dungeons">
@ -108,7 +108,8 @@
<option value="19">Zul'Gurub</option> <option value="19">Zul'Gurub</option>
</optgroup> </optgroup>
</select><select onchange="mapperChooseZone(this)" class="zone-picker"> </select>
<select onchange="mapperChooseZone(this)" class="zone-picker">
<option value="0">More</option> <option value="0">More</option>
<optgroup label="Battlegrounds"> <optgroup label="Battlegrounds">
<option value="2597">Alterac Valley</option> <option value="2597">Alterac Valley</option>