Source for file db.class.php
Documentation is available at db.class.php
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
* @author m2mtech <tech@m2m.at>
* @copyright 2007 m2m server software gmbh
* @license http://www.gnu.org/licenses/gpl.html GNU General Public License Version 2
* @version $Id: db.class.php 141 2007-08-31 20:52:47Z m2mtech $
* @link http://www.ea-geier.at/
* attention: might have been defined already in
* config/config.php or code/config.php
if (!defined('eaADODB_DIR')) define('eaADODB_DIR', '3party/adodb/adodb494/');
require_once(eaADODB_DIR . 'adodb.inc.php');
require_once(eaADODB_DIR . 'session/adodb-cryptsession2.php');
require_once(eaADODB_DIR . 'session/crypt.inc.php');
* wrapper for ADOdb database library
* for basic initialization etc.
* constructor of database wrapper
* defines the environmental db settings
* and starts session if not already done
* @param array configuration data
* @param boolean enable adobdb debug (false)
function eaDB(&$conf, $debug = false) {
if (isset ($conf['dsn'])) $dsn = $conf['dsn'];
if (isset ($conf['tablePrefix'])) $prefix = $conf['tablePrefix'];
if (isset ($conf['sessionName'])) $sessionName = $conf['sessionName'];
if (!$this->_db = ADONewConnection($dsn)) return false;
$this->_db->debug = true;
else $this->_db->debug = $debug;
$this->_db->SetFetchMode(ADODB_FETCH_ASSOC);
// session handling - only with first database connection
if ((!isset ($GLOBALS['ADODB_SESS_CONN']) || !$GLOBALS['ADODB_SESS_CONN']) && !headers_sent()) {
$GLOBALS['ADODB_SESS_CONN'] = & $this->_db;
$vars = array ('HTTP_ACCEPT_CHARSET', 'HTTP_ACCEPT_ENCODING', 'HTTP_ACCEPT_LANGUAGE', 'HTTP_USER_AGENT', 'REMOTE_ADDR');
$sessionKey = 'ea'; foreach($vars as $var) $sessionKey .= $var;
ADOdb_Session::encryptionKey(md5($sessionKey));
ADODB_Session::table($prefix . 'sessions2');
ADODB_Session::optimize(true);
if (!$dummy = $this->select('name, value, what', $this->table('config')))
foreach ($dummy as $item) switch ($item['what']) {
$split = explode(';', $item['value']);
if (!isset ($split[1])) $split = explode(',', $split[0]);
$conf[$item['name']] = trim($split[0]);
if (!isset ($crypt)) $crypt = new MD5Crypt;
$conf[$item['name']] = $this->decrypt($item['value']);
$conf[$item['name']] = $item['value'];
if (isset ($conf['txtClientTables']) && $conf['txtClientTables'])
* switch to client database - if necessary
* @param integer clientID
// write & close session into current database
if (!isset ($this->clients[$client]['db'])) {
if (!$dummy = $this->selectOne('db', $this->table('clients'), array('id' => $client))) return false;
$dsn = $this->decrypt($dummy['db']);
} else $dsn = $this->clients[$client]['db'];
if (strpos($dsn, 'dsnTest') !== false) $dsn = false; // simpletest artefact
$oldDebug = $this->_db->debug;
if (!$this->_db = ADONewConnection($dsn)) return false;
$this->_db->debug = $oldDebug;
$this->_db->SetFetchMode(ADODB_FETCH_ASSOC);
* checks for database error
if (!$this->_db) return true;
* @param eaInput input values
* @return array user data | false
if (($login = $in->post('mailLogin')) && ($password = $in->post('passLogin'))) {
if (!isset ($_SESSION['lg'])) return false;
if (!isset ($_SESSION['pw'])) return false;
$login = $_SESSION['lg'];
$password = $_SESSION['pw'];
$table = $this->table('users') . ' u';
$where = '(mail = ' . $this->escape($login) . ')';
$where .= ' and (pw = ' . $this->escape(md5($password)) . ')';
else $where .= ' and (pw = ' . $this->escape($password) . ')';
if (!$user = $this->selectOne($what, $table, $where)) return false;
adodb_session_regenerate_id();
$_SESSION['lg'] = $user['mail'];
$_SESSION['pw'] = $user['pw'];
// get user configuration
$table = $this->table('userconfig') . ' u, ' . $this->table('config') . ' c';
$where = "(u.userID = '" . $user['id'] . "') and (u.name = c.name) and (c.context = 'user')";
if ($dummy = $this->select('u.*', $table, $where)) {
foreach ($dummy as $var) $conf[$var['name']] = $var['value'];
if (!isset ($_SESSION)) return false;
foreach ($_SESSION as $key => $val) $_SESSION[$key] = '';
* @return boolean/string status/name
function isUser($name, $get = 'name') {
$table = $this->table('users') . ' u';
$where = 'mail = ' . $this->escape($name);
if (!$dummy = $this->selectOne($what, $table, $where)) return false;
if ($dummy['name']) return $dummy['name'];
* @param string/array username/userdata
* @param string password (optional if userdata)
$vars = array('mail', 'name', 'pw');
foreach ($vars as $var) switch ($var) {
if ($pw) $user['pw'] = $pw;
$what['pw'] = md5($user['pw']);
$what[$var] = $user[$var];
$what = array('name' => 'dummy', 'mail' => $user, 'pw' => md5($pw));
$what['lastModified'] = $this->now();
* @param array new userdata
* @param boolean change session
function updateUser($oldUser, $userData, $session = false) {
if (isset ($userData['mail']) && ($userData['mail'] != $oldUser) && $this->isUser($userData['mail']))
$vars = array('mail', 'name', 'pw');
foreach ($vars as $var) if (isset ($userData[$var])) switch ($var) {
$what['pw'] = md5($userData['pw']);
$what[$var] = $userData[$var];
$where = array('mail' => $oldUser);
if (!$this->update($what, $this->table('users'), $where)) return false;
if (isset ($userData['mail'])) $_SESSION['lg'] = $userData['mail'];
if (isset ($userData['pw'])) $_SESSION['pw'] = md5($userData['pw']);
if (!$this->isUser($user)) return false;
$table = $this->table('users');
$where = array('mail' => $user);
if (!$user = $this->selectOne('id', $table, $where)) return false;
$cTable = $this->table('clients');
$cWhere = array('owner' => $user['id']);
$clients = $this->select('id', $cTable, $cWhere);
$this->_db->StartTrans();
if ($clients) foreach ($clients as $client)
$this->delete($this->table('userconfig'), array('userId' => $user['id']));
$this->delete($table, $where);
$this->_db->CompleteTrans();
function setPW($user, $pw) {
return $this->updateUser($user, array('pw' => $pw));
* get user configuration variables
* @return array configuration data
$where = "(context = 'user')";
if ($this->user['mail'] != eaSYSADMIN) $where .= " and (rights = 'user')";
return $this->select('*', $this->table('config'), $where);
* update user configuration
* @param array changed configruration
$table = $this->table('userconfig');
$where = array('userID', 'name');
foreach ($changed as $key => $val) {
$what = array('userID' => $userID, 'name' => $key, 'value' => $val, 'lastModified' => $this->now());
if (!$this->_db->Replace($table, $what, $where, true)) $result = false;
* @param array client data
* @param array optional user data
function createClient(&$data, $user = false, $demo = false) {
if (!$user) $user = & $this->user;
$what['name'] = $data['txtNewClientName'];
$what['owner'] = $user['id'];
$what['db'] = $this->encrypt($conf['dsnNewClientDB']);
$what['lastModified'] = $this->now();
if (!$this->insert($what, $this->table('clients'))) return false;
$oldDebug = $this->_db->debug;
require_once(eaADODB_DIR . 'adodb-xmlschema03.inc.php');
$schema = new adoSchema($this->_db);
$schema->ParseSchemaString(str_replace($table, $this->_prefix . $table, $schema->ConvertSchemaFile('admin/sql/demo_' . $table . '.sql')));
$schema->ParseSchemaString(str_replace($table, $this->_prefix . $table, $schema->ConvertSchemaFile('admin/sql/' . $table . '.sql')));
$schema->ContinueOnError(true);
$schema->ExecuteSchema();
if ($switched) { // switch back
$this->_db = ADONewConnection($conf['dsn']);
$this->_db->SetFetchMode(ADODB_FETCH_ASSOC);
$this->_db->debug = $oldDebug;
* @param integer clientID
* @param array new client data
foreach ($vars as $var) if (isset ($data[$var])) switch ($var) {
$what[$var] = $data[$var];
$where = array('id' => $id);
return $this->update($what, $this->table('clients'), $where);
* @param integer client id
$oldDebug = $this->_db->debug;
$this->_db = ADONewConnection($this->conf['dsn']);
$this->_db->SetFetchMode(ADODB_FETCH_ASSOC);
$this->_db->debug = $oldDebug;
$cTable = $this->table('clients');
$ccTable = $this->table('clientconfig');
$this->_db->StartTrans();
$this->delete($ccTable, array('clientID' => $id));
$this->delete($cTable, array('id' => $id));
$this->_db->CompleteTrans();
* @param eaInput input values
$where = "(owner = '" . $user['id'] . "') or (users like '-" . $user['id'] . "-')";
if (isset ($user['mail']) && ($user['mail'] == eaSYSADMIN)) $where = '1';
if (!$result = $this->select('*', $this->table('clients'), $where, 'name asc')) return false;
foreach ($result as $r) {
$r['db'] = $this->decrypt($r['db']);
$this->clients[$r['id']] = $r;
$opt['clients'][$r['id']] = $r['name'];
* checks if user is owner
* @param integer clientID
if (isset ($user['mail']) && ($user['mail'] == eaSYSADMIN)) return true;
if (isset ($this->clients)) {
if (!isset ($this->clients[$id])) return false;
if ($this->clients[$id]['owner'] != $this->user['id']) return false;
if (!$this->select('id', $this->table('clients'), array('owner' => $user['id'])))
* get client configuration variables
* @param integer clientID
* @return array configuration data
$where = "(context = 'client')";
if ($this->user['mail'] != eaSYSADMIN) $where .= " and (rights = 'owner')";
return $this->select('*', $this->table('config'), $where);
* load client configuration into configuration variables
* @param integer clientID
* @return integer clientID
$table = $this->table('clientconfig');
$where = array('clientID' => $id);
if ($dummy = $this->select('*', $table, $where)) {
foreach ($dummy as $var) $conf[$var['name']] = $var['value'];
* update client configuration
* @param integer client ID
* @param array changed configruration
$table = $this->table('clientconfig');
$where = array('clientID', 'name');
foreach ($changed as $key => $val) {
$what = array('clientID' => $id, 'name' => $key, 'value' => $val, 'lastModified' => $this->now());
if (!$this->_db->Replace($table, $what, $where, true)) $result = false;
* @param integer client ID
* @param string email address
if (!$user = $this->selectOne('id', $this->table('users'), array('mail' => $user)))
$table = $this->table('clients');
if (!$client = $this->selectOne('users', $table, $where)) return false;
if (preg_match('/-' . $user['id'] . '-/', $client['users'])) return true;
if (strlen($client['users']) > 2) $client['users'] .= $user['id'] . '-';
else $client['users'] = '-' . $user['id'] . '-';
return $this->update($client, $table, $where);
* remove user from client
* @param integer clientID
$table = $this->table('clients');
if (!$client = $this->selectOne('users', $table, $where)) return false;
$client['users'] = preg_replace('/-' . $user . '-/', '-', $client['users']);
return $this->update($client, $table, $where);
* @param integer client ID
* @return array user data
$table = $this->table('clients') . ' c, ' . $this->table('users') . ' u';
$where = "(c.id = " . $this->escape($id) . ") and (c.users like " . $this->_db->Concat("'%-'", 'u.id', "'-%'") . ")";
if (!$users = $this->select($what, $table, $where, 'u.mail asc')) return false;
foreach ($users as $user) $result[$user['id']] = $user['mail'];
* get system configuration variables
* @return array configuration data
$where = "(context = 'system')";
return $this->select('*', $this->table('config'), $where);
* update system configuration
* @param array changed configruration
if (!$changed) return false;
foreach ($changed as $key => $val) $what[] = array($val, $key);
$sql = 'update ' . $this->table('config') . ' set value=? where name=?';
if (!$this->_db->Execute($sql, $what)) return false;
* select one single database row
* @param string/array conditions
function selectOne($what, $table = '', $where = '', $order = '') {
return $this->select($what, $table, $where, $order, 1);
* @param string/array conditions
* @param integer number of rows
function select($what, $table = '', $where = '', $order = '', $rows = - 1, $offset = - 1, $group = '') {
if ($table) $table = ' from ' . $table;
$nameQuote = $this->_db->nameQuote;
foreach ($where as $key => $val) {
$dummy .= $next . '(' . $nameQuote . $key . $nameQuote . ' = ' . $this->escape($val) . ')';
$where = ' where ' . $dummy;
} else $where = ' where ' . $where;
if ($order) $order = ' order by ' . $order;
if ($group) $group = ' group by ' . $group;
if (!$rs = $this->_db->SelectLimit('select ' . $what . $table . $where . $group . $order, $rows, $offset))
if ($rows == 1) $arr = $rs->fields;
else $arr = $rs->getArray();
* @param string string to escape
* @return string escaped string
function escape($string, $noQuote = false) {
$return = $this->_db->qstr($string);
if ($noQuote) $return = substr($return, 1, - 1);
* @param string string to escape
* @return string escaped string
return $this->_db->nameQuote . $string . $this->_db->nameQuote;
* @param string string to encrypt
* @param string key [dsn]
* @return string encrypted string
function encrypt($string, $key = false) {
if (!isset ($this->_crypt)) $this->_crypt = new MD5Crypt;
if (isset ($this->conf['dsn'])) $key = $this->conf['dsn'];
return $this->_crypt->Encrypt($string, $key);
* @param string string to decrypt
* @param string key [dsn]
* @return string decrypted string
function decrypt($string, $key = false) {
if (!isset ($this->_crypt)) $this->_crypt = new MD5Crypt;
if (isset ($this->conf['dsn'])) $key = $this->conf['dsn'];
return $this->_crypt->Decrypt($string, $key);
* @param string preliminary table name
* @return string table name
function table($string) {
if (!$this->_prefix) return $string;
* insert array into table
* @param array $what key => value
* @param string $table table
function insert($what, $table) {
$nameQuote = $this->_db->nameQuote;
foreach ($what as $key => $val) {
$cols .= $next . $nameQuote . $key . $nameQuote;
$vals .= $next . $this->escape($val);
$sql = 'insert into ' . $table . '(' . $cols . ') values (' . $vals . ')';
if (!$this->_db->Execute($sql)) return false;
* @param string/array sql string / key => value
* @param string/array conditions
function update($what, $table, $where = '') {
if (!$what) return false;
$nameQuote = $this->_db->nameQuote;
foreach ($what as $key => $val) {
$dummy .= $next . $nameQuote . $key . $nameQuote . ' = ' . $this->escape($val);
$nameQuote = $this->_db->nameQuote;
foreach ($where as $key => $val) {
$dummy .= $next . '(' . $nameQuote . $key . $nameQuote . ' = ' . $this->escape($val) . ')';
} else $where = ' where ' . $where;
$sql = 'update ' . $table . ' set ' . $what . $where;
if (!$this->_db->Execute($sql)) return false;
* @param string/array conditions
function delete($table, $where = '') {
$nameQuote = $this->_db->nameQuote;
foreach ($where as $key => $val) {
$dummy .= $next . '(' . $nameQuote . $key . $nameQuote . ' = ' . $this->escape($val) . ')';
} else $where = ' where ' . $where;
$sql = 'delete from ' . $table . $where;
if (!$this->_db->Execute($sql)) return false;
* @return integer last id
return $this->_db->Insert_ID();
if (!$table) return false;
$sql = 'drop table ' . $table;
if (!$this->_db->Execute($sql)) return false;
* generate sql time string from unix timestamp
* @param integer unix time stamp
* @return string sql time string
* generate sql time string for current time
* @param integer unix time stamp
* @return string sql time string
// require_once(eaADODB_DIR . 'adodb-time.inc.php');
* output function forwarding to error_log
* @param string $msg error message
* @param boolean $newline send new line command
|