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