Example #1
1
 /**
  * Connect to a database and log in as the specified user.
  *
  * @param string $dsn the data source name (see DB::parseDSN for syntax)
  * @param boolean $persistent (optional) whether the connection should
  *                            be persistent
  * @return mixed DB_OK on success, a DB error on failure
  * @access public
  */
 function connect($dsninfo, $persistent = false)
 {
     if (!DB::assertExtension('mysqli')) {
         return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
     }
     $this->dsn = $dsninfo;
     $conn = false;
     @ini_set('track_errors', true);
     if ($this->getOption('ssl') === true) {
         $init = mysqli_init();
         mysqli_ssl_set($init, empty($dsninfo['key']) ? null : $dsninfo['key'], empty($dsninfo['cert']) ? null : $dsninfo['cert'], empty($dsninfo['ca']) ? null : $dsninfo['ca'], empty($dsninfo['capath']) ? null : $dsninfo['capath'], empty($dsninfo['cipher']) ? null : $dsninfo['cipher']);
         if ($conn = @mysqli_real_connect($init, $dsninfo['hostspec'], $dsninfo['username'], $dsninfo['password'], $dsninfo['database'], $dsninfo['port'], $dsninfo['socket'])) {
             $conn = $init;
         }
     } else {
         $conn = @mysqli_connect($dsninfo['hostspec'], $dsninfo['username'], $dsninfo['password'], $dsninfo['database'], $dsninfo['port'], $dsninfo['socket']);
     }
     @ini_restore('track_errors');
     if (!$conn) {
         if (($err = @mysqli_connect_error()) != '') {
             return $this->raiseError(DB_ERROR_CONNECT_FAILED, null, null, null, $err);
         } elseif (empty($php_errormsg)) {
             return $this->raiseError(DB_ERROR_CONNECT_FAILED);
         } else {
             return $this->raiseError(DB_ERROR_CONNECT_FAILED, null, null, null, $php_errormsg);
         }
     }
     if ($dsninfo['database']) {
         $this->_db = $dsninfo['database'];
     }
     $this->connection = $conn;
     return DB_OK;
 }
Example #2
0
 /**
  * Connect to the database
  *
  * @return true on success, MDB2 Error Object on failure
  */
 function connect()
 {
     if (is_object($this->connection)) {
         if (count(array_diff($this->connected_dsn, $this->dsn)) == 0) {
             return MDB2_OK;
         }
         $this->connection = 0;
     }
     if (!PEAR::loadExtension($this->phptype)) {
         return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null, 'extension ' . $this->phptype . ' is not compiled into PHP', __FUNCTION__);
     }
     if ($this->options['ssl']) {
         $init = @mysqli_init();
         @mysqli_ssl_set($init, empty($this->dsn['key']) ? null : $this->dsn['key'], empty($this->dsn['cert']) ? null : $this->dsn['cert'], empty($this->dsn['ca']) ? null : $this->dsn['ca'], empty($this->dsn['capath']) ? null : $this->dsn['capath'], empty($this->dsn['cipher']) ? null : $this->dsn['cipher']);
         if ($connection = @mysqli_real_connect($init, $this->dsn['hostspec'], $this->dsn['username'], $this->dsn['password'], $this->database_name, $this->dsn['port'], $this->dsn['socket'])) {
             $connection = $init;
         }
     } else {
         $connection = @mysqli_connect($this->dsn['hostspec'], $this->dsn['username'], $this->dsn['password'], $this->database_name, $this->dsn['port'], $this->dsn['socket']);
     }
     if (!$connection) {
         if (($err = @mysqli_connect_error()) != '') {
             return $this->raiseError(null, null, null, $err, __FUNCTION__);
         } else {
             return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null, 'unable to establish a connection', __FUNCTION__);
         }
     }
     if (!empty($this->dsn['charset'])) {
         $result = $this->setCharset($this->dsn['charset'], $connection);
         if (PEAR::isError($result)) {
             return $result;
         }
     }
     $this->connection = $connection;
     $this->connected_dsn = $this->dsn;
     $this->connected_database_name = $this->database_name;
     $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;
     $this->supported['transactions'] = $this->options['use_transactions'];
     if ($this->options['default_table_type']) {
         switch (strtoupper($this->options['default_table_type'])) {
             case 'BLACKHOLE':
             case 'MEMORY':
             case 'ARCHIVE':
             case 'CSV':
             case 'HEAP':
             case 'ISAM':
             case 'MERGE':
             case 'MRG_ISAM':
             case 'ISAM':
             case 'MRG_MYISAM':
             case 'MYISAM':
                 $this->supported['transactions'] = false;
                 $this->warnings[] = $this->options['default_table_type'] . ' is not a supported default table type';
                 break;
         }
     }
     $this->_getServerCapabilities();
     return MDB2_OK;
 }
