Esempio n. 1
0
 /**
  * Constructor
  *
  * @access protected
  * @param  array  full liveuser configuration array
  * @return void
  * @see    LiveUser::factory()
  */
 function LiveUser_Admin_Perm_Container_MDB2_Simple(&$connectOptions)
 {
     if (is_array($connectOptions)) {
         $function = 'connect';
         if (isset($connectOptions['function'])) {
             $function = $connectOptions['function'];
             unset($connectOptions['function']);
         }
         foreach ($connectOptions as $key => $value) {
             if (isset($this->{$key})) {
                 $this->{$key} = $value;
             }
         }
         if (isset($connectOptions['connection']) && MDB2::isConnection($connectOptions['connection'])) {
             $this->dbc =& $connectOptions['connection'];
             $this->init_ok = true;
         } elseif (isset($connectOptions['dsn'])) {
             $this->dsn = $connectOptions['dsn'];
             $options = null;
             if (isset($connectOptions['options'])) {
                 $options = $connectOptions['options'];
             }
             $options['portability'] = MDB2_PORTABILITY_ALL;
             if ($function == 'singleton') {
                 $this->dbc =& MDB2::singleton($connectOptions['dsn'], $options);
             } else {
                 $this->dbc =& MDB2::connect($connectOptions['dsn'], $options);
             }
             if (!MDB2::isError($this->dbc)) {
                 $this->init_ok = true;
             }
         }
     }
 }
 /**
  * Create a new instance of a default I2CE  table user access mechanism
  */
 public function __construct()
 {
     $protocol = substr(get_class($this), 16);
     if (!$protocol) {
         $protocol = 'DEFAULT';
     }
     $this->protocol = $protocol;
     $init = I2CE::getUserAccessInit($protocol);
     if (empty($init)) {
         $options = array();
     } else {
         $options = json_decode($init, true);
         if (!is_array($options)) {
             I2CE::raiseError("Invalid user access initilization string");
             $options = array();
         }
     }
     if (!array_key_exists('admin_user', $options)) {
         $options['admin_user'] = '******';
     }
     if (!array_key_exists('admin_pass', $options)) {
         $options['admin_pass'] = MDB2::singleton()->dsn['password'];
     }
     if (!array_key_exists('admin_details', $options) || !is_array($options['admin_details'])) {
         $options['admin_details'] = array();
     }
     if (!array_key_exists('auto_login', $options)) {
         $options['auto_login'] = 0;
     }
     if (!array_key_exists('auto_login_user', $options)) {
         $options['auto_login_user'] = false;
     }
     $this->options = $this->ensureDefaultOptions($options);
 }
