<?PHP

#
#   Axis--Database.php
#   A Simple SQL Database Abstraction Object
#
#   Copyright 1999-2002 Axis Data
#   This code is free software that can be used or redistributed under the
#   terms of Version 2 of the GNU General Public License, as published by the
#   Free Software Foundation (http://www.fsf.org).
#
#   Author:  Edward Almasy (almasy@axisdata.com)
#
#   Part of the AxisPHP library v1.2.5
#   For more information see http://www.axisdata.com/AxisPHP/
#

/**
* SQL database abstraction object with smart query caching.
* \nosubgrouping
*/
class Database {

    # ---- PUBLIC INTERFACE --------------------------------------------------

    /** @name Setup/Initialization */ /*@(*/

    /**
    * Object constructor.  If user name, password, or database name are omitted
    * they must have been set earlier with SetGlobalServerInfo() and
    * SetGlobalDatabaseName().
    * @param string $UserName User name to use to log in to database server.  (OPTIONAL)
    * @param string $Password Password to use to log in to database server.  (OPTIONAL)
    * @param string $DatabaseName Name of database to use once logged in.  (OPTIONAL)
    * @param string $HostName Host name of system on which database server resides.
    *       (OPTIONAL, defaults to "localhost")
    * @see Database::SetGlobalServerInfo()
    * @see Database::SetGlobalDatabaseName()
    */
    function Database(
            $UserName = NULL, $Password = NULL, $DatabaseName = NULL, $HostName = NULL)
    {
        # save DB access parameter values
        $this->DBUserName = $UserName ? $UserName : self::$GlobalDBUserName;
        $this->DBPassword = $Password ? $Password : self::$GlobalDBPassword;
        $this->DBHostName = $HostName ? $HostName :
                (isset(self::$GlobalDBHostName) ? self::$GlobalDBHostName
                    : "localhost");
        $this->DBName = $DatabaseName ? $DatabaseName : self::$GlobalDBName;

        # if we don't already have a connection or DB access parameters were supplied
        $HandleIndex = $this->DBHostName.":".$this->DBName;
        if (!array_key_exists($HandleIndex, self::$ConnectionHandles)
                || $UserName || $Password || $DatabaseName || $HostName)
        {
            # open connection to DB server
            self::$ConnectionHandles[$HandleIndex] = mysql_connect(
                        $this->DBHostName, $this->DBUserName,
                        $this->DBPassword, TRUE)
                    or die("Could not connect to database: ".mysql_error());

            # set local connection handle
            $this->Handle = self::$ConnectionHandles[$HandleIndex];

            # select DB
            mysql_select_db($this->DBName, $this->Handle)
                    or die(mysql_error($this->Handle));
        }
        else
        {
            # set local connection handle
            $this->Handle = self::$ConnectionHandles[$HandleIndex];
        }
    }

    /** @cond */
    /**
    * Specify variables to be saved when serialized.
    */
    function __sleep()
    {
        return array("DBUserName", "DBPassword", "DBHostName", "DBName");
    }
    /**
    * Restore database connection when unserialized.
    */
    function __wakeup()
    {
        # open connection to DB server
        $this->Handle = mysql_connect(
                $this->DBHostName, $this->DBUserName, $this->DBPassword)
                or die("could not connect to database");

        # select DB
        mysql_select_db($this->DBName, $this->Handle)
                or die(mysql_error($this->Handle));
    }
    /** @endcond */

    /**
    * Set default login and host info for database server.
    * @param string $UserName User name to use to log in to database server.
    * @param string $Password Password to use to log in to database server.
    * @param string $HostName Host name of system on which database server resides.
    *       (OPTIONAL, defaults to "localhost")
    */
    static function SetGlobalServerInfo($UserName, $Password, $HostName = "localhost")
    {
        # save default DB access parameters
        self::$GlobalDBUserName = $UserName;
        self::$GlobalDBPassword = $Password;
        self::$GlobalDBHostName = $HostName;

        # clear any existing DB connection handles
        self::$ConnectionHandles = array();
    }

    /**
    * Set default database name.
    * @param string $DatabaseName Name of database to use once logged in.
    */
    static function SetGlobalDatabaseName($DatabaseName)
    {
        # save new default DB name
        self::$GlobalDBName = $DatabaseName;

        # clear any existing DB connection handles
        self::$ConnectionHandles = array();
    }

