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