]> git.mxchange.org Git - friendica.git/blob - include/dba.php
Remove redundancies.
[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                 $connstr = ($this->connected() ? "Connected" : "Disonnected");
222
223                 $stamp1 = microtime(true);
224
225                 $orig_sql = $sql;
226
227                 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
228                         $sql = "/*".$a->callstack()." */ ".$sql;
229                 }
230
231                 $columns = 0;
232
233                 switch ($this->driver) {
234                         case 'pdo':
235                                 $result = @$this->db->query($sql);
236                                 // Is used to separate between queries that returning data - or not
237                                 $columns = $result->columnCount();
238                                 break;
239                         case 'mysqli':
240                                 $result = @$this->db->query($sql);
241                                 break;
242                         case 'mysql':
243                                 $result = @mysql_query($sql,$this->db);
244                                 break;
245                 }
246                 $stamp2 = microtime(true);
247                 $duration = (float)($stamp2-$stamp1);
248
249                 $a->save_timestamp($stamp1, "database");
250
251                 if (strtolower(substr($orig_sql, 0, 6)) != "select") {
252                         $a->save_timestamp($stamp1, "database_write");
253                 }
254                 if (x($a->config,'system') && x($a->config['system'],'db_log')) {
255                         if (($duration > $a->config["system"]["db_loglimit"])) {
256                                 $duration = round($duration, 3);
257                                 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
258                                 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
259                                                 basename($backtrace[1]["file"])."\t".
260                                                 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
261                                                 substr($sql, 0, 2000)."\n", FILE_APPEND);
262                         }
263                 }
264
265                 switch ($this->driver) {
266                         case 'pdo':
267                                 $errorInfo = $this->db->errorInfo();
268                                 if ($errorInfo) {
269                                         $this->error = $errorInfo[2];
270                                         $this->errorno = $errorInfo[1];
271                                 }
272                                 break;
273                         case 'mysqli':
274                                 if ($this->db->errno) {
275                                         $this->error = $this->db->error;
276                                         $this->errorno = $this->db->errno;
277                                 }
278                                 break;
279                         case 'mysql':
280                                 if (mysql_errno($this->db)) {
281                                         $this->error = mysql_error($this->db);
282                                         $this->errorno = mysql_errno($this->db);
283                                 }
284                                 break;
285                 }
286                 if (strlen($this->error)) {
287                         logger('DB Error ('.$connstr.') '.$this->errorno.': '.$this->error);
288                 }
289
290                 if ($this->debug) {
291
292                         $mesg = '';
293
294                         if ($result === false) {
295                                 $mesg = 'false';
296                         } elseif ($result === true) {
297                                 $mesg = 'true';
298                         } else {
299                                 switch ($this->driver) {
300                                         case 'pdo':
301                                                 $mesg = $result->rowCount().' results'.EOL;
302                                                 break;
303                                         case 'mysqli':
304                                                 $mesg = $result->num_rows.' results'.EOL;
305                                                 break;
306                                         case 'mysql':
307                                                 $mesg = mysql_num_rows($result).' results'.EOL;
308                                                 break;
309                                 }
310                         }
311
312                         $str =  'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
313                                 . (($this->error) ? ' error: ' . $this->error : '')
314                                 . EOL;
315
316                         logger('dba: ' . $str );
317                 }
318
319                 /**
320                  * If dbfail.out exists, we will write any failed calls directly to it,
321                  * regardless of any logging that may or may nor be in effect.
322                  * These usually indicate SQL syntax errors that need to be resolved.
323                  */
324
325                 if ($result === false) {
326                         logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
327                         if (file_exists('dbfail.out')) {
328                                 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
329                         }
330                 }
331
332                 if (($result === true) || ($result === false)) {
333                         return $result;
334                 }
335                 if ($onlyquery) {
336                         $this->result = $result;
337                         return true;
338                 }
339
340                 $r = array();
341                 switch ($this->driver) {
342                         case 'pdo':
343                                 while ($x = $result->fetch(PDO::FETCH_ASSOC)) {
344                                         $r[] = $x;
345                                 }
346                                 $result->closeCursor();
347                                 break;
348                         case 'mysqli':
349                                 while ($x = $result->fetch_array(MYSQLI_ASSOC)) {
350                                         $r[] = $x;
351                                 }
352                                 $result->free_result();
353                                 break;
354                         case 'mysql':
355                                 while ($x = mysql_fetch_array($result, MYSQL_ASSOC)) {
356                                         $r[] = $x;
357                                 }
358                                 mysql_free_result($result);
359                                 break;
360                 }
361
362                 // PDO doesn't return "true" on successful operations - like mysqli does
363                 // Emulate this behaviour by checking if the query returned data and had columns
364                 // This should be reliable enough
365                 if (($this->driver == 'pdo') AND (count($r) == 0) AND ($columns == 0)) {
366                         return true;
367                 }
368
369                 //$a->save_timestamp($stamp1, "database");
370
371                 if ($this->debug) {
372                         logger('dba: ' . printable(print_r($r, true)));
373                 }
374                 return($r);
375         }
376
377         public function qfetch() {
378                 $x = false;
379
380                 if ($this->result) {
381                         switch ($this->driver) {
382                                 case 'pdo':
383                                         $x = $this->result->fetch(PDO::FETCH_ASSOC);
384                                         break;
385                                 case 'mysqli':
386                                         $x = $this->result->fetch_array(MYSQLI_ASSOC);
387                                         break;
388                                 case 'mysql':
389                                         $x = mysql_fetch_array($this->result, MYSQL_ASSOC);
390                                         break;
391                         }
392                 }
393                 return($x);
394         }
395
396         public function qclose() {
397                 if ($this->result) {
398                         switch ($this->driver) {
399                                 case 'pdo':
400                                         $this->result->closeCursor();
401                                         break;
402                                 case 'mysqli':
403                                         $this->result->free_result();
404                                         break;
405                                 case 'mysql':
406                                         mysql_free_result($this->result);
407                                         break;
408                         }
409                 }
410         }
411
412         public function dbg($dbg) {
413                 $this->debug = $dbg;
414         }
415
416         public function escape($str) {
417                 if ($this->db && $this->connected) {
418                         switch ($this->driver) {
419                                 case 'pdo':
420                                         return substr(@$this->db->quote($str, PDO::PARAM_STR), 1, -1);
421                                 case 'mysqli':
422                                         return @$this->db->real_escape_string($str);
423                                 case 'mysql':
424                                         return @mysql_real_escape_string($str,$this->db);
425                         }
426                 }
427         }
428
429         function connected() {
430                 switch ($this->driver) {
431                         case 'pdo':
432                                 // Not sure if this really is working like expected
433                                 $connected = ($this->db->getAttribute(PDO::ATTR_CONNECTION_STATUS) != "");
434                                 break;
435                         case 'mysqli':
436                                 $connected = $this->db->ping();
437                                 break;
438                         case 'mysql':
439                                 $connected = mysql_ping($this->db);
440                                 break;
441                 }
442                 return $connected;
443         }
444
445         function insert_id() {
446                 switch ($this->driver) {
447                         case 'pdo':
448                                 $id = $this->db->lastInsertId();
449                                 break;
450                         case 'mysqli':
451                                 $id = $this->db->insert_id;
452                                 break;
453                         case 'mysql':
454                                 $id = mysql_insert_id($this->db);
455                                 break;
456                 }
457                 return $id;
458         }
459
460         function __destruct() {
461                 if ($this->db) {
462                         switch ($this->driver) {
463                                 case 'pdo':
464                                         $this->db = null;
465                                         break;
466                                 case 'mysqli':
467                                         $this->db->close();
468                                         break;
469                                 case 'mysql':
470                                         mysql_close($this->db);
471                                         break;
472                         }
473                 }
474         }
475 }
476
477 function printable($s) {
478         $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
479         $s = str_replace("\x00",'.',$s);
480         if (x($_SERVER,'SERVER_NAME')) {
481                 $s = escape_tags($s);
482         }
483         return $s;
484 }
485
486 // Procedural functions
487 function dbg($state) {
488         global $db;
489
490         if ($db) {
491                 $db->dbg($state);
492         }
493 }
494
495 function dbesc($str) {
496         global $db;
497
498         if ($db && $db->connected) {
499                 return($db->escape($str));
500         } else {
501                 return(str_replace("'","\\'",$str));
502         }
503 }
504
505 // Function: q($sql,$args);
506 // Description: execute SQL query with printf style args.
507 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
508 //                   'user', 1);
509 function q($sql) {
510         global $db;
511         $args = func_get_args();
512         unset($args[0]);
513
514         if ($db && $db->connected) {
515                 $stmt = @vsprintf($sql,$args); // Disabled warnings
516                 //logger("dba: q: $stmt", LOGGER_ALL);
517                 if ($stmt === false)
518                         logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
519
520                 $db->log_index($stmt);
521
522                 return $db->q($stmt);
523         }
524
525         /**
526          *
527          * This will happen occasionally trying to store the
528          * session data after abnormal program termination
529          *
530          */
531         logger('dba: no database: ' . print_r($args,true));
532         return false;
533 }
534
535 /**
536  * @brief Performs a query with "dirty reads"
537  *
538  * By doing dirty reads (reading uncommitted data) no locks are performed
539  * This function can be used to fetch data that doesn't need to be reliable.
540  *
541  * @param $args Query parameters (1 to N parameters of different types)
542  * @return array Query array
543  */
544 function qu($sql) {
545         global $db;
546
547         $args = func_get_args();
548         unset($args[0]);
549
550         if ($db && $db->connected) {
551                 $stmt = @vsprintf($sql,$args); // Disabled warnings
552                 if ($stmt === false)
553                         logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
554
555                 $db->log_index($stmt);
556
557                 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
558                 $retval = $db->q($stmt);
559                 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;");
560                 return $retval;
561         }
562
563         /**
564          *
565          * This will happen occasionally trying to store the
566          * session data after abnormal program termination
567          *
568          */
569         logger('dba: no database: ' . print_r($args,true));
570         return false;
571 }
572
573 /**
574  *
575  * Raw db query, no arguments
576  *
577  */
578 function dbq($sql) {
579         global $db;
580
581         if ($db && $db->connected) {
582                 $ret = $db->q($sql);
583         } else {
584                 $ret = false;
585         }
586         return $ret;
587 }
588
589 // Caller is responsible for ensuring that any integer arguments to
590 // dbesc_array are actually integers and not malformed strings containing
591 // SQL injection vectors. All integer array elements should be specifically
592 // cast to int to avoid trouble.
593 function dbesc_array_cb(&$item, $key) {
594         if (is_string($item))
595                 $item = dbesc($item);
596 }
597
598 function dbesc_array(&$arr) {
599         if (is_array($arr) && count($arr)) {
600                 array_walk($arr,'dbesc_array_cb');
601         }
602 }
603
604 function dba_timer() {
605         return microtime(true);
606 }