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