Esempio n. 3
0
function R3AppInitDB()
{
    global $mdb2;
    global $dsn;
    require_once 'MDB2.php';
    if (!isset($dsn) || $dsn == '') {
        throw new Exception('Missing $dsn');
    }
    $txtDsn = $dsn['dbtype'] . '://' . $dsn['dbuser'] . ':' . $dsn['dbpass'] . '@' . $dsn['dbhost'] . '/' . $dsn['dbname'];
    $db = ezcDbFactory::create($txtDsn);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    PEAR::setErrorHandling(PEAR_ERROR_EXCEPTION);
    $mdb2 = MDB2::singleton($txtDsn);
    // Needed by user manager and import/export
    ezcDbInstance::set($db);
    if (isset($dsn['charset'])) {
        $db->exec("SET client_encoding TO '{$dsn['charset']}'");
        $mdb2->exec("SET client_encoding TO '{$dsn['charset']}'");
    }
    if (isset($dsn['search_path'])) {
        $db->exec("SET search_path TO {$dsn['search_path']}, public");
        $mdb2->exec("SET search_path TO {$dsn['search_path']}, public");
    }
    $db->exec("SET datestyle TO ISO");
    $mdb2->exec("SET datestyle TO ISO");
}
Esempio n. 4
0
 /**
  * コンストラクタ.
  *
  * @param string $dsn データソース名
  * @param boolean $force_run エラーが発生しても処理を続行する場合 true
  * @param boolean $new 新規に接続を行うかどうか
  */
 function SC_Query($dsn = "", $force_run = false, $new = false)
 {
     if ($dsn == "") {
         $dsn = array('phptype' => DB_TYPE, 'username' => DB_USER, 'password' => DB_PASSWORD, 'protocol' => 'tcp', 'hostspec' => DB_SERVER, 'port' => DB_PORT, 'database' => DB_NAME);
     }
     // Debugモード指定
     // 常時ONにするとメモリが解放されない。
     // 連続クエリ実行時に問題が生じる。
     if (DEBUG_MODE) {
         $options['debug'] = PEAR_DB_DEBUG;
     } else {
         $options['debug'] = 0;
     }
     // 持続的接続オプション
     $options['persistent'] = PEAR_DB_PERSISTENT;
     // バッファリング trueにするとメモリが解放されない。
     // 連続クエリ実行時に問題が生じる。
     $options['result_buffering'] = false;
     if ($new) {
         $this->conn = MDB2::connect($dsn, $options);
     } else {
         $this->conn = MDB2::singleton($dsn, $options);
     }
     if (!PEAR::isError($this->conn)) {
         // $this->conn->setCharset("utf8"); XXX SQL Azure では使用できないらしい
         $this->conn->setFetchMode(MDB2_FETCHMODE_ASSOC);
     }
     $this->dbFactory = SC_DB_DBFactory_Ex::getInstance();
     $this->force_run = $force_run;
 }
 public static function alreadyProcessed($node)
 {
     if (!is_array($return = self::getNodeHash($node))) {
         return null;
     }
     list($relationship, $hash) = $return;
     if (!is_string($relationship) || !is_string($hash)) {
         $this->raiseError("Bad parameters");
         return null;
     }
     if (self::$lookup_stmt === null) {
         $db = MDB2::singleton();
         self::$lookup_stmt = $db->prepare("SELECT id FROM form_relationship_importer WHERE relationship = ? and hash= ?", array('text', 'text'), array('text'), MDB2_PREPARE_RESULT);
         if (I2CE::pearError(self::$lookup_stmt, "Could not prepare lookup statement")) {
             return null;
         }
     }
     if (!self::$lookup_stmt) {
         return null;
     }
     $results = self::$lookup_stmt->execute(array($relationship, $hash));
     $row = $results->fetchRow();
     if (!isset($row) || I2CE::pearError($row, "Error getting form id:")) {
         return false;
     }
     return $row->id;
 }
 /**
  * Set up the database and prepared statements if necessary.
  */
 protected static function setupDB()
 {
     if (!self::$db instanceof MDB2_Driver_Common) {
         self::$db = MDB2::singleton();
         self::$prepared = array();
         self::$prepared['user_log'] = self::$db->prepare("SELECT login,logout,activity FROM user_log WHERE user = ? ORDER BY activity DESC LIMIT ?", array('integer', 'integer'), array('date', 'date', 'date'));
         if (I2CE::pearError(self::$prepared['user_log'], "Error preparing user_log statement: ")) {
             return false;
         }
         /*
         self::$prepared['entry_log'] = self::$db->prepare("SELECT COUNT(DISTINCT e.record) AS records,(SELECT name FROM form WHERE id = (SELECT form FROM record WHERE id = e.record)) AS form,DATE(`date`) AS `date` FROM `entry` e WHERE DATE(`date`) >= (SELECT DISTINCT DATE(`date`) FROM entry WHERE who = ? ORDER BY `date` DESC LIMIT ?,1) AND who = ? GROUP BY 2,3 ORDER BY `date` DESC",
                 array( 'integer', 'integer', 'integer' ), array( 'integer', 'text', 'date' ) );
         if ( I2CE::pearError( self::$prepared['entry_log'], "Error preparing entry_log statement: " ) ) {
             return false;
         }
         self::$prepared['person_log'] = self::$db->prepare("SELECT COUNT(DISTINCT(p.person_id)) AS records,DATE(`date`) AS date FROM entry e,(SELECT r.id,id AS person_id FROM record r WHERE form = ( SELECT id FROM form WHERE name =  'person' ) UNION select r.id,r.parent_id AS person_id from record r where parent_form = 'person' UNION select r.id,p.parent_id AS person_id from record r join record p on p.id = r.parent_id AND p.parent_form = 'person' UNION select r.id,g.parent_id AS person_id from record r join record p on p.id = r.parent_id JOIN record g ON g.id = p.parent_id AND g.parent_form = 'person') AS p WHERE e.who = ? AND e.record = p.id GROUP BY 2 ORDER BY `date` DESC LIMIT ?",
                 array( 'integer', 'integer' ), array( 'integer', 'date' ) );
         if ( I2CE::pearError( self::$prepared['person_log'], "Error preparing person_log statement: " ) ) {
             return false;
         }
         */
         self::$prepared['entry_history'] = self::$db->prepare("SELECT DISTINCT record,DATE(`date`) AS `date` FROM `entry` WHERE `date` >= (SELECT DISTINCT DATE(`date`) FROM entry WHERE who = ? ORDER BY `date` DESC LIMIT ?,1) AND who = ? ORDER BY `date` DESC", array('integer', 'integer', 'integer'), array('integer', 'date'));
         if (I2CE::pearError(self::$prepared['entry_history'], "Error preparing entry_history statement: ")) {
             return false;
         }
     }
     return true;
 }
Esempio n. 7
0
 public function connect($options = array())
 {
     $dsn = 'mysql://' . $options['username'] . ':' . $options['password'] . '@' . $options['server'] . '/' . $options['database'];
     $this->link = MDB2::singleton($dsn);
     if (PEAR::isError($this->link)) {
         die("There was an error connecting to the database: " . $this->link->getMessage());
     }
 }
 /**
  * Create a new instance of a report factory.
  */
 public function __construct()
 {
     $this->setStorage();
     $this->loadedPaths = array();
     $this->db = MDB2::singleton();
     //I2CE::pearError($this->db,"Cannot connect to DB");
     $this->classCache = array();
 }
Esempio n. 9
0
 function open_connection($conn = DB_DNS)
 {
     //initialize MDB2
     $this->mdb2 =& MDB2::singleton($conn);
     $this->mdb2->loadModule('Extended');
     $this->mdb2->loadModule('Date');
     $this->mdb2->setFetchMode(MDB2_FETCHMODE_ASSOC);
     return $this->mdb2;
 }
 function connect()
 {
     // connect to database
     $options = array('portability' => MDB2_PORTABILITY_ALL ^ MDB2_PORTABILITY_EMPTY_TO_NULL);
     $this->dbc =& MDB2::singleton($this->_dsn, $options);
     if (PEAR::isError($this->dbc)) {
         return $this->dbc;
     }
 }
Esempio n. 11
0
 protected function _install($table)
 {
     $db = MDB2::singleton(DB_URI);
     $ret = $db->exec('ALTER TABLE `' . $table . '` ADD `archiver_archived` BOOL NOT NULL');
     if (!PEAR::isError($ret)) {
         $this->line('added field to ' . $table);
         return true;
     } else {
         $this->line('Field already added to ' . $table);
     }
 }
