]> git.mxchange.org Git - friendica.git/blob - include/dba.php
Merge remote-tracking branch 'upstream/develop' into 1610-performance
[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                 global $a;
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 number of rows
114          *
115          * @return integer
116          */
117         public function num_rows() {
118                 if (!$this->result) {
119                         return 0;
120                 }
121
122                 if ($this->mysqli) {
123                         $return = $this->result->num_rows;
124                 } else {
125                         $return = mysql_num_rows($this->result);
126                 }
127                 return $return;
128         }
129
130         public function q($sql, $onlyquery = false) {
131                 global $a;
132
133                 if (!$this->db || !$this->connected) {
134                         return false;
135                 }
136
137                 $this->error = '';
138
139                 // Check the connection (This can reconnect the connection - if configured)
140                 if ($this->mysqli) {
141                         $connected = $this->db->ping();
142                 } else {
143                         $connected = mysql_ping($this->db);
144                 }
145                 $connstr = ($connected ? "Connected" : "Disonnected");
146
147                 $stamp1 = microtime(true);
148
149                 $orig_sql = $sql;
150
151                 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
152                         $sql = "/*".$a->callstack()." */ ".$sql;
153                 }
154
155                 if ($this->mysqli) {
156                         $result = @$this->db->query($sql);
157                 } else {
158                         $result = @mysql_query($sql,$this->db);
159                 }
160                 $stamp2 = microtime(true);
161                 $duration = (float)($stamp2-$stamp1);
162
163                 $a->save_timestamp($stamp1, "database");
164
165                 if (strtolower(substr($orig_sql, 0, 6)) != "select") {
166                         $a->save_timestamp($stamp1, "database_write");
167                 }
168                 if (x($a->config,'system') && x($a->config['system'],'db_log')) {
169                         if (($duration > $a->config["system"]["db_loglimit"])) {
170                                 $duration = round($duration, 3);
171                                 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
172                                 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
173                                                 basename($backtrace[1]["file"])."\t".
174                                                 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
175                                                 substr($sql, 0, 2000)."\n", FILE_APPEND);
176                         }
177                 }
178
179                 if ($this->mysqli) {
180                         if ($this->db->errno) {
181                                 $this->error = $this->db->error;
182                                 $this->errorno = $this->db->errno;
183                         }
184                 } elseif (mysql_errno($this->db)) {
185                         $this->error = mysql_error($this->db);
186                         $this->errorno = mysql_errno($this->db);
187                 }
188
189                 if (strlen($this->error)) {
190                         logger('DB Error ('.$connstr.') '.$this->errorno.': '.$this->error);
191                 }
192
193                 if ($this->debug) {
194
195                         $mesg = '';
196
197                         if ($result === false) {
198                                 $mesg = 'false';
199                         } elseif ($result === true) {
200                                 $mesg = 'true';
201                         } else {
202                                 if ($this->mysqli) {
203                                         $mesg = $result->num_rows . ' results' . EOL;
204                                 } else {
205                                         $mesg = mysql_num_rows($result) . ' results' . EOL;
206                                 }
207                         }
208
209                         $str =  'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
210                                 . (($this->error) ? ' error: ' . $this->error : '')
211                                 . EOL;
212
213                         logger('dba: ' . $str );
214                 }
215
216                 /**
217                  * If dbfail.out exists, we will write any failed calls directly to it,
218                  * regardless of any logging that may or may nor be in effect.
219                  * These usually indicate SQL syntax errors that need to be resolved.
220                  */
221
222                 if ($result === false) {
223                         logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
224                         if (file_exists('dbfail.out')) {
225                                 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
226                         }
227                 }
228
229                 if (($result === true) || ($result === false)) {
230                         return $result;
231                 }
232                 if ($onlyquery) {
233                         $this->result = $result;
234                         return true;
235                 }
236
237                 $r = array();
238                 if ($this->mysqli) {
239                         if ($result->num_rows) {
240                                 while($x = $result->fetch_array(MYSQLI_ASSOC))
241                                         $r[] = $x;
242                                 $result->free_result();
243                         }
244                 } else {
245                         if (mysql_num_rows($result)) {
246                                 while($x = mysql_fetch_array($result, MYSQL_ASSOC))
247                                         $r[] = $x;
248                                 mysql_free_result($result);
249                         }
250                 }
251
252                 //$a->save_timestamp($stamp1, "database");
253
254                 if ($this->debug) {
255                         logger('dba: ' . printable(print_r($r, true)));
256                 }
257                 return($r);
258         }
259
260         public function qfetch() {
261                 $x = false;
262
263                 if ($this->result) {
264                         if ($this->mysqli) {
265                                 if ($this->result->num_rows)
266                                         $x = $this->result->fetch_array(MYSQLI_ASSOC);
267                         } else {
268                                 if (mysql_num_rows($this->result))
269                                         $x = mysql_fetch_array($this->result, MYSQL_ASSOC);
270                         }
271                 }
272                 return($x);
273         }
274
275         public function qclose() {
276                 if ($this->result) {
277                         if ($this->mysqli) {
278                                 $this->result->free_result();
279                         } else {
280                                 mysql_free_result($this->result);
281                         }
282                 }
283         }
284
285         public function dbg($dbg) {
286                 $this->debug = $dbg;
287         }
288
289         public function escape($str) {
290                 if ($this->db && $this->connected) {
291                         if ($this->mysqli) {
292                                 return @$this->db->real_escape_string($str);
293                         } else {
294                                 return @mysql_real_escape_string($str,$this->db);
295                         }
296                 }
297         }
298
299         function connected() {
300                 if ($this->mysqli) {
301                         $connected = $this->db->ping();
302                 } else {
303                         $connected = mysql_ping($this->db);
304                 }
305                 return $connected;
306         }
307
308         function __destruct() {
309                 if ($this->db) {
310                         if ($this->mysqli) {
311                                 $this->db->close();
312                         } else {
313                                 mysql_close($this->db);
314                         }
315                 }
316         }
317 }}
318
319 if (! function_exists('printable')) {
320 function printable($s) {
321         $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
322         $s = str_replace("\x00",'.',$s);
323         if (x($_SERVER,'SERVER_NAME')) {
324                 $s = escape_tags($s);
325         }
326         return $s;
327 }}
328
329 // Procedural functions
330 if (! function_exists('dbg')) {
331 function dbg($state) {
332         global $db;
333         if ($db) {
334                 $db->dbg($state);
335         }
336 }}
337
338 if (! function_exists('dbesc')) {
339 function dbesc($str) {
340         global $db;
341         if ($db && $db->connected) {
342                 return($db->escape($str));
343         } else {
344                 return(str_replace("'","\\'",$str));
345         }
346 }}
347
348
349
350 // Function: q($sql,$args);
351 // Description: execute SQL query with printf style args.
352 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
353 //                   'user', 1);
354
355 if (! function_exists('q')) {
356 function q($sql) {
357
358         global $db;
359         $args = func_get_args();
360         unset($args[0]);
361
362         if ($db && $db->connected) {
363                 $stmt = @vsprintf($sql,$args); // Disabled warnings
364                 //logger("dba: q: $stmt", LOGGER_ALL);
365                 if ($stmt === false)
366                         logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
367                 return $db->q($stmt);
368         }
369
370         /**
371          *
372          * This will happen occasionally trying to store the
373          * session data after abnormal program termination
374          *
375          */
376         logger('dba: no database: ' . print_r($args,true));
377         return false;
378
379 }}
380
381 /**
382  * @brief Performs a query with "dirty reads"
383  *
384  * By doing dirty reads (reading uncommitted data) no locks are performed
385  * This function can be used to fetch data that doesn't need to be reliable.
386  *
387  * @param $args Query parameters (1 to N parameters of different types)
388  * @return array Query array
389  */
390 function qu($sql) {
391
392         global $db;
393         $args = func_get_args();
394         unset($args[0]);
395
396         if ($db && $db->connected) {
397                 $stmt = @vsprintf($sql,$args); // Disabled warnings
398                 if ($stmt === false)
399                         logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
400                 $db->q("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
401                 $retval = $db->q($stmt);
402                 $db->q("COMMIT;");
403                 return $retval;
404         }
405
406         /**
407          *
408          * This will happen occasionally trying to store the
409          * session data after abnormal program termination
410          *
411          */
412         logger('dba: no database: ' . print_r($args,true));
413         return false;
414
415 }
416
417 /**
418  *
419  * Raw db query, no arguments
420  *
421  */
422
423 if (! function_exists('dbq')) {
424 function dbq($sql) {
425
426         global $db;
427         if ($db && $db->connected) {
428                 $ret = $db->q($sql);
429         } else {
430                 $ret = false;
431         }
432         return $ret;
433 }}
434
435
436 // Caller is responsible for ensuring that any integer arguments to
437 // dbesc_array are actually integers and not malformed strings containing
438 // SQL injection vectors. All integer array elements should be specifically
439 // cast to int to avoid trouble.
440
441
442 if (! function_exists('dbesc_array_cb')) {
443 function dbesc_array_cb(&$item, $key) {
444         if (is_string($item))
445                 $item = dbesc($item);
446 }}
447
448
449 if (! function_exists('dbesc_array')) {
450 function dbesc_array(&$arr) {
451         if (is_array($arr) && count($arr)) {
452                 array_walk($arr,'dbesc_array_cb');
453         }
454 }}
455
456
457 function dba_timer() {
458         return microtime(true);
459 }