Esempio n. 1
0
/**
 * Creates global database connection.
 *
 * @param string $error returns a message in case of an error
 * @param bool   $debug turns On or Off trace calls when making connections. Suggested debug mode Off during Zabbix setup
 *
 * @return bool
 */
function DBconnect(&$error)
{
    global $DB;
    if (isset($DB['DB'])) {
        $error = _('Cannot create another database connection.');
        return false;
    }
    $result = true;
    $DB['DB'] = null;
    // global db handler
    $DB['TRANSACTIONS'] = 0;
    // level of a nested transation
    $DB['TRANSACTION_NO_FAILED_SQLS'] = true;
    // true - if no statements failed in transaction, false - there are failed statements
    $DB['SELECT_COUNT'] = 0;
    // stats
    $DB['EXECUTE_COUNT'] = 0;
    if (!isset($DB['TYPE'])) {
        $error = 'Unknown database type.';
        $result = false;
    } else {
        $DB['TYPE'] = strtoupper($DB['TYPE']);
        switch ($DB['TYPE']) {
            case ZBX_DB_MYSQL:
                $DB['DB'] = @mysqli_connect($DB['SERVER'], $DB['USER'], $DB['PASSWORD'], $DB['DATABASE'], $DB['PORT']);
                if (!$DB['DB']) {
                    $error = 'Error connecting to database: ' . trim(mysqli_connect_error());
                    $result = false;
                } else {
                    DBexecute('SET NAMES utf8');
                }
                if ($result) {
                    $dbBackend = new MysqlDbBackend();
                }
                break;
            case ZBX_DB_POSTGRESQL:
                $pg_connection_string = (!empty($DB['SERVER']) ? 'host=\'' . pg_connect_escape($DB['SERVER']) . '\' ' : '') . 'dbname=\'' . pg_connect_escape($DB['DATABASE']) . '\' ' . (!empty($DB['USER']) ? 'user=\'' . pg_connect_escape($DB['USER']) . '\' ' : '') . (!empty($DB['PASSWORD']) ? 'password=\'' . pg_connect_escape($DB['PASSWORD']) . '\' ' : '') . (!empty($DB['PORT']) ? 'port=' . pg_connect_escape($DB['PORT']) : '');
                $DB['DB'] = @pg_connect($pg_connection_string);
                if (!$DB['DB']) {
                    $error = 'Error connecting to database.';
                    $result = false;
                } else {
                    $schemaSet = DBexecute('SET search_path = ' . zbx_dbstr($DB['SCHEMA'] ? $DB['SCHEMA'] : 'public'), true);
                    if (!$schemaSet) {
                        clear_messages();
                        $error = pg_last_error();
                        $result = false;
                    } else {
                        if (false !== ($pgsql_version = pg_parameter_status('server_version'))) {
                            if ((int) $pgsql_version >= 9) {
                                // change the output format for values of type bytea from hex (the default) to escape
                                DBexecute('SET bytea_output = escape');
                            }
                        }
                    }
                }
                if ($result) {
                    $dbBackend = new PostgresqlDbBackend();
                }
                break;
            case ZBX_DB_ORACLE:
                $connect = '';
                if (!empty($DB['SERVER'])) {
                    $connect = '//' . $DB['SERVER'];
                    if ($DB['PORT'] != '0') {
                        $connect .= ':' . $DB['PORT'];
                    }
                    if ($DB['DATABASE']) {
                        $connect .= '/' . $DB['DATABASE'];
                    }
                }
                $DB['DB'] = @oci_connect($DB['USER'], $DB['PASSWORD'], $connect);
                if ($DB['DB']) {
                    DBexecute('ALTER SESSION SET NLS_NUMERIC_CHARACTERS=' . zbx_dbstr('. '));
                } else {
                    $ociError = oci_error();
                    $error = 'Error connecting to database: ' . $ociError['message'];
                    $result = false;
                }
                if ($result) {
                    $dbBackend = new OracleDbBackend();
                }
                break;
            case ZBX_DB_DB2:
                $connect = '';
                $connect .= 'DATABASE=' . $DB['DATABASE'] . ';';
                $connect .= 'HOSTNAME=' . $DB['SERVER'] . ';';
                $connect .= 'PORT=' . $DB['PORT'] . ';';
                $connect .= 'PROTOCOL=TCPIP;';
                $connect .= 'UID=' . $DB['USER'] . ';';
                $connect .= 'PWD=' . $DB['PASSWORD'] . ';';
                $DB['DB'] = @db2_connect($connect, $DB['USER'], $DB['PASSWORD']);
                if (!$DB['DB']) {
                    $error = 'Error connecting to database: ' . db2_conn_errormsg();
                    $result = false;
                } else {
                    $options = array('db2_attr_case' => DB2_CASE_LOWER);
                    db2_set_option($DB['DB'], $options, 1);
                    if (isset($DB['SCHEMA']) && $DB['SCHEMA'] != '') {
                        DBexecute('SET CURRENT SCHEMA=' . zbx_dbstr($DB['SCHEMA']));
                    }
                }
                if ($result) {
                    $dbBackend = new Db2DbBackend();
                }
                break;
            case ZBX_DB_SQLITE3:
                if (file_exists($DB['DATABASE'])) {
                    init_sqlite3_access();
                    lock_sqlite3_access();
                    try {
                        $DB['DB'] = @new SQLite3($DB['DATABASE'], SQLITE3_OPEN_READWRITE);
                    } catch (Exception $e) {
                        $error = 'Error connecting to database.';
                        $result = false;
                    }
                    unlock_sqlite3_access();
                } else {
                    $error = 'Missing database';
                    $result = false;
                }
                if ($result) {
                    $dbBackend = new SqliteDbBackend();
                }
                break;
            default:
                $error = 'Unsupported database';
                $result = false;
        }
    }
    if ($result && !$dbBackend->checkDbVersion()) {
        $error = $dbBackend->getError();
        $result = false;
    }
    if (false == $result) {
        $DB['DB'] = null;
    }
    return $result;
}
Esempio n. 2
0
 /**
  * Opens a database connection and returns it
  * Closes any existing connection
  * @return a fresh connection
  * @param $server String: hostname
  * @param $user String
  * @param $password String
  * @param $dbName String: database name
  */
 public function open($server, $user, $password, $dbName)
 {
     // Load the port number
     global $wgDBport_db2, $wgDBcataloged;
     wfProfileIn(__METHOD__);
     // Load IBM DB2 driver if missing
     if (!@extension_loaded('ibm_db2')) {
         @dl('ibm_db2.so');
     }
     // Test for IBM DB2 support, to avoid suppressed fatal error
     if (!function_exists('db2_connect')) {
         $error = "DB2 functions missing, have you enabled the ibm_db2 extension for PHP?\n";
         $this->installPrint($error);
         $this->reportConnectionError($error);
     }
     if (!strlen($user)) {
         // Copied from Postgres
         return null;
     }
     // Close existing connection
     $this->close();
     // Cache conn info
     $this->mServer = $server;
     $this->mPort = $port = $wgDBport_db2;
     $this->mUser = $user;
     $this->mPassword = $password;
     $this->mDBname = $dbName;
     $this->mCataloged = $cataloged = $wgDBcataloged;
     if ($cataloged == self::CATALOGED) {
         $this->openCataloged($dbName, $user, $password);
     } elseif ($cataloged == self::UNCATALOGED) {
         $this->openUncataloged($dbName, $user, $password, $server, $port);
     }
     // Apply connection config
     db2_set_option($this->mConn, $this->mConnOptions, 1);
     // Not all MediaWiki code is transactional
     // Rather, turn autocommit off in the begin function and turn on after a commit
     db2_autocommit($this->mConn, DB2_AUTOCOMMIT_ON);
     if ($this->mConn == false) {
         $this->installPrint("DB connection error\n");
         $this->installPrint("Server: {$server}, Database: {$dbName}, User: {$user}, Password: "******"...\n");
         $this->installPrint($this->lastError() . "\n");
         return null;
     }
     $this->mOpened = true;
     $this->applySchema();
     wfProfileOut(__METHOD__);
     return $this->mConn;
 }