Esempio n. 12
0
function getDBConnection()
{
    $dsn = array('phptype' => 'mysql', 'hostspec' => 'localhost', 'database' => 'cicada', 'username' => 'root', 'password' => '');
    $options = array('debug' => 2);
    $mdb2 =& MDB2::singleton($dsn, $options);
    if (PEAR::isError($mdb2)) {
        die($mdb2->getMessage());
    }
    $mdb2->setFetchMode(MDB2_FETCHMODE_ASSOC);
    return $mdb2;
}
Esempio n. 13
0
File: Sql.php Progetto: vih/vih.dk
 function DB_Sql($dbhost = '', $dbuser = '', $dbpass = '', $dbname = '')
 {
     if (empty($dbhost) or empty($dbuser) or empty($dbpass) or empty($dbname)) {
         $this->db = MDB2::singleton(DB_DSN);
     } else {
         $this->db = MDB2::singleton('mysql://' . $dbuser . ':' . $dbpass . '@' . $dbhost . '/' . $dbname);
     }
     if (PEAR::isError($this->db)) {
         die($this->db->getMessage() . ' ' . $this->db->getUserInfo());
     }
     $this->db->query('SET NAMES utf8');
 }
Esempio n. 14
0
 function new_MDB2_Driver_Common()
 {
     $options = array("debug" => 2);
     $db = MDB2::singleton(DB_DSN, $options);
     if (PEAR::isError($db)) {
         throw new Exception($db->getMessage());
     }
     $db->setOption("portability", MDB2_PORTABILITY_NONE);
     $db->setFetchMode(MDB2_FETCHMODE_ASSOC);
     $db->exec("SET time_zone=\"-01:00\"");
     $db->query('SET NAMES utf8');
     return $db;
 }
 /**
  * Adds the last_modifed column to the uuid_map table if it is not there
  * @returns true on success
  */
 protected function addLastModifiedColumn()
 {
     $db = MDB2::singleton();
     $rows = $db->queryAll("SHOW FULL COLUMNS FROM `uuid_map` WHERE Field='last_modifed'");
     if (count($rows) > 0) {
         I2CE::raiseError("uuid_map table already has last_modifed");
     } else {
         $qry_alter = "ALTER TABLE `uuid_map` ADD COLUMN   `last_modified` timestamp  NULL DEFAULT CURRENT_TIMESTAMP;";
         if (I2CE::pearError($db->exec($qry_alter), "Error adding parent_id, parent_form column to {$table} table:")) {
             return false;
         }
     }
     return true;
 }
Esempio n. 16
0
 /**
  * @TODO Describe function
  */
 public function setUp()
 {
     $this->validFieldset = $this->readFieldSet("valid1.txt");
     $this->_host = Config::$dbHost;
     $this->_user = Config::$dbUser;
     $this->_pass = Config::$dbPass;
     $this->_database = Config::$dbDatabase;
     $this->_table = Config::$dbTable;
     $dsn = "mysql://{$this->_user}:{$this->_pass}@{$this->_host}/{$this->_database}";
     $this->_dbh =& MDB2::singleton($dsn);
     if (PEAR::isError($this->_dbh)) {
         die($this->_dbh->getMessage());
     }
 }
Esempio n. 17
0
 public function setUp()
 {
     $this->validFieldset = array('payment_date' => urldecode('09%3A12%3A10+Sep+28%2C+2007+PDT'), 'payment_status' => 'Completed', 'payment_type' => 'instant', 'mc_gross' => "15.00", 'mc_currency' => "GBP", 'mc_fee' => "mc_fee TEST", 'first_name' => "testDbUtil", 'last_name' => "User", 'txn_type' => "cart", 'txn_id' => "2WF26980GL452844A", 'address_zip' => 'W12+4LQ', 'address_country_code' => 'GB', 'address_name' => 'Test+User+DbUtil', 'address_status' => 'confirmed', 'address_street' => '1+Main+Terrace', 'address_zip' => 'W12+4LQ', 'address_city' => 'Wolverhampton', 'address_country' => 'United+Kingdom', 'address_state' => 'West+Midlands', 'payer_id' => 'G5KV3TRTXQN6L', 'payer_status' => 'unverified', 'payer_email' => 'paypal_1190066309_per%40dafyddjames.com', 'receiver_email' => 'paypal_1190065579_biz%40dafyddjames.com', 'receiver_id' => 'XLLRP7LLA86KG', 'business' => "business TEST", 'num_cart_items' => "1", 'quantity1' => "2", 'item_name1' => "Test item name");
     $this->_host = Config::$dbHost;
     $this->_user = Config::$dbUser;
     $this->_pass = Config::$dbPass;
     $this->_database = Config::$dbDatabase;
     $this->_table = Config::$dbTable;
     $dsn = "mysql://{$this->_user}:{$this->_pass}@{$this->_host}/{$this->_database}";
     $this->_dbh =& MDB2::singleton($dsn);
     if (PEAR::isError($this->_dbh)) {
         die($this->_dbh->getMessage());
     }
 }
Esempio n. 18
0
 function __construct()
 {
     // Globalizacja tablicy $_CONFIG
     global $_CONFIG;
     //
     $dsn = "mysql://" . $_CONFIG['DB']['user'] . ":" . $_CONFIG['DB']['pass'] . "@" . $_CONFIG['DB']['host'] . "/" . $_CONFIG['DB']['base'];
     $options = array('debug' => 2, 'result_buffering' => false, 'use_transactions' => true, 'portability' => MDB2_PORTABILITY_ALL);
     $this->mdb2 =& MDB2::singleton($dsn, $options);
     if (PEAR::isError($this->mdb2)) {
         echo 'B│╣d po│╣czenia z baz╣ danych!';
         die($this->mdb2->getMessage());
     }
     $this->mdb2->query("SET NAMES 'utf8'");
     $this->dbstate = true;
     //return $this->$mdb2;
 }
