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