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(
55 'CONNECTION' => "mysql:host=$server;dbname=$db",
61 $stamp1 = microtime(true);
63 $server = trim($server);
68 if (!(strlen($server) && strlen($user))) {
69 $this->connected = false;
74 if ($install && strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) {
75 if (! dns_get_record($server, DNS_A + DNS_CNAME + DNS_PTR)) {
76 $this->error = sprintf( t('Cannot locate DNS info for database server \'%s\''), $server);
77 $this->connected = false;
83 // Establish connection to database and store PDO object
85 $this->db = DDDBL\getDB();
87 if (DDDBL\isConnected()) {
88 $this->connected = true;
91 if (! $this->connected) {
98 $a->save_timestamp($stamp1, "network");
101 public function getdb() {
105 public function q($sql, $onlyquery = false) {
108 $strHandler = (true === $onlyquery) ? 'PDOStatement' : 'MULTI';
110 $strQueryAlias = md5($sql);
111 $strSQLType = strtoupper(strstr($sql, ' ', true));
113 $objPreparedQueryPool = new DataObjectPool('Query-Definition');
115 // check if query do not exists till now, if so create its definition
116 if (!$objPreparedQueryPool->exists($strQueryAlias)) {
117 $objPreparedQueryPool->add($strQueryAlias, array(
119 'HANDLER' => $strHandler
123 if ((! $this->db) || (! $this->connected)) {
129 $stamp1 = microtime(true);
132 $r = DDDBL\get($strQueryAlias);
134 // bad workaround to emulate the bizzare behavior of mysql_query
135 if (in_array($strSQLType, array('INSERT', 'UPDATE', 'DELETE', 'CREATE', 'DROP', 'SET'))) {
138 $intErrorCode = false;
139 } catch (Exception $objException) {
141 $intErrorCode = $objPreparedQueryPool->get($strQueryAlias)->get('PDOStatement')->errorCode();
144 $stamp2 = microtime(true);
145 $duration = (float)($stamp2-$stamp1);
147 $a->save_timestamp($stamp1, "database");
149 /// @TODO really check $a->config for 'system'? it is very generic and should be there
150 if (x($a->config, 'system') && x($a->config['system'], 'db_log')) {
151 if (($duration > $a->config["system"]["db_loglimit"])) {
152 $duration = round($duration, 3);
153 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
154 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
155 basename($backtrace[1]["file"])."\t".
156 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
157 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) AND ($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) AND (($result === true) || ($result === false))) {
205 $this->result = $r; # this will store an PDOStatement Object in result
206 $this->result->execute(); # execute the Statement, to get its result
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
266 if (! function_exists('dbg')) {
267 function dbg($state) {
273 if (! function_exists('dbesc')) {
274 function dbesc($str) {
276 if ($db && $db->connected)
277 return($db->escape($str));
279 return(str_replace("'","\\'",$str));
282 if (! function_exists('q')) {
284 * Function: q($sql,$args);
285 * Description: execute SQL query with printf style args.
286 * Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
292 $args = func_get_args();
295 if ($db && $db->connected) {
296 $stmt = @vsprintf($sql,$args); // Disabled warnings
297 //logger("dba: q: $stmt", LOGGER_ALL);
298 if ($stmt === false) {
299 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
301 return $db->q($stmt);
306 * This will happen occasionally trying to store the
307 * session data after abnormal program termination
310 logger('dba: no database: ' . print_r($args,true));
315 if (! function_exists('dbq')) {
317 * Raw db query, no arguments
322 if ($db && $db->connected) {
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 (! function_exists('dbesc_array_cb')) {
338 function dbesc_array_cb(&$item, $key) {
339 if (is_string($item)) {
340 $item = dbesc($item);
345 if (! function_exists('dbesc_array')) {
346 function dbesc_array(&$arr) {
347 if (is_array($arr) && count($arr)) {
348 array_walk($arr,'dbesc_array_cb');
352 if (! function_exists('dba_timer')) {
353 function dba_timer() {
354 return microtime(true);