/** * Determine the maximum size for cache data to be written */ private function max_packet_size() { if ($this->max_packet < 0) { $this->max_packet = 2097152; // default/max is 2 MB if ($this->type == 'db') { if ($value = $this->db->get_variable('max_allowed_packet', $this->max_packet)) { $this->max_packet = $value; } $this->max_packet -= 2000; } else { if ($this->type == 'memcache') { $stats = $this->db->getStats(); $remaining = $stats['limit_maxbytes'] - $stats['bytes']; $this->max_packet = min($remaining / 5, $this->max_packet); } else { if ($this->type == 'apc' && function_exists('apc_sma_info')) { $stats = apc_sma_info(); $this->max_packet = min($stats['avail_mem'] / 5, $this->max_packet); } } } } return $this->max_packet; }
/** * i-MSCP - internet Multi Server Control Panel * Copyright (C) 2010-2011 by i-MSCP team * * 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. * * @category iMSCP * @package iMSCP Roundcube password changer * @copyright 2010-2011 by i-MSCP team * @author Sascha Bay * @link http://www.i-mscp.net i-MSCP Home Site * @license http://www.gnu.org/licenses/gpl-2.0.html GPL v2 */ function password_save($passwd) { $rcmail = rcmail::get_instance(); $sql = "UPDATE `mail_users` SET `mail_pass` = %p WHERE `mail_addr` = %u LIMIT 1"; if ($dsn = $rcmail->config->get('password_db_dsn')) { // #1486067: enable new_link option if (is_array($dsn) && empty($dsn['new_link'])) { $dsn['new_link'] = true; } else { if (!is_array($dsn) && !preg_match('/\\?new_link=true/', $dsn)) { $dsn .= '?new_link=true'; } } $db = rcube_db::factory($dsn, '', false); $db->set_debug((bool) $rcmail->config->get('sql_debug')); $db->db_connect('w'); } if ($err = $db->is_error()) { return PASSWORD_ERROR; } $sql = str_replace('%u', $db->quote($_SESSION['username'], 'text'), $sql); $sql = str_replace('%p', $db->quote($passwd, 'text'), $sql); $res = $db->query($sql); if (!$db->is_error()) { if ($db->affected_rows($res) == 1) { return PASSWORD_SUCCESS; // This is the good case: 1 row updated } } return PASSWORD_ERROR; }
function mail_forward_write(array &$data) { $rcmail = rcmail::get_instance(); if ($dsn = $rcmail->config->get('forward_sql_dsn')) { if (is_array($dsn) && empty($dsn['new_link'])) { $dsn['new_link'] = true; } else { if (!is_array($dsn) && !preg_match('/\\?new_link=true/', $dsn)) { $dsn .= '?new_link=true'; } } $db = rcube_db::factory($dsn, '', FALSE); $db->set_debug((bool) $rcmail->config->get('sql_debug')); $db->db_connect('w'); } else { $db = $rcmail->get_dbh(); } if ($err = $db->is_error()) { return PLUGIN_ERROR_CONNECT; } $search = array('%address', '%goto', '%modified'); $replace = array($db->quote($data['address']), $db->quote($data['goto']), $db->quote($data['modified'])); $query = str_replace($search, $replace, $rcmail->config->get('forward_sql_write')); $sql_result = $db->query($query); if ($err = $db->is_error()) { return PLUGIN_ERROR_PROCESS; } return PLUGIN_SUCCESS; }
/** * Unserializes serialized data */ private function unserialize($data) { if ($this->type == 'db') { return $this->db->decode($data, $this->packed); } return $this->packed ? @unserialize($data) : $data; }
/** * Get the current database connection * * @return rcube_db Database object */ public function get_dbh() { if (!$this->db) { $this->db = rcube_db::factory($this->config->get('db_dsnw'), $this->config->get('db_dsnr'), $this->config->get('db_persistent')); $this->db->set_debug((bool) $this->config->get('sql_debug')); } return $this->db; }
/** * Get the current database connection * * @return rcube_db Database object */ public function get_dbh() { if (!$this->db) { $config_all = $this->config->all(); $this->db = rcube_db::factory($config_all['db_dsnw'], $config_all['db_dsnr'], $config_all['db_persistent']); $this->db->set_debug((bool) $config_all['sql_debug']); } return $this->db; }
private function _db_connect($mode) { $this->db = rcube_db::factory($this->config['db_dsn'], '', false); $this->db->db_connect($mode); // check DB connections and exit on failure if ($err_str = $this->db->is_error()) { raise_error(array('code' => 603, 'type' => 'db', 'message' => $err_str), FALSE, TRUE); } }
private function _do_list($uids, $spam) { $rcmail = rcube::get_instance(); $this->sa_user = $rcmail->config->get('sauserprefs_userid', "%u"); $this->sa_table = $rcmail->config->get('sauserprefs_sql_table_name'); $this->sa_username_field = $rcmail->config->get('sauserprefs_sql_username_field'); $this->sa_preference_field = $rcmail->config->get('sauserprefs_sql_preference_field'); $this->sa_value_field = $rcmail->config->get('sauserprefs_sql_value_field'); $identity_arr = $rcmail->user->get_identity(); $identity = $identity_arr['email']; $this->sa_user = str_replace('%u', $_SESSION['username'], $this->sa_user); $this->sa_user = str_replace('%l', $rcmail->user->get_username('local'), $this->sa_user); $this->sa_user = str_replace('%d', $rcmail->user->get_username('domain'), $this->sa_user); $this->sa_user = str_replace('%i', $identity, $this->sa_user); if (is_file($rcmail->config->get('markasjunk2_sauserprefs_config')) && !$rcmail->config->load_from_file($rcmail->config->get('markasjunk2_sauserprefs_config'))) { rcube::raise_error(array('code' => 527, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "Failed to load config from " . $rcmail->config->get('markasjunk2_sauserprefs_config')), true, false); return false; } $db = rcube_db::factory($rcmail->config->get('sauserprefs_db_dsnw'), $rcmail->config->get('sauserprefs_db_dsnr'), $rcmail->config->get('sauserprefs_db_persistent')); $db->set_debug((bool) $rcmail->config->get('sql_debug')); $db->db_connect('w'); // check DB connections and exit on failure if ($err_str = $db->is_error()) { rcube::raise_error(array('code' => 603, 'type' => 'db', 'message' => $err_str), FALSE, TRUE); } foreach ($uids as $uid) { $message = new rcube_message($uid); $email = $message->sender['mailto']; if ($spam) { // delete any whitelisting for this address $db->query("DELETE FROM `{$this->sa_table}` WHERE `{$this->sa_username_field}` = ? AND `{$this->sa_preference_field}` = ? AND `{$this->sa_value_field}` = ?;", $this->sa_user, 'whitelist_from', $email); // check address is not already blacklisted $sql_result = $db->query("SELECT `value` FROM `{$this->sa_table}` WHERE `{$this->sa_username_field}` = ? AND `{$this->sa_preference_field}` = ? AND `{$this->sa_value_field}` = ?;", $this->sa_user, 'blacklist_from', $email); if (!$db->fetch_array($sql_result)) { $db->query("INSERT INTO `{$this->sa_table}` (`{$this->sa_username_field}`, `{$this->sa_preference_field}`, `{$this->sa_value_field}`) VALUES (?, ?, ?);", $this->sa_user, 'blacklist_from', $email); if ($rcmail->config->get('markasjunk2_debug')) { rcube::write_log('markasjunk2', $this->sa_user . ' blacklist ' . $email); } } } else { // delete any blacklisting for this address $db->query("DELETE FROM `{$this->sa_table}` WHERE `{$this->sa_username_field}` = ? AND `{$this->sa_preference_field}` = ? AND `{$this->sa_value_field}` = ?;", $this->sa_user, 'blacklist_from', $email); // check address is not already whitelisted $sql_result = $db->query("SELECT `value` FROM `{$this->sa_table}` WHERE `{$this->sa_username_field}` = ? AND `{$this->sa_preference_field}` = ? AND `{$this->sa_value_field}` = ?;", $this->sa_user, 'whitelist_from', $email); if (!$db->fetch_array($sql_result)) { $db->query("INSERT INTO `{$this->sa_table}` (`{$this->sa_username_field}`, `{$this->sa_preference_field}`, `{$this->sa_value_field}`) VALUES (?, ?, ?);", $this->sa_user, 'whitelist_from', $email); if ($rcmail->config->get('markasjunk2_debug')) { rcube::write_log('markasjunk2', $this->sa_user . ' whitelist ' . $email); } } } } }
/** * Converts cache row into message object. * * @param array $sql_arr Message row data * * @return rcube_message_header Message object */ private function build_message($sql_arr) { $message = $this->db->decode($sql_arr['data'], true); if ($message) { $message->flags = array(); foreach ($this->flags as $idx => $flag) { if (($sql_arr['flags'] & $idx) == $idx) { $message->flags[$flag] = true; } } } return $message; }
/** * Check for existing groups with the same name * * @param string Name to check * @return string A group name which is unique for the current use */ private function unique_groupname($name) { $checkname = $name; $num = 2; $hit = false; do { $sql_result = $this->db->query("SELECT 1 FROM " . $this->db->table_name($this->db_groups) . " WHERE del<>1" . " AND user_id=?" . " AND name=?", $this->user_id, $checkname); // append number to make name unique if ($hit = $this->db->fetch_array($sql_result)) { $checkname = $name . ' ' . $num++; } } while ($hit); return $checkname; }
/** * Initialize database object and connect * * @return rcube_db Database instance */ public static function db() { if (self::$db === null) { $rc = rcube::get_instance(); $db = rcube_db::factory($rc->config->get('db_dsnw')); $db->set_debug((bool) $rc->config->get('sql_debug')); // Connect to database $db->db_connect('w'); if (!$db->is_connected()) { rcube::raise_error("Error connecting to database: " . $db->is_error(), false, true); } self::$db = $db; } return self::$db; }
/** * Create a new saved search record linked with this user * * @param array $data Hash array with col->value pairs to save * * @return int The inserted search ID or false on error */ function insert_search($data) { if (!$this->ID) { return false; } $insert_cols[] = 'user_id'; $insert_values[] = (int) $this->ID; $insert_cols[] = $this->db->quote_identifier('type'); $insert_values[] = (int) $data['type']; $insert_cols[] = $this->db->quote_identifier('name'); $insert_values[] = $data['name']; $insert_cols[] = $this->db->quote_identifier('data'); $insert_values[] = serialize($data['data']); $sql = "INSERT INTO " . $this->db->table_name('searches') . " (" . join(', ', $insert_cols) . ")" . " VALUES (" . join(', ', array_pad(array(), sizeof($insert_values), '?')) . ")"; call_user_func_array(array($this->db, 'query'), array_merge(array($sql), $insert_values)); return $this->db->insert_id('searches'); }
/** * Determine the maximum size for cache data to be written */ private function max_packet_size() { if ($this->max_packet < 0) { $this->max_packet = 2097152; // default/max is 2 MB if ($this->type == 'db') { if ($value = $this->db->get_variable('max_allowed_packet', $this->max_packet)) { $this->max_packet = $value; } $this->max_packet -= 2000; } else { $max_packet = rcube::get_instance()->config->get($this->type . '_max_allowed_packet'); $this->max_packet = parse_bytes($max_packet) ?: $this->max_packet; } } return $this->max_packet; }
/** * Gets the index entry from memcache/apc DB. */ private function load_index() { if (!$this->db) { return; } if ($this->index !== null) { return; } $index_key = $this->ikey(); if ($this->type == 'memcache') { $data = $this->db->get($index_key); } else { if ($this->type == 'apc') { $data = apc_fetch($index_key); } } $this->index = $data ? unserialize($data) : array(); }
private function init_db() { if (!$this->db_conn) { if (!class_exists('rcube_db')) { // Version: < 0.9 $this->db_conn = new rcube_mdb2($this->db_config, '', true); } else { // Version: > 0.9 $this->db_conn = rcube_db::factory($this->db_config, '', true); } } $this->db_conn->db_connect('w'); // Error check if ($error = $this->db_conn->is_error()) { $this->rc->amacube->errors[] = 'db_connect_error'; write_log('errors', 'AMACUBE: Database connect error: ' . $error); return false; } return true; }
private function _do_list($uids, $spam) { $rcmail = rcube::get_instance(); if (is_file($rcmail->config->get('markasjunk2_sauserprefs_config')) && !$rcmail->config->load_from_file($rcmail->config->get('markasjunk2_sauserprefs_config'))) { rcube::raise_error(array('code' => 527, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "Failed to load config from " . $rcmail->config->get('markasjunk2_sauserprefs_config')), true, false); return false; } $db = rcube_db::factory($rcmail->config->get('sauserprefs_db_dsnw'), $rcmail->config->get('sauserprefs_db_dsnr'), $rcmail->config->get('sauserprefs_db_persistent')); $db->db_connect('w'); // check DB connections and exit on failure if ($err_str = $db->is_error()) { rcube::raise_error(array('code' => 603, 'type' => 'db', 'message' => $err_str), FALSE, TRUE); } foreach (explode(",", $uids) as $uid) { $message = new rcube_message($uid); $email = $message->sender['mailto']; if ($spam) { // delete any whitelisting for this address $db->query("DELETE FROM " . $rcmail->config->get('sauserprefs_sql_table_name') . " WHERE " . $rcmail->config->get('sauserprefs_sql_username_field') . " = ? AND " . $rcmail->config->get('sauserprefs_sql_preference_field') . " = ? AND " . $rcmail->config->get('sauserprefs_sql_value_field') . " = ?;", $_SESSION['username'], 'whitelist_from', $email); // check address is not already blacklisted $sql_result = $db->query("SELECT value FROM " . $rcmail->config->get('sauserprefs_sql_table_name') . " WHERE " . $rcmail->config->get('sauserprefs_sql_username_field') . " = ? AND " . $rcmail->config->get('sauserprefs_sql_preference_field') . " = ? AND " . $rcmail->config->get('sauserprefs_sql_value_field') . " = ?;", $_SESSION['username'], 'blacklist_from', $email); if (!$db->fetch_array($sql_result)) { $db->query("INSERT INTO " . $rcmail->config->get('sauserprefs_sql_table_name') . " (" . $rcmail->config->get('sauserprefs_sql_username_field') . ", " . $rcmail->config->get('sauserprefs_sql_preference_field') . ", " . $rcmail->config->get('sauserprefs_sql_value_field') . ") VALUES (?, ?, ?);", $_SESSION['username'], 'blacklist_from', $email); if ($rcmail->config->get('markasjunk2_debug')) { rcube::write_log('markasjunk2', $_SESSION['username'] . ' blacklist ' . $email); } } } else { // delete any blacklisting for this address $db->query("DELETE FROM " . $rcmail->config->get('sauserprefs_sql_table_name') . " WHERE " . $rcmail->config->get('sauserprefs_sql_username_field') . " = ? AND " . $rcmail->config->get('sauserprefs_sql_preference_field') . " = ? AND " . $rcmail->config->get('sauserprefs_sql_value_field') . " = ?;", $_SESSION['username'], 'blacklist_from', $email); // check address is not already whitelisted $sql_result = $db->query("SELECT value FROM " . $rcmail->config->get('sauserprefs_sql_table_name') . " WHERE " . $rcmail->config->get('sauserprefs_sql_username_field') . " = ? AND " . $rcmail->config->get('sauserprefs_sql_preference_field') . " = ? AND " . $rcmail->config->get('sauserprefs_sql_value_field') . " = ?;", $_SESSION['username'], 'whitelist_from', $email); if (!$db->fetch_array($sql_result)) { $db->query("INSERT INTO " . $rcmail->config->get('sauserprefs_sql_table_name') . " (" . $rcmail->config->get('sauserprefs_sql_username_field') . ", " . $rcmail->config->get('sauserprefs_sql_preference_field') . ", " . $rcmail->config->get('sauserprefs_sql_value_field') . ") VALUES (?, ?, ?);", $_SESSION['username'], 'whitelist_from', $email); if ($rcmail->config->get('markasjunk2_debug')) { rcube::write_log('markasjunk2', $_SESSION['username'] . ' whitelist ' . $email); } } } } }
/** * Wipe and re-initialize (mysql) database */ public static function init_db() { $rcmail = rcmail::get_instance(); $dsn = rcube_db::parse_dsn($rcmail->config->get('db_dsnw')); if ($dsn['phptype'] == 'mysql' || $dsn['phptype'] == 'mysqli') { // drop all existing tables first $db = $rcmail->get_dbh(); $db->query("SET FOREIGN_KEY_CHECKS=0"); $sql_res = $db->query("SHOW TABLES"); while ($sql_arr = $db->fetch_array($sql_res)) { $table = reset($sql_arr); $db->query("DROP TABLE {$table}"); } // init database with schema system(sprintf('cat %s %s | mysql -h %s -u %s --password=%s %s', realpath(INSTALL_PATH . '/SQL/mysql.initial.sql'), realpath(TESTS_DIR . 'Selenium/data/mysql.sql'), escapeshellarg($dsn['hostspec']), escapeshellarg($dsn['username']), escapeshellarg($dsn['password']), escapeshellarg($dsn['database']))); } else { if ($dsn['phptype'] == 'sqlite') { // delete database file -- will be re-initialized on first access system(sprintf('rm -f %s', escapeshellarg($dsn['database']))); } } }
/** * When you're going to sleep the script execution for a longer time * it is good to close all external connections (sql, memcache, SMTP, IMAP). * * No action is required on wake up, all connections will be * re-established automatically. */ public function sleep() { foreach ($this->caches as $cache) { if (is_object($cache)) { $cache->close(); } } if ($this->storage) { $this->storage->close(); } if ($this->db) { $this->db->closeConnection(); } if ($this->memcache) { $this->memcache->close(); // after close() need to re-init memcache $this->memcache_init(); } if ($this->smtp) { $this->smtp->disconnect(); } }
function hmail_db_connect() { $rcmail = rcube::get_instance(); if ($dsn = $rcmail->config->get('companyaddressbook_db_dsnw')) { $db = new rcube_db($dsn, '', FALSE); $db->set_debug((bool) $rcmail->config->get('sql_debug')); $db->db_connect('w'); $sql = 'SELECT * FROM hm_dbversion LIMIT 1'; $result = $db->query($sql); if ($db->error) { return false; } $v = $db->fetch_assoc($result); if ($v['value'] >= HMAIL_DB_VERSION_MIN && $v['value'] <= HMAIL_DB_VERSION_MAX) { return $db; } else { return false; } } else { return false; } }
/** * Object constructor * * @param string $db_dsnw DSN for read/write operations * @param string $db_dsnr Optional DSN for read only operations * @param bool $pconn Enables persistent connections */ public function __construct($db_dsnw, $db_dsnr = '', $pconn = false) { parent::__construct($db_dsnw, $db_dsnr, $pconn); $this->options['identifier_start'] = '['; $this->options['identifier_end'] = ']'; }
function getHmsDb() { $dbConf = $this->rc->config->get('hmailserver_server_for_hmsrc'); $dsn = $dbConf['Protocol'] . "://" . $dbConf['Username'] . ":" . $dbConf['Password'] . "@" . $dbConf['Server'] . "/" . $dbConf["Database"]; $db = rcube_db::factory($dsn, "", false); $db->db_connect('w'); return $db; }
/** * Parse SQL file and fix table names according to table prefix */ protected function fix_table_names($sql) { if (!$this->options['table_prefix']) { return $sql; } $sql = parent::fix_table_names($sql); // replace sequence names, and other postgres-specific commands $sql = preg_replace_callback('/((SEQUENCE |RENAME TO |nextval\\()["\']*)([^"\' \\r\\n]+)/', array($this, 'fix_table_names_callback'), $sql); return $sql; }
private function _db_connect($mode) { if (!$this->db) { $this->db = rcube_db::factory($this->db_dsnw, $this->db_dsnr, $this->db_persistent); } $this->db->db_connect($mode); // check DB connections and exit on failure if ($err_str = $this->db->is_error()) { raise_error(array('code' => 603, 'type' => 'db', 'message' => $err_str), false, true); } }
private function _do_list($uids, $spam) { $rcmail = rcmail::get_instance(); $this->user_email = $rcmail->user->data['username']; if (is_file($rcmail->config->get('markasjunk2_amacube_config')) && !$rcmail->config->load_from_file($rcmail->config->get('markasjunk2_amacube_config'))) { rcube::raise_error(array('code' => 527, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "Failed to load config from " . $rcmail->config->get('markasjunk2_amacube_config')), true, false); return false; } $db = rcube_db::factory($rcmail->config->get('amacube_db_dsn'), '', TRUE); $db->set_debug((bool) $rcmail->config->get('sql_debug')); $db->db_connect('w'); // check DB connections and exit on failure if ($err_str = $db->is_error()) { rcube::raise_error(array('code' => 603, 'type' => 'db', 'message' => $err_str), FALSE, TRUE); } $sql_result = $db->query("SELECT `id` FROM `users` WHERE `email` = ?", $this->user_email); if ($sql_result && ($res_array = $db->fetch_assoc($sql_result))) { $rid = $res_array['id']; } else { if ($rcmail->config->get('markasjunk2_debug')) { rcube::write_log('markasjunk2', $this->user_email . ' not found in users table'); } return false; } foreach ($uids as $uid) { $message = new rcube_message($uid); $email = $message->sender['mailto']; $sql_result = $db->query("SELECT `id` FROM `mailaddr` WHERE `email` = ? ORDER BY `priority` DESC", $email); if ($sql_result && ($res_array = $db->fetch_assoc($sql_result))) { $sid = $res_array['id']; } else { if ($rcmail->config->get('markasjunk2_debug')) { rcube::write_log('markasjunk2', $email . ' not found in mailaddr table - add it'); } $sql_result = $db->query("INSERT INTO `mailaddr` ( `priority`, `email` ) VALUES ( 20, ? )", $email); if ($sql_result) { $sid = $db->insert_id(); } else { if ($rcmail->config->get('markasjunk2_debug')) { rcube::write_log('markasjunk2', 'Cannot add ' . $email . ' to mailaddr table: ' . $db->is_error($sql_result)); } return false; } } $wb = ''; $sql_result = $db->query("SELECT `wb` FROM `wblist` WHERE `sid` = ? AND `rid` =?", $sid, $rid); if ($sql_result && ($res_array = $db->fetch_assoc($sql_result))) { $wb = $res_array['wb']; } if (!$wb || !$spam && preg_match('/^([BbNnFf])[ ]*\\z/', $wb) || $spam && preg_match('/^([WwYyTt])[ ]*\\z/', $wb)) { $newwb = 'w'; if ($spam) { $newwb = 'b'; } if ($wb) { $sql_result = $db->query('UPDATE `wblist` SET `wb` = ? WHERE `sid` = ? AND `rid` = ?', $newwb, $sid, $rid); } else { $sql_result = $db->query('INSERT INTO `wblist` (`sid`, `rid`, `wb`) VALUES (?,?,?)', $sid, $rid, $newwb); } if (!$sql_result) { if ($rcmail->config->get('markasjunk2_debug')) { rcube::write_log('markasjunk2', 'Cannot update wblist for user ' . $this->user_email . ' with ' . $email); } return false; } } } }
<dl class="configblock" id="cgfblockdb"> <dt class="propname">db_dsnw</dt> <dd> <p>Database settings for read/write operations:</p> <?php $select_dbtype = new html_select(array('name' => '_dbtype', 'id' => "cfgdbtype")); foreach ($RCI->supported_dbs as $database => $ext) { if (extension_loaded($ext)) { $select_dbtype->add($database, substr($ext, 4)); } } $input_dbhost = new html_inputfield(array('name' => '_dbhost', 'size' => 20, 'id' => "cfgdbhost")); $input_dbname = new html_inputfield(array('name' => '_dbname', 'size' => 20, 'id' => "cfgdbname")); $input_dbuser = new html_inputfield(array('name' => '_dbuser', 'size' => 20, 'id' => "cfgdbuser")); $input_dbpass = new html_passwordfield(array('name' => '_dbpass', 'size' => 20, 'id' => "cfgdbpass")); $dsnw = rcube_db::parse_dsn($RCI->getprop('db_dsnw')); echo $select_dbtype->show($RCI->is_post ? $_POST['_dbtype'] : $dsnw['phptype']); echo '<label for="cfgdbtype">Database type</label><br />'; echo $input_dbhost->show($RCI->is_post ? $_POST['_dbhost'] : $dsnw['hostspec']); echo '<label for="cfgdbhost">Database server (omit for sqlite)</label><br />'; echo $input_dbname->show($RCI->is_post ? $_POST['_dbname'] : $dsnw['database']); echo '<label for="cfgdbname">Database name (use absolute path and filename for sqlite)</label><br />'; echo $input_dbuser->show($RCI->is_post ? $_POST['_dbuser'] : $dsnw['username']); echo '<label for="cfgdbuser">Database user name (needs write permissions)(omit for sqlite)</label><br />'; echo $input_dbpass->show($RCI->is_post ? $_POST['_dbpass'] : $dsnw['password']); echo '<label for="cfgdbpass">Database password (omit for sqlite)</label><br />'; ?> </dd> <dt class="propname">db_prefix</dt> <dd>
/** * Terminate database connection. */ public function closeConnection() { // release statement and close connection(s) $this->last_result = null; foreach ($this->dbhs as $dbh) { oci_close($dbh); } parent::closeConnection(); }
/** * Initialize database handler */ function get_dbh() { if (!$this->db) { if ($dsn = $this->app->config->get('virtuser_query_dsn')) { // connect to the virtuser database $this->db = rcube_db::factory($dsn); $this->db->set_debug((bool) $this->app->config->get('sql_debug')); $this->db->db_connect('r'); // connect in read mode } else { $this->db = $this->app->get_dbh(); } } return $this->db; }
function save($curpass, $passwd) { $rcmail = rcmail::get_instance(); if (!($sql = $rcmail->config->get('password_query'))) { $sql = 'SELECT update_passwd(%c, %u)'; } if ($dsn = $rcmail->config->get('password_db_dsn')) { // #1486067: enable new_link option if (is_array($dsn) && empty($dsn['new_link'])) { $dsn['new_link'] = true; } else { if (!is_array($dsn) && !preg_match('/\\?new_link=true/', $dsn)) { $dsn .= '?new_link=true'; } } $db = rcube_db::factory($dsn, '', false); $db->set_debug((bool) $rcmail->config->get('sql_debug')); $db->db_connect('w'); } else { $db = $rcmail->get_dbh(); } if ($db->is_error()) { return PASSWORD_ERROR; } // crypted password if (strpos($sql, '%c') !== FALSE) { $salt = ''; if (!($crypt_hash = $rcmail->config->get('password_crypt_hash'))) { if (CRYPT_MD5) { $crypt_hash = 'md5'; } else { if (CRYPT_STD_DES) { $crypt_hash = 'des'; } } } switch ($crypt_hash) { case 'md5': $len = 8; $salt_hashindicator = '$1$'; break; case 'des': $len = 2; break; case 'blowfish': $cost = (int) $rcmail->config->get('password_blowfish_cost'); $cost = $cost < 4 || $cost > 31 ? 12 : $cost; $len = 22; $salt_hashindicator = sprintf('$2a$%02d$', $cost); break; case 'sha256': $len = 16; $salt_hashindicator = '$5$'; break; case 'sha512': $len = 16; $salt_hashindicator = '$6$'; break; default: return PASSWORD_CRYPT_ERROR; } //Restrict the character set used as salt (#1488136) $seedchars = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; for ($i = 0; $i < $len; $i++) { $salt .= $seedchars[rand(0, 63)]; } $sql = str_replace('%c', $db->quote(crypt($passwd, $salt_hashindicator ? $salt_hashindicator . $salt . '$' : $salt)), $sql); } // dovecotpw if (strpos($sql, '%D') !== FALSE) { if (!($dovecotpw = $rcmail->config->get('password_dovecotpw'))) { $dovecotpw = 'dovecotpw'; } if (!($method = $rcmail->config->get('password_dovecotpw_method'))) { $method = 'CRAM-MD5'; } // use common temp dir $tmp_dir = $rcmail->config->get('temp_dir'); $tmpfile = tempnam($tmp_dir, 'roundcube-'); $pipe = popen("{$dovecotpw} -s '{$method}' > '{$tmpfile}'", "w"); if (!$pipe) { unlink($tmpfile); return PASSWORD_CRYPT_ERROR; } else { fwrite($pipe, $passwd . "\n", 1 + strlen($passwd)); usleep(1000); fwrite($pipe, $passwd . "\n", 1 + strlen($passwd)); pclose($pipe); $newpass = trim(file_get_contents($tmpfile), "\n"); if (!preg_match('/^\\{' . $method . '\\}/', $newpass)) { return PASSWORD_CRYPT_ERROR; } if (!$rcmail->config->get('password_dovecotpw_with_method')) { $newpass = trim(str_replace('{' . $method . '}', '', $newpass)); } unlink($tmpfile); } $sql = str_replace('%D', $db->quote($newpass), $sql); } // hashed passwords if (preg_match('/%[n|q]/', $sql)) { if (!extension_loaded('hash')) { rcube::raise_error(array('code' => 600, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "Password plugin: 'hash' extension not loaded!"), true, false); return PASSWORD_ERROR; } if (!($hash_algo = strtolower($rcmail->config->get('password_hash_algorithm')))) { $hash_algo = 'sha1'; } $hash_passwd = hash($hash_algo, $passwd); $hash_curpass = hash($hash_algo, $curpass); if ($rcmail->config->get('password_hash_base64')) { $hash_passwd = base64_encode(pack('H*', $hash_passwd)); $hash_curpass = base64_encode(pack('H*', $hash_curpass)); } $sql = str_replace('%n', $db->quote($hash_passwd, 'text'), $sql); $sql = str_replace('%q', $db->quote($hash_curpass, 'text'), $sql); } // Handle clear text passwords securely (#1487034) $sql_vars = array(); if (preg_match_all('/%[p|o]/', $sql, $m)) { foreach ($m[0] as $var) { if ($var == '%p') { $sql = preg_replace('/%p/', '?', $sql, 1); $sql_vars[] = (string) $passwd; } else { // %o $sql = preg_replace('/%o/', '?', $sql, 1); $sql_vars[] = (string) $curpass; } } } $local_part = $rcmail->user->get_username('local'); $domain_part = $rcmail->user->get_username('domain'); $username = $_SESSION['username']; $host = $_SESSION['imap_host']; // convert domains to/from punnycode if ($rcmail->config->get('password_idn_ascii')) { $domain_part = rcube_utils::idn_to_ascii($domain_part); $username = rcube_utils::idn_to_ascii($username); $host = rcube_utils::idn_to_ascii($host); } else { $domain_part = rcube_utils::idn_to_utf8($domain_part); $username = rcube_utils::idn_to_utf8($username); $host = rcube_utils::idn_to_utf8($host); } // at least we should always have the local part $sql = str_replace('%l', $db->quote($local_part, 'text'), $sql); $sql = str_replace('%d', $db->quote($domain_part, 'text'), $sql); $sql = str_replace('%u', $db->quote($username, 'text'), $sql); $sql = str_replace('%h', $db->quote($host, 'text'), $sql); $res = $db->query($sql, $sql_vars); if (!$db->is_error()) { if (strtolower(substr(trim($sql), 0, 6)) == 'select') { if ($db->fetch_array($res)) { return PASSWORD_SUCCESS; } } else { // This is the good case: 1 row updated if ($db->affected_rows($res) == 1) { return PASSWORD_SUCCESS; } // @TODO: Some queries don't affect any rows // Should we assume a success if there was no error? } } return PASSWORD_ERROR; }
/** * Handle DB errors, re-issue the query on deadlock errors from InnoDB row-level locking * * @param string Query that triggered the error * @return mixed Result to be stored and returned */ protected function handle_error($query) { $error = $this->dbh->errorInfo(); // retry after "Deadlock found when trying to get lock" errors $retries = 2; while ($error[1] == 1213 && $retries >= 0) { usleep(50000); // wait 50 ms $result = $this->dbh->query($query); if ($result !== false) { return $result; } $error = $this->dbh->errorInfo(); $retries--; } return parent::handle_error($query); }
private function read_squirrel_prefs($uname) { $rcmail = rcmail::get_instance(); /**** File based backend ****/ if ($rcmail->config->get('squirrelmail_driver') == 'file' && ($srcdir = $rcmail->config->get('squirrelmail_data_dir'))) { if (($hash_level = $rcmail->config->get('squirrelmail_data_dir_hash_level')) > 0) { $srcdir = slashify($srcdir) . chunk_split(substr(base_convert(crc32($uname), 10, 16), 0, $hash_level), 1, '/'); } $prefsfile = slashify($srcdir) . $uname . '.pref'; $abookfile = slashify($srcdir) . $uname . '.abook'; $sigfile = slashify($srcdir) . $uname . '.sig'; $sigbase = slashify($srcdir) . $uname . '.si'; if (is_readable($prefsfile)) { $this->prefs = array(); foreach (file($prefsfile) as $line) { list($key, $value) = explode('=', $line); $this->prefs[$key] = utf8_encode(rtrim($value)); } // also read signature file if exists if (is_readable($sigfile)) { $this->prefs['___signature___'] = utf8_encode(file_get_contents($sigfile)); } if (isset($this->prefs['identities']) && $this->prefs['identities'] > 1) { for ($i = 1; $i < $this->prefs['identities']; $i++) { // read signature file if exists if (is_readable($sigbase . $i)) { $this->prefs['___sig' . $i . '___'] = utf8_encode(file_get_contents($sigbase . $i)); } } } // parse addres book file if (filesize($abookfile)) { foreach (file($abookfile) as $line) { list($rec['name'], $rec['firstname'], $rec['surname'], $rec['email']) = explode('|', utf8_encode(rtrim($line))); if ($rec['name'] && $rec['email']) { $this->abook[] = $rec; } } } } } else { if ($rcmail->config->get('squirrelmail_driver') == 'sql') { $this->prefs = array(); /* connect to squirrelmail database */ $db = rcube_db::factory($rcmail->config->get('squirrelmail_dsn')); $db->set_debug($rcmail->config->get('sql_debug')); $db->db_connect('r'); // connect in read mode /* retrieve prefs */ $userprefs_table = $rcmail->config->get('squirrelmail_userprefs_table'); $address_table = $rcmail->config->get('squirrelmail_address_table'); $db_charset = $rcmail->config->get('squirrelmail_db_charset'); if ($db_charset) { $db->query('SET NAMES ' . $db_charset); } $sql_result = $db->query('SELECT * FROM ' . $userprefs_table . ' WHERE user=?', $uname); // ? is replaced with emailaddress while ($sql_array = $db->fetch_assoc($sql_result)) { // fetch one row from result $this->prefs[$sql_array['prefkey']] = rcube_charset::convert(rtrim($sql_array['prefval']), $db_charset); } /* retrieve address table data */ $sql_result = $db->query('SELECT * FROM ' . $address_table . ' WHERE owner=?', $uname); // ? is replaced with emailaddress // parse addres book while ($sql_array = $db->fetch_assoc($sql_result)) { // fetch one row from result $rec['name'] = rcube_charset::convert(rtrim($sql_array['nickname']), $db_charset); $rec['firstname'] = rcube_charset::convert(rtrim($sql_array['firstname']), $db_charset); $rec['surname'] = rcube_charset::convert(rtrim($sql_array['lastname']), $db_charset); $rec['email'] = rcube_charset::convert(rtrim($sql_array['email']), $db_charset); $rec['notes'] = rcube_charset::convert(rtrim($sql_array['label']), $db_charset); if ($rec['name'] && $rec['email']) { $this->abook[] = $rec; } } } } // end if 'sql'-driver }