3 require_once('include/datetime.php');
9 * For debugging, insert 'dbg(1);' anywhere in the program flow.
10 * dbg(0); will turn it off. Logging is performed at LOGGER_DATA level.
11 * When logging, all binary info is converted to
12 * text and html entities are escaped so that
13 * the debugging stream is safe to view
14 * within both terminals and web pages.
18 if(! class_exists('dba')) {
26 public $mysqli = true;
27 public $connected = false;
28 public $error = false;
30 function __construct($server,$user,$pass,$db,$install = false) {
32 $server = trim($server);
37 //we need both, server and username, so fail if one is missing
38 if (!(strlen($server) && strlen($user))){
39 $this->connected = false;
41 throw new InvalidArgumentException(t("Server name of user name are missing. "));
44 //when we are installing
46 if(strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) {
47 if(! dns_get_record($server, DNS_A + DNS_CNAME + DNS_PTR)) {
48 $this->connected = false;
50 throw new InvalidArgumentException( t('Cannot locate DNS info for database server \'%s\''), $server);
55 if(class_exists('mysqli')) {
56 $this->db = new mysqli($server,$user,$pass,$db);
57 if(NULL === $this->db->connect_error) {
58 $this->connected = true;
60 throw new RuntimeException($this->db->connect_error);
63 $this->mysqli = false;
64 $this->db = mysql_connect($server,$user,$pass);
65 if($this->db && mysql_select_db($db,$this->db)) {
66 $this->connected = true;
68 throw new RuntimeException(mysql_error());
73 public function excep($excep) {
74 $this->exceptions=$excep;
77 public function getdb() {
81 public function q($sql) {
83 if((! $this->db) || (! $this->connected)) {
84 $this->throwOrLog(new RuntimeException(t("There is no db connection. ")));
89 $result = $this->db->query($sql);
91 $result = mysql_query($sql,$this->db);
94 //on debug mode or fail, the query is written to the log.
95 //this won't work if logger can not read it's logging level
97 if($this->debug || FALSE === $result) {
101 if($result === false) {
102 $mesg = 'false '.$this->error();
103 } elseif($result === true) {
107 $mesg = $result->num_rows . t(' results') . EOL;
109 $mesg = mysql_num_rows($result) . t(' results') . EOL;
113 $str = 'SQL = ' . printable($sql) . EOL . t('SQL returned ') . $mesg . EOL;
116 // If dbfail.out exists, we will write any failed calls directly to it,
117 // regardless of any logging that may or may nor be in effect.
118 // These usually indicate SQL syntax errors that need to be resolved.
119 if(file_exists('dbfail.out')) {
\r
120 file_put_contents('dbfail.out', datetime_convert() . "\n" . $str . "\n", FILE_APPEND);
122 logger('dba: ' . $str );
123 if(FALSE===$result) {
124 $this->throwOrLog(new RuntimeException('dba: ' . $str));
130 if($result === true) {
136 if($result->num_rows) {
137 while($x = $result->fetch_array(MYSQLI_ASSOC)) {
140 $result->free_result();
143 if(mysql_num_rows($result)) {
144 while($x = mysql_fetch_array($result, MYSQL_ASSOC)) {
147 mysql_free_result($result);
153 logger('dba: ' . printable(print_r($r, true)));
158 private function error() {
160 return $this->db->error;
162 return mysql_error($this->db);
166 private function throwOrLog(Exception $ex) {
167 if($this->exceptions) {
170 logger('dba: '.$ex->getMessage());
175 * starts a transaction. Transactions need to be finished with
176 * commit() or rollback(). Please mind that the db table engine may
179 public function beginTransaction() {
\r
180 if($this->mysqli) {
\r
181 return $this->db->autocommit(false);
\r
183 //no transaction support in mysql module...
184 mysql_query('SET AUTOCOMMIT = 0;', $db);
\r
189 * rollback a transaction. So, rollback anything that was done since the last call
190 * to beginTransaction().
192 public function rollback() {
\r
193 if($this->mysqli) {
\r
194 return $this->db->rollback();
\r
196 //no transaction support in mysql module...
197 mysql_query('ROLLBACK;', $db);
\r
199 $this->stopTransaction();
\r
203 * commit a transaction. So, write any query to the database.
205 public function commit() {
\r
206 if($this->mysqli) {
\r
207 return $this->db->commit();
\r
209 //no transaction support in mysql module...
\r
210 mysql_query('COMMIT;', $db);
\r
212 $this->stopTransaction();
\r
215 private function stopTransaction() {
\r
216 if($this->mysqli) {
\r
217 return $this->db->autocommit(true);
\r
219 //no transaction support in mysql module...
\r
220 mysql_query('SET AUTOCOMMIT = 1;', $db);
\r
224 public function dbg($dbg) {
228 public function escape($str) {
229 if($this->db && $this->connected) {
231 return $this->db->real_escape_string($str);
233 return mysql_real_escape_string($str,$this->db);
238 function __destruct() {
244 mysql_close($this->db);
250 if(! function_exists('printable')) {
251 function printable($s) {
252 $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
253 $s = str_replace("\x00",'.',$s);
254 if(x($_SERVER,'SERVER_NAME'))
255 $s = escape_tags($s);
260 // Procedural functions
261 if(! function_exists('dbg')) {
262 function dbg($state) {
269 if(! function_exists('dbesc')) {
270 function dbesc($str) {
272 if($db && $db->connected)
273 return($db->escape($str));
275 return(str_replace("'","\\'",$str));
281 // Function: q($sql,$args);
282 // Description: execute SQL query with printf style args.
283 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
286 if(! function_exists('q')) {
290 $args = func_get_args();
293 if($db && $db->connected) {
294 $stmt = vsprintf($sql,$args);
296 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true));
297 return $db->q($stmt);
302 * This will happen occasionally trying to store the
303 * session data after abnormal program termination
306 logger('dba: no database: ' . print_r($args,true));
314 * Raw db query, no arguments
318 if(! function_exists('dbq')) {
322 if($db && $db->connected)
331 // Caller is responsible for ensuring that any integer arguments to
332 // dbesc_array are actually integers and not malformed strings containing
333 // SQL injection vectors. All integer array elements should be specifically
334 // cast to int to avoid trouble.
337 if(! function_exists('dbesc_array_cb')) {
338 function dbesc_array_cb(&$item, $key) {
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');