]> git.mxchange.org Git - friendica.git/blob - include/dba.php
Merge remote-tracking branch 'upstream/master'
[friendica.git] / include / dba.php
1 <?php
2
3 if(class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
4   require_once("library/dddbl2/dddbl.php");
5   require_once("include/dba_pdo.php");
6 }
7
8 require_once('include/datetime.php');
9
10 /**
11  *
12  * MySQL database class
13  *
14  * For debugging, insert 'dbg(1);' anywhere in the program flow.
15  * dbg(0); will turn it off. Logging is performed at LOGGER_DATA level.
16  * When logging, all binary info is converted to text and html entities are escaped so that 
17  * the debugging stream is safe to view within both terminals and web pages.
18  *
19  */
20  
21 if(! class_exists('dba')) { 
22 class dba {
23
24         private $debug = 0;
25         private $db;
26         private $result;
27         public  $mysqli = true;
28         public  $connected = false;
29         public  $error = false;
30
31         function __construct($server,$user,$pass,$db,$install = false) {
32                 global $a;
33
34                 $stamp1 = microtime(true);
35
36                 $server = trim($server);
37                 $user = trim($user);
38                 $pass = trim($pass);
39                 $db = trim($db);
40
41                 if (!(strlen($server) && strlen($user))){
42                         $this->connected = false;
43                         $this->db = null;
44                         return;
45                 }
46
47                 if($install) {
48                         if(strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) {
49                                 if(! dns_get_record($server, DNS_A + DNS_CNAME + DNS_PTR)) {
50                                         $this->error = sprintf( t('Cannot locate DNS info for database server \'%s\''), $server);
51                                         $this->connected = false;
52                                         $this->db = null;
53                                         return;
54                                 }
55                         }
56                 }
57
58                 if(class_exists('mysqli')) {
59                         $this->db = @new mysqli($server,$user,$pass,$db);
60                         if(! mysqli_connect_errno()) {
61                                 $this->connected = true;
62                         }
63                 }
64                 else {
65                         $this->mysqli = false;
66                         $this->db = mysql_connect($server,$user,$pass);
67                         if($this->db && mysql_select_db($db,$this->db)) {
68                                 $this->connected = true;
69                         }
70                 }
71                 if(! $this->connected) {
72                         $this->db = null;
73                         if(! $install)
74                                 system_unavailable();
75                 }
76
77                 $a->save_timestamp($stamp1, "network");
78         }
79
80         public function getdb() {
81                 return $this->db;
82         }
83
84         public function q($sql, $onlyquery = false) {
85                 global $a;
86
87                 if((! $this->db) || (! $this->connected))
88                         return false;
89
90                 $this->error = '';
91
92                 $stamp1 = microtime(true);
93
94                 if($this->mysqli)
95                         $result = @$this->db->query($sql);
96                 else
97                         $result = @mysql_query($sql,$this->db);
98
99                 $stamp2 = microtime(true);
100                 $duration = (float)($stamp2-$stamp1);
101
102                 $a->save_timestamp($stamp1, "database");
103
104                 if(x($a->config,'system') && x($a->config['system'],'db_log')) {
105                         if (($duration > $a->config["system"]["db_loglimit"])) {
106                                 $duration = round($duration, 3);
107                                 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
108                                 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
109                                                 basename($backtrace[1]["file"])."\t".
110                                                 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
111                                                 substr($sql, 0, 2000)."\n", FILE_APPEND);
112                         }
113                 }
114
115                 if($this->mysqli) {
116                         if($this->db->errno)
117                                 $this->error = $this->db->error;
118                 }
119                 elseif(mysql_errno($this->db))
120                                 $this->error = mysql_error($this->db);
121
122                 if(strlen($this->error)) {
123                         logger('dba: ' . $this->error);
124                 }
125
126                 if($this->debug) {
127
128                         $mesg = '';
129
130                         if($result === false)
131                                 $mesg = 'false';
132                         elseif($result === true)
133                                 $mesg = 'true';
134                         else {
135                                 if($this->mysqli)
136                                         $mesg = $result->num_rows . ' results' . EOL;
137                         else
138                                         $mesg = mysql_num_rows($result) . ' results' . EOL;
139                         }
140
141                         $str =  'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
142                                 . (($this->error) ? ' error: ' . $this->error : '')
143                                 . EOL;
144
145                         logger('dba: ' . $str );
146                 }
147
148                 /**
149                  * If dbfail.out exists, we will write any failed calls directly to it,
150                  * regardless of any logging that may or may nor be in effect.
151                  * These usually indicate SQL syntax errors that need to be resolved.
152                  */
153
154                 if($result === false) {
155                         logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
156                         if(file_exists('dbfail.out'))
157                                 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
158                 }
159
160                 if(($result === true) || ($result === false))
161                         return $result;
162
163                 if ($onlyquery) {
164                         $this->result = $result;
165                         return true;
166                 }
167
168                 $r = array();
169                 if($this->mysqli) {
170                         if($result->num_rows) {
171                                 while($x = $result->fetch_array(MYSQLI_ASSOC))
172                                         $r[] = $x;
173                                 $result->free_result();
174                         }
175                 }
176                 else {
177                         if(mysql_num_rows($result)) {
178                                 while($x = mysql_fetch_array($result, MYSQL_ASSOC))
179                                         $r[] = $x;
180                                 mysql_free_result($result);
181                         }
182                 }
183
184                 //$a->save_timestamp($stamp1, "database");
185
186                 if($this->debug)
187                         logger('dba: ' . printable(print_r($r, true)));
188                 return($r);
189         }
190
191         public function qfetch() {
192                 $x = false;
193
194                 if ($this->result)
195                         if($this->mysqli) {
196                                 if($this->result->num_rows)
197                                         $x = $this->result->fetch_array(MYSQLI_ASSOC);
198                         } else {
199                                 if(mysql_num_rows($this->result))
200                                         $x = mysql_fetch_array($this->result, MYSQL_ASSOC);
201                         }
202
203                 return($x);
204         }
205
206         public function qclose() {
207                 if ($this->result)
208                         if($this->mysqli) {
209                                 $this->result->free_result();
210                         } else {
211                                 mysql_free_result($this->result);
212                         }
213         }
214
215         public function dbg($dbg) {
216                 $this->debug = $dbg;
217         }
218
219         public function escape($str) {
220                 if($this->db && $this->connected) {
221                         if($this->mysqli)
222                                 return @$this->db->real_escape_string($str);
223                         else
224                                 return @mysql_real_escape_string($str,$this->db);
225                 }
226         }
227
228         function __destruct() {
229                 if ($this->db) 
230                         if($this->mysqli)
231                                 $this->db->close();
232                         else
233                                 mysql_close($this->db);
234         }
235 }}
236
237 if(! function_exists('printable')) {
238 function printable($s) {
239         $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
240         $s = str_replace("\x00",'.',$s);
241         if(x($_SERVER,'SERVER_NAME'))
242                 $s = escape_tags($s);
243         return $s;
244 }}
245
246 // Procedural functions
247 if(! function_exists('dbg')) { 
248 function dbg($state) {
249         global $db;
250         if($db)
251         $db->dbg($state);
252 }}
253
254 if(! function_exists('dbesc')) { 
255 function dbesc($str) {
256         global $db;
257         if($db && $db->connected)
258                 return($db->escape($str));
259         else
260                 return(str_replace("'","\\'",$str));
261 }}
262
263
264
265 // Function: q($sql,$args);
266 // Description: execute SQL query with printf style args.
267 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
268 //                   'user', 1);
269
270 if(! function_exists('q')) { 
271 function q($sql) {
272
273         global $db;
274         $args = func_get_args();
275         unset($args[0]);
276
277         if($db && $db->connected) {
278                 $stmt = @vsprintf($sql,$args); // Disabled warnings
279                 //logger("dba: q: $stmt", LOGGER_ALL);
280                 if($stmt === false)
281                         logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
282                 return $db->q($stmt);
283         }
284
285         /**
286          *
287          * This will happen occasionally trying to store the 
288          * session data after abnormal program termination 
289          *
290          */
291         logger('dba: no database: ' . print_r($args,true));
292         return false; 
293
294 }}
295
296 /**
297  *
298  * Raw db query, no arguments
299  *
300  */
301
302 if(! function_exists('dbq')) { 
303 function dbq($sql) {
304
305         global $db;
306         if($db && $db->connected)
307                 $ret = $db->q($sql);
308         else
309                 $ret = false;
310         return $ret;
311 }}
312
313
314 // Caller is responsible for ensuring that any integer arguments to 
315 // dbesc_array are actually integers and not malformed strings containing
316 // SQL injection vectors. All integer array elements should be specifically 
317 // cast to int to avoid trouble. 
318
319
320 if(! function_exists('dbesc_array_cb')) {
321 function dbesc_array_cb(&$item, $key) {
322         if(is_string($item))
323                 $item = dbesc($item);
324 }}
325
326
327 if(! function_exists('dbesc_array')) {
328 function dbesc_array(&$arr) {
329         if(is_array($arr) && count($arr)) {
330                 array_walk($arr,'dbesc_array_cb');
331         }
332 }}
333
334
335 function dba_timer() {
336         return microtime(true);
337 }
338