    /**
    * Get host name of system on which database server resides.
    * @return Host name of database server.
    * @see SetGlobalServerInfo()
    */
    function DBHostName() {  return $this->DBHostName;  }

    /**
    * Get current database name.
    * @return Database name.
    * @see SetGlobalDatabaseName()
    */
    function DBName() {  return $this->DBName;  }

    /**
    * Get name used to connect with database server.
    * @return Login name.
    * @see SetGlobalServerInfo()
    */
    function DBUserName() {  return $this->DBUserName;  }

    /**
    * Get or set whether query result caching is currently enabled.
    * Caching is <b>enabled</b> by default.
    * This setting applies to <b>all</b> instances of the Database class.
    * @param bool $NewSetting TRUE to enable caching or FALSE to disable.  (OPTIONAL)
    * @return Current caching setting.
    */
    static function Caching($NewSetting = NULL)
    {
        # if cache setting has changed
        if (($NewSetting !== NULL) && ($NewSetting != self::$CachingFlag))
        {
            # save new setting
            self::$CachingFlag = $NewSetting;

            # clear any existing cached results
            self::$QueryResultCache = array();
        }

        # return current setting to caller
        return self::$CachingFlag;
    }

    /**
    * Get or set whether advanced query result cachine is currently enabled.
    * Advanced caching attempts to determine whether a query has modified any
    * of the referenced tables since the data was last cached.
    * Advanced caching is <b>disabled</b> by default.
    * This setting applies to <b>all</b> instances of the Database class.
    * @param bool $NewSetting TRUE to enable advanced caching or FALSE to
    *       disable.  (OPTIONAL)
    * @return Current advanced caching setting.
    */
    static function AdvancedCaching($NewSetting = NULL)
    {
        if ($NewSetting !== NULL)
        {
            self::$AdvancedCachingFlag = $NewSetting;
        }
        return self::$AdvancedCachingFlag;
    }

    /**
    * Set query errors to ignore.  The command and error message patterns should be
    *       formatted for preg_match().  For example:
    * @code
    * $SqlErrorsWeCanIgnore = array(
    *        "/ALTER TABLE [a-z]+ ADD COLUMN/i" => "/Duplicate column name/i",
    *        "/CREATE TABLE /i" => "/Table '[a-z0-9_]+' already exists/i",
    *        );
    * @endcode
    * @param array $ErrorsToIgnore Associative array containing errors to ignore when
    *       running queries, with patterns for SQL commands as the indexes and the
    *       patterns for the SQL error messages as the values.  Pass in NULL to
    *       clear list of errors to ignore.
    */
    function SetQueryErrorsToIgnore($ErrorsToIgnore)
    {
        $this->ErrorsToIgnore = $ErrorsToIgnore;
    }

    /*@)*/ /* Setup/Initialization */
    /** @name Data Manipulation */ /*@(*/