Esempio n. 19
0
 function __construct($params)
 {
     if (!isset($this->_dbh) || empty($this->_dbh)) {
         $this->_host = Config::$dbHost;
         $this->_user = Config::$dbUser;
         $this->_pass = Config::$dbPass;
         $this->_database = Config::$dbDatabase;
         $this->_table = Config::$dbTable;
         $dsn = "mysql://{$this->_user}:{$this->_pass}@{$this->_host}/{$this->_database}";
         Logger::debug("Initializing database: mysql://{$this->_user}@{$this->_host}/{$this->_database}");
         $db =& MDB2::singleton($dsn);
         if (PEAR::isError($db)) {
             die($db->getMessage() . ', ' . $db->getDebugInfo());
         }
         $this->_dbh = $db;
     }
 }
    public function createTable()
    {
        $qry = 'CREATE TABLE IF NOT EXISTS form_relationship_importer  (
   hash char(32) NOT NULL,
   relationship text  NOT NULL,
   id text  NOT NULL,
   KEY hash_rey ( hash, relationship (130) )
) ENGINE=InnoDB DEFAULT CHARSET=utf8
';
        $db = MDB2::singleton();
        $result = $db->query($qry);
        if (I2CE::pearError($result, "Cannot execute  query:\n{$qry}")) {
            I2CE::raiseError("Could not create form_relationship_importer table");
            return false;
        }
        return true;
    }
Esempio n. 21
0
function db_conn()
{
    global $portal_db;
    global $db_dsn;
    if (!isset($db_dsn)) {
        $db_dsn = 'pgsql://*****:*****@localhost/portal';
    }
    $db_options = array('debug' => 5, 'result_buffering' => false);
    if ($portal_db == null) {
        $portal_db =& MDB2::singleton($db_dsn, $db_options);
    }
    if (PEAR::isError($portal_db)) {
        error_log("DB ERROR: Error connecting: " . $portal_db);
        die("Error connecting: " . $portal_db);
    }
    return $portal_db;
}
 public function __construct($name)
 {
     parent::__construct($name);
     $this->db = MDB2::singleton();
     $this->setUpStatements();
     $this->db->query("SET SESSION group_concat_max_len = @@max_allowed_packet");
     $res = $this->db->query("SELECT @@group_concat_max_len = @@max_allowed_packet AS use_quick,  @@group_concat_max_len as len");
     if (I2CE::pearError($res, "Bad statement") || !($row = $res->fetchRow())) {
         I2CE::raiseError("Bad group concat check");
         return false;
     }
     if ($row->use_quick) {
         $this->use_quick = true;
     } else {
         I2CE::raiseError("Using slow config_alt retreival.  Please set group_concat_max_len in mysql's config to be the same as max_allowed_packet.  Currently it is set " . $row->len . " to bytes");
     }
 }
Esempio n. 23
0
 function AddDSN($dsn, $name)
 {
     $name = !$name ? "default" : $name;
     $conn =& MDB2::singleton($dsn, array('debug' => '1'));
     if (PEAR::iserror($conn)) {
         die($conn->GetMessage());
     }
     $conn->loadModule('Extended');
     if ($name == 'manager') {
         $conn->loadModule('Reverse', null, true);
         $conn->loadModule('Manager', null, true);
     }
     /* Without the below line, accessor db methods returning "" are interpreted as NULL
        when sent to autoExecute which makes it impossable to put an empty string in a 
        field.*/
     $conn->setOption('portability', MDB2_PORTABILITY_ALL ^ MDB2_PORTABILITY_EMPTY_TO_NULL);
     $this->_connections[$name] =& $conn;
 }
 public function isAvailable()
 {
     if (!$this->m instanceof Mongo) {
         return false;
     }
     $db = MDB2::singleton();
     if (!($db_name = $db->database_name)) {
         I2CE::raiseError("No database to connect to MongoDB");
         return false;
     }
     if (!is_array($dbs = $this->m->listDBs()) || !array_key_exists('databases', $dbs) || !is_array($dbs['databases'])) {
         I2CE::raiseError("MongoDB: {$db_name} needs to be created:" . print_r($dbs, true));
         return false;
     } else {
         $found = false;
         foreach ($dbs['databases'] as $info) {
             if (!is_array($info) || !array_key_exists('name', $info) || !($info['name'] = $db_name)) {
                 continue;
             }
             $found = true;
         }
     }
     if (!$found) {
         I2CE::raiseError("MongoDB: The database {$db_name} needs to be created:" . print_r($dbs, true));
         return false;
     }
     if (!($this->mdb = $this->m->selectDB($db_name)) instanceof MongoDB) {
         I2CE::raiseError("Cannot connect to mongo database {$db_name}");
         return false;
     }
     if (!is_array($mcolls = $this->mdb->listCollections()) || count($mcolls) == 0 || !in_array($db_name . ".config", $mcolls)) {
         I2CE::raiseError("MongoDB: collection {$db_name}.config needs to be created");
         //this is done automatically when we select below
         return false;
     }
     if (!($this->mcoll = $this->mdb->selectCollection('config')) instanceof MongoCollection) {
         I2CE::raiseError("Cannot connect to  config collection in  mongo database {$db_name}");
         return false;
     }
     //I2CE::raiseError("MongoDB is available for config");
     return true;
 }