Example #3
0
 /**
  * connects to the database server
  *
  * @param string $user                 mysql user name
  * @param string $password             mysql user password
  * @param bool   $is_controluser       whether this is a control user connection
  * @param array  $server               host/port/socket/persistent
  * @param bool   $auxiliary_connection (when true, don't go back to login if
  *                                     connection fails)
  *
  * @return mixed false on error or a mysqli object on success
  */
 public function connect($user, $password, $is_controluser = false, $server = null, $auxiliary_connection = false)
 {
     global $cfg;
     $server_port = $GLOBALS['dbi']->getServerPort($server);
     if ($server_port === null) {
         $server_port = 0;
     }
     $server_socket = $GLOBALS['dbi']->getServerSocket($server);
     if ($server) {
         $server['host'] = empty($server['host']) ? 'localhost' : $server['host'];
     }
     // NULL enables connection to the default socket
     $link = mysqli_init();
     mysqli_options($link, MYSQLI_OPT_LOCAL_INFILE, true);
     $client_flags = 0;
     /* Optionally compress connection */
     if ($cfg['Server']['compress'] && defined('MYSQLI_CLIENT_COMPRESS')) {
         $client_flags |= MYSQLI_CLIENT_COMPRESS;
     }
     /* Optionally enable SSL */
     if ($cfg['Server']['ssl'] && defined('MYSQLI_CLIENT_SSL')) {
         mysqli_ssl_set($link, $cfg['Server']['ssl_key'], $cfg['Server']['ssl_cert'], $cfg['Server']['ssl_ca'], $cfg['Server']['ssl_ca_path'], $cfg['Server']['ssl_ciphers']);
         $ssl_flag = MYSQLI_CLIENT_SSL;
         /*
          * disables SSL certificate validation on mysqlnd for MySQL 5.6 or later
          * @link https://bugs.php.net/bug.php?id=68344
          * @link https://github.com/phpmyadmin/phpmyadmin/pull/11838
          */
         if (!$cfg['Server']['ssl_verify'] && defined('MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT')) {
             $ssl_flag = MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT;
         }
         $client_flags |= $ssl_flag;
     }
     if (!$server) {
         $return_value = @$this->_realConnect($link, $cfg['Server']['host'], $user, $password, false, $server_port, $server_socket, $client_flags);
         // Retry with empty password if we're allowed to
         if ($return_value == false && isset($cfg['Server']['nopassword']) && $cfg['Server']['nopassword'] && !$is_controluser) {
             $return_value = @$this->_realConnect($link, $cfg['Server']['host'], $user, '', false, $server_port, $server_socket, $client_flags);
         }
     } else {
         $return_value = @$this->_realConnect($link, $server['host'], $user, $password, false, $server_port, $server_socket);
     }
     if ($return_value === false) {
         return false;
     }
     return $link;
 }
 /**
  * connects to the database server
  *
  * @param string $user                 mysql user name
  * @param string $password             mysql user password
  * @param bool   $is_controluser       whether this is a control user connection
  * @param array  $server               host/port/socket/persistent
  * @param bool   $auxiliary_connection (when true, don't go back to login if
  *                                     connection fails)
  *
  * @return mixed false on error or a mysqli object on success
  */
 public function connect($user, $password, $is_controluser = false, $server = null, $auxiliary_connection = false)
 {
     global $cfg;
     $server_port = $GLOBALS['dbi']->getServerPort($server);
     $server_socket = $GLOBALS['dbi']->getServerSocket($server);
     if ($server) {
         $server['host'] = empty($server['host']) ? 'localhost' : $server['host'];
     }
     // NULL enables connection to the default socket
     $link = mysqli_init();
     mysqli_options($link, MYSQLI_OPT_LOCAL_INFILE, true);
     $client_flags = 0;
     /* Optionally compress connection */
     if ($cfg['Server']['compress'] && defined('MYSQLI_CLIENT_COMPRESS')) {
         $client_flags |= MYSQLI_CLIENT_COMPRESS;
     }
     /* Optionally enable SSL */
     if ($cfg['Server']['ssl'] && defined('MYSQLI_CLIENT_SSL')) {
         mysqli_ssl_set($link, $cfg['Server']['ssl_key'], $cfg['Server']['ssl_cert'], $cfg['Server']['ssl_ca'], $cfg['Server']['ssl_ca_path'], $cfg['Server']['ssl_ciphers']);
         $client_flags |= MYSQLI_CLIENT_SSL;
     }
     if (!$server) {
         $return_value = @$this->_realConnect($link, $cfg['Server']['host'], $user, $password, false, $server_port, $server_socket, $client_flags);
         // Retry with empty password if we're allowed to
         if ($return_value == false && isset($cfg['Server']['nopassword']) && $cfg['Server']['nopassword'] && !$is_controluser) {
             $return_value = @$this->_realConnect($link, $cfg['Server']['host'], $user, '', false, $server_port, $server_socket, $client_flags);
         }
     } else {
         $return_value = @$this->_realConnect($link, $server['host'], $user, $password, false, $server_port, $server_socket);
     }
     if ($return_value === false) {
         return false;
     }
     return $link;
 }
 /**
  * Connect to the database server, log in and open the database
  *
  * Don't call this method directly.  Use DB::connect() instead.
  *
  * PEAR DB's mysqli driver supports the following extra DSN options:
  *   + When the 'ssl' $option passed to DB::connect() is true:
  *     + key      The path to the key file.
  *     + cert     The path to the certificate file.
  *     + ca       The path to the certificate authority file.
  *     + capath   The path to a directory that contains trusted SSL
  *                 CA certificates in pem format.
  *     + cipher   The list of allowable ciphers for SSL encryption.
  *
  * Example of how to connect using SSL:
  * <code>
  * require_once 'DB.php';
  * 
  * $dsn = array(
  *     'phptype'  => 'mysqli',
  *     'username' => 'someuser',
  *     'password' => 'apasswd',
  *     'hostspec' => 'localhost',
  *     'database' => 'thedb',
  *     'key'      => 'client-key.pem',
  *     'cert'     => 'client-cert.pem',
  *     'ca'       => 'cacert.pem',
  *     'capath'   => '/path/to/ca/dir',
  *     'cipher'   => 'AES',
  * );
  * 
  * $options = array(
  *     'ssl' => true,
  * );
  * 
  * $db =& DB::connect($dsn, $options);
  * if (PEAR::isError($db)) {
  *     die($db->getMessage());
  * }
  * </code>
  *
  * @param array $dsn         the data source name
  * @param bool  $persistent  should the connection be persistent?
  *
  * @return int  DB_OK on success. A DB_Error object on failure.
  */
 function connect($dsn, $persistent = false)
 {
     if (!PEAR::loadExtension('mysqli')) {
         return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
     }
     $this->dsn = $dsn;
     if ($dsn['dbsyntax']) {
         $this->dbsyntax = $dsn['dbsyntax'];
     }
     $ini = ini_get('track_errors');
     ini_set('track_errors', 1);
     $php_errormsg = '';
     if ($this->getOption('ssl') === true) {
         $init = mysqli_init();
         mysqli_ssl_set($init, empty($dsn['key']) ? null : $dsn['key'], empty($dsn['cert']) ? null : $dsn['cert'], empty($dsn['ca']) ? null : $dsn['ca'], empty($dsn['capath']) ? null : $dsn['capath'], empty($dsn['cipher']) ? null : $dsn['cipher']);
         if ($this->connection = @mysqli_real_connect($init, $dsn['hostspec'], $dsn['username'], $dsn['password'], $dsn['database'], $dsn['port'], $dsn['socket'])) {
             $this->connection = $init;
         }
     } else {
         $this->connection = @mysqli_connect($dsn['hostspec'], $dsn['username'], $dsn['password'], $dsn['database'], $dsn['port'], $dsn['socket']);
     }
     ini_set('track_errors', $ini);
     if (!$this->connection) {
         if (($err = @mysqli_connect_error()) != '') {
             return $this->raiseError(DB_ERROR_CONNECT_FAILED, null, null, null, $err);
         } else {
             return $this->raiseError(DB_ERROR_CONNECT_FAILED, null, null, null, $php_errormsg);
         }
     }
     if ($dsn['database']) {
         $this->_db = $dsn['database'];
     }
     return DB_OK;
 }