    /**
    * Query database (with caching if enabled).
    * @param string $QueryString SQL query string.
    * @param string $FieldName Name of field for which to return value to
    *       caller.  (OPTIONAL)
    * @return Query handle, retrieved value (if FieldName supplied), or FALSE on error.
    */
    function Query($QueryString, $FieldName = "")
    {
        # if caching is enabled
        if (self::$CachingFlag)
        {
            # if SQL statement is read-only
            if ($this->IsReadOnlyStatement($QueryString))
            {
                # if we have statement in cache
                if (isset(self::$QueryResultCache[$QueryString]["NumRows"]))
                {
                    if (self::$QueryDebugOutputFlag)
                            {  print("DB-C: $QueryString<br>\n");  }

                    # make sure query result looks okay
                    $this->QueryHandle = TRUE;

                    # increment cache hit counter
                    self::$CachedQueryCounter++;

                    # make local copy of results
                    $this->QueryResults = self::$QueryResultCache[$QueryString];
                    $this->NumRows = self::$QueryResultCache[$QueryString]["NumRows"];

                    # set flag to indicate that results should be retrieved from cache
                    $this->GetResultsFromCache = TRUE;
                }
                else
                {
                    # execute SQL statement
                    $this->QueryHandle = $this->RunQuery($QueryString);
                    if (!is_resource($this->QueryHandle)) {  return FALSE;  }

                    # save number of rows in result
                    $this->NumRows = mysql_num_rows($this->QueryHandle);

                    # if too many rows to cache
                    if ($this->NumRows >= 50)
                    {
                        # set flag to indicate that query results should not
                        #       be retrieved from cache
                        $this->GetResultsFromCache = FALSE;
                    }
                    else
                    {
                        # if advanced caching is enabled
                        if (self::$AdvancedCachingFlag)
                        {
                            # save tables accessed by query
                            self::$QueryResultCache[$QueryString]["TablesAccessed"] =
                                    $this->TablesAccessed($QueryString);
                        }

                        # if rows found
                        if ($this->NumRows > 0)
                        {
                            # load query results
                            for ($Row = 0;  $Row < $this->NumRows;  $Row++)
                            {
                                $this->QueryResults[$Row] =
                                        mysql_fetch_assoc($this->QueryHandle);
                            }

                            # cache query results
                            self::$QueryResultCache[$QueryString] = $this->QueryResults;
                        }
                        else
                        {
                            # clear local query results
                            unset($this->QueryResults);
                        }

                        # cache number of rows
                        self::$QueryResultCache[$QueryString]["NumRows"] = $this->NumRows;

                        # set flag to indicate that query results should be retrieved from cache
                        $this->GetResultsFromCache = TRUE;
                    }
                }
            }
            else
            {
                # if advanced caching is enabled
                if (self::$AdvancedCachingFlag)
                {
                    # if table modified by statement is known
                    $TableModified = $this->TableModified($QueryString);
                    if ($TableModified)
                    {
                        # for each cached query
                        foreach (self::$QueryResultCache
                                as $CachedQueryString => $CachedQueryResult)
                        {
                            # if we know what tables were accessed
                            if ($CachedQueryResult["TablesAccessed"])
                            {
                                # if tables accessed include the one we may modify
                                if (in_array($TableModified, $CachedQueryResult["TablesAccessed"]))
                                {
                                    # clear cached query results
                                    unset($GLOBALS["APDBQueryResultCache"][$CachedQueryString]);
                                }
                            }
                            else
                            {
                                # clear cached query results
                                unset($GLOBALS["APDBQueryResultCache"][$CachedQueryString]);
                            }
                        }
                    }
                    else
                    {
                        # clear entire query result cache
                        self::$QueryResultCache = array();
                    }
                }
                else
                {
                    # clear entire query result cache
                    self::$QueryResultCache = array();
                }

                # execute SQL statement
                $this->QueryHandle = $this->RunQuery($QueryString);
                if ($this->QueryHandle === FALSE) {  return FALSE;  }

                # set flag to indicate that query results should not be retrieved from cache
                $this->GetResultsFromCache = FALSE;
            }

            # reset row counter
            $this->RowCounter = 0;

            # increment query counter
            self::$QueryCounter++;
        }
        else
        {
            # execute SQL statement
            $this->QueryHandle = $this->RunQuery($QueryString);
            if ($this->QueryHandle === FALSE) {  return FALSE;  }
        }

        if (($FieldName != "") && ($this->QueryHandle != FALSE))
        {
            return $this->FetchField($FieldName);
        }
        else
        {
            return $this->QueryHandle;
        }
    }

    /**
    * Execute queries from specified file.  Comment lines are ignored.
    * Multiple queries on a single line are not handled.  Execution continues
    * until all queries are run or an error occurs that has not been
    * previously specified to be ignored.  If a query fails, information
    * about the failure can be retrieved with QueryErrMsg() and QueryErrNo().
    * @param string $FileName Name of file to load queries from.
    * @return Number of queries executed or NULL if query failed.
    * @see Database::SetQueryErrorsToIgnore()
    * @see Database::QueryErrMsg()
    * @see Database::QueryErrNo()
    */
    function ExecuteQueriesFromFile($FileName)
    {
        # open file
        $FHandle = fopen($FileName, "r");

        # if file open succeeded
        if ($FHandle !== FALSE)
        {
            # while lines left in file
            $Query = "";
            $QueryCount = 0;
            while (!feof($FHandle))
            {
                # read in line from file
                $Line = fgets($FHandle, 32767);

                # trim whitespace from line
                $Line = trim($Line);

                # if line is not empty and not a comment
                if (!preg_match("/^#/", $Line)
                        && !preg_match("/^--/", $Line)
                        && strlen($Line))
                {
                    # add line to current query
                    $Query .= " ".$Line;

                    # if line completes a query
                    if (preg_match("/;$/", $Line))
                    {
                        # run query
                        $QueryCount++;
                        $Result = $this->Query($Query);
                        $Query = "";

                        # if query resulted in an error that is not ignorable
                        if ($Result === FALSE)
                        {
                            # stop processing queries and set error code
                            $QueryCount = NULL;
                            break;
                        }
                    }
                }
            }

            # close file
            fclose($FHandle);
        }

        # return number of executed queries to caller
        return $QueryCount;
    }

