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