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