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