Example #6
0
function ss_get_mysql_stats($options)
{
    # Process connection options.
    global $debug, $mysql_user, $mysql_pass, $cache_dir, $poll_time, $chk_options, $mysql_port, $mysql_ssl, $mysql_ssl_key, $mysql_ssl_cert, $mysql_ssl_ca, $mysql_connection_timeout, $heartbeat, $heartbeat_table, $heartbeat_server_id, $heartbeat_utc;
    $user = isset($options['user']) ? $options['user'] : $mysql_user;
    $pass = isset($options['pass']) ? $options['pass'] : $mysql_pass;
    $host = $options['host'];
    $port = isset($options['port']) ? $options['port'] : $mysql_port;
    $connection_timeout = isset($options['connection-timeout']) ? $options['connection-timeout'] : $mysql_connection_timeout;
    $heartbeat_server_id = isset($options['server-id']) ? $options['server-id'] : $heartbeat_server_id;
    $sanitized_host = str_replace(array(":", "/"), array("", "_"), $host);
    $cache_file = "{$cache_dir}/{$sanitized_host}-mysql_cacti_stats.txt" . ($port != 3306 ? ":{$port}" : '');
    debug("Cache file is {$cache_file}");
    # First, check the cache.
    $fp = null;
    if ($cache_dir && !array_key_exists('nocache', $options)) {
        if ($fp = fopen($cache_file, 'a+')) {
            $locked = flock($fp, 1);
            # LOCK_SH
            if ($locked) {
                if (filesize($cache_file) > 0 && filectime($cache_file) + $poll_time / 2 > time() && ($arr = file($cache_file))) {
                    # The cache file is good to use.
                    debug("Using the cache file");
                    fclose($fp);
                    return $arr[0];
                } else {
                    debug("The cache file seems too small or stale");
                    # Escalate the lock to exclusive, so we can write to it.
                    if (flock($fp, 2)) {
                        # LOCK_EX
                        # We might have blocked while waiting for that LOCK_EX, and
                        # another process ran and updated it.  Let's see if we can just
                        # return the data now:
                        if (filesize($cache_file) > 0 && filectime($cache_file) + $poll_time / 2 > time() && ($arr = file($cache_file))) {
                            # The cache file is good to use.
                            debug("Using the cache file");
                            fclose($fp);
                            return $arr[0];
                        }
                        ftruncate($fp, 0);
                        # Now it's ready for writing later.
                    }
                }
            } else {
                $fp = null;
                debug("Couldn't lock the cache file, ignoring it");
            }
        } else {
            $fp = null;
            debug("Couldn't open the cache file");
        }
    } else {
        debug("Caching is disabled.");
    }
    # Connect to MySQL.
    debug(array('Connecting to', $host, $port, $user, $pass));
    if (!extension_loaded('mysqli')) {
        debug("PHP MySQLi extension is not loaded");
        die("PHP MySQLi extension is not loaded");
    }
    if ($mysql_ssl) {
        $conn = mysqli_init();
        $conn->options(MYSQLI_OPT_CONNECT_TIMEOUT, $connection_timeout);
        mysqli_ssl_set($conn, $mysql_ssl_key, $mysql_ssl_cert, $mysql_ssl_ca, NULL, NULL);
        mysqli_real_connect($conn, $host, $user, $pass, NULL, $port);
    } else {
        $conn = mysqli_init();
        $conn->options(MYSQLI_OPT_CONNECT_TIMEOUT, $connection_timeout);
        mysqli_real_connect($conn, $host, $user, $pass, NULL, $port);
    }
    if (mysqli_connect_errno()) {
        debug("MySQL connection failed: " . mysqli_connect_error());
        die("ERROR: " . mysqli_connect_error());
    }
    # MySQL server version.
    # The form of this version number is main_version * 10000 + minor_version * 100 + sub_version
    # i.e. version 5.5.44 is 50544.
    $mysql_version = mysqli_get_server_version($conn);
    debug("MySQL server version is " . $mysql_version);
    # Set up variables.
    $status = array('relay_log_space' => null, 'binary_log_space' => null, 'current_transactions' => 0, 'locked_transactions' => 0, 'active_transactions' => 0, 'innodb_locked_tables' => 0, 'innodb_tables_in_use' => 0, 'innodb_lock_structs' => 0, 'innodb_lock_wait_secs' => 0, 'innodb_sem_waits' => 0, 'innodb_sem_wait_time_ms' => 0, 'State_closing_tables' => 0, 'State_copying_to_tmp_table' => 0, 'State_end' => 0, 'State_freeing_items' => 0, 'State_init' => 0, 'State_locked' => 0, 'State_login' => 0, 'State_preparing' => 0, 'State_reading_from_net' => 0, 'State_sending_data' => 0, 'State_sorting_result' => 0, 'State_statistics' => 0, 'State_updating' => 0, 'State_writing_to_net' => 0, 'State_none' => 0, 'State_other' => 0);
    # Get SHOW STATUS and convert the name-value array into a simple
    # associative array.
    $result = run_query("SHOW /*!50002 GLOBAL */ STATUS", $conn);
    foreach ($result as $row) {
        $status[$row[0]] = $row[1];
    }
    # Get SHOW VARIABLES and do the same thing, adding it to the $status array.
    $result = run_query("SHOW VARIABLES", $conn);
    foreach ($result as $row) {
        $status[$row[0]] = $row[1];
    }
    # Get SHOW SLAVE STATUS, and add it to the $status array.
    if ($chk_options['slave']) {
        # Leverage lock-free SHOW SLAVE STATUS if available
        $result = run_query("SHOW SLAVE STATUS NONBLOCKING", $conn);
        if (!$result) {
            $result = run_query("SHOW SLAVE STATUS NOLOCK", $conn);
            if (!$result) {
                $result = run_query("SHOW SLAVE STATUS", $conn);
            }
        }
        $slave_status_rows_gotten = 0;
        foreach ($result as $row) {
            $slave_status_rows_gotten++;
            # Must lowercase keys because different MySQL versions have different
            # lettercase.
            $row = array_change_key_case($row, CASE_LOWER);
            $status['relay_log_space'] = $row['relay_log_space'];
            $status['slave_lag'] = $row['seconds_behind_master'];
            # Check replication heartbeat, if present.
            if ($heartbeat) {
                if ($heartbeat_utc) {
                    $now_func = 'UNIX_TIMESTAMP(UTC_TIMESTAMP)';
                } else {
                    $now_func = 'UNIX_TIMESTAMP()';
                }
                $result2 = run_query("SELECT MAX({$now_func} - ROUND(UNIX_TIMESTAMP(ts)))" . " AS delay FROM {$heartbeat_table}" . " WHERE {$heartbeat_server_id} = 0 OR server_id = {$heartbeat_server_id}", $conn);
                $slave_delay_rows_gotten = 0;
                foreach ($result2 as $row2) {
                    $slave_delay_rows_gotten++;
                    if ($row2 && is_array($row2) && array_key_exists('delay', $row2)) {
                        $status['slave_lag'] = $row2['delay'];
                    } else {
                        debug("Couldn't get slave lag from {$heartbeat_table}");
                    }
                }
                if ($slave_delay_rows_gotten == 0) {
                    debug("Got nothing from heartbeat query");
                }
            }
            # Scale slave_running and slave_stopped relative to the slave lag.
            $status['slave_running'] = $row['slave_sql_running'] == 'Yes' ? $status['slave_lag'] : 0;
            $status['slave_stopped'] = $row['slave_sql_running'] == 'Yes' ? 0 : $status['slave_lag'];
        }
        if ($slave_status_rows_gotten == 0) {
            debug("Got nothing from SHOW SLAVE STATUS");
        }
    }
    # Get SHOW MASTER STATUS, and add it to the $status array.
    if ($chk_options['master'] && array_key_exists('log_bin', $status) && $status['log_bin'] == 'ON') {
        # See issue #8
        $binlogs = array(0);
        $result = run_query("SHOW MASTER LOGS", $conn);
        foreach ($result as $row) {
            $row = array_change_key_case($row, CASE_LOWER);
            # Older versions of MySQL may not have the File_size column in the
            # results of the command.  Zero-size files indicate the user is
            # deleting binlogs manually from disk (bad user! bad!).
            if (array_key_exists('file_size', $row) && $row['file_size'] > 0) {
                $binlogs[] = $row['file_size'];
            }
        }
        if (count($binlogs)) {
            $status['binary_log_space'] = to_int(array_sum($binlogs));
        }
    }
    # Get SHOW PROCESSLIST and aggregate it by state, then add it to the array
    # too.
    if ($chk_options['procs']) {
        $result = run_query('SHOW PROCESSLIST', $conn);
        foreach ($result as $row) {
            $state = $row['State'];
            if (is_null($state)) {
                $state = 'NULL';
            }
            if ($state == '') {
                $state = 'none';
            }
            # MySQL 5.5 replaces the 'Locked' state with a variety of "Waiting for
            # X lock" types of statuses.  Wrap these all back into "Locked" because
            # we don't really care about the type of locking it is.
            $state = preg_replace('/^(Table lock|Waiting for .*lock)$/', 'Locked', $state);
            $state = str_replace(' ', '_', strtolower($state));
            if (array_key_exists("State_{$state}", $status)) {
                increment($status, "State_{$state}", 1);
            } else {
                increment($status, "State_other", 1);
            }
        }
    }
    # Get SHOW ENGINES to be able to determine whether InnoDB is present.
    $engines = array();
    $result = run_query("SHOW ENGINES", $conn);
    foreach ($result as $row) {
        $engines[$row[0]] = $row[1];
    }
    # Get SHOW INNODB STATUS and extract the desired metrics from it, then add
    # those to the array too.
    if ($chk_options['innodb'] && array_key_exists('InnoDB', $engines) && $engines['InnoDB'] == 'YES' || $engines['InnoDB'] == 'DEFAULT') {
        $result = run_query("SHOW /*!50000 ENGINE*/ INNODB STATUS", $conn);
        $istatus_text = $result[0]['Status'];
        $istatus_vals = get_innodb_array($istatus_text, $mysql_version);
        # Get response time histogram from Percona Server or MariaDB if enabled.
        if ($chk_options['get_qrt'] && (isset($status['have_response_time_distribution']) && $status['have_response_time_distribution'] == 'YES' || isset($status['query_response_time_stats']) && $status['query_response_time_stats'] == 'ON')) {
            debug('Getting query time histogram');
            $i = 0;
            $result = run_query("SELECT `count`, ROUND(total * 1000000) AS total " . "FROM INFORMATION_SCHEMA.QUERY_RESPONSE_TIME " . "WHERE `time` <> 'TOO LONG'", $conn);
            foreach ($result as $row) {
                if ($i > 13) {
                    # It's possible that the number of rows returned isn't 14.
                    # Don't add extra status counters.
                    break;
                }
                $count_key = sprintf("Query_time_count_%02d", $i);
                $total_key = sprintf("Query_time_total_%02d", $i);
                $status[$count_key] = $row['count'];
                $status[$total_key] = $row['total'];
                $i++;
            }
            # It's also possible that the number of rows returned is too few.
            # Don't leave any status counters unassigned; it will break graphs.
            while ($i <= 13) {
                $count_key = sprintf("Query_time_count_%02d", $i);
                $total_key = sprintf("Query_time_total_%02d", $i);
                $status[$count_key] = 0;
                $status[$total_key] = 0;
                $i++;
            }
        } else {
            debug('Not getting time histogram because it is not enabled');
        }
        # Override values from InnoDB parsing with values from SHOW STATUS,
        # because InnoDB status might not have everything and the SHOW STATUS is
        # to be preferred where possible.
        $overrides = array('Innodb_buffer_pool_pages_data' => 'database_pages', 'Innodb_buffer_pool_pages_dirty' => 'modified_pages', 'Innodb_buffer_pool_pages_free' => 'free_pages', 'Innodb_buffer_pool_pages_total' => 'pool_size', 'Innodb_data_fsyncs' => 'file_fsyncs', 'Innodb_data_pending_reads' => 'pending_normal_aio_reads', 'Innodb_data_pending_writes' => 'pending_normal_aio_writes', 'Innodb_os_log_pending_fsyncs' => 'pending_log_flushes', 'Innodb_pages_created' => 'pages_created', 'Innodb_pages_read' => 'pages_read', 'Innodb_pages_written' => 'pages_written', 'Innodb_rows_deleted' => 'rows_deleted', 'Innodb_rows_inserted' => 'rows_inserted', 'Innodb_rows_read' => 'rows_read', 'Innodb_rows_updated' => 'rows_updated', 'Innodb_buffer_pool_reads' => 'pool_reads', 'Innodb_buffer_pool_read_requests' => 'pool_read_requests');
        # If the SHOW STATUS value exists, override...
        foreach ($overrides as $key => $val) {
            if (array_key_exists($key, $status)) {
                debug("Override {$key}");
                $istatus_vals[$val] = $status[$key];
            }
        }
        # Now copy the values into $status.
        foreach ($istatus_vals as $key => $val) {
            $status[$key] = $istatus_vals[$key];
        }
    }
    # Make table_open_cache backwards-compatible (issue 63).
    if (array_key_exists('table_open_cache', $status)) {
        $status['table_cache'] = $status['table_open_cache'];
    }
    # Compute how much of the key buffer is used and unflushed (issue 127).
    $status['Key_buf_bytes_used'] = big_sub($status['key_buffer_size'], big_multiply($status['Key_blocks_unused'], $status['key_cache_block_size']));
    $status['Key_buf_bytes_unflushed'] = big_multiply($status['Key_blocks_not_flushed'], $status['key_cache_block_size']);
    if (array_key_exists('unflushed_log', $status) && $status['unflushed_log']) {
        # TODO: I'm not sure what the deal is here; need to debug this.  But the
        # unflushed log bytes spikes a lot sometimes and it's impossible for it to
        # be more than the log buffer.
        debug("Unflushed log: {$status['unflushed_log']}");
        $status['unflushed_log'] = max($status['unflushed_log'], $status['innodb_log_buffer_size']);
    }
    # Define the variables to output.  I use shortened variable names so maybe
    # it'll all fit in 1024 bytes for Cactid and Spine's benefit.  Strings must
    # have some non-hex characters (non a-f0-9) to avoid a Cacti bug.  This list
    # must come right after the word MAGIC_VARS_DEFINITIONS.  The Perl script
    # parses it and uses it as a Perl variable.
    $keys = array('Key_read_requests' => 'gg', 'Key_reads' => 'gh', 'Key_write_requests' => 'gi', 'Key_writes' => 'gj', 'history_list' => 'gk', 'innodb_transactions' => 'gl', 'read_views' => 'gm', 'current_transactions' => 'gn', 'locked_transactions' => 'go', 'active_transactions' => 'gp', 'pool_size' => 'gq', 'free_pages' => 'gr', 'database_pages' => 'gs', 'modified_pages' => 'gt', 'pages_read' => 'gu', 'pages_created' => 'gv', 'pages_written' => 'gw', 'file_fsyncs' => 'gx', 'file_reads' => 'gy', 'file_writes' => 'gz', 'log_writes' => 'hg', 'pending_aio_log_ios' => 'hh', 'pending_aio_sync_ios' => 'hi', 'pending_buf_pool_flushes' => 'hj', 'pending_chkp_writes' => 'hk', 'pending_ibuf_aio_reads' => 'hl', 'pending_log_flushes' => 'hm', 'pending_log_writes' => 'hn', 'pending_normal_aio_reads' => 'ho', 'pending_normal_aio_writes' => 'hp', 'ibuf_inserts' => 'hq', 'ibuf_merged' => 'hr', 'ibuf_merges' => 'hs', 'spin_waits' => 'ht', 'spin_rounds' => 'hu', 'os_waits' => 'hv', 'rows_inserted' => 'hw', 'rows_updated' => 'hx', 'rows_deleted' => 'hy', 'rows_read' => 'hz', 'Table_locks_waited' => 'ig', 'Table_locks_immediate' => 'ih', 'Slow_queries' => 'ii', 'Open_files' => 'ij', 'Open_tables' => 'ik', 'Opened_tables' => 'il', 'innodb_open_files' => 'im', 'open_files_limit' => 'in', 'table_cache' => 'io', 'Aborted_clients' => 'ip', 'Aborted_connects' => 'iq', 'Max_used_connections' => 'ir', 'Slow_launch_threads' => 'is', 'Threads_cached' => 'it', 'Threads_connected' => 'iu', 'Threads_created' => 'iv', 'Threads_running' => 'iw', 'max_connections' => 'ix', 'thread_cache_size' => 'iy', 'Connections' => 'iz', 'slave_running' => 'jg', 'slave_stopped' => 'jh', 'Slave_retried_transactions' => 'ji', 'slave_lag' => 'jj', 'Slave_open_temp_tables' => 'jk', 'Qcache_free_blocks' => 'jl', 'Qcache_free_memory' => 'jm', 'Qcache_hits' => 'jn', 'Qcache_inserts' => 'jo', 'Qcache_lowmem_prunes' => 'jp', 'Qcache_not_cached' => 'jq', 'Qcache_queries_in_cache' => 'jr', 'Qcache_total_blocks' => 'js', 'query_cache_size' => 'jt', 'Questions' => 'ju', 'Com_update' => 'jv', 'Com_insert' => 'jw', 'Com_select' => 'jx', 'Com_delete' => 'jy', 'Com_replace' => 'jz', 'Com_load' => 'kg', 'Com_update_multi' => 'kh', 'Com_insert_select' => 'ki', 'Com_delete_multi' => 'kj', 'Com_replace_select' => 'kk', 'Select_full_join' => 'kl', 'Select_full_range_join' => 'km', 'Select_range' => 'kn', 'Select_range_check' => 'ko', 'Select_scan' => 'kp', 'Sort_merge_passes' => 'kq', 'Sort_range' => 'kr', 'Sort_rows' => 'ks', 'Sort_scan' => 'kt', 'Created_tmp_tables' => 'ku', 'Created_tmp_disk_tables' => 'kv', 'Created_tmp_files' => 'kw', 'Bytes_sent' => 'kx', 'Bytes_received' => 'ky', 'innodb_log_buffer_size' => 'kz', 'unflushed_log' => 'lg', 'log_bytes_flushed' => 'lh', 'log_bytes_written' => 'li', 'relay_log_space' => 'lj', 'binlog_cache_size' => 'lk', 'Binlog_cache_disk_use' => 'll', 'Binlog_cache_use' => 'lm', 'binary_log_space' => 'ln', 'innodb_locked_tables' => 'lo', 'innodb_lock_structs' => 'lp', 'State_closing_tables' => 'lq', 'State_copying_to_tmp_table' => 'lr', 'State_end' => 'ls', 'State_freeing_items' => 'lt', 'State_init' => 'lu', 'State_locked' => 'lv', 'State_login' => 'lw', 'State_preparing' => 'lx', 'State_reading_from_net' => 'ly', 'State_sending_data' => 'lz', 'State_sorting_result' => 'mg', 'State_statistics' => 'mh', 'State_updating' => 'mi', 'State_writing_to_net' => 'mj', 'State_none' => 'mk', 'State_other' => 'ml', 'Handler_commit' => 'mm', 'Handler_delete' => 'mn', 'Handler_discover' => 'mo', 'Handler_prepare' => 'mp', 'Handler_read_first' => 'mq', 'Handler_read_key' => 'mr', 'Handler_read_next' => 'ms', 'Handler_read_prev' => 'mt', 'Handler_read_rnd' => 'mu', 'Handler_read_rnd_next' => 'mv', 'Handler_rollback' => 'mw', 'Handler_savepoint' => 'mx', 'Handler_savepoint_rollback' => 'my', 'Handler_update' => 'mz', 'Handler_write' => 'ng', 'innodb_tables_in_use' => 'nh', 'innodb_lock_wait_secs' => 'ni', 'hash_index_cells_total' => 'nj', 'hash_index_cells_used' => 'nk', 'total_mem_alloc' => 'nl', 'additional_pool_alloc' => 'nm', 'uncheckpointed_bytes' => 'nn', 'ibuf_used_cells' => 'no', 'ibuf_free_cells' => 'np', 'ibuf_cell_count' => 'nq', 'adaptive_hash_memory' => 'nr', 'page_hash_memory' => 'ns', 'dictionary_cache_memory' => 'nt', 'file_system_memory' => 'nu', 'lock_system_memory' => 'nv', 'recovery_system_memory' => 'nw', 'thread_hash_memory' => 'nx', 'innodb_sem_waits' => 'ny', 'innodb_sem_wait_time_ms' => 'nz', 'Key_buf_bytes_unflushed' => 'og', 'Key_buf_bytes_used' => 'oh', 'key_buffer_size' => 'oi', 'Innodb_row_lock_time' => 'oj', 'Innodb_row_lock_waits' => 'ok', 'Query_time_count_00' => 'ol', 'Query_time_count_01' => 'om', 'Query_time_count_02' => 'on', 'Query_time_count_03' => 'oo', 'Query_time_count_04' => 'op', 'Query_time_count_05' => 'oq', 'Query_time_count_06' => 'or', 'Query_time_count_07' => 'os', 'Query_time_count_08' => 'ot', 'Query_time_count_09' => 'ou', 'Query_time_count_10' => 'ov', 'Query_time_count_11' => 'ow', 'Query_time_count_12' => 'ox', 'Query_time_count_13' => 'oy', 'Query_time_total_00' => 'oz', 'Query_time_total_01' => 'pg', 'Query_time_total_02' => 'ph', 'Query_time_total_03' => 'pi', 'Query_time_total_04' => 'pj', 'Query_time_total_05' => 'pk', 'Query_time_total_06' => 'pl', 'Query_time_total_07' => 'pm', 'Query_time_total_08' => 'pn', 'Query_time_total_09' => 'po', 'Query_time_total_10' => 'pp', 'Query_time_total_11' => 'pq', 'Query_time_total_12' => 'pr', 'Query_time_total_13' => 'ps', 'wsrep_replicated_bytes' => 'pt', 'wsrep_received_bytes' => 'pu', 'wsrep_replicated' => 'pv', 'wsrep_received' => 'pw', 'wsrep_local_cert_failures' => 'px', 'wsrep_local_bf_aborts' => 'py', 'wsrep_local_send_queue' => 'pz', 'wsrep_local_recv_queue' => 'qg', 'wsrep_cluster_size' => 'qh', 'wsrep_cert_deps_distance' => 'qi', 'wsrep_apply_window' => 'qj', 'wsrep_commit_window' => 'qk', 'wsrep_flow_control_paused' => 'ql', 'wsrep_flow_control_sent' => 'qm', 'wsrep_flow_control_recv' => 'qn', 'pool_reads' => 'qo', 'pool_read_requests' => 'qp');
    # Return the output.
    $output = array();
    foreach ($keys as $key => $short) {
        # If the value isn't defined, return -1 which is lower than (most graphs')
        # minimum value of 0, so it'll be regarded as a missing value.
        $val = isset($status[$key]) ? $status[$key] : -1;
        $output[] = "{$short}:{$val}";
    }
    $result = implode(' ', $output);
    if ($fp) {
        if (fwrite($fp, $result) === FALSE) {
            die("Can't write '{$cache_file}'");
        }
        fclose($fp);
    }
    return $result;
}
Example #7
0
 /**
  * do the grunt work of the connect
  *
  * @return connection on success or MDB2 Error Object on failure
  * @access protected
  */
 function _doConnect($username, $password, $persistent = false)
 {
     if (!PEAR::loadExtension($this->phptype)) {
         return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null, 'extension ' . $this->phptype . ' is not compiled into PHP', __FUNCTION__);
     }
     $connection = @mysqli_init();
     if (!empty($this->dsn['charset']) && defined('MYSQLI_SET_CHARSET_NAME')) {
         @mysqli_options($connection, MYSQLI_SET_CHARSET_NAME, $this->dsn['charset']);
     }
     if ($this->options['ssl']) {
         @mysqli_ssl_set($connection, empty($this->dsn['key']) ? null : $this->dsn['key'], empty($this->dsn['cert']) ? null : $this->dsn['cert'], empty($this->dsn['ca']) ? null : $this->dsn['ca'], empty($this->dsn['capath']) ? null : $this->dsn['capath'], empty($this->dsn['cipher']) ? null : $this->dsn['cipher']);
     }
     if (!@mysqli_real_connect($connection, $this->dsn['hostspec'], $username, $password, $this->database_name, $this->dsn['port'], $this->dsn['socket'])) {
         if (($err = @mysqli_connect_error()) != '') {
             return $this->raiseError(null, null, null, $err, __FUNCTION__);
         } else {
             return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null, 'unable to establish a connection', __FUNCTION__);
         }
     }
     if (!empty($this->dsn['charset']) && !defined('MYSQLI_SET_CHARSET_NAME')) {
         $result = $this->setCharset($this->dsn['charset'], $connection);
         if (PEAR::isError($result)) {
             return $result;
         }
     }
     return $connection;
 }
