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