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) {
17 $objPDO = $objQueue->getState()->get('PDOStatement');
18 $objQueue->getState()->update(array('result' => $objPDO));
21 * delete handler which closes the PDOStatement-cursor
22 * this will be done manual if using this handler
24 $objQueue->deleteHandler(QUEUE_CLOSE_CURSOR_POSITION);
27 $objDDDBLResultHandler->add('PDOStatement', array('HANDLER' => $cloPDOStatementResultHandler));
29 if (! class_exists('dba')) {
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.
45 public $connected = false;
46 public $error = false;
48 function __construct($server,$user,$pass,$db,$install = false) {
51 // work around, to store the database - configuration in DDDBL
52 $objDataObjectPool = new DataObjectPool('Database-Definition');
53 $objDataObjectPool->add('DEFAULT', array(
54 'CONNECTION' => "mysql:host=$server;dbname=$db",
60 $stamp1 = microtime(true);
62 $server = trim($server);
67 if (!(strlen($server) && strlen($user))) {
68 $this->connected = false;
73 if ($install && 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;
82 // Establish connection to database and store PDO object
84 $this->db = DDDBL\getDB();
86 if (DDDBL\isConnected()) {
87 $this->connected = true;
90 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(
118 'HANDLER' => $strHandler
122 if ((! $this->db) || (! $this->connected)) {
128 $stamp1 = microtime(true);
131 $r = DDDBL\get($strQueryAlias);
133 // bad workaround to emulate the bizzare behavior of mysql_query
134 if (in_array($strSQLType, array('INSERT', 'UPDATE', 'DELETE', 'CREATE', 'DROP', 'SET'))) {
137 $intErrorCode = false;
138 } catch (Exception $objException) {
140 $intErrorCode = $objPreparedQueryPool->get($strQueryAlias)->get('PDOStatement')->errorCode();
143 $stamp2 = microtime(true);
144 $duration = (float)($stamp2-$stamp1);
146 $a->save_timestamp($stamp1, "database");
148 /// @TODO really check $a->config for 'system'? it is very generic and should be there
149 if (x($a->config, 'system') && x($a->config['system'], 'db_log') && ($duration > $a->config["system"]["db_loglimit"])) {
150 $duration = round($duration, 3);
151 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
152 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
153 basename($backtrace[1]["file"])."\t".
154 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
155 substr($sql, 0, 2000)."\n", FILE_APPEND);
159 $this->error = $intErrorCode;
162 if (strlen($this->error)) {
163 logger('dba: ' . $this->error);
169 if ($result === false) {
171 } elseif ($result === true) {
174 /// @TODO this needs fixing, but is a bug itself
175 // $mesg = mysql_num_rows($result) . ' results' . EOL;
178 $str = 'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
179 . (($this->error) ? ' error: ' . $this->error : '')
182 logger('dba: ' . $str );
186 * If dbfail.out exists, we will write any failed calls directly to it,
187 * regardless of any logging that may or may nor be in effect.
188 * These usually indicate SQL syntax errors that need to be resolved.
190 if (isset($result) AND ($result === false)) {
191 logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
192 if (file_exists('dbfail.out')) {
193 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
197 if (isset($result) AND (($result === true) || ($result === false))) {
202 // this will store an PDOStatement Object in result
205 // execute the Statement, to get its result
206 $this->result->execute();
210 //$a->save_timestamp($stamp1, "database");
213 logger('dba: ' . printable(print_r($r, true)));
219 public function qfetch() {
220 if (false === $this->result) {
224 return $this->result->fetch();
227 public function qclose() {
229 return $this->result->closeCursor();
233 public function dbg($dbg) {
237 public function escape($str) {
238 if ($this->db && $this->connected) {
239 $strQuoted = $this->db->quote($str);
241 * this workaround is needed, because quote creates "'" and the beginning and the end
242 * of the string, which is correct. but until now the queries set this delimiter manually,
243 * so we must remove them from here and wait until everything uses prepared statements
245 return mb_substr($strQuoted, 1, mb_strlen($strQuoted) - 2);
249 public function __destruct() {
256 if (! function_exists('printable')) {
257 function printable($s) {
258 $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
259 $s = str_replace("\x00",'.',$s);
260 if (x($_SERVER,'SERVER_NAME'))
261 $s = escape_tags($s);
265 // --- Procedural functions ---
267 if (! function_exists('dbg')) {
268 function dbg($state) {
274 if (! function_exists('dbesc')) {
275 function dbesc($str) {
278 if ($db && $db->connected) {
279 return $db->escape($str);
281 return str_replace("'","\\'",$str);
285 if (! function_exists('q')) {
287 * Function: q($sql,$args);
288 * Description: execute SQL query with printf style args.
289 * Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
295 $args = func_get_args();
298 if ($db && $db->connected) {
299 $stmt = @vsprintf($sql,$args); // Disabled warnings
300 //logger("dba: q: $stmt", LOGGER_ALL);
301 if ($stmt === false) {
302 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
304 return $db->q($stmt);
308 * This will happen occasionally trying to store the
309 * session data after abnormal program termination
311 logger('dba: no database: ' . print_r($args,true));
315 if (! function_exists('dbq')) {
317 * Raw db query, no arguments
321 if ($db && $db->connected) {
329 if (! function_exists('dbesc_array_cb')) {
330 function dbesc_array_cb(&$item, $key) {
332 * Caller is responsible for ensuring that any integer arguments to
333 * dbesc_array are actually integers and not malformed strings containing
334 * SQL injection vectors. All integer array elements should be specifically
335 * cast to int to avoid trouble.
337 if (is_string($item)) {
338 $item = dbesc($item);
343 if (! function_exists('dbesc_array')) {
344 function dbesc_array(&$arr) {
345 if (is_array($arr) && count($arr)) {
346 array_walk($arr,'dbesc_array_cb');
350 if (! function_exists('dba_timer')) {
351 function dba_timer() {
352 return microtime(true);