    /**
    * Get most recent error message text set by Query().
    * @return Error message text from database server.
    * @see QueryErrNo()
    */
    function QueryErrMsg()
    {
        return $this->ErrMsg;
    }

    /**
    * Get most recent error code set by Query().
    * @return Error code from database server.
    * @see QueryErrMsg()
    */
    function QueryErrNo()
    {
        return $this->ErrNo;
    }

    /**
    * Get/set whether Query() errors will be displayed.  By default errors
    *       are not displayed.
    * @param bool $NewValue TRUE to display errors or FALSE to not display.  (OPTIONAL)
    * @return Current value of whether Query() errors will be displayed.
    */
    static function DisplayQueryErrors($NewValue = NULL)
    {
        if ($NewValue !== NULL) {  self::$DisplayErrors = $NewValue;  }
        return self::$DisplayErrors;
    }

    /**
    * Get number of rows returned by last query.
    * @return Number of database rows selected by last query.
    */
    function NumRowsSelected()
    {
        # if caching is enabled and query was cached
        if (self::$CachingFlag && $this->GetResultsFromCache)
        {
            # return cached number of rows to caller
            return $this->NumRows;
        }
        else
        {
            # call to this method after an unsuccessful query
            if (!is_resource($this->QueryHandle))
            {
                return 0;
            }

            # retrieve number of rows and return to caller
            return mysql_num_rows($this->QueryHandle);
        }
    }

    /**
    * Get next database row retrieved by most recent query.
    * @return Array of database values with field names for indexes.  Returns
    *       FALSE if no more rows are available.
    */
    function FetchRow()
    {
        # if caching is enabled and query was cached
        if (self::$CachingFlag && $this->GetResultsFromCache)
        {
            # if rows left to return
            if ($this->RowCounter < $this->NumRows)
            {
                # retrieve row from cache
                $Result = $this->QueryResults[$this->RowCounter];

                # increment row counter
                $this->RowCounter++;
            }
            else
            {
                # return nothing
                $Result = FALSE;
            }
        }
        else
        {
            # call to this method after successful query
            if (is_resource($this->QueryHandle))
            {
                $Result = mysql_fetch_assoc($this->QueryHandle);
            }

            # call to this method after unsuccessful query
            else
            {
                $Result = FALSE;
            }
        }

        # return row to caller
        return $Result;
    }

    /**
    * Get specified number of database rows retrieved by most recent query.
    * @param int $NumberOfRows Maximum number of rows to return.  (OPTIONAL -- if
    *       not specified then all available rows are returned)
    * @return Array of rows.  Each row is an associative array indexed by field name.
    */
    function FetchRows($NumberOfRows = NULL)
    {
        # assume no rows will be returned
        $Result = array();

        # for each available row
        $RowsFetched = 0;
        while ((($RowsFetched < $NumberOfRows) || ($NumberOfRows == NULL))
                && ($Row = $this->FetchRow()))
        {
            # add row to results
            $Result[] = $Row;
            $RowsFetched++;
        }

        # return array of rows to caller
        return $Result;
    }

