<?PHP
#
#   FILE:  OpenId_AxisDatabase.php
#
#   Part of the Collection Workflow Integration System (CWIS)
#   Copyright 2011 Edward Almasy and Internet Scout
#   http://scout.wisc.edu
#

# NOTE:
#
# The php-openid library has its own database abstraction system.
# To hook a new DB into it, one must implement an object following their specification.
# This class is created only for use with php-openid, and SHOULD NOT
#  be used in other code.  Use the Database() class instead.

# Don't include in CWIS developer documentation, since this is just a shim to talk to
# an external library.
/** \cond */

require_once('Auth/OpenID/DatabaseConnection.php');

/**
* Wrapper for Axis--Database so that php-openid can talk to it
*/
class Auth_OpenId_AxisDatabase extends Auth_OpenId_DatabaseConnection {
    /**
    * Perform a query.
    */
    function query($sql, $params=array())
    {
        global $DB;

        return $DB->Query( $this->do_params_insert($sql,$params) );
    }

    /**
    * Perform a query returning the first column of the first result.
    */
    function getOne($sql, $params=array())
    {
        global $DB;

        if ($DB->Query( $this->do_params_insert($sql,$params) ) !== FALSE)
        {
            $Row = $DB->FetchRow();
            $rc = array_shift($Row);
            return $rc;
        }
        else
        {
            return FALSE;
        }
    }

    /**
    * Perform a query, returning all columns of the first result.
    */
    function getRow($sql, $params=array())
    {
        global $DB;

        if ($DB->Query( $this->do_params_insert($sql,$params) ) !== FALSE)
        {
            $Row = $DB->FetchRow();
            return $Row;
        }
        else
        {
            return FALSE;
        }
    }

    /**
    * Perform a query, returning all columns of all rows.
    */
    function getAll($sql, $params=array())
    {
        global $DB;

        if ($DB->Query( $this->do_params_insert($sql,$params) ) !== FALSE)
        {
            $All = array();
            while ($Row = $DB->FetchRow())
            {
                $All []= $Row;
            }
            return $All;
        }
        else
        {
            return FALSE;
        }
    }

    /**
    * Insert parameters into an SQL query.
    */
    private function do_params_insert($sql, $params=array())
    {
        $rc ="";
        for ($i=0; $i<strlen($sql); $i++)
        {
            if ($sql[$i] == '?' || $sql[$i] == '!' )
            {
                $data = array_shift($params);

                if (preg_match("/^[0-9]+$/", $data) ||
                    preg_match("/^0x[0-9a-f]+$/", $data) )
                {
                    $rc .= $data;
                }
                else
                {
                    $rc .= "'".addslashes($data)."'";
                }
            }
            else
            {
                $rc .= $sql[$i];
            }
        }

        return $rc;
    }
}

/** \endcond */
?>
