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')))
129 $intErrorCode = false;
131 } catch (\Exception $objException) {
133 $intErrorCode = $objPreparedQueryPool->get($strQueryAlias)->get('PDOStatement')->errorCode();
136 $stamp2 = microtime(true);
137 $duration = (float)($stamp2-$stamp1);
139 $a->save_timestamp($stamp1, "database");
141 if(x($a->config,'system') && x($a->config['system'],'db_log')) {
142 if (($duration > $a->config["system"]["db_loglimit"])) {
143 $duration = round($duration, 3);
144 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
145 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
146 basename($backtrace[1]["file"])."\t".
147 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
148 substr($sql, 0, 2000)."\n", FILE_APPEND);
153 $this->error = $intErrorCode;
155 if(strlen($this->error)) {
156 logger('dba: ' . $this->error);
163 if($result === false)
165 elseif($result === true)
168 # this needs fixing, but is a bug itself
169 #$mesg = mysql_num_rows($result) . ' results' . EOL;
172 $str = 'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
173 . (($this->error) ? ' error: ' . $this->error : '')
176 logger('dba: ' . $str );
180 * If dbfail.out exists, we will write any failed calls directly to it,
181 * regardless of any logging that may or may nor be in effect.
182 * These usually indicate SQL syntax errors that need to be resolved.
185 if(isset($result) AND ($result === false)) {
186 logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
187 if(file_exists('dbfail.out'))
188 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
191 if(isset($result) AND (($result === true) || ($result === false)))
195 $this->result = $r; # this will store an PDOStatement Object in result
196 $this->result->execute(); # execute the Statement, to get its result
200 //$a->save_timestamp($stamp1, "database");
203 logger('dba: ' . printable(print_r($r, true)));
207 public function qfetch() {
209 if (false === $this->result)
212 return $this->result->fetch();
216 public function qclose() {
218 return $this->result->closeCursor();
221 public function dbg($dbg) {
225 public function escape($str) {
226 if($this->db && $this->connected) {
227 $strQuoted = $this->db->quote($str);
228 # this workaround is needed, because quote creates "'" and the beginning and the end
229 # of the string, which is correct. but until now the queries set this delimiter manually,
230 # so we must remove them from here and wait until everything uses prepared statements
231 return mb_substr($strQuoted, 1, mb_strlen($strQuoted) - 2);
236 * Checks if $array is a filled array with at least one entry.
238 * @param $array mixed A filled array with at least one entry
239 * @return Whether $array is a filled array
241 public function is_result ($array) {
242 return (is_array($array) && count($array) > 0);
245 function __destruct() {
251 if(! function_exists('printable')) {
252 function printable($s) {
253 $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
254 $s = str_replace("\x00",'.',$s);
255 if(x($_SERVER,'SERVER_NAME'))
256 $s = escape_tags($s);
260 // Procedural functions
261 if(! function_exists('dbg')) {
262 function dbg($state) {
268 if(! function_exists('dbesc')) {
269 function dbesc($str) {
271 if($db && $db->connected)
272 return($db->escape($str));
274 return(str_replace("'","\\'",$str));
279 // Function: q($sql,$args);
280 // Description: execute SQL query with printf style args.
281 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
284 if(! function_exists('q')) {
288 $args = func_get_args();
291 if($db && $db->connected) {
292 $stmt = @vsprintf($sql,$args); // Disabled warnings
293 //logger("dba: q: $stmt", LOGGER_ALL);
295 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
296 return $db->q($stmt);
301 * This will happen occasionally trying to store the
302 * session data after abnormal program termination
305 logger('dba: no database: ' . print_r($args,true));
312 * Raw db query, no arguments
316 if(! function_exists('dbq')) {
320 if($db && $db->connected)
328 // Caller is responsible for ensuring that any integer arguments to
329 // dbesc_array are actually integers and not malformed strings containing
330 // SQL injection vectors. All integer array elements should be specifically
331 // cast to int to avoid trouble.
334 if(! function_exists('dbesc_array_cb')) {
335 function dbesc_array_cb(&$item, $key) {
337 $item = dbesc($item);
341 if(! function_exists('dbesc_array')) {
342 function dbesc_array(&$arr) {
343 if(is_array($arr) && count($arr)) {
344 array_walk($arr,'dbesc_array_cb');
348 if(! function_exists('dba_timer')) {
349 function dba_timer() {
350 return microtime(true);