Example #8
0
 /**
  * connects to the database server
  *
  * @param string $user                 mysql user name
  * @param string $password             mysql user password
  * @param bool   $is_controluser       whether this is a control user connection
  * @param array  $server               host/port/socket/persistent
  * @param bool   $auxiliary_connection (when true, don't go back to login if
  *                                     connection fails)
  *
  * @return mixed false on error or a mysqli object on success
  */
 public function connect($user, $password, $is_controluser = false, $server = null, $auxiliary_connection = false)
 {
     global $cfg;
     if ($server) {
         $server_port = empty($server['port']) ? false : (int) $server['port'];
         $server_socket = empty($server['socket']) ? '' : $server['socket'];
         $server['host'] = empty($server['host']) ? 'localhost' : $server['host'];
     } else {
         $server_port = empty($cfg['Server']['port']) ? false : (int) $cfg['Server']['port'];
         $server_socket = empty($cfg['Server']['socket']) ? null : $cfg['Server']['socket'];
     }
     // NULL enables connection to the default socket
     $link = mysqli_init();
     mysqli_options($link, MYSQLI_OPT_LOCAL_INFILE, true);
     $client_flags = 0;
     /* Optionally compress connection */
     if ($cfg['Server']['compress'] && defined('MYSQLI_CLIENT_COMPRESS')) {
         $client_flags |= MYSQLI_CLIENT_COMPRESS;
     }
     /* Optionally enable SSL */
     if ($cfg['Server']['ssl'] && defined('MYSQLI_CLIENT_SSL')) {
         mysqli_ssl_set($link, $cfg['Server']['ssl_key'], $cfg['Server']['ssl_cert'], $cfg['Server']['ssl_ca'], $cfg['Server']['ssl_ca_path'], $cfg['Server']['ssl_ciphers']);
         $client_flags |= MYSQLI_CLIENT_SSL;
     }
     if (!$server) {
         $return_value = @$this->_realConnect($link, $cfg['Server']['host'], $user, $password, false, $server_port, $server_socket, $client_flags);
         // Retry with empty password if we're allowed to
         if ($return_value == false && isset($cfg['Server']['nopassword']) && $cfg['Server']['nopassword'] && !$is_controluser) {
             $return_value = @$this->_realConnect($link, $cfg['Server']['host'], $user, '', false, $server_port, $server_socket, $client_flags);
         }
     } else {
         $return_value = @$this->_realConnect($link, $server['host'], $user, $password, false, $server_port, $server_socket);
     }
     if ($return_value == false) {
         if ($is_controluser) {
             trigger_error(__('Connection for controluser as defined in your configuration failed.'), E_USER_WARNING);
             return false;
         }
         // we could be calling $GLOBALS['dbi']->connect() to connect to another
         // server, for example in the Synchronize feature, so do not
         // go back to main login if it fails
         if (!$auxiliary_connection) {
             PMA_logUser($user, 'mysql-denied');
             global $auth_plugin;
             $auth_plugin->authFails();
         } else {
             return false;
         }
     } else {
         $GLOBALS['dbi']->postConnect($link, $is_controluser);
     }
     return $link;
 }
 protected function _connect()
 {
     $host = $this->profile['persistent'] ? 'p:' . $this->profile['host'] : $this->profile['host'];
     if (isset($this->profile['ssl']) && $this->profile['ssl']) {
         $cnx = mysqli_init();
         if (!$cnx) {
             throw new jException('jelix~db.error.connection', $this->profile['host']);
         }
         mysqli_ssl_set($cnx, isset($this->profile['ssl_key_pem']) ? $this->profile['ssl_key_pem'] : NULL, isset($this->profile['ssl_cert_pem']) ? $this->profile['ssl_cert_pem'] : NULL, isset($this->profile['ssl_cacert_pem']) ? $this->profile['ssl_cacert_pem'] : NULL, NULL, NULL);
         if (!mysqli_real_connect($cnx, $host, $this->profile['user'], $this->profile['password'], $this->profile['database'])) {
             throw new jException('jelix~db.error.connection', $this->profile['host']);
         }
     } else {
         $cnx = @new mysqli($host, $this->profile['user'], $this->profile['password'], $this->profile['database']);
     }
     if ($cnx->connect_errno) {
         throw new jException('jelix~db.error.connection', $this->profile['host']);
     } else {
         if (isset($this->profile['force_encoding']) && $this->profile['force_encoding'] == true && isset($this->_charsets[jApp::config()->charset])) {
             $cnx->set_charset($this->_charsets[jApp::config()->charset]);
         }
         return $cnx;
     }
 }
