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