Esempio n. 25
0
 /**
  * コンストラクタ.
  *
  * @param string  $dsn       データソース名
  * @param boolean $force_run エラーが発生しても処理を続行する場合 true
  * @param boolean $new       新規に接続を行うかどうか
  */
 public function __construct($dsn = '', $force_run = false, $new = false)
 {
     if ($dsn == '') {
         $dsn = array('phptype' => DB_TYPE, 'username' => DB_USER, 'password' => DB_PASSWORD, 'protocol' => 'tcp', 'hostspec' => DB_SERVER, 'port' => DB_PORT, 'database' => DB_NAME);
     }
     // オプション
     $options = array('persistent' => PEAR_DB_PERSISTENT, 'debug' => PEAR_DB_DEBUG, 'result_buffering' => false);
     if ($new) {
         $this->conn = \MDB2::connect($dsn, $options);
     } else {
         $this->conn = \MDB2::singleton($dsn, $options);
     }
     if (!\PEAR::isError($this->conn)) {
         $this->conn->setCharset('utf8');
         $this->conn->setFetchMode(MDB2_FETCHMODE_ASSOC);
     }
     // XXX 上書きインストール時にDBを変更するケースを想定し第1引数を与えている。
     $this->dbFactory = DB\DBFactory::getInstance($this->conn->dsn['phptype']);
     $this->dbFactory->initObjQuery($this);
     $this->force_run = $force_run;
 }
 /**
  * Run the upgrade for this module.
  * @param string $old_vers
  * @param string $new_vers
  * @return boolean
  */
 public function upgrade($old_vers, $new_vers)
 {
     if (I2CE_Validate::checkVersion($old_vers, '<', '4.0.3.2')) {
         I2CE::raiseError("Upgrading sample data for license end_date");
         $db = MDB2::singleton();
         $updated = $db->exec("UPDATE last_entry SET date = NOW(), date_value = '2015-01-01 00:00:00' WHERE form_field = 75 AND date_value = '2010-01-01 00:00:00'");
         if (!I2CE::pearError($updated, "Unable to update license end_date for Qualify Sample Data.")) {
             I2CE::raiseError("Update {$updated} entries.");
             $last_mod = $db->exec("UPDATE record SET last_modified = NOW() WHERE form = 16");
             if (!I2CE::pearError($last_mod, "Unable to update license end_date for Qualify Sample Data record last modified.")) {
                 I2CE::raiseError("Updated {$last_mod} records.");
             } else {
                 return false;
             }
         } else {
             return false;
         }
         I2CE::getConfig()->modules->CachedForms->dirty->license = time();
     }
     return parent::upgrade($old_vers, $new_vers);
 }
