6 * Driver for passwords stored in SQL database
9 * @author Aleksander 'A.L.E.C' Machniak <alec@alec.pl>
13 function password_save($curpass, $passwd)
15 $rcmail = rcmail::get_instance();
17 if (!($sql = $rcmail->config->get('password_query')))
18 $sql = 'SELECT update_passwd(%c, %u)';
20 if ($dsn = $rcmail->config->get('password_db_dsn')) {
21 // #1486067: enable new_link option
22 if (is_array($dsn) && empty($dsn['new_link']))
23 $dsn['new_link'] = true;
24 else if (!is_array($dsn) && !preg_match('/\?new_link=true/', $dsn))
25 $dsn .= '?new_link=true';
27 $db = new rcube_mdb2($dsn, '', FALSE);
28 $db->set_debug((bool)$rcmail->config->get('sql_debug'));
31 $db = $rcmail->get_dbh();
34 if ($err = $db->is_error())
35 return PASSWORD_ERROR;
38 if (strpos($sql, '%c') !== FALSE) {
41 $len = rand(3, CRYPT_SALT_LENGTH);
42 } else if (CRYPT_STD_DES) {
45 return PASSWORD_CRYPT_ERROR;
47 for ($i = 0; $i < $len ; $i++) {
48 $salt .= chr(rand(ord('.'), ord('z')));
50 $sql = str_replace('%c', $db->quote(crypt($passwd, CRYPT_MD5 ? '$1$'.$salt.'$' : $salt)), $sql);
54 if (preg_match('/%[n|q]/', $sql)) {
56 if (!extension_loaded('hash')) {
61 'message' => "Password plugin: 'hash' extension not loaded!"
63 return PASSWORD_ERROR;
66 if (!($hash_algo = strtolower($rcmail->config->get('password_hash_algorithm'))))
69 $hash_passwd = hash($hash_algo, $passwd);
70 $hash_curpass = hash($hash_algo, $curpass);
72 if ($rcmail->config->get('password_hash_base64')) {
73 $hash_passwd = base64_encode(pack('H*', $hash_passwd));
74 $hash_curpass = base64_encode(pack('H*', $hash_curpass));
77 $sql = str_replace('%n', $db->quote($hash_passwd, 'text'), $sql);
78 $sql = str_replace('%q', $db->quote($hash_curpass, 'text'), $sql);
81 $user_info = explode('@', $_SESSION['username']);
82 if (count($user_info) >= 2) {
83 $sql = str_replace('%l', $db->quote($user_info[0], 'text'), $sql);
84 $sql = str_replace('%d', $db->quote($user_info[0], 'text'), $sql);
87 $sql = str_replace('%u', $db->quote($_SESSION['username'],'text'), $sql);
88 $sql = str_replace('%h', $db->quote($_SESSION['imap_host'],'text'), $sql);
89 $sql = str_replace('%p', $db->quote($passwd,'text'), $sql);
90 $sql = str_replace('%o', $db->quote($curpass,'text'), $sql);
92 $res = $db->query($sql);
94 if (!$db->is_error()) {
95 if (strtolower(substr(trim($query),0,6))=='select') {
96 if ($result = $db->fetch_array($res))
97 return PASSWORD_SUCCESS;
99 if ($db->affected_rows($res) == 1)
100 return PASSWORD_SUCCESS; // This is the good case: 1 row updated
104 return PASSWORD_ERROR;