]> git.mxchange.org Git - friendica.git/blobdiff - include/dba.php
Merge pull request #3221 from strk/remember-openid
[friendica.git] / include / dba.php
index 36986ebc7c549d7e82289dce509445bd5541edc2..8e2d18db600cd5f39c3ffdb295082db85270b1f1 100644 (file)
@@ -34,8 +34,8 @@ class dba {
        public  $connected = false;
        public  $error = false;
 
-       function __construct($server,$user,$pass,$db,$install = false) {
-               global $a;
+       function __construct($server, $user, $pass, $db, $install = false) {
+               $a = get_app();
 
                $stamp1 = microtime(true);
 
@@ -80,8 +80,9 @@ class dba {
                }
                if (!$this->connected) {
                        $this->db = null;
-                       if (!$install)
+                       if (!$install) {
                                system_unavailable();
+                       }
                }
 
                $a->save_timestamp($stamp1, "network");
@@ -108,14 +109,26 @@ class dba {
                return $return;
        }
 
+       /**
+        * @brief Returns the selected database name
+        *
+        * @return string
+        */
+       public function database_name() {
+               $r = $this->q("SELECT DATABASE() AS `db`");
+
+               return $r[0]['db'];
+       }
+
        /**
         * @brief Returns the number of rows
         *
         * @return integer
         */
        public function num_rows() {
-               if (!$this->result)
+               if (!$this->result) {
                        return 0;
+               }
 
                if ($this->mysqli) {
                        $return = $this->result->num_rows;
@@ -125,11 +138,68 @@ class dba {
                return $return;
        }
 
+       /**
+        * @brief Analyze a database query and log this if some conditions are met.
+        *
+        * @param string $query The database query that will be analyzed
+        */
+       public function log_index($query) {
+               $a = get_app();
+
+               if ($a->config["system"]["db_log_index"] == "") {
+                       return;
+               }
+
+               // Don't explain an explain statement
+               if (strtolower(substr($query, 0, 7)) == "explain") {
+                       return;
+               }
+
+               // Only do the explain on "select", "update" and "delete"
+               if (!in_array(strtolower(substr($query, 0, 6)), array("select", "update", "delete"))) {
+                       return;
+               }
+
+               $r = $this->q("EXPLAIN ".$query);
+               if (!dbm::is_result($r)) {
+                       return;
+               }
+
+               $watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
+               $blacklist = explode(',', $a->config["system"]["db_log_index_blacklist"]);
+
+               foreach ($r AS $row) {
+                       if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
+                               $log = (in_array($row['key'], $watchlist) AND
+                                       ($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
+                       } else
+                               $log = false;
+
+                       if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) AND ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
+                               $log = true;
+                       }
+
+                       if (in_array($row['key'], $blacklist) OR ($row['key'] == "")) {
+                               $log = false;
+                       }
+
+                       if ($log) {
+                               $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
+                               @file_put_contents($a->config["system"]["db_log_index"], datetime_convert()."\t".
+                                               $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
+                                               basename($backtrace[1]["file"])."\t".
+                                               $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
+                                               substr($query, 0, 2000)."\n", FILE_APPEND);
+                       }
+               }
+       }
+
        public function q($sql, $onlyquery = false) {
-               global $a;
+               $a = get_app();
 
-               if ((!$this->db) || (!$this->connected))
+               if (!$this->db || !$this->connected) {
                        return false;
+               }
 
                $this->error = '';
 
@@ -139,13 +209,13 @@ class dba {
                } else {
                        $connected = mysql_ping($this->db);
                }
-               $connstr = ($connected ? "Connected": "Disonnected");
+               $connstr = ($connected ? "Connected" : "Disonnected");
 
                $stamp1 = microtime(true);
 
                $orig_sql = $sql;
 
-               if (x($a->config,'system') && x($a->config['system'],'db_callstack')) {
+               if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
                        $sql = "/*".$a->callstack()." */ ".$sql;
                }
 
@@ -159,9 +229,9 @@ class dba {
 
                $a->save_timestamp($stamp1, "database");
 
-               if (strtolower(substr($orig_sql, 0, 6)) != "select")
+               if (strtolower(substr($orig_sql, 0, 6)) != "select") {
                        $a->save_timestamp($stamp1, "database_write");
-
+               }
                if (x($a->config,'system') && x($a->config['system'],'db_log')) {
                        if (($duration > $a->config["system"]["db_loglimit"])) {
                                $duration = round($duration, 3);
@@ -218,13 +288,14 @@ class dba {
 
                if ($result === false) {
                        logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
-                       if (file_exists('dbfail.out'))
+                       if (file_exists('dbfail.out')) {
                                file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
+                       }
                }
 
-               if (($result === true) || ($result === false))
+               if (($result === true) || ($result === false)) {
                        return $result;
-
+               }
                if ($onlyquery) {
                        $this->result = $result;
                        return true;
@@ -247,15 +318,16 @@ class dba {
 
                //$a->save_timestamp($stamp1, "database");
 
-               if ($this->debug)
+               if ($this->debug) {
                        logger('dba: ' . printable(print_r($r, true)));
+               }
                return($r);
        }
 
        public function qfetch() {
                $x = false;
 
-               if ($this->result)
+               if ($this->result) {
                        if ($this->mysqli) {
                                if ($this->result->num_rows)
                                        $x = $this->result->fetch_array(MYSQLI_ASSOC);
@@ -263,17 +335,18 @@ class dba {
                                if (mysql_num_rows($this->result))
                                        $x = mysql_fetch_array($this->result, MYSQL_ASSOC);
                        }
-
+               }
                return($x);
        }
 
        public function qclose() {
-               if ($this->result)
+               if ($this->result) {
                        if ($this->mysqli) {
                                $this->result->free_result();
                        } else {
                                mysql_free_result($this->result);
                        }
+               }
        }
 
        public function dbg($dbg) {
@@ -314,8 +387,9 @@ if (! function_exists('printable')) {
 function printable($s) {
        $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
        $s = str_replace("\x00",'.',$s);
-       if (x($_SERVER,'SERVER_NAME'))
+       if (x($_SERVER,'SERVER_NAME')) {
                $s = escape_tags($s);
+       }
        return $s;
 }}
 
@@ -323,8 +397,9 @@ function printable($s) {
 if (! function_exists('dbg')) {
 function dbg($state) {
        global $db;
-       if ($db)
-       $db->dbg($state);
+       if ($db) {
+               $db->dbg($state);
+       }
 }}
 
 if (! function_exists('dbesc')) {
@@ -356,6 +431,9 @@ function q($sql) {
                //logger("dba: q: $stmt", LOGGER_ALL);
                if ($stmt === false)
                        logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
+
+               $db->log_index($stmt);
+
                return $db->q($stmt);
        }
 
@@ -389,9 +467,12 @@ function qu($sql) {
                $stmt = @vsprintf($sql,$args); // Disabled warnings
                if ($stmt === false)
                        logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
-               $db->q("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
+
+               $db->log_index($stmt);
+
+               $db->q("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
                $retval = $db->q($stmt);
-               $db->q("COMMIT;");
+               $db->q("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;");
                return $retval;
        }