Example #10
0
<?php

include "connect.inc";
$db1 = new mysqli();
$flags = MYSQLI_CLIENT_SSL;
$link = mysqli_init();
mysqli_ssl_set($link, null, null, null, null, "RC4-MD5");
if (my_mysqli_real_connect($link, 'p:' . $host, $user, $passwd, $db, $port, null, $flags)) {
    $r = $link->query("SHOW STATUS LIKE 'Ssl_cipher'");
    var_dump($r->fetch_row());
}
/* non-persistent connection */
$link2 = mysqli_init();
mysqli_ssl_set($link2, null, null, null, null, "RC4-MD5");
if (my_mysqli_real_connect($link2, $host, $user, $passwd, $db, $port, null, $flags)) {
    $r2 = $link2->query("SHOW STATUS LIKE 'Ssl_cipher'");
    var_dump($r2->fetch_row());
}
echo "done\n";
Example #11
0
 /**
  * Connect to the database
  *
  * @return true on success, MDB2 Error Object on failure
  */
 function connect()
 {
     if (is_object($this->connection)) {
         if (count(array_diff($this->connected_dsn, $this->dsn)) == 0) {
             return MDB2_OK;
         }
         $this->connection = 0;
     }
     if (!PEAR::loadExtension($this->phptype)) {
         return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null, 'extension ' . $this->phptype . ' is not compiled into PHP', __FUNCTION__);
     }
     @ini_set('track_errors', true);
     $php_errormsg = '';
     if ($this->options['ssl']) {
         $init = @mysqli_init();
         @mysqli_ssl_set($init, empty($this->dsn['key']) ? null : $this->dsn['key'], empty($this->dsn['cert']) ? null : $this->dsn['cert'], empty($this->dsn['ca']) ? null : $this->dsn['ca'], empty($this->dsn['capath']) ? null : $this->dsn['capath'], empty($this->dsn['cipher']) ? null : $this->dsn['cipher']);
         if ($connection = @mysqli_real_connect($init, $this->dsn['hostspec'], $this->dsn['username'], $this->dsn['password'], $this->database_name, $this->dsn['port'], $this->dsn['socket'])) {
             $connection = $init;
         }
     } else {
         $connection = @mysqli_connect($this->dsn['hostspec'], $this->dsn['username'], $this->dsn['password'], $this->database_name, $this->dsn['port'], $this->dsn['socket']);
     }
     @ini_restore('track_errors');
     if (!$connection) {
         if (($err = @mysqli_connect_error()) != '') {
             return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null, $err, __FUNCTION__);
         } else {
             return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null, $php_errormsg, __FUNCTION__);
         }
     }
     if (!empty($this->dsn['charset'])) {
         $result = $this->setCharset($this->dsn['charset'], $connection);
         if (PEAR::isError($result)) {
             return $result;
         }
     }
     $this->connection = $connection;
     $this->connected_dsn = $this->dsn;
     $this->connected_database_name = $this->database_name;
     $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;
     $this->supported['transactions'] = $this->options['use_transactions'];
     if ($this->options['default_table_type']) {
         switch (strtoupper($this->options['default_table_type'])) {
             case 'BLACKHOLE':
             case 'MEMORY':
             case 'ARCHIVE':
             case 'CSV':
             case 'HEAP':
             case 'ISAM':
             case 'MERGE':
             case 'MRG_ISAM':
             case 'ISAM':
             case 'MRG_MYISAM':
             case 'MYISAM':
                 $this->supported['transactions'] = false;
                 $this->warnings[] = $default_table_type . ' is not a supported default table type';
                 break;
         }
     }
     $this->supported['sub_selects'] = 'emulated';
     $this->supported['prepared_statements'] = 'emulated';
     $this->start_transaction = false;
     $this->varchar_max_length = 255;
     $server_info = $this->getServerVersion();
     if (is_array($server_info)) {
         if (!version_compare($server_info['major'] . '.' . $server_info['minor'] . '.' . $server_info['patch'], '4.1.0', '<')) {
             $this->supported['sub_selects'] = true;
             $this->supported['prepared_statements'] = true;
         }
         if (!version_compare($server_info['major'] . '.' . $server_info['minor'] . '.' . $server_info['patch'], '4.0.14', '<') || !version_compare($server_info['major'] . '.' . $server_info['minor'] . '.' . $server_info['patch'], '4.1.1', '<')) {
             $this->supported['savepoints'] = true;
         }
         if (!version_compare($server_info['major'] . '.' . $server_info['minor'] . '.' . $server_info['patch'], '4.0.11', '<')) {
             $this->start_transaction = true;
         }
         if (!version_compare($server_info['major'] . '.' . $server_info['minor'] . '.' . $server_info['patch'], '5.0.3', '<')) {
             $this->varchar_max_length = 65532;
         }
     }
     return MDB2_OK;
 }
