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");
149 * Check if the configuration group 'system' and db_log is there. The
150 * extra first check needs to be done to avoid endless loop.
152 if (x($a->config, 'system') && x($a->config['system'], 'db_log') && ($duration > $a->config["system"]["db_loglimit"])) {
153 $duration = round($duration, 3);
154 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
155 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
156 basename($backtrace[1]["file"])."\t".
157 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
158 substr($sql, 0, 2000)."\n", FILE_APPEND);
162 $this->error = $intErrorCode;
165 if (strlen($this->error)) {
166 logger('dba: ' . $this->error);
172 if ($result === false) {
174 } elseif ($result === true) {
177 /// @TODO this needs fixing, but is a bug itself
178 // $mesg = mysql_num_rows($result) . ' results' . EOL;
181 $str = 'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
182 . (($this->error) ? ' error: ' . $this->error : '')
185 logger('dba: ' . $str );
189 * If dbfail.out exists, we will write any failed calls directly to it,
190 * regardless of any logging that may or may nor be in effect.
191 * These usually indicate SQL syntax errors that need to be resolved.
193 if (isset($result) && ($result === false)) {
194 logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
195 if (file_exists('dbfail.out')) {
196 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
200 if (isset($result) && (($result === true) || ($result === false))) {
205 // this will store an PDOStatement Object in result
208 // execute the Statement, to get its result
209 $this->result->execute();
213 //$a->save_timestamp($stamp1, "database");
216 logger('dba: ' . printable(print_r($r, true)));
222 public function qfetch() {
223 if (false === $this->result) {
227 return $this->result->fetch();
230 public function qclose() {
232 return $this->result->closeCursor();
236 public function dbg($dbg) {
240 public function escape($str) {
241 if ($this->db && $this->connected) {
242 $strQuoted = $this->db->quote($str);
244 * this workaround is needed, because quote creates "'" and the beginning and the end
245 * of the string, which is correct. but until now the queries set this delimiter manually,
246 * so we must remove them from here and wait until everything uses prepared statements
248 return mb_substr($strQuoted, 1, mb_strlen($strQuoted) - 2);
252 public function __destruct() {
259 if (! function_exists('printable')) {
260 function printable($s) {
261 $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
262 $s = str_replace("\x00",'.',$s);
263 if (x($_SERVER,'SERVER_NAME'))
264 $s = escape_tags($s);
268 // --- Procedural functions ---
270 if (! function_exists('dbg')) {
271 function dbg($state) {
277 if (! function_exists('dbesc')) {
278 function dbesc($str) {
281 if ($db && $db->connected) {
282 return $db->escape($str);
284 return str_replace("'","\\'",$str);
288 if (! function_exists('q')) {
290 * Function: q($sql,$args);
291 * Description: execute SQL query with printf style args.
292 * Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
298 $args = func_get_args();
301 if ($db && $db->connected) {
302 $stmt = @vsprintf($sql,$args); // Disabled warnings
303 //logger("dba: q: $stmt", LOGGER_ALL);
304 if ($stmt === false) {
305 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
307 return $db->q($stmt);
311 * This will happen occasionally trying to store the
312 * session data after abnormal program termination
314 logger('dba: no database: ' . print_r($args,true));
318 if (! function_exists('dbq')) {
320 * Raw db query, no arguments
324 if ($db && $db->connected) {
332 if (! function_exists('dbesc_array_cb')) {
333 function dbesc_array_cb(&$item, $key) {
335 * Caller is responsible for ensuring that any integer arguments to
336 * dbesc_array are actually integers and not malformed strings containing
337 * SQL injection vectors. All integer array elements should be specifically
338 * cast to int to avoid trouble.
340 if (is_string($item)) {
341 $item = dbesc($item);
346 if (! function_exists('dbesc_array')) {
347 function dbesc_array(&$arr) {
348 if (is_array($arr) && count($arr)) {
349 array_walk($arr,'dbesc_array_cb');
353 if (! function_exists('dba_timer')) {
354 function dba_timer() {
355 return microtime(true);