]> git.mxchange.org Git - friendica.git/blob - include/dba_pdo.php
Use `use` instead of `\`
[friendica.git] / include / dba_pdo.php
1 <?php
2
3 use DDDBL;
4
5 use Exception;
6
7 require_once('include/datetime.php');
8
9 $objDDDBLResultHandler = new DDDBL\DataObjectPool('Result-Handler');
10
11 /**
12   * create handler, which returns just the PDOStatement object
13   * this allows usage of the cursor to scroll through
14   * big result-sets
15   *
16   **/
17 $cloPDOStatementResultHandler = function(DDDBL\Queue $objQueue) {
18
19   $objPDO = $objQueue->getState()->get('PDOStatement');
20   $objQueue->getState()->update(array('result' => $objPDO));
21
22   # delete handler which closes the PDOStatement-cursor
23   # this will be done manual if using this handler
24   $objQueue->deleteHandler(QUEUE_CLOSE_CURSOR_POSITION);
25
26 };
27
28 $objDDDBLResultHandler->add('PDOStatement', array('HANDLER' => $cloPDOStatementResultHandler));
29
30 /**
31  *
32  * MySQL database class
33  *
34  * For debugging, insert 'dbg(1);' anywhere in the program flow.
35  * dbg(0); will turn it off. Logging is performed at LOGGER_DATA level.
36  * When logging, all binary info is converted to text and html entities are escaped so that
37  * the debugging stream is safe to view within both terminals and web pages.
38  *
39  */
40
41 if (! class_exists('dba')) {
42 class dba {
43
44         private $debug = 0;
45         private $db;
46         private $result;
47         public  $connected = false;
48         public  $error = false;
49
50         function __construct($server,$user,$pass,$db,$install = false) {
51                 $a = get_app();
52
53     # work around, to store the database - configuration in DDDBL
54     $objDataObjectPool = new DDDBL\DataObjectPool('Database-Definition');
55     $objDataObjectPool->add('DEFAULT', array('CONNECTION' => "mysql:host=$server;dbname=$db",
56                                              'USER'       => $user,
57                                              'PASS'       => $pass,
58                                              'DEFAULT'    => true));
59
60                 $stamp1 = microtime(true);
61
62                 $server = trim($server);
63                 $user = trim($user);
64                 $pass = trim($pass);
65                 $db = trim($db);
66
67                 if (!(strlen($server) && strlen($user))){
68                         $this->connected = false;
69                         $this->db = null;
70                         return;
71                 }
72
73                 if ($install) {
74                         if (strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) {
75                                 if (! dns_get_record($server, DNS_A + DNS_CNAME + DNS_PTR)) {
76                                         $this->error = sprintf( t('Cannot locate DNS info for database server \'%s\''), $server);
77                                         $this->connected = false;
78                                         $this->db = null;
79                                         return;
80                                 }
81                         }
82                 }
83
84     # etablish connection to database and store PDO object
85     DDDBL\connect();
86     $this->db = DDDBL\getDB();
87
88     if (DDDBL\isConnected()) {
89       $this->connected = true;
90     }
91
92                 if (! $this->connected) {
93                         $this->db = null;
94                         if (! $install)
95                                 system_unavailable();
96                 }
97
98                 $a->save_timestamp($stamp1, "network");
99         }
100
101         public function getdb() {
102                 return $this->db;
103         }
104
105         public function q($sql, $onlyquery = false) {
106                 $a = get_app();
107
108     $strHandler = (true === $onlyquery) ? 'PDOStatement' : 'MULTI';
109
110     $strQueryAlias = md5($sql);
111     $strSQLType    = strtoupper(strstr($sql, ' ', true));
112
113     $objPreparedQueryPool = new DDDBL\DataObjectPool('Query-Definition');
114
115     # check if query do not exists till now, if so create its definition
116     if (!$objPreparedQueryPool->exists($strQueryAlias))
117       $objPreparedQueryPool->add($strQueryAlias, array('QUERY'   => $sql,
118                                                        'HANDLER' => $strHandler));
119
120                 if ((! $this->db) || (! $this->connected))
121                         return false;
122
123                 $this->error = '';
124
125                 $stamp1 = microtime(true);
126
127     try {
128       $r = DDDBL\get($strQueryAlias);
129
130       # bad workaround to emulate the bizzare behavior of mysql_query
131       if (in_array($strSQLType, array('INSERT', 'UPDATE', 'DELETE', 'CREATE', 'DROP', 'SET')))
132         $result = true;
133       $intErrorCode = false;
134
135     } catch (Exception $objException) {
136       $result = false;
137       $intErrorCode = $objPreparedQueryPool->get($strQueryAlias)->get('PDOStatement')->errorCode();
138     }
139
140                 $stamp2 = microtime(true);
141                 $duration = (float)($stamp2-$stamp1);
142
143                 $a->save_timestamp($stamp1, "database");
144
145                 if (x($a->config,'system') && x($a->config['system'],'db_log')) {
146                         if (($duration > $a->config["system"]["db_loglimit"])) {
147                                 $duration = round($duration, 3);
148                                 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
149                                 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
150                                                 basename($backtrace[1]["file"])."\t".
151                                                 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
152                                                 substr($sql, 0, 2000)."\n", FILE_APPEND);
153                         }
154                 }
155
156                 if ($intErrorCode)
157       $this->error = $intErrorCode;
158
159                 if (strlen($this->error)) {
160                         logger('dba: ' . $this->error);
161                 }
162
163                 if ($this->debug) {
164
165                         $mesg = '';
166
167                         if ($result === false)
168                                 $mesg = 'false';
169                         elseif ($result === true)
170                                 $mesg = 'true';
171                         else {
172         # this needs fixing, but is a bug itself
173                                 #$mesg = mysql_num_rows($result) . ' results' . EOL;
174                         }
175
176                         $str =  'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
177                                 . (($this->error) ? ' error: ' . $this->error : '')
178                                 . EOL;
179
180                         logger('dba: ' . $str );
181                 }
182
183                 /**
184                  * If dbfail.out exists, we will write any failed calls directly to it,
185                  * regardless of any logging that may or may nor be in effect.
186                  * These usually indicate SQL syntax errors that need to be resolved.
187                  */
188
189                 if (isset($result) AND ($result === false)) {
190                         logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
191                         if (file_exists('dbfail.out'))
192                                 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
193                 }
194
195                 if (isset($result) AND (($result === true) || ($result === false)))
196                         return $result;
197
198                 if ($onlyquery) {
199                         $this->result = $r;       # this will store an PDOStatement Object in result
200       $this->result->execute(); # execute the Statement, to get its result
201                         return true;
202                 }
203
204                 //$a->save_timestamp($stamp1, "database");
205
206                 if ($this->debug)
207                         logger('dba: ' . printable(print_r($r, true)));
208                 return($r);
209         }
210
211         public function qfetch() {
212
213                 if (false === $this->result)
214       return false;
215
216     return $this->result->fetch();
217
218         }
219
220         public function qclose() {
221                 if ($this->result)
222       return $this->result->closeCursor();
223         }
224
225         public function dbg($dbg) {
226                 $this->debug = $dbg;
227         }
228
229         public function escape($str) {
230                 if ($this->db && $this->connected) {
231       $strQuoted = $this->db->quote($str);
232       # this workaround is needed, because quote creates "'" and the beginning and the end
233       # of the string, which is correct. but until now the queries set this delimiter manually,
234       # so we must remove them from here and wait until everything uses prepared statements
235       return mb_substr($strQuoted, 1, mb_strlen($strQuoted) - 2);
236                 }
237         }
238
239         function __destruct() {
240                 if ($this->db)
241                   DDDBL\disconnect();
242         }
243 }}
244
245 if (! function_exists('printable')) {
246 function printable($s) {
247         $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
248         $s = str_replace("\x00",'.',$s);
249         if (x($_SERVER,'SERVER_NAME'))
250                 $s = escape_tags($s);
251         return $s;
252 }}
253
254 // Procedural functions
255 if (! function_exists('dbg')) {
256 function dbg($state) {
257         global $db;
258         if ($db)
259         $db->dbg($state);
260 }}
261
262 if (! function_exists('dbesc')) {
263 function dbesc($str) {
264         global $db;
265         if ($db && $db->connected)
266                 return($db->escape($str));
267         else
268                 return(str_replace("'","\\'",$str));
269 }}
270
271
272
273 // Function: q($sql,$args);
274 // Description: execute SQL query with printf style args.
275 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
276 //                   'user', 1);
277
278 if (! function_exists('q')) {
279 function q($sql) {
280
281         global $db;
282         $args = func_get_args();
283         unset($args[0]);
284
285         if ($db && $db->connected) {
286                 $stmt = @vsprintf($sql,$args); // Disabled warnings
287                 //logger("dba: q: $stmt", LOGGER_ALL);
288                 if ($stmt === false)
289                         logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
290                 return $db->q($stmt);
291         }
292
293         /**
294          *
295          * This will happen occasionally trying to store the
296          * session data after abnormal program termination
297          *
298          */
299         logger('dba: no database: ' . print_r($args,true));
300         return false;
301
302 }}
303
304 /**
305  *
306  * Raw db query, no arguments
307  *
308  */
309
310 if (! function_exists('dbq')) {
311 function dbq($sql) {
312
313         global $db;
314         if ($db && $db->connected)
315                 $ret = $db->q($sql);
316         else
317                 $ret = false;
318         return $ret;
319 }}
320
321
322 // Caller is responsible for ensuring that any integer arguments to
323 // dbesc_array are actually integers and not malformed strings containing
324 // SQL injection vectors. All integer array elements should be specifically
325 // cast to int to avoid trouble.
326
327
328 if (! function_exists('dbesc_array_cb')) {
329 function dbesc_array_cb(&$item, $key) {
330         if (is_string($item))
331                 $item = dbesc($item);
332 }}
333
334
335 if (! function_exists('dbesc_array')) {
336 function dbesc_array(&$arr) {
337         if (is_array($arr) && count($arr)) {
338                 array_walk($arr,'dbesc_array_cb');
339         }
340 }}
341
342 if (! function_exists('dba_timer')) {
343 function dba_timer() {
344   return microtime(true);
345 }}