if (!is_null($tmp = @mysqli_ssl_set())) {
    printf("[001] Expecting NULL, got %s/%s\n", gettype($tmp), $tmp);
}
if (!is_null($tmp = @mysqli_ssl_set($link))) {
    printf("[002] Expecting NULL, got %s/%s\n", gettype($tmp), $tmp);
}
if (!is_null($tmp = @mysqli_ssl_set($link, $link))) {
    printf("[003] Expecting NULL, got %s/%s\n", gettype($tmp), $tmp);
}
if (!is_null($tmp = @mysqli_ssl_set($link, $link, $link))) {
    printf("[004] Expecting NULL, got %s/%s\n", gettype($tmp), $tmp);
}
if (!is_null($tmp = @mysqli_ssl_set($link, $link, $link, $link))) {
    printf("[005] Expecting NULL, got %s/%s\n", gettype($tmp), $tmp);
}
if (!is_null($tmp = @mysqli_ssl_set($link, $link, $link, $link, $link))) {
    printf("[006] Expecting NULL, got %s/%s\n", gettype($tmp), $tmp);
}
/*
This function always returns TRUE value.

$link = mysqli_init();
if (NULL !== ($tmp = @mysqli_ssl_set(
	$link,
	'The path name to the key file.',
	'The path name to the certificate file.',
	'The path name to the certificate authority file.',
	'The pathname to a directory that contains trusted SSL CA certificates in PEM format.',
	'A list of allowable ciphers to use for SSL encryption.')))
	printf("[007] Expecting boolean/true, got %s/%s\n", gettype($tmp), $tmp);
Example #13
0
 /**
  * Connect to and select database.
  *
  * If $allow_bail is false, the lack of database connection will need
  * to be handled manually.
  *
  * @since 3.0.0
  * @since 3.9.0 $allow_bail parameter added.
  *
  * @param bool $allow_bail Optional. Allows the function to bail. Default true.
  * @return bool True with a successful connection, false on failure.
  */
 public function db_connect($allow_bail = true)
 {
     $this->is_mysql = true;
     /*
      * Deprecated in 3.9+ when using MySQLi. No equivalent
      * $new_link parameter exists for mysqli_* functions.
      */
     $new_link = defined('MYSQL_NEW_LINK') ? MYSQL_NEW_LINK : true;
     $client_flags = defined('MYSQL_CLIENT_FLAGS') ? MYSQL_CLIENT_FLAGS : 0;
     if ($this->use_mysqli) {
         $this->dbh = mysqli_init();
         // mysqli_real_connect doesn't support the host param including a port or socket
         // like mysql_connect does. This duplicates how mysql_connect detects a port and/or socket file.
         $port = null;
         $socket = null;
         $host = $this->dbhost;
         $port_or_socket = strstr($host, ':');
         if (!empty($port_or_socket)) {
             $host = substr($host, 0, strpos($host, ':'));
             $port_or_socket = substr($port_or_socket, 1);
             if (0 !== strpos($port_or_socket, '/')) {
                 $port = intval($port_or_socket);
                 $maybe_socket = strstr($port_or_socket, ':');
                 if (!empty($maybe_socket)) {
                     $socket = substr($maybe_socket, 1);
                 }
             } else {
                 $socket = $port_or_socket;
             }
         }
         // Set SSL certs if we want to use secure DB connections
         if ($client_flags & MYSQLI_CLIENT_SSL) {
             $ssl_key = defined('MYSQL_SSL_KEY') && is_file(MYSQL_SSL_KEY) ? MYSQL_SSL_KEY : null;
             $ssl_cert = defined('MYSQL_SSL_CERT') && is_file(MYSQL_SSL_CERT) ? MYSQL_SSL_CERT : null;
             $ssl_ca = defined('MYSQL_SSL_CA') && is_file(MYSQL_SSL_CA) ? MYSQL_SSL_CA : null;
             $ssl_capath = defined('MYSQL_SSL_CA_PATH') && is_dir(MYSQL_SSL_CA_PATH) ? MYSQL_SSL_CA_PATH : null;
             $ssl_cipher = defined('MYSQL_SSL_CIPHER') ? MYSQL_SSL_CIPHER : null;
             mysqli_ssl_set($this->dbh, $ssl_key, $ssl_cert, $ssl_ca, $ssl_capath, $ssl_cipher);
         }
         if (WP_DEBUG) {
             mysqli_real_connect($this->dbh, $host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags);
         } else {
             @mysqli_real_connect($this->dbh, $host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags);
         }
         if ($this->dbh->connect_errno) {
             $this->dbh = null;
             /* It's possible ext/mysqli is misconfigured. Fall back to ext/mysql if:
              *  - We haven't previously connected, and
              *  - WP_USE_EXT_MYSQL isn't set to false, and
              *  - ext/mysql is loaded.
              */
             $attempt_fallback = true;
             if ($this->has_connected) {
                 $attempt_fallback = false;
             } else {
                 if (defined('WP_USE_EXT_MYSQL') && !WP_USE_EXT_MYSQL) {
                     $attempt_fallback = false;
                 } else {
                     if (!function_exists('mysql_connect')) {
                         $attempt_fallback = false;
                     }
                 }
             }
             if ($attempt_fallback) {
                 $this->use_mysqli = false;
                 $this->db_connect();
             }
         }
     } else {
         if (WP_DEBUG) {
             $this->dbh = mysql_connect($this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags);
         } else {
             $this->dbh = @mysql_connect($this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags);
         }
     }
     if (!$this->dbh && $allow_bail) {
         wp_load_translations_early();
         // Load custom DB error template, if present.
         if (file_exists(WP_CONTENT_DIR . '/db-error.php')) {
             require_once WP_CONTENT_DIR . '/db-error.php';
             die;
         }
         $this->bail(sprintf(__("\n<h1>Error establishing a database connection</h1>\n<p>This either means that the username and password information in your <code>wp-config.php</code> file is incorrect or we can't contact the database server at <code>%s</code>. This could mean your host's database server is down.</p>\n<ul>\n\t<li>Are you sure you have the correct username and password?</li>\n\t<li>Are you sure that you have typed the correct hostname?</li>\n\t<li>Are you sure that the database server is running?</li>\n</ul>\n<p>If you're unsure what these terms mean you should probably contact your host. If you still need help you can always visit the <a href='https://wordpress.org/support/'>WordPress Support Forums</a>.</p>\n"), htmlspecialchars($this->dbhost, ENT_QUOTES)), 'db_connect_fail');
         return false;
     } else {
         if ($this->dbh) {
             $this->has_connected = true;
             $this->set_charset($this->dbh);
             $this->set_sql_mode();
             $this->ready = true;
             $this->select($this->dbname, $this->dbh);
             return true;
         }
     }
     return false;
 }
