]> git.mxchange.org Git - friendica.git/blob - include/dba.php
Merge commit 'upstream/master'
[friendica.git] / include / dba.php
1 <?php
2
3 require_once('include/datetime.php');
4
5 /**
6  *
7  * MySQL database class
8  *
9  * For debugging, insert 'dbg(1);' anywhere in the program flow.
10  * dbg(0); will turn it off. Logging is performed at LOGGER_DATA level.
11  * When logging, all binary info is converted to text and html entities are escaped so that 
12  * the debugging stream is safe to view within both terminals and web pages.
13  *
14  */
15  
16 if(! class_exists('dba')) { 
17 class dba {
18
19         private $debug = 0;
20         private $db;
21         public  $mysqli = true;
22         public  $connected = false;
23         public  $error = false;
24
25         function __construct($server,$user,$pass,$db,$install = false) {
26
27                 $server = trim($server);
28                 $user = trim($user);
29                 $pass = trim($pass);
30                 $db = trim($db);
31
32                 if (!(strlen($server) && strlen($user))){
33                         $this->connected = false;
34                         $this->db = null;
35                         return;                 
36                 }
37                 
38                 if($install) {
39                         if(strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) {
40                                 if(! dns_get_record($server, DNS_A + DNS_CNAME + DNS_PTR)) {
41                                         $this->error = sprintf( t('Cannot locate DNS info for database server \'%s\''), $server);
42                                         $this->connected = false;
43                                         $this->db = null;
44                                         return;
45                                 }
46                         }
47                 }
48
49                 if(class_exists('mysqli')) {
50                         $this->db = @new mysqli($server,$user,$pass,$db);
51                         if(! mysqli_connect_errno()) {
52                                 $this->connected = true;
53                         }
54                 }
55                 else {
56                         $this->mysqli = false;
57                         $this->db = mysql_connect($server,$user,$pass);
58                         if($this->db && mysql_select_db($db,$this->db)) {
59                                 $this->connected = true;
60                         }
61                 }
62                 if(! $this->connected) {
63                         $this->db = null;
64                         if(! $install)
65                                 system_unavailable();
66                 }
67         }
68
69         public function getdb() {
70                 return $this->db;
71         }
72
73         public function q($sql) {
74                 
75                 if((! $this->db) || (! $this->connected))
76                         return false;
77                 
78                 if($this->mysqli)
79                         $result = @$this->db->query($sql);
80                 else
81                         $result = @mysql_query($sql,$this->db);
82
83                 if($this->debug) {
84
85                         $mesg = '';
86
87 <<<<<<< HEAD:include/dba.php
88                          // If dbfail.out exists, we will write any failed calls directly to it,
89                          // regardless of any logging that may or may nor be in effect.
90                          // These usually indicate SQL syntax errors that need to be resolved.
91                                 if(file_exists('dbfail.out')) {
92                                         file_put_contents('dbfail.out', datetime_convert() . "\n" . $str . "\n", FILE_APPEND);
93                                 }
94                                 logger('dba: ' . $str );
95                                 if(FALSE===$result) {
96                                         $this->throwOrLog(new RuntimeException('dba: ' . $str));
97                                         return; 
98                                 }
99 =======
100                         if($this->mysqli) {
101                                 if($this->db->errno)
102                                         logger('dba: ' . $this->db->error);
103 >>>>>>> upstream/master:include/dba.php
104                         }
105                         elseif(mysql_errno($this->db))
106                                 logger('dba: ' . mysql_error($this->db));
107
108                         if($result === false)
109                                 $mesg = 'false';
110                         elseif($result === true)
111                                 $mesg = 'true';
112                         else {
113                                 if($this->mysqli)
114                                         $mesg = $result->num_rows . ' results' . EOL;
115                         else
116                                         $mesg = mysql_num_rows($result) . ' results' . EOL;
117                         }
118     
119                         $str =  'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg . EOL;
120
121                         logger('dba: ' . $str );
122                 }
123
124                 /**
125                  * If dbfail.out exists, we will write any failed calls directly to it,
126                  * regardless of any logging that may or may nor be in effect.
127                  * These usually indicate SQL syntax errors that need to be resolved.
128                  */
129
130                 if($result === false) {
131                         logger('dba: ' . printable($sql) . ' returned false.');
132                         if(file_exists('dbfail.out'))
133                                 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n", FILE_APPEND);
134                 }
135
136                 if(($result === true) || ($result === false))
137                         return $result;
138
139                 $r = array();
140                 if($this->mysqli) {
141                         if($result->num_rows) {
142                                 while($x = $result->fetch_array(MYSQLI_ASSOC))
143                                         $r[] = $x;
144                                 $result->free_result();
145                         }
146                 }
147 <<<<<<< HEAD:include/dba.php
148                 
149                 /**
150                  * starts a transaction. Transactions need to be finished with 
151                  * commit() or rollback(). Please mind that the db table engine may
152                  * not support this. 
153                  */
154                 public function beginTransaction() {
155                         if($this->mysqli) {
156                                 return $this->db->autocommit(false);
157                         } else {
158                                 //no transaction support in mysql module...
159                                 mysql_query('SET AUTOCOMMIT = 0;', $db); 
160                         }
161                 }
162                 
163                 /**
164                  * rollback a transaction. So, rollback anything that was done since the last call 
165                  * to beginTransaction(). 
166                  */
167                 public function rollback() {
168                         if($this->mysqli) {
169                                 return $this->db->rollback();
170                         } else {
171                                 //no transaction support in mysql module...
172                                 mysql_query('ROLLBACK;', $db);
173                         }
174                         $this->stopTransaction(); 
175                 }
176
177                 /**
178                  * commit a transaction. So, write any query to the database. 
179                  */
180                 public function commit() {
181                         if($this->mysqli) {
182                                 return $this->db->commit();
183                         } else {
184                                 //no transaction support in mysql module...
185                                 mysql_query('COMMIT;', $db);
186                         }
187                         $this->stopTransaction();
188                 }
189                 
190                 private function stopTransaction() {
191                         if($this->mysqli) {
192                                 return $this->db->autocommit(true);
193                         } else {
194                                 //no transaction support in mysql module...
195                                 mysql_query('SET AUTOCOMMIT = 1;', $db);
196                         }
197                 }
198                 
199                 public function dbg($dbg) {
200                         $this->debug = $dbg;
201                 }
202 =======
203                 else {
204                         if(mysql_num_rows($result)) {
205                                 while($x = mysql_fetch_array($result, MYSQL_ASSOC))
206                                         $r[] = $x;
207                                 mysql_free_result($result);
208                         }
209                 }
210
211     
212                 if($this->debug)
213                         logger('dba: ' . printable(print_r($r, true)));
214                 return($r);
215         }
216 >>>>>>> upstream/master:include/dba.php
217
218         public function dbg($dbg) {
219                 $this->debug = $dbg;
220         }
221
222         public function escape($str) {
223                 if($this->db && $this->connected) {
224                         if($this->mysqli)
225                                 return @$this->db->real_escape_string($str);
226                         else
227                                 return @mysql_real_escape_string($str,$this->db);
228                 }
229         }
230
231         function __destruct() {
232                 if ($this->db) 
233                         if($this->mysqli)
234                                 $this->db->close();
235                         else
236                                 mysql_close($this->db);
237         }
238 }}
239
240 if(! function_exists('printable')) {
241 function printable($s) {
242         $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
243         $s = str_replace("\x00",'.',$s);
244         if(x($_SERVER,'SERVER_NAME'))
245                 $s = escape_tags($s);
246         return $s;
247 }}
248
249 // Procedural functions
250 if(! function_exists('dbg')) { 
251 function dbg($state) {
252         global $db;
253         if($db)
254         $db->dbg($state);
255 }}
256
257 if(! function_exists('dbesc')) { 
258 function dbesc($str) {
259         global $db;
260         if($db && $db->connected)
261                 return($db->escape($str));
262         else
263                 return(str_replace("'","\\'",$str));
264 }}
265
266
267
268 // Function: q($sql,$args);
269 // Description: execute SQL query with printf style args.
270 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
271 //                   'user', 1);
272
273 if(! function_exists('q')) { 
274 function q($sql) {
275
276         global $db;
277         $args = func_get_args();
278         unset($args[0]);
279
280         if($db && $db->connected) {
281                 $stmt = vsprintf($sql,$args);
282                 if($stmt === false)
283                         logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true));
284                 return $db->q($stmt);
285         }
286
287         /**
288          *
289          * This will happen occasionally trying to store the 
290          * session data after abnormal program termination 
291          *
292          */
293         logger('dba: no database: ' . print_r($args,true));
294         return false; 
295
296 }}
297
298 /**
299  *
300  * Raw db query, no arguments
301  *
302  */
303
304 if(! function_exists('dbq')) { 
305 function dbq($sql) {
306
307         global $db;
308         if($db && $db->connected)
309                 $ret = $db->q($sql);
310         else
311                 $ret = false;
312         return $ret;
313 }}
314
315
316 // Caller is responsible for ensuring that any integer arguments to 
317 // dbesc_array are actually integers and not malformed strings containing
318 // SQL injection vectors. All integer array elements should be specifically 
319 // cast to int to avoid trouble. 
320
321
322 if(! function_exists('dbesc_array_cb')) {
323 function dbesc_array_cb(&$item, $key) {
324         if(is_string($item))
325                 $item = dbesc($item);
326 }}
327
328
329 if(! function_exists('dbesc_array')) {
330 function dbesc_array(&$arr) {
331         if(is_array($arr) && count($arr)) {
332                 array_walk($arr,'dbesc_array_cb');
333         }
334 }}              
335
336