    /**
    * Get all available values for specified database field retrieved by most
    * recent query.  If a second database field name is specified then the array
    * returned will be indexed by the values from that field.  If all index field
    * values are not unique then some values will be overwritten.
     *
    * A common use for this method is to retrieve a set of values with an ID field
    * specified for the index:<br>
    *  <code>$CNames = $DB->FetchColumn("ControlledName", "ControlledNameId");</code>
    * @param string $FieldName Name of database field.
    * @param string $IndexFieldName Name of second database field to use for
    *       array index.  (OPTIONAL)
    * @return Array of values from specified field, indexed numerically.  If
    *       IndexFieldName is supplied then array will be indexed by
    *       corresponding values from that field.
    */
    function FetchColumn($FieldName, $IndexFieldName = NULL)
    {
        $Array = array();
        while ($Record = $this->FetchRow())
        {
            if ($IndexFieldName != NULL)
            {
                $Array[$Record[$IndexFieldName]] = $Record[$FieldName];
            }
            else
            {
                $Array[] = $Record[$FieldName];
            }
        }
        return $Array;
    }

    /**
    * Pull next row from last DB query and get a specific value from that row.
    * This is a convenience method that in effect combines a FetchRow() with getting
    * a value from the array returned.  This method <b>does</b> advance the pointer
    * to the next row returned by the query each time it is called.
    * @param string $FieldName Name of field.
    * @return Value from specified field.
    */
    function FetchField($FieldName)
    {
        $Record = $this->FetchRow();
        return isset($Record[$FieldName]) ? $Record[$FieldName] : NULL;
    }

    /**
    * Get ID of row added by the last SQL "INSERT" statement.  It should be
    * called immediately after the INSERT statement query.  This method uses the
    * SQL "LAST_INSERT_ID()" function.
    * @param string $TableName Name of SQL table into which row was inserted.
    * @return Numerical ID value.
    */
    function LastInsertId($TableName)
    {
        return (int)$this->Query(
                "SELECT LAST_INSERT_ID() AS InsertId FROM ".$TableName,
                "InsertId");
    }

    /**
    * A convenience function to get or set a value in the database.  This will
    * typically be called from inside a private convenience method within an object
    * that supplies the table name, condition, and cache.
    * @param string $TableName Name of database table.
    * @param string $FieldName Name of database field.
    * @param mixed $NewValue New value to set.  Use DB_NOVALUE to not set a
    *       new value (i.e. when just getting a value).
    * @param string $Condition SQL query conditional to use in SELECT or UPDATE
    *       statements (should not include "WHERE").  Use NULL if no conditional
    *       is needed.
    * @param array $CachedRecord Variable to use to cache values.  Accessed by reference.
    * @return Requested value.
    */
    function UpdateValue(
            $TableName, $FieldName, $NewValue, $Condition, &$CachedRecord)
    {
        # expand condition if supplied
        if ($Condition != NULL) {  $Condition = " WHERE ".$Condition;  }

        # read cached record from database if not already loaded
        if (!isset($CachedRecord))
        {
            $this->Query("SELECT * FROM `".$TableName."` ".$Condition);
            $CachedRecord = $this->FetchRow();
        }

        # if new value supplied
        if ($NewValue !== DB_NOVALUE)
        {
            # update value in database
            $this->Query("UPDATE `".$TableName."` SET `".$FieldName."` = "
                    .(($NewValue === NULL) ? "NULL" : "'"
                            .mysql_real_escape_string($NewValue)."'")
                    .$Condition);

            # update value in cached record
            $CachedRecord[$FieldName] = $NewValue;
        }

        # return value from cached record to caller
        return isset($CachedRecord[$FieldName])
                ? $CachedRecord[$FieldName] : NULL;
    }

    /**
    * A convenience function to get or set an integer value in the database.  This will
    * typically be called from inside a private convenience method within an object
    * that supplies the table name, condition, and cache.  This method should be used
    * instead of UpdateValue() in situations where the incoming value specifically
    * needs to be forced to an int.
    * @param string $TableName Name of database table.
    * @param string $FieldName Name of database field.
    * @param int $NewValue New value to set.  Use DB_NOVALUE to not set a new
    *       value (i.e. when just getting a value).
    * @param string $Condition SQL query conditional to use in SELECT or UPDATE
    *       statements (should not include "WHERE").  Use NULL if no conditional
    *       is needed.
    * @param array $CachedRecord Variable to use to cache values.  Accessed by reference.
    * @return Requested value.
    */
    function UpdateIntValue(
            $TableName, $FieldName, $NewValue, $Condition, &$CachedRecord)
    {
        return $this->UpdateValue($TableName, $FieldName,
                (($NewValue === DB_NOVALUE) ? DB_NOVALUE : (int)$NewValue),
                $Condition, $CachedRecord);
    }