Example #14
0
 function _connect()
 {
     if (YADB_PHPVER < 50000) {
         return false;
     }
     $this->_conn = @mysqli_init();
     if (is_null($this->_conn)) {
         // mysqli_init() only fails if insufficient memory
         trigger_error('YADB: mysqli_init() failed (insufficient memory).', E_USER_WARNING);
         return false;
     }
     if (empty($this->_socket)) {
         $host = $this->_host;
         $port = $this->_port;
         $sock = null;
     } else {
         $host = null;
         $port = null;
         $sock = $this->_socket;
     }
     $clientFlags = 0;
     if (@array_key_exists('ssl', $this->_drvOpts) && $this->_drvOpts['ssl']) {
         $clientFlags += MYSQLI_CLIENT_SSL;
         mysqli_ssl_set($this->_conn, $this->_drvOpts['ssl_key'], $this->_drvOpts['ssl_cert'], $this->_drvOpts['ssl_ca'], $this->_drvOpts['ssl_capath'], $this->_drvOpts['ssl_cipher']);
     }
     if (@array_key_exists('compress', $this->_drvOpts) && $this->_drvOpts['compress'] && !empty($host) && $host !== 'localhost' && $host !== '127.0.0.1' && empty($sock)) {
         $clientFlags += MYSQLI_CLIENT_COMPRESS;
     }
     mysqli_options($this->_conn, MYSQLI_OPT_CONNECT_TIMEOUT, array_key_exists('timeout', $this->_drvOpts) ? $this->_drvOpts['timeout'] : 10);
     if (!@mysqli_real_connect($this->_conn, $host, $this->_user, $this->_pwd, !empty($this->_db) ? $this->_db : null, $port, $sock, $clientFlags)) {
         // try without SSL:
         $clientFlags -= MYSQLI_CLIENT_SSL;
         mysqli_ssl_set($this->_conn, null, null, null, null, null);
         if (!@mysqli_real_connect($this->_conn, $host, $this->_user, $this->_pwd, !empty($this->_db) ? $this->_db : null, $port, $sock, $clientFlags)) {
             return false;
         }
     }
     if (function_exists('mysqli_disable_rpl_parse')) {
         @mysqli_disable_rpl_parse($this->_conn);
     }
     // get and store server version so we know capabilities:
     $this->serverVers();
     // stores version array in _drvSrvVersArr
     $this->_drvSrvVers = $this->_drvSrvVersArr['vint'];
     if ($this->_drvSrvVers < 40101) {
         trigger_error('YADB: MySQL server version is ' . $this->_drvSrvVers . ', at least 4.1.1 is recommended.', E_USER_NOTICE);
     }
     if (function_exists('mysqli_disable_rpl_parse')) {
         @mysqli_disable_rpl_parse($this->_conn);
     }
     return true;
 }
