]> git.mxchange.org Git - friendica.git/blob - include/dba.php
Make Hypolite happy
[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         /**
142          * @brief Analyze a database query and log this if some conditions are met.
143          *
144          * @param string $query The database query that will be analyzed
145          */
146         public function log_index($query) {
147                 $a = get_app();
148
149                 if ($a->config["system"]["db_log_index"] == "") {
150                         return;
151                 }
152
153                 // Don't explain an explain statement
154                 if (strtolower(substr($query, 0, 7)) == "explain") {
155                         return;
156                 }
157
158                 // Only do the explain on "select", "update" and "delete"
159                 if (!in_array(strtolower(substr($query, 0, 6)), array("select", "update", "delete"))) {
160                         return;
161                 }
162
163                 $r = $this->q("EXPLAIN ".$query);
164                 if (!dbm::is_result($r)) {
165                         return;
166                 }
167
168                 $watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
169                 $blacklist = explode(',', $a->config["system"]["db_log_index_blacklist"]);
170
171                 foreach ($r AS $row) {
172                         if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
173                                 $log = (in_array($row['key'], $watchlist) AND
174                                         ($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
175                         } else
176                                 $log = false;
177
178                         if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) AND ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
179                                 $log = true;
180                         }
181
182                         if (in_array($row['key'], $blacklist) OR ($row['key'] == "")) {
183                                 $log = false;
184                         }
185
186                         if ($log) {
187                                 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
188                                 @file_put_contents($a->config["system"]["db_log_index"], datetime_convert()."\t".
189                                                 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
190                                                 basename($backtrace[1]["file"])."\t".
191                                                 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
192                                                 substr($query, 0, 2000)."\n", FILE_APPEND);
193                         }
194                 }
195         }
196
197         public function q($sql, $onlyquery = false) {
198                 $a = get_app();
199
200                 if (!$this->db || !$this->connected) {
201                         return false;
202                 }
203
204                 $this->error = '';
205
206                 // Check the connection (This can reconnect the connection - if configured)
207                 if ($this->mysqli) {
208                         $connected = $this->db->ping();
209                 } else {
210                         $connected = mysql_ping($this->db);
211                 }
212                 $connstr = ($connected ? "Connected" : "Disonnected");
213
214                 $stamp1 = microtime(true);
215
216                 $orig_sql = $sql;
217
218                 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
219                         $sql = "/*".$a->callstack()." */ ".$sql;
220                 }
221
222                 if ($this->mysqli) {
223                         $result = @$this->db->query($sql);
224                 } else {
225                         $result = @mysql_query($sql,$this->db);
226                 }
227                 $stamp2 = microtime(true);
228                 $duration = (float)($stamp2-$stamp1);
229
230                 $a->save_timestamp($stamp1, "database");
231
232                 if (strtolower(substr($orig_sql, 0, 6)) != "select") {
233                         $a->save_timestamp($stamp1, "database_write");
234                 }
235                 if (x($a->config,'system') && x($a->config['system'],'db_log')) {
236                         if (($duration > $a->config["system"]["db_loglimit"])) {
237                                 $duration = round($duration, 3);
238                                 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
239                                 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
240                                                 basename($backtrace[1]["file"])."\t".
241                                                 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
242                                                 substr($sql, 0, 2000)."\n", FILE_APPEND);
243                         }
244                 }
245
246                 if ($this->mysqli) {
247                         if ($this->db->errno) {
248                                 $this->error = $this->db->error;
249                                 $this->errorno = $this->db->errno;
250                         }
251                 } elseif (mysql_errno($this->db)) {
252                         $this->error = mysql_error($this->db);
253                         $this->errorno = mysql_errno($this->db);
254                 }
255
256                 if (strlen($this->error)) {
257                         logger('DB Error ('.$connstr.') '.$this->errorno.': '.$this->error);
258                 }
259
260                 if ($this->debug) {
261
262                         $mesg = '';
263
264                         if ($result === false) {
265                                 $mesg = 'false';
266                         } elseif ($result === true) {
267                                 $mesg = 'true';
268                         } else {
269                                 if ($this->mysqli) {
270                                         $mesg = $result->num_rows . ' results' . EOL;
271                                 } else {
272                                         $mesg = mysql_num_rows($result) . ' results' . EOL;
273                                 }
274                         }
275
276                         $str =  'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
277                                 . (($this->error) ? ' error: ' . $this->error : '')
278                                 . EOL;
279
280                         logger('dba: ' . $str );
281                 }
282
283                 /**
284                  * If dbfail.out exists, we will write any failed calls directly to it,
285                  * regardless of any logging that may or may nor be in effect.
286                  * These usually indicate SQL syntax errors that need to be resolved.
287                  */
288
289                 if ($result === false) {
290                         logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
291                         if (file_exists('dbfail.out')) {
292                                 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
293                         }
294                 }
295
296                 if (($result === true) || ($result === false)) {
297                         return $result;
298                 }
299                 if ($onlyquery) {
300                         $this->result = $result;
301                         return true;
302                 }
303
304                 $r = array();
305                 if ($this->mysqli) {
306                         if ($result->num_rows) {
307                                 while($x = $result->fetch_array(MYSQLI_ASSOC))
308                                         $r[] = $x;
309                                 $result->free_result();
310                         }
311                 } else {
312                         if (mysql_num_rows($result)) {
313                                 while($x = mysql_fetch_array($result, MYSQL_ASSOC))
314                                         $r[] = $x;
315                                 mysql_free_result($result);
316                         }
317                 }
318
319                 //$a->save_timestamp($stamp1, "database");
320
321                 if ($this->debug) {
322                         logger('dba: ' . printable(print_r($r, true)));
323                 }
324                 return($r);
325         }
326
327         public function qfetch() {
328                 $x = false;
329
330                 if ($this->result) {
331                         if ($this->mysqli) {
332                                 if ($this->result->num_rows)
333                                         $x = $this->result->fetch_array(MYSQLI_ASSOC);
334                         } else {
335                                 if (mysql_num_rows($this->result))
336                                         $x = mysql_fetch_array($this->result, MYSQL_ASSOC);
337                         }
338                 }
339                 return($x);
340         }
341
342         public function qclose() {
343                 if ($this->result) {
344                         if ($this->mysqli) {
345                                 $this->result->free_result();
346                         } else {
347                                 mysql_free_result($this->result);
348                         }
349                 }
350         }
351
352         public function dbg($dbg) {
353                 $this->debug = $dbg;
354         }
355
356         public function escape($str) {
357                 if ($this->db && $this->connected) {
358                         if ($this->mysqli) {
359                                 return @$this->db->real_escape_string($str);
360                         } else {
361                                 return @mysql_real_escape_string($str,$this->db);
362                         }
363                 }
364         }
365
366         function connected() {
367                 if ($this->mysqli) {
368                         $connected = $this->db->ping();
369                 } else {
370                         $connected = mysql_ping($this->db);
371                 }
372                 return $connected;
373         }
374
375         function __destruct() {
376                 if ($this->db) {
377                         if ($this->mysqli) {
378                                 $this->db->close();
379                         } else {
380                                 mysql_close($this->db);
381                         }
382                 }
383         }
384 }}
385
386 if (! function_exists('printable')) {
387 function printable($s) {
388         $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
389         $s = str_replace("\x00",'.',$s);
390         if (x($_SERVER,'SERVER_NAME')) {
391                 $s = escape_tags($s);
392         }
393         return $s;
394 }}
395
396 // Procedural functions
397 if (! function_exists('dbg')) {
398 function dbg($state) {
399         global $db;
400         if ($db) {
401                 $db->dbg($state);
402         }
403 }}
404
405 if (! function_exists('dbesc')) {
406 function dbesc($str) {
407         global $db;
408         if ($db && $db->connected) {
409                 return($db->escape($str));
410         } else {
411                 return(str_replace("'","\\'",$str));
412         }
413 }}
414
415
416
417 // Function: q($sql,$args);
418 // Description: execute SQL query with printf style args.
419 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
420 //                   'user', 1);
421
422 if (! function_exists('q')) {
423 function q($sql) {
424
425         global $db;
426         $args = func_get_args();
427         unset($args[0]);
428
429         if ($db && $db->connected) {
430                 $stmt = @vsprintf($sql,$args); // Disabled warnings
431                 //logger("dba: q: $stmt", LOGGER_ALL);
432                 if ($stmt === false)
433                         logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
434
435                 $db->log_index($stmt);
436
437                 return $db->q($stmt);
438         }
439
440         /**
441          *
442          * This will happen occasionally trying to store the
443          * session data after abnormal program termination
444          *
445          */
446         logger('dba: no database: ' . print_r($args,true));
447         return false;
448
449 }}
450
451 /**
452  * @brief Performs a query with "dirty reads"
453  *
454  * By doing dirty reads (reading uncommitted data) no locks are performed
455  * This function can be used to fetch data that doesn't need to be reliable.
456  *
457  * @param $args Query parameters (1 to N parameters of different types)
458  * @return array Query array
459  */
460 function qu($sql) {
461
462         global $db;
463         $args = func_get_args();
464         unset($args[0]);
465
466         if ($db && $db->connected) {
467                 $stmt = @vsprintf($sql,$args); // Disabled warnings
468                 if ($stmt === false)
469                         logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
470
471                 $db->log_index($stmt);
472
473                 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
474                 $retval = $db->q($stmt);
475                 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;");
476                 return $retval;
477         }
478
479         /**
480          *
481          * This will happen occasionally trying to store the
482          * session data after abnormal program termination
483          *
484          */
485         logger('dba: no database: ' . print_r($args,true));
486         return false;
487
488 }
489
490 /**
491  *
492  * Raw db query, no arguments
493  *
494  */
495
496 if (! function_exists('dbq')) {
497 function dbq($sql) {
498
499         global $db;
500         if ($db && $db->connected) {
501                 $ret = $db->q($sql);
502         } else {
503                 $ret = false;
504         }
505         return $ret;
506 }}
507
508
509 // Caller is responsible for ensuring that any integer arguments to
510 // dbesc_array are actually integers and not malformed strings containing
511 // SQL injection vectors. All integer array elements should be specifically
512 // cast to int to avoid trouble.
513
514
515 if (! function_exists('dbesc_array_cb')) {
516 function dbesc_array_cb(&$item, $key) {
517         if (is_string($item))
518                 $item = dbesc($item);
519 }}
520
521
522 if (! function_exists('dbesc_array')) {
523 function dbesc_array(&$arr) {
524         if (is_array($arr) && count($arr)) {
525                 array_walk($arr,'dbesc_array_cb');
526         }
527 }}
528
529
530 function dba_timer() {
531         return microtime(true);
532 }