    /**
    * A convenience function to get or set a float value in the database.  This will
    * typically be called from inside a private convenience method within an object
    * that supplies the table name, condition, and cache.  This method should be used
    * instead of UpdateValue() in situations where the incoming value specifically
    * needs to be forced to an float.
    * @param string $TableName Name of database table.
    * @param string $FieldName Name of database field.
    * @param float $NewValue New value to set.  Use DB_NOVALUE to not set a
    *       new value (i.e. when just getting a value).
    * @param string $Condition SQL query conditional to use in SELECT or
    *       UPDATE statements (should not include "WHERE").  Use NULL if no
    *       conditional is needed.
    * @param array $CachedRecord Variable to use to cache values.  Accessed by reference.
    * @return Requested value.
    */
    function UpdateFloatValue(
            $TableName, $FieldName, $NewValue, $Condition, &$CachedRecord)
    {
        return $this->UpdateValue($TableName, $FieldName,
                (($NewValue === DB_NOVALUE) ? DB_NOVALUE : (float)$NewValue),
                $Condition, $CachedRecord);
    }

    /*@)*/ /* Data Manipulation */
    /** @name Miscellaneous */ /*@(*/

    /**
    * Peform query that consists of SQL comment statement.  This is used primarily
    * when query debug output is turned on, to insert additional information into
    * the query stream.
    * @param string $String Debug string.
    */
    function LogComment($String)
    {
        $this->Query("-- ".$String);
    }

    /**
    * Get whether specified field exists in specified table.
    * @param string $TableName Name of database table.
    * @param string $FieldName Name of database field.
    * @return bool TRUE if table and field exist, or FALSE otherwise.
    */
    function FieldExists($TableName, $FieldName)
    {
        $this->Query("DESC ".$TableName);
        while ($CurrentFieldName = $this->FetchField("Field"))
        {
            if ($CurrentFieldName == $FieldName) {  return TRUE;  }
        }
        return FALSE;
    }

    /**
    * Get field (column) type.
    * @param string $TableName Name of database table.
    * @param string $FieldName Name of database field.
    * @return string Field type or NULL if field was not found.
    */
    function GetFieldType($TableName, $FieldName)
    {
        $this->Query("DESC ".$TableName);
        return $this->FetchField("Type");
    }

    /**
    * Enable or disable debugging output for queries.  Output is disabled by default.
    * This setting applies to <b>all</b> instances of the Database class.
    * @param bool $NewSetting TRUE to enable output or FALSE to disable output.
    */
    static function QueryDebugOutput($NewSetting)
    {
        self::$QueryDebugOutputFlag = $NewSetting;
    }

    /**
    * Get the number of queries that have been run since program execution began.
    * The value returned is for <b>all</b> instances of the Database class.
    * @return Number of queries.
    */
    static function NumQueries()
    {
        return self::$QueryCounter;
    }

    /**
    * Get the number of queries that have resulted in cache hits since program
    * execution began.
    * The value returned is for <b>all</b> instances of the Database class.
    * @return Number of queries that resulted in cache hits.
    */
    static function NumCacheHits()
    {
        return self::$CachedQueryCounter;
    }

    /**
    * Get the ratio of query cache hits to queries as a percentage.
    * The value returned is for <b>all</b> instances of the Database class.
    * @return Percentage of queries that resulted in hits.
    */
    static function CacheHitRate()
    {
        if (self::$QueryCounter)
        {
            return (self::$CachedQueryCounter / self::$QueryCounter) * 100;
        }
        else
        {
            return 0;
        }
    }

    /*@)*/ /* Miscellaneous */

    # ---- PRIVATE INTERFACE -------------------------------------------------

    protected $DBUserName;
    protected $DBPassword;
    protected $DBHostName;
    protected $DBName;

    private $Handle;
    private $QueryHandle;
    private $QueryResults;
    private $RowCounter;
    private $NumRows;
    private $GetResultsFromCache;
    private $ErrorsToIgnore = NULL;
    private $ErrMsg = NULL;
    private $ErrNo = NULL;

    private static $DisplayErrors = FALSE;

    private static $GlobalDBUserName;
    private static $GlobalDBPassword;
    private static $GlobalDBHostName;
    private static $GlobalDBName;

