]> git.mxchange.org Git - friendica.git/blob - include/dba.php
Merge pull request #2758 from annando/1609-sql-charset
[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 __destruct() {
253                 if ($this->db)
254                         if($this->mysqli)
255                                 $this->db->close();
256                         else
257                                 mysql_close($this->db);
258         }
259 }}
260
261 if(! function_exists('printable')) {
262 function printable($s) {
263         $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
264         $s = str_replace("\x00",'.',$s);
265         if(x($_SERVER,'SERVER_NAME'))
266                 $s = escape_tags($s);
267         return $s;
268 }}
269
270 // Procedural functions
271 if(! function_exists('dbg')) {
272 function dbg($state) {
273         global $db;
274         if($db)
275         $db->dbg($state);
276 }}
277
278 if(! function_exists('dbesc')) {
279 function dbesc($str) {
280         global $db;
281         if($db && $db->connected)
282                 return($db->escape($str));
283         else
284                 return(str_replace("'","\\'",$str));
285 }}
286
287
288
289 // Function: q($sql,$args);
290 // Description: execute SQL query with printf style args.
291 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
292 //                   'user', 1);
293
294 if(! function_exists('q')) {
295 function q($sql) {
296
297         global $db;
298         $args = func_get_args();
299         unset($args[0]);
300
301         if($db && $db->connected) {
302                 $stmt = @vsprintf($sql,$args); // Disabled warnings
303                 //logger("dba: q: $stmt", LOGGER_ALL);
304                 if($stmt === false)
305                         logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
306                 return $db->q($stmt);
307         }
308
309         /**
310          *
311          * This will happen occasionally trying to store the
312          * session data after abnormal program termination
313          *
314          */
315         logger('dba: no database: ' . print_r($args,true));
316         return false;
317
318 }}
319
320 /**
321  *
322  * Raw db query, no arguments
323  *
324  */
325
326 if(! function_exists('dbq')) {
327 function dbq($sql) {
328
329         global $db;
330         if($db && $db->connected)
331                 $ret = $db->q($sql);
332         else
333                 $ret = false;
334         return $ret;
335 }}
336
337
338 // Caller is responsible for ensuring that any integer arguments to
339 // dbesc_array are actually integers and not malformed strings containing
340 // SQL injection vectors. All integer array elements should be specifically
341 // cast to int to avoid trouble.
342
343
344 if(! function_exists('dbesc_array_cb')) {
345 function dbesc_array_cb(&$item, $key) {
346         if(is_string($item))
347                 $item = dbesc($item);
348 }}
349
350
351 if(! function_exists('dbesc_array')) {
352 function dbesc_array(&$arr) {
353         if(is_array($arr) && count($arr)) {
354                 array_walk($arr,'dbesc_array_cb');
355         }
356 }}
357
358
359 function dba_timer() {
360         return microtime(true);
361 }