Esempio n. 3
0
    /**
     * Opens a database connection and returns it
     * Closes any existing connection
     *
     * @param $server String: hostname
     * @param $user String
     * @param $password String
     * @param $dbName String: database name
     * @return a fresh connection
     */
    public function open($server, $user, $password, $dbName)
    {
        // Load the port number
        global $wgDBport;
        wfProfileIn(__METHOD__);
        // Load IBM DB2 driver if missing
        wfDl('ibm_db2');
        // Test for IBM DB2 support, to avoid suppressed fatal error
        if (!function_exists('db2_connect')) {
            $error = <<<ERROR
DB2 functions missing, have you enabled the ibm_db2 extension for PHP?

ERROR;
            $this->installPrint($error);
            $this->reportConnectionError($error);
        }
        if (strlen($user) < 1) {
            wfProfileOut(__METHOD__);
            return null;
        }
        // Close existing connection
        $this->close();
        // Cache conn info
        $this->mServer = $server;
        $this->mPort = $port = $wgDBport;
        $this->mUser = $user;
        $this->mPassword = $password;
        $this->mDBname = $dbName;
        $this->openUncataloged($dbName, $user, $password, $server, $port);
        // Apply connection config
        db2_set_option($this->mConn, $this->mConnOptions, 1);
        // Some MediaWiki code is still transaction-less (?).
        // The strategy is to keep AutoCommit on for that code
        //  but switch it off whenever a transaction is begun.
        db2_autocommit($this->mConn, DB2_AUTOCOMMIT_ON);
        if (!$this->mConn) {
            $this->installPrint("DB connection error\n");
            $this->installPrint("Server: {$server}, Database: {$dbName}, User: {$user}, Password: "******"...\n");
            $this->installPrint($this->lastError() . "\n");
            wfProfileOut(__METHOD__);
            return null;
        }
        $this->mOpened = true;
        $this->applySchema();
        wfProfileOut(__METHOD__);
        return $this->mConn;
    }
