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