3 use DDDBL\DataObjectPool;
6 require_once('include/datetime.php');
8 $objDDDBLResultHandler = new DataObjectPool('Result-Handler');
11 * create handler, which returns just the PDOStatement object
12 * this allows usage of the cursor to scroll through
16 $cloPDOStatementResultHandler = function(Queue $objQueue) {
18 $objPDO = $objQueue->getState()->get('PDOStatement');
19 $objQueue->getState()->update(array('result' => $objPDO));
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);
27 $objDDDBLResultHandler->add('PDOStatement', array('HANDLER' => $cloPDOStatementResultHandler));
31 * MySQL database class
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.
40 if (! class_exists('dba')) {
46 public $connected = false;
47 public $error = false;
49 function __construct($server,$user,$pass,$db,$install = false) {
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",
59 $stamp1 = microtime(true);
61 $server = trim($server);
66 if (!(strlen($server) && strlen($user))){
67 $this->connected = false;
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;
83 # etablish connection to database and store PDO object
85 $this->db = DDDBL\getDB();
87 if (DDDBL\isConnected()) {
88 $this->connected = true;
91 if (! $this->connected) {
97 $a->save_timestamp($stamp1, "network");
100 public function getdb() {
104 public function q($sql, $onlyquery = false) {
107 $strHandler = (true === $onlyquery) ? 'PDOStatement' : 'MULTI';
109 $strQueryAlias = md5($sql);
110 $strSQLType = strtoupper(strstr($sql, ' ', true));
112 $objPreparedQueryPool = new DataObjectPool('Query-Definition');
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));
119 if ((! $this->db) || (! $this->connected))
124 $stamp1 = microtime(true);
127 $r = DDDBL\get($strQueryAlias);
129 # bad workaround to emulate the bizzare behavior of mysql_query
130 if (in_array($strSQLType, array('INSERT', 'UPDATE', 'DELETE', 'CREATE', 'DROP', 'SET')))
132 $intErrorCode = false;
134 } catch (Exception $objException) {
136 $intErrorCode = $objPreparedQueryPool->get($strQueryAlias)->get('PDOStatement')->errorCode();
139 $stamp2 = microtime(true);
140 $duration = (float)($stamp2-$stamp1);
142 $a->save_timestamp($stamp1, "database");
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);
156 $this->error = $intErrorCode;
158 if (strlen($this->error)) {
159 logger('dba: ' . $this->error);
166 if ($result === false)
168 elseif ($result === true)
171 # this needs fixing, but is a bug itself
172 #$mesg = mysql_num_rows($result) . ' results' . EOL;
175 $str = 'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
176 . (($this->error) ? ' error: ' . $this->error : '')
179 logger('dba: ' . $str );
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.
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);
194 if (isset($result) AND (($result === true) || ($result === false)))
198 $this->result = $r; # this will store an PDOStatement Object in result
199 $this->result->execute(); # execute the Statement, to get its result
203 //$a->save_timestamp($stamp1, "database");
206 logger('dba: ' . printable(print_r($r, true)));
210 public function qfetch() {
212 if (false === $this->result)
215 return $this->result->fetch();
219 public function qclose() {
221 return $this->result->closeCursor();
224 public function dbg($dbg) {
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);
238 function __destruct() {
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);
253 // Procedural functions
254 if (! function_exists('dbg')) {
255 function dbg($state) {
261 if (! function_exists('dbesc')) {
262 function dbesc($str) {
264 if ($db && $db->connected)
265 return($db->escape($str));
267 return(str_replace("'","\\'",$str));
272 // Function: q($sql,$args);
273 // Description: execute SQL query with printf style args.
274 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
277 if (! function_exists('q')) {
281 $args = func_get_args();
284 if ($db && $db->connected) {
285 $stmt = @vsprintf($sql,$args); // Disabled warnings
286 //logger("dba: q: $stmt", LOGGER_ALL);
288 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
289 return $db->q($stmt);
294 * This will happen occasionally trying to store the
295 * session data after abnormal program termination
298 logger('dba: no database: ' . print_r($args,true));
305 * Raw db query, no arguments
309 if (! function_exists('dbq')) {
313 if ($db && $db->connected)
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.
327 if (! function_exists('dbesc_array_cb')) {
328 function dbesc_array_cb(&$item, $key) {
329 if (is_string($item))
330 $item = dbesc($item);
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');
341 if (! function_exists('dba_timer')) {
342 function dba_timer() {
343 return microtime(true);