Esempio n. 27
0
 /**
  * A method to return a singleton database connection resource.
  *
  * Example usage:
  * $oDbh = OA_DB::singleton();
  *
  * Warning: In order to work correctly, the singleton method must
  * be instantiated statically and by reference, as in the above
  * example.
  *
  * @static
  * @param string $dsn Optional database DSN details - connects to the
  *                    database defined by the configuration file otherwise.
  *                    See {@link OA_DB::getDsn()} for format.
  *
  * @param array $aDriverOptions An optional array of driver options. Currently
  *                              supported options are:
  *                  - For MySQL:
  *                      ['ssl']      = false|true Perform connection over SSL?
  *                      ['ca']       = Name of CA file, if "ssl" true
  *                      ['capath']   = Path to CA file above, is "ssl" true
  *                      ['compress'] = false|true Use client compression?
  *
  * @return MDB2_Driver_Common An MDB2 connection resource, or PEAR_Error
  *                            on failure to connect.
  */
 static function singleton($dsn = null, $aDriverOptions = array())
 {
     $aConf = $GLOBALS['_MAX']['CONF'];
     // Get the driver options, if not set
     if (!is_array($aDriverOptions) || is_null($dsn) && empty($aDriverOptions)) {
         $aDriverOptions = OA_DB::getDsnOptions();
     }
     // Get the DSN, if not set
     $dsn = is_null($dsn) ? OA_DB::getDsn() : $dsn;
     // Check that the parameter is a string, not an array
     if (is_array($dsn)) {
         return Max::raiseError('Bad argument: DSN should be a string', MAX_ERROR_INVALIDARGS);
     }
     // A hack to allow for installation on pgsql
     // If the configuration hasn't been defined prevent
     // loading mysql MDB2 driver.
     if (strpos($dsn, '//:@') !== false) {
         // Return a silent error
         return new PEAR_Error('Bad argument: Empty DSN');
     }
     // Get the database type in use from the DNS, not from the
     // configuration file
     $aDSN = MDB2::parseDSN($dsn);
     $databaseType = $aDSN['phptype'];
     // Is this a MySQL database connection that should happen via SSL?
     if (strcasecmp($databaseType, 'mysql') === 0 && @$aDriverOptions['ssl']) {
         // Modify the DSN string to include the required CA and CAPATH options
         if (!empty($aDriverOptions['ca']) && !empty($aDriverOptions['capath'])) {
             $dsn .= "?ca={$aDriverOptions['ca']}&capth={$aDriverOptions['capath']}";
         }
     }
     // Create an MD5 checksum of the DSN
     $dsnMd5 = md5($dsn);
     // Does this database connection already exist?
     if (isset($GLOBALS['_OA']['CONNECTIONS'])) {
         $aConnections = array_keys($GLOBALS['_OA']['CONNECTIONS']);
     } else {
         $aConnections = array();
     }
     if (!(count($aConnections) > 0) || !in_array($dsnMd5, $aConnections)) {
         // Prepare options for a new database connection
         $aOptions = array();
         // Sequence column name
         $aOptions['seqcol_name'] = 'id';
         // Set the index name format
         $aOptions['idxname_format'] = '%s';
         // Use 4 decimal places in DECIMAL nativetypes
         $aOptions['decimal_places'] = 4;
         // Set the portability options
         $aOptions['portability'] = OA_DB_MDB2_DEFAULT_OPTIONS;
         // Set the default table type for MySQL, if appropriate
         if (strcasecmp($databaseType, 'mysql') === 0) {
             if (!empty($aConf['table']['type'])) {
                 $aOptions['default_table_type'] = $aConf['table']['type'];
                 // Enable transaction support when using InnoDB tables
                 if (strcasecmp($aOptions['default_table_type'], 'innodb') === 0) {
                     // Enable transaction support
                     $aOptions['use_transactions'] = true;
                 }
             }
         } elseif (strcasecmp($databaseType, 'pgsql') === 0) {
             $aOptions['quote_identifier'] = true;
         }
         // Add default charset - custom OpenX
         if (defined('OA_DB_MDB2_DEFAULT_CHARSET')) {
             $aOptions['default_charset'] = OA_DB_MDB2_DEFAULT_CHARSET;
         } else {
             $aOptions['default_charset'] = 'utf8';
         }
         // this will log select queries to a var/sql.log
         // currently used for analysis purposes
         if (isset($aConf['debug']['logSQL']) && $aConf['debug']['logSQL']) {
             $aOptions['log_statements'] = explode('|', $aConf['debug']['logSQL']);
             $aOptions['debug'] = true;
             $aOptions['debug_handler'] = 'logSQL';
         }
         $aOptions += OA_DB::getDatatypeMapOptions();
         // Is this a MySQL database connection?
         if (strcasecmp($databaseType, 'mysql') === 0) {
             // Should this connection happen over SSL?
             if (@$aDriverOptions['ssl']) {
                 $aOptions['ssl'] = true;
             }
         }
         // Create the new database connection
         OA::disableErrorHandling();
         $oDbh = MDB2::singleton($dsn, $aOptions);
         OA::enableErrorHandling();
         if (PEAR::isError($oDbh)) {
             return $oDbh;
         }
         // Is this a MySQL database connection?
         if (strcasecmp($databaseType, 'mysql') === 0) {
             $client_flags = 0;
             // Should this connection happen over SSL?
             if (@$aDriverOptions['ssl']) {
                 $client_flags = $client_flags | MYSQL_CLIENT_SSL;
             }
             // Should this connection use compression?
             if (@$aDriverOptions['compress']) {
                 $client_flags = $client_flags | MYSQL_CLIENT_COMPRESS;
             }
             // Are there any MySQL connection flags to set?
             if ($client_flags != 0) {
                 $oDbh->dsn['client_flags'] = $client_flags;
             }
         }
         OA::disableErrorHandling();
         $success = $oDbh->connect();
         OA::enableErrorHandling();
         if (PEAR::isError($success)) {
             return $success;
         }
         // Set charset if needed
         $success = OA_DB::setCharset($oDbh);
         if (PEAR::isError($success)) {
             return $success;
         }
         // Set schema if needed
         $success = OA_DB::setSchema($oDbh);
         if (PEAR::isError($success)) {
             return $success;
         }
         // Set the fetchmode to be use used
         $oDbh->setFetchMode(MDB2_FETCHMODE_ASSOC);
         // Load modules that are likely to be needed
         $oDbh->loadModule('Extended');
         $oDbh->loadModule('Datatype');
         $oDbh->loadModule('Manager');
         // Store the database connection
         $GLOBALS['_OA']['CONNECTIONS'][$dsnMd5] = $oDbh;
         // Set MySQL 4 compatibility if needed
         if (strcasecmp($databaseType, 'mysql') === 0 && !empty($aConf['database']['mysql4_compatibility'])) {
             $oDbh->exec("SET SESSION sql_mode='MYSQL40'");
         }
     }
     return $GLOBALS['_OA']['CONNECTIONS'][$dsnMd5];
 }
 /**
  *  Construct a query (to be used as a sub-select) to view the fields of the given form.  It always will return the id of the form as well
  *  @param string $form
  *  @param mixed $fields.  Either a string, the field, or an array of string, the fields.
  *  @param mixed $id.  Defaults to null.  If non-null it is the id that we wish to limit to.
  *  @param boolean $parent. Defaults to false.  If true, we include the parent id as a referenced field
  *  If it is scalar and non-boolean, it is consider to be the ID of the parent, and then we get all forms with parent the given id.
  *  @param callback $field_refernece_callback.  A callback function whose first arguement is the form, the second arguements
  *  is the field and which returns the way the field value should be references as a field.  If the callback is null (the default) then
  *  the reference used is "$form+$field"
  *  @param integer $mod_time. Defaults to -1.  If non-negative, we only list the requested fields for an id if at least one of them has a modification
  *    time greater than or equal to $mod_time.  If the form storage has no way of tracking modifucation time, all entries are listed.
  * @param mixed $user The user id of the user to limit the results to so it only returns results limited to that user.  This can be a single value or an array
  *  @returns string the query or false on failed.
  */
 public function getRequiredFieldsQuery($form, $fields, $id = null, $parent = false, $field_reference_callback = null, $mod_time = -1, $user = false)
 {
     if ($fields === null) {
         $fields = array();
     }
     if (is_string($fields)) {
         $fields = array($fields);
     }
     if (!is_array($fields)) {
         I2CE::raiseError("Invalid fields");
         return false;
     }
     if (!($options = $this->getStorageOptions($form))) {
         I2CE::raiseError("No valid multi_flat storage options for {$form}");
         return false;
     }
     if (!is_array($this->databases) || count($this->databases) == 0) {
         I2CE::raiseError("No databases specified");
         return false;
     }
     $formObj = $this->getFormObj($form);
     if (!$formObj instanceof I2CE_Form) {
         I2CE::raiseError("Could not instantiate form {$form}");
         return false;
     }
     if (!in_array($form, $this->componentized_forms)) {
         I2CE::raiseError("Form {$form} is not specified as being componentized.  Valid componentized forms:" . print_r($this->componentized_forms, true));
         return false;
     }
     $table = '';
     $options->setIfIsSet($table, 'table');
     $table = trim($table);
     if (strlen($table) == 0) {
         if (array_key_exists('table_prefix', $this->global_options) && is_string($this->global_options['table_prefix']) && strlen(trim($this->global_options['table_prefix'])) > 0) {
             $table_prefix = trim($this->global_options['table_prefix']);
         } else {
             $table_prefix = 'hippo_';
         }
         $table = $table_prefix . $form;
     }
     if (strlen($table) == 0) {
         I2CE::raiseError("No table specified for {$form}");
         return false;
     }
     $id_ref = false;
     if ($field_reference_callback != null) {
         if (!is_string($id_ref = call_user_func($field_reference_callback, $form, 'id'))) {
             I2CE::raiseError("Invalid field reference callback function");
             return false;
         }
     } else {
         $id_ref = "`{$form}+id`";
     }
     $id_qry = 'id';
     if ($options->is_parent('id')) {
         $id_qry = $this->getFieldData($options->id);
     }
     $form_prepended = true;
     $options->setIfIsSet($form_prepended, "id/form_prepended");
     $unions = array();
     $p_componentized = false;
     if (is_scalar($id)) {
         if (($pos = strrpos($id, '@')) === false) {
             //get the last @ sign
             I2CE::raiseError("No component specified in id: {$id} for form {$form}");
             return false;
         }
         $component = substr($id, $pos + 1);
         $id_no_comp = substr($id, 0, $pos);
         if (strlen($component) == 0) {
             I2CE::raiseError("zero length component specified in id:{$id}");
             return false;
         }
         if (!array_key_exists($component, $this->databases)) {
             I2CE::raiseError("Component {$component} is not associated to a database in id {$id} for form {$form}");
             return false;
         }
         $databases = array($component => $this->databases[$component]);
         $componentParentForms = array_intersect(I2CE_Form::getAllowedParentForms($form), $this->componentized_forms);
     } else {
         if (!is_bool($parent) && is_scalar($parent)) {
             list($p_form, $p_id) = explode('|', $parent, 2);
             if (strlen($p_form) == 0) {
                 I2CE::raiseError("sNo parent form given in {$parent}");
                 return false;
             }
             if (strlen($p_id) == 0) {
                 I2CE::raiseError("No parent id given in {$parent}");
                 return false;
             }
             if (in_array($p_form, $this->componentized_forms)) {
                 $p_componentized = true;
                 if (($pos = strrpos($p_id, '@')) === false) {
                     //get the last @ sign
                     I2CE::raiseError("No component specified in parent id: {$parent}");
                     return false;
                 }
                 $component = substr($p_id, $pos + 1);
                 $p_id_no_comp = substr($p_id, 0, $pos);
                 if (strlen($component) == 0) {
                     I2CE::raiseError("zero length component specified in parent id:{$parent}");
                     return false;
                 }
                 if (!array_key_exists($component, $this->databases)) {
                     I2CE::raiseError("Component {$component} is not associated to a database in parent id: {$parent}");
                     return false;
                 }
                 $databases = array($component => $this->databases[$component]);
                 $componentParentForms = array($p_form);
             } else {
                 $componentParentForms = array_intersect(I2CE_Form::getAllowedParentForms($form), $this->componentized_forms);
             }
         } else {
             $databases = $this->databases;
             $componentParentForms = array_intersect(I2CE_Form::getAllowedParentForms($form), $this->componentized_forms);
         }
     }
     //now verify that the databases and associated table are indeed present:
     $db = MDB2::singleton();
     foreach ($databases as $component => $database) {
         $check_qry = "SELECT null FROM information_schema.TABLES WHERE TABLE_SCHEMA = '" . addslashes($database) . "'" . " AND TABLE_NAME = '" . addslashes($table) . "'";
         $result = $db->query($check_qry);
         if (I2CE::pearError($result, "Cannot execute  query:\n{$check_qry}")) {
             return false;
         }
         if ($result->numRows() > 0) {
             //the table exists.
             continue;
         }
         unset($databases[$component]);
     }
     if (count($databases) == 0) {
         I2CE::raiseError("No databases defined for multi-flat formstorage on table {$table}");
         return false;
     }
     foreach ($databases as $component => $database) {
         $select_list = array();
         if ($form_prepended) {
             $select_list[] = "CONCAT( SUBSTRING(" . $id_qry . "," . (strlen($form) + 2) . "),'@','" . mysql_real_escape_string($component) . "') AS {$id_ref}";
         } else {
             $select_list[] = "CONCAT( " . $id_qry . ",'@','" . mysql_real_escape_string($component) . "') AS {$id_ref}";
         }
         foreach ($formObj as $field => $fieldObj) {
             if (!in_array($field, $fields)) {
                 continue;
             }
             if (!$fieldObj->isInDB()) {
                 continue;
             }
             if ($options->is_parent("fields/{$field}")) {
                 $data = $options->traverse("fields/{$field}");
                 if ($data->is_scalar('enabled') && !$data->enabled) {
                     continue;
                 }
                 $f_qry = $this->getFieldData($data, $database, $table);
             } else {
                 if (!$this->hasColumn($field, $database, $table)) {
                     $f_qry = ' NULL ';
                 } else {
                     $f_qry = "`{$field}`";
                     //default to the field name
                 }
             }
             if ($fieldObj instanceof I2CE_FormField_MAPPED) {
                 $comp_map_forms = array_intersect($fieldObj->getSelectableForms(), $this->componentized_forms);
                 $f_qry = $fieldObj->getSQLComponentization($f_qry, $comp_map_forms, $component);
             }
             $f_ref = false;
             if ($field_reference_callback != null) {
                 if (!is_string($f_ref = call_user_func($field_reference_callback, $form, $field))) {
                     I2CE::raiseError("Invalid field reference callback function");
                     return false;
                 }
             } else {
                 $f_ref = "`{$form}+{$field}`";
             }
             $select_list[] = "{$f_qry} AS {$f_ref}";
         }
         $wheres = array();
         if (is_array($mod_time) && array_key_exists('mod_time', $mod_time)) {
             $mod_time = $mod_time['mod_time'];
         }
         $get_mod_time = is_scalar($mod_time) && $mod_time >= 0 || in_array('last_modified', $fields);
         if ($get_mod_time) {
             if ($options->is_scalar('last_modified/enabled') && !$options->last_modified->enabled) {
                 $mod_qry = "NULL";
             } else {
                 if ($options->is_scalar('last_modified/col') && $options->last_modified->col) {
                     if ($this->hasColumn($options->last_modified->col, $database, $table)) {
                         $mod_qry = $options->last_modified->col;
                     } else {
                         $mod_qry = 'NULL';
                     }
                 } else {
                     if ($options->is_scalar('last_modified/function') && $options->last_modified->function) {
                         $mod_qry = $options->last_modified->function;
                     } else {
                         if ($this->hasColumn('last_modified', $database, $table)) {
                             $mod_qry = " last_modified ";
                         } else {
                             //perhaps we are using a hippo_XXX table which does not have a last_modified column
                             $mod_qry = 'NULL';
                         }
                     }
                 }
             }
             if ($field_reference_callback !== null) {
                 if (!is_string($mod_ref = call_user_func($field_reference_callback, $form, 'last_modified'))) {
                     I2CE::raiseError("Invalid parent reference callback function:\nlast_modified --> {$mod_ref}");
                     return false;
                 }
             } else {
                 $mod_ref = '`' . $form . '+last_modified`';
             }
             $select_list[] = "{$mod_qry} AS {$mod_ref}";
             if (is_scalar($mod_time) && $mod_time >= 0) {
                 $wheres[] = "({$mod_qry} IS NULL OR {$mod_qry} > FROM_UNIXTIME(" . $mod_time . "))";
             }
         }
         if ($parent !== false || in_array($parent, $fields)) {
             $p_qry = false;
             $p_ref = false;
             if ($field_reference_callback != null) {
                 if (!is_string($p_ref = call_user_func($field_reference_callback, $form, 'parent'))) {
                     I2CE::raiseError("Invalid field reference callback function");
                     return false;
                 }
             } else {
                 $p_ref = "`{$form}+parent`";
             }
             if (!$options->is_scalar('parent/enabled') || $options->parent->enabled) {
                 if ($options->is_parent('parent')) {
                     $p_qry = $this->getFieldData($options->parent);
                 }
                 if ($p_qry === false) {
                     $p_qry = 'parent';
                 }
             } else {
                 $p_qry = '0';
             }
             $select_list[] = I2CE_List::componentizeQuery($p_qry, $componentParentForms, $component) . " AS {$p_ref}";
             if (!is_bool($parent) && is_scalar($parent)) {
                 if (!$p_componentized) {
                     $wheres[] = " ( " . I2CE_List::componentizeQuery($p_qry, $componentParentForms, $component) . " = '" . mysql_real_escape_string($parent) . "' ) ";
                 } else {
                     $wheres[] = " ( {$p_qry} = '" . mysql_real_escape_string($p_form . '|' . $p_id_no_comp) . "') ";
                 }
             }
         }
         //want either select id as `form+id`, name as `form+name` from table
         //or select id as `form+id`, name as `form+name` from (select * from table where id=5)
         //select  substr(my_id,1,4) as `form+id`, surname as `form+name` from (select * from table where id=5)
         //or with a function..
         //select id as `form+id`, substr(surname,1,3) as `form+name` from table
         //select  id as `form+id`, substr(surname,1,3) as `form+name` from (select * from table where id=5)
         //select  substr(my_id,1,4) as `form+id`, surname as `form+name` from table wher `form+id`
         $qry = 'SELECT ' . implode(',', $select_list) . " FROM `{$database}`.`{$table}`";
         if (is_scalar($id)) {
             if ($form_prepended) {
                 $wheres[] = " ({$id_qry} ='" . mysql_real_escape_string($form . '|' . $id_no_comp) . "') ";
             } else {
                 $wheres[] = " ({$id_qry} ='" . mysql_real_escape_string($id_no_comp) . "') ";
             }
         }
         if (count($wheres) > 0) {
             $qry .= ' WHERE (' . implode("AND", $wheres) . ")";
         }
         $unions[] = $qry;
     }
     if (count($databases) > 1) {
         foreach ($unions as &$union) {
             $union = '(' . $union . ')';
         }
         //I2CE::raiseError("QRY:" . implode('UNION' ,$unions));
         return implode('UNION', $unions);
     } else {
         reset($unions);
         //I2CE::raiseError("QRY:" . current($unions));
         return current($unions);
     }
 }
 /**
  * Create a new instance of a dhis user access mechanism
  */
 public function __construct()
 {
     parent::__construct();
     $this->db = MDB2::singleton();
     $this->passTable = $this->options['passTable'];
     $this->accessTable = $this->options['accessTable'];
     $this->logTable = $this->options['logTable'];
     $this->detailTable = $this->options['detailTable'];
 }
 function testSingleton()
 {
     $db =& MDB2::singleton();
     $this->assertTrue(MDB2::isConnection($db));
     // should have a different database name set
     $db =& MDB2::singleton($this->dsn, $this->options);
     $this->assertTrue($db->db_index != $this->db->db_index);
 }