Example #15
0
 /**
  * connects to the database server
  *
  * @param string $user     mysql user name
  * @param string $password mysql user password
  * @param array  $server   host/port/socket/persistent
  *
  * @return mixed false on error or a mysqli object on success
  */
 public function connect($user, $password, $server)
 {
     if ($server) {
         $server['host'] = empty($server['host']) ? 'localhost' : $server['host'];
     }
     // NULL enables connection to the default socket
     $link = mysqli_init();
     if (defined('PMA_ENABLE_LDI')) {
         mysqli_options($link, MYSQLI_OPT_LOCAL_INFILE, true);
     } else {
         mysqli_options($link, MYSQLI_OPT_LOCAL_INFILE, false);
     }
     $client_flags = 0;
     /* Optionally compress connection */
     if ($server['compress'] && defined('MYSQLI_CLIENT_COMPRESS')) {
         $client_flags |= MYSQLI_CLIENT_COMPRESS;
     }
     /* Optionally enable SSL */
     if ($server['ssl']) {
         $client_flags |= MYSQLI_CLIENT_SSL;
         if (!empty($server['ssl_key'])) {
             mysqli_ssl_set($link, $server['ssl_key'], $server['ssl_cert'], $server['ssl_ca'], $server['ssl_ca_path'], $server['ssl_ciphers']);
         }
         /*
          * disables SSL certificate validation on mysqlnd for MySQL 5.6 or later
          * @link https://bugs.php.net/bug.php?id=68344
          * @link https://github.com/phpmyadmin/phpmyadmin/pull/11838
          */
         if (!$server['ssl_verify']) {
             mysqli_options($link, MYSQLI_OPT_SSL_VERIFY_SERVER_CERT, $server['ssl_verify']);
             $client_flags |= MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT;
         }
     }
     $return_value = $this->_realConnect($link, $server['host'], $user, $password, $server['port'], $server['socket']);
     if ($return_value === false || is_null($return_value)) {
         return false;
     }
     return $link;
 }
Example #16
0
 private function connect()
 {
     $this->mysql_link = mysqli_init();
     if ($this->useSSL) {
         if (!file_exists($this->SSLKeyFile)) {
             echo "SSL Key file doesn't exist" . LINEBREAK;
             exit;
         }
         if (!file_exists($this->SSLCertFile)) {
             echo "SSL Key Cert doesn't exist" . LINEBREAK;
             exit;
         }
         if (!file_exists($this->SSLCAFile)) {
             echo "SSL CA file doesn't exist" . LINEBREAK;
             exit;
         }
         mysqli_ssl_set($this->mysql_link, $this->SSLKeyFile, $this->SSLCertFile, $this->SSLCAFile, NULL, NULL);
     }
     if (!mysqli_real_connect($this->mysql_link, $this->SQLhost, $this->SQLusername, $this->SQLpass, $this->SQLdatabase, $this->SQLport)) {
         printf("Can't connect to DB. Error: %s" . LINEBREAK, mysqli_connect_error());
         debug_print_backtrace();
         exit;
     }
     mysqli_autocommit($this->mysql_link, FALSE);
     $this->do_query('SET GROUP_CONCAT_MAX_LEN = 1000000');
     $this->connected = true;
 }