]> git.mxchange.org Git - friendica.git/blob - include/dba.php
Emulation for the mysqli behaviour when executing insert, update, ...
[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                 } elseif (($this->driver == 'pdo') AND (strtolower(substr($orig_sql, 0, 6)) != "select")) {
338                         // mysqli separates the return value between "select" and "update" - pdo doesn't
339                         $result = true;
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                 //$a->save_timestamp($stamp1, "database");
376
377                 if ($this->debug) {
378                         logger('dba: ' . printable(print_r($r, true)));
379                 }
380                 return($r);
381         }
382
383         public function qfetch() {
384                 $x = false;
385
386                 if ($this->result) {
387                         switch ($this->driver) {
388                                 case 'pdo':
389                                         if ($this->result->rowCount()) {
390                                                 $x = $this->result->fetch(PDO::FETCH_ASSOC);
391                                         }
392                                         break;
393                                 case 'mysqli':
394                                         if ($this->result->num_rows) {
395                                                 $x = $this->result->fetch_array(MYSQLI_ASSOC);
396                                         }
397                                         break;
398                                 case 'mysql':
399                                         if (mysql_num_rows($this->result)) {
400                                                 $x = mysql_fetch_array($this->result, MYSQL_ASSOC);
401                                         }
402                                         break;
403                         }
404                 }
405                 return($x);
406         }
407
408         public function qclose() {
409                 if ($this->result) {
410                         switch ($this->driver) {
411                                 case 'pdo':
412                                         $this->result->closeCursor();
413                                         break;
414                                 case 'mysqli':
415                                         $this->result->free_result();
416                                         break;
417                                 case 'mysql':
418                                         mysql_free_result($this->result);
419                                         break;
420                         }
421                 }
422         }
423
424         public function dbg($dbg) {
425                 $this->debug = $dbg;
426         }
427
428         public function escape($str) {
429                 if ($this->db && $this->connected) {
430                         switch ($this->driver) {
431                                 case 'pdo':
432                                         return substr(@$this->db->quote($str, PDO::PARAM_STR), 1, -1);
433                                 case 'mysqli':
434                                         return @$this->db->real_escape_string($str);
435                                 case 'mysql':
436                                         return @mysql_real_escape_string($str,$this->db);
437                         }
438                 }
439         }
440
441         function connected() {
442                 switch ($this->driver) {
443                         case 'pdo':
444                                 // Not sure if this really is working like expected
445                                 $connected = ($this->db->getAttribute(PDO::ATTR_CONNECTION_STATUS) != "");
446                                 break;
447                         case 'mysqli':
448                                 $connected = $this->db->ping();
449                                 break;
450                         case 'mysql':
451                                 $connected = mysql_ping($this->db);
452                                 break;
453                 }
454                 return $connected;
455         }
456
457         function insert_id() {
458                 switch ($this->driver) {
459                         case 'pdo':
460                                 $id = $this->db->lastInsertId();
461                                 break;
462                         case 'mysqli':
463                                 $id = $this->db->insert_id;
464                                 break;
465                         case 'mysql':
466                                 $id = mysql_insert_id($this->db);
467                                 break;
468                 }
469                 return $id;
470         }
471
472         function __destruct() {
473                 if ($this->db) {
474                         switch ($this->driver) {
475                                 case 'pdo':
476                                         $this->db = null;
477                                         break;
478                                 case 'mysqli':
479                                         $this->db->close();
480                                         break;
481                                 case 'mysql':
482                                         mysql_close($this->db);
483                                         break;
484                         }
485                 }
486         }
487 }
488
489 function printable($s) {
490         $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
491         $s = str_replace("\x00",'.',$s);
492         if (x($_SERVER,'SERVER_NAME')) {
493                 $s = escape_tags($s);
494         }
495         return $s;
496 }
497
498 // Procedural functions
499 function dbg($state) {
500         global $db;
501
502         if ($db) {
503                 $db->dbg($state);
504         }
505 }
506
507 function dbesc($str) {
508         global $db;
509
510         if ($db && $db->connected) {
511                 return($db->escape($str));
512         } else {
513                 return(str_replace("'","\\'",$str));
514         }
515 }
516
517 // Function: q($sql,$args);
518 // Description: execute SQL query with printf style args.
519 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
520 //                   'user', 1);
521 function q($sql) {
522         global $db;
523         $args = func_get_args();
524         unset($args[0]);
525
526         if ($db && $db->connected) {
527                 $stmt = @vsprintf($sql,$args); // Disabled warnings
528                 //logger("dba: q: $stmt", LOGGER_ALL);
529                 if ($stmt === false)
530                         logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
531
532                 $db->log_index($stmt);
533
534                 return $db->q($stmt);
535         }
536
537         /**
538          *
539          * This will happen occasionally trying to store the
540          * session data after abnormal program termination
541          *
542          */
543         logger('dba: no database: ' . print_r($args,true));
544         return false;
545 }
546
547 /**
548  * @brief Performs a query with "dirty reads"
549  *
550  * By doing dirty reads (reading uncommitted data) no locks are performed
551  * This function can be used to fetch data that doesn't need to be reliable.
552  *
553  * @param $args Query parameters (1 to N parameters of different types)
554  * @return array Query array
555  */
556 function qu($sql) {
557         global $db;
558
559         $args = func_get_args();
560         unset($args[0]);
561
562         if ($db && $db->connected) {
563                 $stmt = @vsprintf($sql,$args); // Disabled warnings
564                 if ($stmt === false)
565                         logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
566
567                 $db->log_index($stmt);
568
569                 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
570                 $retval = $db->q($stmt);
571                 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;");
572                 return $retval;
573         }
574
575         /**
576          *
577          * This will happen occasionally trying to store the
578          * session data after abnormal program termination
579          *
580          */
581         logger('dba: no database: ' . print_r($args,true));
582         return false;
583 }
584
585 /**
586  *
587  * Raw db query, no arguments
588  *
589  */
590 function dbq($sql) {
591         global $db;
592
593         if ($db && $db->connected) {
594                 $ret = $db->q($sql);
595         } else {
596                 $ret = false;
597         }
598         return $ret;
599 }
600
601 // Caller is responsible for ensuring that any integer arguments to
602 // dbesc_array are actually integers and not malformed strings containing
603 // SQL injection vectors. All integer array elements should be specifically
604 // cast to int to avoid trouble.
605 function dbesc_array_cb(&$item, $key) {
606         if (is_string($item))
607                 $item = dbesc($item);
608 }
609
610 function dbesc_array(&$arr) {
611         if (is_array($arr) && count($arr)) {
612                 array_walk($arr,'dbesc_array_cb');
613         }
614 }
615
616 function dba_timer() {
617         return microtime(true);
618 }