Esempio n. 4
0
function db2_operate($query, array $args = array(), array $options = array())
{
    global $db2_conn;
    if (!$db2_conn) {
        $conn_string = variable_get('simsauth_connect_string');
        $db2_conn = db2_pconnect($conn_string, '', '');
    }
    if (!empty($args)) {
        $stmt = db2_prepare($db2_conn, $query);
        if (!empty($options)) {
            $op_result = db2_set_option($stmt, $options, 2);
            if (!$op_result) {
                debug(db2_stmt_errormsg(), 'simsauth');
            }
        }
        $result = db2_execute($stmt, $args);
        if (!$result) {
            debug(db2_stmt_errormsg(), 'simsauth');
        } else {
            return TRUE;
        }
    } else {
        if (!empty($options)) {
            $op_result = db2_set_option($db2_conn, $options, 1);
            if (!$op_result) {
                debug(db2_conn_errormsg(), 'simsauth');
            }
        }
        $rs = db2_exec($db2_conn, $query);
        if (!$rs) {
            debug(db2_conn_errormsg(), 'simsauth');
        } else {
            return TRUE;
        }
    }
    return FALSE;
}
Esempio n. 5
0
function DBconnect(&$error)
{
    $result = true;
    global $DB;
    $DB['DB'] = null;
    $DB['TRANSACTIONS'] = 0;
    //Stats
    $DB['SELECT_COUNT'] = 0;
    $DB['EXECUTE_COUNT'] = 0;
    //SDI('type: '.$DB['TYPE'].'; server: '.$DB['SERVER'].'; port: '.$DB['PORT'].'; db: '.$DB['DATABASE'].'; usr: '******'USER'].'; pass: '******'PASSWORD']);
    if (!isset($DB['TYPE'])) {
        $error = "Unknown database type.";
        $result = false;
    } else {
        $DB['TYPE'] = zbx_strtoupper($DB['TYPE']);
        switch ($DB['TYPE']) {
            case 'MYSQL':
                $mysql_server = $DB['SERVER'] . (!empty($DB['PORT']) ? ':' . $DB['PORT'] : '');
                if (!($DB['DB'] = mysql_connect($mysql_server, $DB['USER'], $DB['PASSWORD']))) {
                    $error = 'Error connecting to database [' . mysql_error() . ']';
                    $result = false;
                } else {
                    if (!mysql_select_db($DB['DATABASE'])) {
                        $error = 'Error database in selection [' . mysql_error() . ']';
                        $result = false;
                    } else {
                        DBexecute('SET NAMES utf8');
                        DBexecute('SET CHARACTER SET utf8');
                    }
                }
                break;
            case 'POSTGRESQL':
                $pg_connection_string = (!empty($DB['SERVER']) ? 'host=\'' . $DB['SERVER'] . '\' ' : '') . 'dbname=\'' . $DB['DATABASE'] . '\' ' . (!empty($DB['USER']) ? 'user=\'' . $DB['USER'] . '\' ' : '') . (!empty($DB['PASSWORD']) ? 'password=\'' . $DB['PASSWORD'] . '\' ' : '') . (!empty($DB['PORT']) ? 'port=' . $DB['PORT'] : '');
                $DB['DB'] = pg_connect($pg_connection_string);
                if (!$DB['DB']) {
                    $error = 'Error connecting to database';
                    $result = false;
                }
                break;
            case 'ORACLE':
                $connect = '';
                if (!empty($DB['SERVER'])) {
                    $connect = '//' . $DB['SERVER'];
                    if ($DB['PORT'] != '0') {
                        $connect .= ':' . $DB['PORT'];
                    }
                    if ($DB['DATABASE']) {
                        $connect .= '/' . $DB['DATABASE'];
                    }
                }
                $DB['DB'] = ociplogon($DB['USER'], $DB['PASSWORD'], $connect);
                //					$DB['DB']= ociplogon($DB['USER'], $DB['PASSWORD'], '(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST='.$DB['SERVER'].')(PORT=1521))(CONNECT_DATA=(SERVICE_NAME='.$DB['DATABASE'].')))');
                if (!$DB['DB']) {
                    $error = 'Error connecting to database';
                    $result = false;
                }
                break;
            case 'IBM_DB2':
                $connect = '';
                $connect .= 'DATABASE=' . $DB['DATABASE'] . ';';
                $connect .= 'HOSTNAME=' . $DB['SERVER'] . ';';
                $connect .= 'PORT=' . $DB['PORT'] . ';';
                $connect .= 'PROTOCOL=TCPIP;';
                $connect .= 'UID=' . $DB['USER'] . ';';
                $connect .= 'PWD=' . $DB['PASSWORD'] . ';';
                $DB['DB'] = db2_connect($connect, $DB['USER'], $DB['PASSWORD']);
                if (!$DB['DB']) {
                    $error = 'Error connecting to database';
                    $result = false;
                } else {
                    $options = array('db2_attr_case' => DB2_CASE_LOWER);
                    db2_set_option($DB['DB'], $options, 1);
                    if (isset($DB['SCHEMA']) && $DB['SCHEMA'] != '') {
                        DBexecute("SET CURRENT SCHEMA='" . $DB['SCHEMA'] . "'");
                    }
                }
                break;
            case 'SQLITE3':
                $DB['TRANSACTIONS'] = 0;
                if (!function_exists('init_db_access')) {
                    function init_db_access()
                    {
                        global $DB, $ZBX_SEM_ID;
                        $ZBX_SEM_ID = false;
                        if (function_exists('ftok') && function_exists('sem_get') && file_exists($DB['DATABASE'])) {
                            $ZBX_SEM_ID = sem_get(ftok($DB['DATABASE'], 'z'), 1);
                        }
                    }
                }
                if (!function_exists('lock_db_access')) {
                    function lock_db_access()
                    {
                        global $ZBX_SEM_ID;
                        if ($ZBX_SEM_ID && function_exists('sem_acquire')) {
                            sem_acquire($ZBX_SEM_ID);
                        }
                    }
                }
                if (!function_exists('unlock_db_access')) {
                    function unlock_db_access()
                    {
                        global $ZBX_SEM_ID;
                        if ($ZBX_SEM_ID && function_exists('sem_release')) {
                            sem_release($ZBX_SEM_ID);
                        }
                    }
                }
                if (!function_exists('free_db_access')) {
                    function free_db_access()
                    {
                        global $ZBX_SEM_ID;
                        if ($ZBX_SEM_ID && function_exists('sem_remove')) {
                            sem_remove($ZBX_SEM_ID);
                        }
                        $ZBX_SEM_ID = false;
                    }
                }
                if (file_exists($DB['DATABASE'])) {
                    $DB['DB'] = sqlite3_open($DB['DATABASE']);
                    if (!$DB['DB']) {
                        $error = 'Error connecting to database';
                        $result = false;
                    }
                } else {
                    $error = 'Missing database';
                    $result = false;
                }
                init_db_access();
                break;
            default:
                $error = 'Unsupported database';
                $result = false;
        }
    }
    if (false == $result) {
        $DB['DB'] = null;
    }
    return $result;
}