3 require_once('include/datetime.php');
5 $objDDDBLResultHandler = new \DDDBL\DataObjectPool('Result-Handler');
8 * create handler, which returns just the PDOStatement object
9 * this allows usage of the cursor to scroll through
13 $cloPDOStatementResultHandler = function(\DDDBL\Queue $objQueue) {
15 $objPDO = $objQueue->getState()->get('PDOStatement');
16 $objQueue->getState()->update(array('result' => $objPDO));
18 # delete handler which closes the PDOStatement-cursor
19 # this will be done manual if using this handler
20 $objQueue->deleteHandler(QUEUE_CLOSE_CURSOR_POSITION);
24 $objDDDBLResultHandler->add('PDOStatement', array('HANDLER' => $cloPDOStatementResultHandler));
28 * MySQL database class
30 * For debugging, insert 'dbg(1);' anywhere in the program flow.
31 * dbg(0); will turn it off. Logging is performed at LOGGER_DATA level.
32 * When logging, all binary info is converted to text and html entities are escaped so that
33 * the debugging stream is safe to view within both terminals and web pages.
37 if(! class_exists('dba')) {
43 public $connected = false;
44 public $error = false;
46 function __construct($server,$user,$pass,$db,$install = false) {
49 # work around, to store the database - configuration in DDDBL
50 $objDataObjectPool = new \DDDBL\DataObjectPool('Database-Definition');
51 $objDataObjectPool->add('DEFAULT', array('CONNECTION' => "mysql:host=$server;dbname=$db",
56 $stamp1 = microtime(true);
58 $server = trim($server);
63 if (!(strlen($server) && strlen($user))){
64 $this->connected = false;
70 if(strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) {
71 if(! dns_get_record($server, DNS_A + DNS_CNAME + DNS_PTR)) {
72 $this->error = sprintf( t('Cannot locate DNS info for database server \'%s\''), $server);
73 $this->connected = false;
80 # etablish connection to database and store PDO object
82 $this->db = \DDDBL\getDB();
84 if(\DDDBL\isConnected()) {
85 $this->connected = true;
88 if(! $this->connected) {
94 $a->save_timestamp($stamp1, "network");
97 public function getdb() {
101 public function q($sql, $onlyquery = false) {
104 $strHandler = (true === $onlyquery) ? 'PDOStatement' : 'MULTI';
106 $strQueryAlias = md5($sql);
107 $strSQLType = strtoupper(strstr($sql, ' ', true));
109 $objPreparedQueryPool = new \DDDBL\DataObjectPool('Query-Definition');
111 # check if query do not exists till now, if so create its definition
112 if(!$objPreparedQueryPool->exists($strQueryAlias))
113 $objPreparedQueryPool->add($strQueryAlias, array('QUERY' => $sql,
114 'HANDLER' => $strHandler));
116 if((! $this->db) || (! $this->connected))
121 $stamp1 = microtime(true);
124 $r = \DDDBL\get($strQueryAlias);
126 # bad workaround to emulate the bizzare behavior of mysql_query
127 if(in_array($strSQLType, array('INSERT', 'UPDATE', 'DELETE', 'CREATE', 'DROP', 'SET')))
130 } catch (\Exception $objException) {
132 $intErrorCode = $objPreparedQueryPool->get($strQueryAlias)->get('PDOStatement')->errorCode();
135 $stamp2 = microtime(true);
136 $duration = (float)($stamp2-$stamp1);
138 $a->save_timestamp($stamp1, "database");
140 if(x($a->config,'system') && x($a->config['system'],'db_log')) {
141 if (($duration > $a->config["system"]["db_loglimit"])) {
142 $duration = round($duration, 3);
143 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
144 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
145 basename($backtrace[1]["file"])."\t".
146 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
147 substr($sql, 0, 2000)."\n", FILE_APPEND);
152 $this->error = $intErrorCode;
154 if(strlen($this->error)) {
155 logger('dba: ' . $this->error);
162 if($result === false)
164 elseif($result === true)
167 # this needs fixing, but is a bug itself
168 #$mesg = mysql_num_rows($result) . ' results' . EOL;
171 $str = 'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
172 . (($this->error) ? ' error: ' . $this->error : '')
175 logger('dba: ' . $str );
179 * If dbfail.out exists, we will write any failed calls directly to it,
180 * regardless of any logging that may or may nor be in effect.
181 * These usually indicate SQL syntax errors that need to be resolved.
184 if($result === false) {
185 logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
186 if(file_exists('dbfail.out'))
187 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
190 if(($result === true) || ($result === false))
194 $this->result = $r; # this will store an PDOStatement Object in result
195 $this->result->execute(); # execute the Statement, to get its result
199 //$a->save_timestamp($stamp1, "database");
202 logger('dba: ' . printable(print_r($r, true)));
206 public function qfetch() {
208 if (false === $this->result)
211 return $this->result->fetch();
215 public function qclose() {
217 return $this->result->closeCursor();
220 public function dbg($dbg) {
224 public function escape($str) {
225 if($this->db && $this->connected) {
226 $strQuoted = $this->db->quote($str);
227 # this workaround is needed, because quote creates "'" and the beginning and the end
228 # of the string, which is correct. but until now the queries set this delimiter manually,
229 # so we must remove them from here and wait until everything uses prepared statements
230 return mb_substr($strQuoted, 1, mb_strlen($strQuoted) - 2);
234 function __destruct() {
240 if(! function_exists('printable')) {
241 function printable($s) {
242 $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
243 $s = str_replace("\x00",'.',$s);
244 if(x($_SERVER,'SERVER_NAME'))
245 $s = escape_tags($s);
249 // Procedural functions
250 if(! function_exists('dbg')) {
251 function dbg($state) {
257 if(! function_exists('dbesc')) {
258 function dbesc($str) {
260 if($db && $db->connected)
261 return($db->escape($str));
263 return(str_replace("'","\\'",$str));
268 // Function: q($sql,$args);
269 // Description: execute SQL query with printf style args.
270 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
273 if(! function_exists('q')) {
277 $args = func_get_args();
280 if($db && $db->connected) {
281 $stmt = @vsprintf($sql,$args); // Disabled warnings
282 //logger("dba: q: $stmt", LOGGER_ALL);
284 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
285 return $db->q($stmt);
290 * This will happen occasionally trying to store the
291 * session data after abnormal program termination
294 logger('dba: no database: ' . print_r($args,true));
301 * Raw db query, no arguments
305 if(! function_exists('dbq')) {
309 if($db && $db->connected)
317 // Caller is responsible for ensuring that any integer arguments to
318 // dbesc_array are actually integers and not malformed strings containing
319 // SQL injection vectors. All integer array elements should be specifically
320 // cast to int to avoid trouble.
323 if(! function_exists('dbesc_array_cb')) {
324 function dbesc_array_cb(&$item, $key) {
326 $item = dbesc($item);
330 if(! function_exists('dbesc_array')) {
331 function dbesc_array(&$arr) {
332 if(is_array($arr) && count($arr)) {
333 array_walk($arr,'dbesc_array_cb');
337 if(! function_exists('dba_timer')) {
338 function dba_timer() {
339 return microtime(true);