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