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