    # debug output flag
    private static $QueryDebugOutputFlag = FALSE;
    # flag for whether caching is turned on
    private static $CachingFlag = TRUE;
    # query result advanced caching flag
    private static $AdvancedCachingFlag = FALSE;
    # global cache for query results
    private static $QueryResultCache = array();
    # stats counters
    private static $QueryCounter = 0;
    private static $CachedQueryCounter = 0;
    # database connection link handles
    private static $ConnectionHandles = array();

    /**
    * Attempt to determine whether a specified SQL statement may modify data.
    * @param string $QueryString SQL query string to examine.
    * @return bool TRUE if statement is unlikely to modify data, otherwise FALSE.
    */
    private function IsReadOnlyStatement($QueryString)
    {
        return preg_match("/^[ ]*SELECT /i", $QueryString) ? TRUE : FALSE;
    }

    /**
    * Attempt to determine which tables might be modified by an SQL statement.
    * @param string $QueryString SQL query string to examine.
    * @return string Table name that will be modified, or FALSE if no table is
    *       modified or it is unclear what table will be modified.
    */
    private function TableModified($QueryString)
    {
        # assume we're not going to be able to determine table
        $TableName = FALSE;

        # split query into pieces
        $QueryString = trim($QueryString);
        $Words = preg_split("/\s+/", $QueryString);

        # if INSERT statement
        $WordIndex = 1;
        if (strtoupper($Words[0]) == "INSERT")
        {
            # skip over modifying keywords
            while ((strtoupper($Words[$WordIndex]) == "LOW_PRIORITY")
                    || (strtoupper($Words[$WordIndex]) == "DELAYED")
                    || (strtoupper($Words[$WordIndex]) == "IGNORE")
                    || (strtoupper($Words[$WordIndex]) == "INTO"))
            {
                $WordIndex++;
            }

            # next word is table name
            $TableName = $Words[$WordIndex];
        }
        # else if UPDATE statement
        elseif (strtoupper($Words[0]) == "UPDATE")
        {
            # skip over modifying keywords
            while ((strtoupper($Words[$WordIndex]) == "LOW_PRIORITY")
                    || (strtoupper($Words[$WordIndex]) == "IGNORE"))
            {
                $WordIndex++;
            }

            # if word following next word is SET
            if (strtoupper($Words[$WordIndex + 1]) == "SET")
            {
                # next word is table name
                $TableName = $Words[$WordIndex];
            }
        }
        # else if DELETE statement
        elseif (strtoupper($Words[0]) == "DELETE")
        {
            # skip over modifying keywords
            while ((strtoupper($Words[$WordIndex]) == "LOW_PRIORITY")
                    || (strtoupper($Words[$WordIndex]) == "IGNORE")
                    || (strtoupper($Words[$WordIndex]) == "QUICK"))
            {
                $WordIndex++;
            }

            # if next term is FROM
            if (strtoupper($Words[$WordIndex]) == "FROM")
            {
                # next word is table name
                $WordIndex++;
                $TableName = $Words[$WordIndex];
            }
        }

        # discard table name if it looks at all suspicious
        if ($TableName)
        {
            if (!preg_match("/[a-zA-Z0-9]+/", $TableName))
            {
                $TableName = FALSE;
            }
        }

        # return table name (or lack thereof) to caller
        return $TableName;
    }

