7 require_once('include/datetime.php');
9 $objDDDBLResultHandler = new DDDBL\DataObjectPool('Result-Handler');
12 * create handler, which returns just the PDOStatement object
13 * this allows usage of the cursor to scroll through
17 $cloPDOStatementResultHandler = function(DDDBL\Queue $objQueue) {
19 $objPDO = $objQueue->getState()->get('PDOStatement');
20 $objQueue->getState()->update(array('result' => $objPDO));
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);
28 $objDDDBLResultHandler->add('PDOStatement', array('HANDLER' => $cloPDOStatementResultHandler));
32 * MySQL database class
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.
41 if (! class_exists('dba')) {
47 public $connected = false;
48 public $error = false;
50 function __construct($server,$user,$pass,$db,$install = false) {
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",
60 $stamp1 = microtime(true);
62 $server = trim($server);
67 if (!(strlen($server) && strlen($user))){
68 $this->connected = false;
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;
84 # etablish connection to database and store PDO object
86 $this->db = DDDBL\getDB();
88 if (DDDBL\isConnected()) {
89 $this->connected = true;
92 if (! $this->connected) {
98 $a->save_timestamp($stamp1, "network");
101 public function getdb() {
105 public function q($sql, $onlyquery = false) {
108 $strHandler = (true === $onlyquery) ? 'PDOStatement' : 'MULTI';
110 $strQueryAlias = md5($sql);
111 $strSQLType = strtoupper(strstr($sql, ' ', true));
113 $objPreparedQueryPool = new DDDBL\DataObjectPool('Query-Definition');
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));
120 if ((! $this->db) || (! $this->connected))
125 $stamp1 = microtime(true);
128 $r = DDDBL\get($strQueryAlias);
130 # bad workaround to emulate the bizzare behavior of mysql_query
131 if (in_array($strSQLType, array('INSERT', 'UPDATE', 'DELETE', 'CREATE', 'DROP', 'SET')))
133 $intErrorCode = false;
135 } catch (Exception $objException) {
137 $intErrorCode = $objPreparedQueryPool->get($strQueryAlias)->get('PDOStatement')->errorCode();
140 $stamp2 = microtime(true);
141 $duration = (float)($stamp2-$stamp1);
143 $a->save_timestamp($stamp1, "database");
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);
157 $this->error = $intErrorCode;
159 if (strlen($this->error)) {
160 logger('dba: ' . $this->error);
167 if ($result === false)
169 elseif ($result === true)
172 # this needs fixing, but is a bug itself
173 #$mesg = mysql_num_rows($result) . ' results' . EOL;
176 $str = 'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
177 . (($this->error) ? ' error: ' . $this->error : '')
180 logger('dba: ' . $str );
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.
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);
195 if (isset($result) AND (($result === true) || ($result === false)))
199 $this->result = $r; # this will store an PDOStatement Object in result
200 $this->result->execute(); # execute the Statement, to get its result
204 //$a->save_timestamp($stamp1, "database");
207 logger('dba: ' . printable(print_r($r, true)));
211 public function qfetch() {
213 if (false === $this->result)
216 return $this->result->fetch();
220 public function qclose() {
222 return $this->result->closeCursor();
225 public function dbg($dbg) {
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);
239 function __destruct() {
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);
254 // Procedural functions
255 if (! function_exists('dbg')) {
256 function dbg($state) {
262 if (! function_exists('dbesc')) {
263 function dbesc($str) {
265 if ($db && $db->connected)
266 return($db->escape($str));
268 return(str_replace("'","\\'",$str));
273 // Function: q($sql,$args);
274 // Description: execute SQL query with printf style args.
275 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
278 if (! function_exists('q')) {
282 $args = func_get_args();
285 if ($db && $db->connected) {
286 $stmt = @vsprintf($sql,$args); // Disabled warnings
287 //logger("dba: q: $stmt", LOGGER_ALL);
289 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
290 return $db->q($stmt);
295 * This will happen occasionally trying to store the
296 * session data after abnormal program termination
299 logger('dba: no database: ' . print_r($args,true));
306 * Raw db query, no arguments
310 if (! function_exists('dbq')) {
314 if ($db && $db->connected)
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.
328 if (! function_exists('dbesc_array_cb')) {
329 function dbesc_array_cb(&$item, $key) {
330 if (is_string($item))
331 $item = dbesc($item);
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');
342 if (! function_exists('dba_timer')) {
343 function dba_timer() {
344 return microtime(true);