]> git.mxchange.org Git - friendica.git/blob - include/dba.php
Merge branch 'master' of git://github.com/friendica/friendica
[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                 $this->error = '';
79
80                 //if (get_config("system", "db_log") != "")
81                 //      @file_put_contents(get_config("system", "db_log"), datetime_convert().':'.session_id(). ' Start '.$sql."\n", FILE_APPEND);
82
83                 if($this->mysqli)
84                         $result = @$this->db->query($sql);
85                 else
86                         $result = @mysql_query($sql,$this->db);
87
88                 //if (get_config("system", "db_log") != "")
89                 //      @file_put_contents(get_config("system", "db_log"), datetime_convert().':'.session_id(). ' Stop '."\n", FILE_APPEND);
90
91                 if($this->mysqli) {
92                         if($this->db->errno)
93                                 $this->error = $this->db->error;
94                 }
95                 elseif(mysql_errno($this->db))
96                                 $this->error = mysql_error($this->db);
97
98                 if(strlen($this->error)) {
99                         logger('dba: ' . $this->error);
100                 }
101
102                 if($this->debug) {
103
104                         $mesg = '';
105
106                         if($result === false)
107                                 $mesg = 'false';
108                         elseif($result === true)
109                                 $mesg = 'true';
110                         else {
111                                 if($this->mysqli)
112                                         $mesg = $result->num_rows . ' results' . EOL;
113                         else
114                                         $mesg = mysql_num_rows($result) . ' results' . EOL;
115                         }
116
117                         $str =  'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
118                                 . (($this->error) ? ' error: ' . $this->error : '')
119                                 . 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.' . "\n" . $this->error);
132                         if(file_exists('dbfail.out'))
133                                 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\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                 else {
148                         if(mysql_num_rows($result)) {
149                                 while($x = mysql_fetch_array($result, MYSQL_ASSOC))
150                                         $r[] = $x;
151                                 mysql_free_result($result);
152                         }
153                 }
154
155
156                 if($this->debug)
157                         logger('dba: ' . printable(print_r($r, true)));
158                 return($r);
159         }
160
161         public function dbg($dbg) {
162                 $this->debug = $dbg;
163         }
164
165         public function escape($str) {
166                 if($this->db && $this->connected) {
167                         if($this->mysqli)
168                                 return @$this->db->real_escape_string($str);
169                         else
170                                 return @mysql_real_escape_string($str,$this->db);
171                 }
172         }
173
174         function __destruct() {
175                 if ($this->db) 
176                         if($this->mysqli)
177                                 $this->db->close();
178                         else
179                                 mysql_close($this->db);
180         }
181 }}
182
183 if(! function_exists('printable')) {
184 function printable($s) {
185         $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
186         $s = str_replace("\x00",'.',$s);
187         if(x($_SERVER,'SERVER_NAME'))
188                 $s = escape_tags($s);
189         return $s;
190 }}
191
192 // Procedural functions
193 if(! function_exists('dbg')) { 
194 function dbg($state) {
195         global $db;
196         if($db)
197         $db->dbg($state);
198 }}
199
200 if(! function_exists('dbesc')) { 
201 function dbesc($str) {
202         global $db;
203         if($db && $db->connected)
204                 return($db->escape($str));
205         else
206                 return(str_replace("'","\\'",$str));
207 }}
208
209
210
211 // Function: q($sql,$args);
212 // Description: execute SQL query with printf style args.
213 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
214 //                   'user', 1);
215
216 if(! function_exists('q')) { 
217 function q($sql) {
218
219         global $db;
220         $args = func_get_args();
221         unset($args[0]);
222
223         if($db && $db->connected) {
224                 $stmt = vsprintf($sql,$args);
225                 if($stmt === false)
226                         logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true));
227                 return $db->q($stmt);
228         }
229
230         /**
231          *
232          * This will happen occasionally trying to store the 
233          * session data after abnormal program termination 
234          *
235          */
236         logger('dba: no database: ' . print_r($args,true));
237         return false; 
238
239 }}
240
241 /**
242  *
243  * Raw db query, no arguments
244  *
245  */
246
247 if(! function_exists('dbq')) { 
248 function dbq($sql) {
249
250         global $db;
251         if($db && $db->connected)
252                 $ret = $db->q($sql);
253         else
254                 $ret = false;
255         return $ret;
256 }}
257
258
259 // Caller is responsible for ensuring that any integer arguments to 
260 // dbesc_array are actually integers and not malformed strings containing
261 // SQL injection vectors. All integer array elements should be specifically 
262 // cast to int to avoid trouble. 
263
264
265 if(! function_exists('dbesc_array_cb')) {
266 function dbesc_array_cb(&$item, $key) {
267         if(is_string($item))
268                 $item = dbesc($item);
269 }}
270
271
272 if(! function_exists('dbesc_array')) {
273 function dbesc_array(&$arr) {
274         if(is_array($arr) && count($arr)) {
275                 array_walk($arr,'dbesc_array_cb');
276         }
277 }}