    /**
    * Attempt to determine which tables might be accessed by an SQL statement.
    * @param string $QueryString SQL query string to examine.
    * @return array Array of table name that may be accessed, or FALSE if no
    *       table is accessed or it is unclear what tables may be accessed.
    */
    private function TablesAccessed($QueryString)
    {
        # assume we're not going to be able to determine tables
        $TableNames = FALSE;

        # split query into pieces
        $QueryString = trim($QueryString);
        $Words = preg_split("/\s+/", $QueryString);
        $UQueryString = strtoupper($QueryString);
        $UWords = preg_split("/\s+/", $UQueryString);

        # if SELECT statement
        if ($UWords[0] == "SELECT")
        {
            # keep going until we hit FROM or last word
            $WordIndex = 1;
            while (($UWords[$WordIndex] != "FROM")
                    && strlen($UWords[$WordIndex]))
            {
                $WordIndex++;
            }

            # if we hit FROM
            if ($UWords[$WordIndex] == "FROM")
            {
                # for each word after FROM
                $WordIndex++;
                while (strlen($UWords[$WordIndex]))
                {
                    # if current word ends with comma
                    if (preg_match("/,$/", $Words[$WordIndex]))
                    {
                        # strip off comma and add word to table name list
                        $TableNames[] = substr($Words[$WordIndex], 0, -1);
                    }
                    else
                    {
                        # add word to table name list
                        $TableNames[] = $Words[$WordIndex];

                        # if next word is not comma
                        $WordIndex++;
                        if ($Words[$WordIndex] != ",")
                        {
                            # if word begins with comma
                            if (preg_match("/^,/", $Words[$WordIndex]))
                            {
                                # strip off comma (NOTE: modifies $Words array!)
                                $Words[$WordIndex] = substr($Words[$WordIndex], 1);

                                # decrement index so we start with this word next pass
                                $WordIndex--;
                            }
                            else
                            {
                                # stop scanning words (non-basic JOINs not yet handled)
                                break;
                            }
                        }
                    }

                    # move to next word
                    $WordIndex++;
                }
            }
        }

        # discard table names if they look at all suspicious
        if ($TableNames)
        {
            foreach ($TableNames as $Name)
            {
                if (!preg_match("/^[a-zA-Z0-9]+$/", $Name))
                {
                    $TableNames = FALSE;
                    break;
                }
            }
        }

        # return table name (or lack thereof) to caller
        return $TableNames;
    }

    /**
    * Run SQL query, ignoring or reporting errors as appropriate.
    * @param string $QueryString SQL query to run.
    * @return mixed SQL query handle or FALSE if query failed or TRUE if query
    *       failed by error was ignored.
    */
    private function RunQuery($QueryString)
    {
        if (self::$QueryDebugOutputFlag) {  $QueryStartTime = microtime(TRUE);  }
        $this->QueryHandle = mysql_query($QueryString, $this->Handle);
        if (self::$QueryDebugOutputFlag)
        {
            print "DB: ".$QueryString." ["
                    .sprintf("%.2f", microtime(TRUE) - $QueryStartTime)
                    ."s]"."<br>\n";
        }
        if (($this->QueryHandle === FALSE) && $this->ErrorsToIgnore)
        {
            foreach ($this->ErrorsToIgnore as $SqlPattern => $ErrMsgPattern)
            {
                if (preg_match($SqlPattern, $QueryString)
                        && preg_match($ErrMsgPattern, mysql_error($this->Handle)))
                {
                    $this->QueryHandle = TRUE;
                    break;
                }
            }
        }

        if ($this->QueryHandle === FALSE)
        {
            $this->ErrMsg = mysql_error($this->Handle);
            $this->ErrNo = mysql_errno($this->Handle);
            $this->NumRows = 0;
            if (self::$DisplayErrors)
            {
                print("<b>SQL Error:</b> <i>".$this->ErrMsg
                        ."</i> (".$this->ErrNo.")<br/>\n");
                print("<b>SQL Statement:</b> <i>"
                        .htmlspecialchars($QueryString)."</i><br/>\n");
            }
        }
        return $this->QueryHandle;
    }
}

# define return values  (numerical values correspond to MySQL error codes)
define("DB_OKAY",               0);
define("DB_ERROR",              1);
define("DB_ACCESSDENIED",       2);
define("DB_UNKNOWNDB",          3);
define("DB_UNKNOWNTABLE",       4);
define("DB_SYNTAXERROR",        5);
define("DB_DBALREADYEXISTS",    6);
define("DB_DBDOESNOTEXIST",     7);
define("DB_DISKFULL",           8);

# define value to designate omitted arguments (so DB values can be set to NULL)
define("DB_NOVALUE", "!-_-_-DB_NOVALUE-_-_-!");

# MySQL error code mapping
$APDBErrorCodeMappings = array(
        1045    => DB_ACCESSDENIED,
        1049    => DB_UNKNOWNDB,
        1046    => DB_UNKNOWNTABLE,
        1064    => DB_SYNTAXERROR,
        1007    => DB_DBALREADYEXISTS,  # ?  (not sure)
        1008    => DB_DBDOESNOTEXIST,   # ?  (not sure)
        1021    => DB_DISKFULL,         # ?  (not sure)
        );

?>
