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