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