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