]> git.mxchange.org Git - friendica.git/blob - include/dba.php
Frio: recalculate sticky aside on click only on a tags
[friendica.git] / include / dba.php
1 <?php
2 require_once("dbm.php");
3 require_once('include/datetime.php');
4
5 /**
6  * @class MySQL database class
7  *
8  * For debugging, insert 'dbg(1);' anywhere in the program flow.
9  * dbg(0); will turn it off. Logging is performed at LOGGER_DATA level.
10  * When logging, all binary info is converted to text and html entities are escaped so that
11  * the debugging stream is safe to view within both terminals and web pages.
12  *
13  */
14
15 class dba {
16
17         private $debug = 0;
18         private $db;
19         private $result;
20         private $driver;
21         public  $connected = false;
22         public  $error = false;
23         private $_server_info = '';
24
25         function __construct($server, $user, $pass, $db, $install = false) {
26                 $a = get_app();
27
28                 $stamp1 = microtime(true);
29
30                 $server = trim($server);
31                 $user = trim($user);
32                 $pass = trim($pass);
33                 $db = trim($db);
34
35                 if (!(strlen($server) && strlen($user))) {
36                         $this->connected = false;
37                         $this->db = null;
38                         return;
39                 }
40
41                 if ($install) {
42                         if (strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) {
43                                 if (! dns_get_record($server, DNS_A + DNS_CNAME + DNS_PTR)) {
44                                         $this->error = sprintf(t('Cannot locate DNS info for database server \'%s\''), $server);
45                                         $this->connected = false;
46                                         $this->db = null;
47                                         return;
48                                 }
49                         }
50                 }
51
52                 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
53                         $this->driver = 'pdo';
54                         $connect = "mysql:host=".$server.";dbname=".$db;
55                         if (isset($a->config["system"]["db_charset"])) {
56                                 $connect .= ";charset=".$a->config["system"]["db_charset"];
57                         }
58                         $this->db = @new PDO($connect, $user, $pass);
59                         if (!$this->db->errorCode()) {
60                                 $this->connected = true;
61                         }
62                 } elseif (class_exists('mysqli')) {
63                         $this->driver = 'mysqli';
64                         $this->db = @new mysqli($server,$user,$pass,$db);
65                         if (!mysqli_connect_errno()) {
66                                 $this->connected = true;
67
68                                 if (isset($a->config["system"]["db_charset"])) {
69                                         $this->db->set_charset($a->config["system"]["db_charset"]);
70                                 }
71                         }
72                 } elseif (function_exists('mysql_connect')) {
73                         $this->driver = 'mysql';
74                         $this->db = mysql_connect($server,$user,$pass);
75                         if ($this->db && mysql_select_db($db,$this->db)) {
76                                 $this->connected = true;
77
78                                 if (isset($a->config["system"]["db_charset"])) {
79                                         mysql_set_charset($a->config["system"]["db_charset"], $this->db);
80                                 }
81                         }
82                 } else {
83                         // No suitable SQL driver was found.
84                         if (!$install) {
85                                 system_unavailable();
86                         }
87                 }
88
89                 if (!$this->connected) {
90                         $this->db = null;
91                         if (!$install) {
92                                 system_unavailable();
93                         }
94                 }
95                 $a->save_timestamp($stamp1, "network");
96         }
97
98         /**
99          * @brief Returns the MySQL server version string
100          * 
101          * This function discriminate between the deprecated mysql API and the current
102          * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
103          *
104          * @return string
105          */
106         public function server_info() {
107                 if ($this->_server_info == '') {
108                         switch ($this->driver) {
109                                 case 'pdo':
110                                         $this->_server_info = $this->db->getAttribute(PDO::ATTR_SERVER_VERSION);
111                                         break;
112                                 case 'mysqli':
113                                         $this->_server_info = $this->db->server_info;
114                                         break;
115                                 case 'mysql':
116                                         $this->_server_info = mysql_get_server_info($this->db);
117                                         break;
118                         }
119                 }
120                 return $this->_server_info;
121         }
122
123         /**
124          * @brief Returns the selected database name
125          *
126          * @return string
127          */
128         public function database_name() {
129                 $r = $this->q("SELECT DATABASE() AS `db`");
130
131                 return $r[0]['db'];
132         }
133
134         /**
135          * @brief Returns the number of rows
136          *
137          * @return integer
138          */
139         public function num_rows() {
140                 if (!$this->result) {
141                         return 0;
142                 }
143
144                 switch ($this->driver) {
145                         case 'pdo':
146                                 $rows = $this->result->rowCount();
147                                 break;
148                         case 'mysqli':
149                                 $rows = $this->result->num_rows;
150                                 break;
151                         case 'mysql':
152                                 $rows = mysql_num_rows($this->result);
153                                 break;
154                 }
155                 return $rows;
156         }
157
158         /**
159          * @brief Analyze a database query and log this if some conditions are met.
160          *
161          * @param string $query The database query that will be analyzed
162          */
163         public function log_index($query) {
164                 $a = get_app();
165
166                 if ($a->config["system"]["db_log_index"] == "") {
167                         return;
168                 }
169
170                 // Don't explain an explain statement
171                 if (strtolower(substr($query, 0, 7)) == "explain") {
172                         return;
173                 }
174
175                 // Only do the explain on "select", "update" and "delete"
176                 if (!in_array(strtolower(substr($query, 0, 6)), array("select", "update", "delete"))) {
177                         return;
178                 }
179
180                 $r = $this->q("EXPLAIN ".$query);
181                 if (!dbm::is_result($r)) {
182                         return;
183                 }
184
185                 $watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
186                 $blacklist = explode(',', $a->config["system"]["db_log_index_blacklist"]);
187
188                 foreach ($r AS $row) {
189                         if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
190                                 $log = (in_array($row['key'], $watchlist) AND
191                                         ($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
192                         } else {
193                                 $log = false;
194                         }
195
196                         if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) AND ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
197                                 $log = true;
198                         }
199
200                         if (in_array($row['key'], $blacklist) OR ($row['key'] == "")) {
201                                 $log = false;
202                         }
203
204                         if ($log) {
205                                 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
206                                 @file_put_contents($a->config["system"]["db_log_index"], datetime_convert()."\t".
207                                                 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
208                                                 basename($backtrace[1]["file"])."\t".
209                                                 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
210                                                 substr($query, 0, 2000)."\n", FILE_APPEND);
211                         }
212                 }
213         }
214
215         public function q($sql, $onlyquery = false) {
216                 $a = get_app();
217
218                 if (!$this->db || !$this->connected) {
219                         return false;
220                 }
221
222                 $this->error = '';
223
224                 $connstr = ($this->connected() ? "Connected" : "Disonnected");
225
226                 $stamp1 = microtime(true);
227
228                 $orig_sql = $sql;
229
230                 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
231                         $sql = "/*".$a->callstack()." */ ".$sql;
232                 }
233
234                 $columns = 0;
235
236                 switch ($this->driver) {
237                         case 'pdo':
238                                 $result = @$this->db->query($sql);
239                                 // Is used to separate between queries that returning data - or not
240                                 if (!is_bool($result)) {
241                                         $columns = $result->columnCount();
242                                 }
243                                 break;
244                         case 'mysqli':
245                                 $result = @$this->db->query($sql);
246                                 break;
247                         case 'mysql':
248                                 $result = @mysql_query($sql,$this->db);
249                                 break;
250                 }
251                 $stamp2 = microtime(true);
252                 $duration = (float)($stamp2-$stamp1);
253
254                 $a->save_timestamp($stamp1, "database");
255
256                 if (strtolower(substr($orig_sql, 0, 6)) != "select") {
257                         $a->save_timestamp($stamp1, "database_write");
258                 }
259                 if (x($a->config,'system') && x($a->config['system'],'db_log')) {
260                         if (($duration > $a->config["system"]["db_loglimit"])) {
261                                 $duration = round($duration, 3);
262                                 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
263                                 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
264                                                 basename($backtrace[1]["file"])."\t".
265                                                 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
266                                                 substr($sql, 0, 2000)."\n", FILE_APPEND);
267                         }
268                 }
269
270                 switch ($this->driver) {
271                         case 'pdo':
272                                 $errorInfo = $this->db->errorInfo();
273                                 if ($errorInfo) {
274                                         $this->error = $errorInfo[2];
275                                         $this->errorno = $errorInfo[1];
276                                 }
277                                 break;
278                         case 'mysqli':
279                                 if ($this->db->errno) {
280                                         $this->error = $this->db->error;
281                                         $this->errorno = $this->db->errno;
282                                 }
283                                 break;
284                         case 'mysql':
285                                 if (mysql_errno($this->db)) {
286                                         $this->error = mysql_error($this->db);
287                                         $this->errorno = mysql_errno($this->db);
288                                 }
289                                 break;
290                 }
291                 if (strlen($this->error)) {
292                         logger('DB Error ('.$connstr.') '.$this->errorno.': '.$this->error);
293                 }
294
295                 if ($this->debug) {
296
297                         $mesg = '';
298
299                         if ($result === false) {
300                                 $mesg = 'false';
301                         } elseif ($result === true) {
302                                 $mesg = 'true';
303                         } else {
304                                 switch ($this->driver) {
305                                         case 'pdo':
306                                                 $mesg = $result->rowCount().' results'.EOL;
307                                                 break;
308                                         case 'mysqli':
309                                                 $mesg = $result->num_rows.' results'.EOL;
310                                                 break;
311                                         case 'mysql':
312                                                 $mesg = mysql_num_rows($result).' results'.EOL;
313                                                 break;
314                                 }
315                         }
316
317                         $str =  'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
318                                 . (($this->error) ? ' error: ' . $this->error : '')
319                                 . EOL;
320
321                         logger('dba: ' . $str );
322                 }
323
324                 /**
325                  * If dbfail.out exists, we will write any failed calls directly to it,
326                  * regardless of any logging that may or may nor be in effect.
327                  * These usually indicate SQL syntax errors that need to be resolved.
328                  */
329
330                 if ($result === false) {
331                         logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
332                         if (file_exists('dbfail.out')) {
333                                 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
334                         }
335                 }
336
337                 if (is_bool($result)) {
338                         return $result;
339                 }
340                 if ($onlyquery) {
341                         $this->result = $result;
342                         return true;
343                 }
344
345                 $r = array();
346                 switch ($this->driver) {
347                         case 'pdo':
348                                 while ($x = $result->fetch(PDO::FETCH_ASSOC)) {
349                                         $r[] = $x;
350                                 }
351                                 $result->closeCursor();
352                                 break;
353                         case 'mysqli':
354                                 while ($x = $result->fetch_array(MYSQLI_ASSOC)) {
355                                         $r[] = $x;
356                                 }
357                                 $result->free_result();
358                                 break;
359                         case 'mysql':
360                                 while ($x = mysql_fetch_array($result, MYSQL_ASSOC)) {
361                                         $r[] = $x;
362                                 }
363                                 mysql_free_result($result);
364                                 break;
365                 }
366
367                 // PDO doesn't return "true" on successful operations - like mysqli does
368                 // Emulate this behaviour by checking if the query returned data and had columns
369                 // This should be reliable enough
370                 if (($this->driver == 'pdo') AND (count($r) == 0) AND ($columns == 0)) {
371                         return true;
372                 }
373
374                 //$a->save_timestamp($stamp1, "database");
375
376                 if ($this->debug) {
377                         logger('dba: ' . printable(print_r($r, true)));
378                 }
379                 return($r);
380         }
381
382         public function qfetch() {
383                 $x = false;
384
385                 if ($this->result) {
386                         switch ($this->driver) {
387                                 case 'pdo':
388                                         $x = $this->result->fetch(PDO::FETCH_ASSOC);
389                                         break;
390                                 case 'mysqli':
391                                         $x = $this->result->fetch_array(MYSQLI_ASSOC);
392                                         break;
393                                 case 'mysql':
394                                         $x = mysql_fetch_array($this->result, MYSQL_ASSOC);
395                                         break;
396                         }
397                 }
398                 return($x);
399         }
400
401         public function qclose() {
402                 if ($this->result) {
403                         switch ($this->driver) {
404                                 case 'pdo':
405                                         $this->result->closeCursor();
406                                         break;
407                                 case 'mysqli':
408                                         $this->result->free_result();
409                                         break;
410                                 case 'mysql':
411                                         mysql_free_result($this->result);
412                                         break;
413                         }
414                 }
415         }
416
417         public function dbg($dbg) {
418                 $this->debug = $dbg;
419         }
420
421         public function escape($str) {
422                 if ($this->db && $this->connected) {
423                         switch ($this->driver) {
424                                 case 'pdo':
425                                         return substr(@$this->db->quote($str, PDO::PARAM_STR), 1, -1);
426                                 case 'mysqli':
427                                         return @$this->db->real_escape_string($str);
428                                 case 'mysql':
429                                         return @mysql_real_escape_string($str,$this->db);
430                         }
431                 }
432         }
433
434         function connected() {
435                 switch ($this->driver) {
436                         case 'pdo':
437                                 // Not sure if this really is working like expected
438                                 $connected = ($this->db->getAttribute(PDO::ATTR_CONNECTION_STATUS) != "");
439                                 break;
440                         case 'mysqli':
441                                 $connected = $this->db->ping();
442                                 break;
443                         case 'mysql':
444                                 $connected = mysql_ping($this->db);
445                                 break;
446                 }
447                 return $connected;
448         }
449
450         function insert_id() {
451                 switch ($this->driver) {
452                         case 'pdo':
453                                 $id = $this->db->lastInsertId();
454                                 break;
455                         case 'mysqli':
456                                 $id = $this->db->insert_id;
457                                 break;
458                         case 'mysql':
459                                 $id = mysql_insert_id($this->db);
460                                 break;
461                 }
462                 return $id;
463         }
464
465         function __destruct() {
466                 if ($this->db) {
467                         switch ($this->driver) {
468                                 case 'pdo':
469                                         $this->db = null;
470                                         break;
471                                 case 'mysqli':
472                                         $this->db->close();
473                                         break;
474                                 case 'mysql':
475                                         mysql_close($this->db);
476                                         break;
477                         }
478                 }
479         }
480
481         /**
482          * @brief Replaces ANY_VALUE() function by MIN() function,
483          *  if the database server does not support ANY_VALUE().
484          *
485          * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
486          * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
487          * A standard fall-back is to use MIN().
488          *
489          * @param string $sql An SQL string without the values
490          * @return string The input SQL string modified if necessary.
491          */
492         public function any_value_fallback($sql) {
493                 $server_info = $this->server_info();
494                 if (version_compare($server_info, '5.7.5', '<') ||
495                         (stripos($server_info, 'MariaDB') !== false)) {
496                         $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
497                 }
498                 return $sql;
499         }
500 }
501
502 function printable($s) {
503         $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
504         $s = str_replace("\x00",'.',$s);
505         if (x($_SERVER,'SERVER_NAME')) {
506                 $s = escape_tags($s);
507         }
508         return $s;
509 }
510
511 // Procedural functions
512 function dbg($state) {
513         global $db;
514
515         if ($db) {
516                 $db->dbg($state);
517         }
518 }
519
520 function dbesc($str) {
521         global $db;
522
523         if ($db && $db->connected) {
524                 return($db->escape($str));
525         } else {
526                 return(str_replace("'","\\'",$str));
527         }
528 }
529
530 // Function: q($sql,$args);
531 // Description: execute SQL query with printf style args.
532 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
533 //                   'user', 1);
534 function q($sql) {
535         global $db;
536         $args = func_get_args();
537         unset($args[0]);
538
539         if ($db && $db->connected) {
540                 $sql = $db->any_value_fallback($sql);
541                 $stmt = @vsprintf($sql,$args); // Disabled warnings
542                 //logger("dba: q: $stmt", LOGGER_ALL);
543                 if ($stmt === false)
544                         logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
545
546                 $db->log_index($stmt);
547
548                 return $db->q($stmt);
549         }
550
551         /**
552          *
553          * This will happen occasionally trying to store the
554          * session data after abnormal program termination
555          *
556          */
557         logger('dba: no database: ' . print_r($args,true));
558         return false;
559 }
560
561 /**
562  * @brief Performs a query with "dirty reads"
563  *
564  * By doing dirty reads (reading uncommitted data) no locks are performed
565  * This function can be used to fetch data that doesn't need to be reliable.
566  *
567  * @param $args Query parameters (1 to N parameters of different types)
568  * @return array Query array
569  */
570 function qu($sql) {
571         global $db;
572
573         $args = func_get_args();
574         unset($args[0]);
575
576         if ($db && $db->connected) {
577                 $sql = $db->any_value_fallback($sql);
578                 $stmt = @vsprintf($sql,$args); // Disabled warnings
579                 if ($stmt === false)
580                         logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
581
582                 $db->log_index($stmt);
583
584                 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
585                 $retval = $db->q($stmt);
586                 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;");
587                 return $retval;
588         }
589
590         /**
591          *
592          * This will happen occasionally trying to store the
593          * session data after abnormal program termination
594          *
595          */
596         logger('dba: no database: ' . print_r($args,true));
597         return false;
598 }
599
600 /**
601  *
602  * Raw db query, no arguments
603  *
604  */
605 function dbq($sql) {
606         global $db;
607
608         if ($db && $db->connected) {
609                 $ret = $db->q($sql);
610         } else {
611                 $ret = false;
612         }
613         return $ret;
614 }
615
616 // Caller is responsible for ensuring that any integer arguments to
617 // dbesc_array are actually integers and not malformed strings containing
618 // SQL injection vectors. All integer array elements should be specifically
619 // cast to int to avoid trouble.
620 function dbesc_array_cb(&$item, $key) {
621         if (is_string($item))
622                 $item = dbesc($item);
623 }
624
625 function dbesc_array(&$arr) {
626         if (is_array($arr) && count($arr)) {
627                 array_walk($arr,'dbesc_array_cb');
628         }
629 }
630
631 function dba_timer() {
632         return microtime(true);
633 }