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