function SQLAuthenticate()
{
    global $db;
    global $password_encryption;
    global $session_key;
    if (isset($_SESSION["userlogin"]) && isset($_SESSION["userpwd"])) {
        //Username and password are set, lets try to authenticate.
        $session_pass = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($session_key), base64_decode($_SESSION["userpwd"]), MCRYPT_MODE_CBC, md5(md5($session_key))), "");
        $rowObj = $db->queryRow("SELECT id, fullname, password FROM users WHERE username="******"userlogin"], 'text') . " AND active=1");
        if ($rowObj) {
            if ($password_encryption == 'md5salt') {
                $session_password = mix_salt(extract_salt($rowObj["password"]), $session_pass);
            } else {
                $session_password = md5($session_pass);
            }
            if ($session_password == $rowObj["password"]) {
                $_SESSION["userid"] = $rowObj["id"];
                $_SESSION["name"] = $rowObj["fullname"];
                $_SESSION["auth_used"] = "internal";
                if (isset($_POST["authenticate"])) {
                    log_notice(sprintf('Successful authentication attempt from [%s] for user \'%s\'', $_SERVER['REMOTE_ADDR'], $_SESSION["userlogin"]));
                    //If a user has just authenticated, redirect him to requested page
                    session_write_close();
                    $redirect_url = $_POST["query_string"] ? $_SERVER['SCRIPT_NAME'] . "?" . $_POST["query_string"] : $_SERVER['SCRIPT_NAME'];
                    clean_page($redirect_url);
                    exit;
                }
            } else {
                if (isset($_POST['authenticate'])) {
                    //				auth( _('Authentication failed! - <a href="reset_password.php">(forgot password)</a>'),"error");
                    auth(_('Authentication failed!'), "error");
                } else {
                    auth();
                }
            }
        } else {
            if (isset($_POST['authenticate'])) {
                log_warn(sprintf('Failed authentication attempt from [%s]', $_SERVER['REMOTE_ADDR']));
                //Authentication failed, retry.
                //			auth( _('Authentication failed! - <a href="reset_password.php">(forgot password)</a>'),"error");
                auth(_('Authentication failed!'), "error");
            } else {
                unset($_SESSION["userpwd"]);
                unset($_SESSION["userlogin"]);
                auth();
            }
        }
    } else {
        //No username and password set, show auth form (again).
        auth();
    }
}
function doAuthenticate()
{
    global $db;
    global $iface_expire;
    global $syslog_use, $syslog_ident, $syslog_facility;
    global $session_key;
    global $password_encryption;
    if (isset($_SESSION['userid']) && isset($_SERVER["QUERY_STRING"]) && $_SERVER["QUERY_STRING"] == "logout") {
        logout(_('You have logged out.'), 'success');
    }
    // If a user had just entered his/her login && password, store them in our session.
    if (isset($_POST["authenticate"])) {
        $_SESSION["userpwd"] = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($session_key), $_POST['password'], MCRYPT_MODE_CBC, md5(md5($session_key))));
        $_SESSION["userlogin"] = $_POST["username"];
    }
    // Check if the session hasnt expired yet.
    if (isset($_SESSION["userid"]) && $_SESSION["lastmod"] != "" && time() - $_SESSION["lastmod"] > $iface_expire) {
        logout(_('Session expired, please login again.'), 'error');
    }
    // If the session hasn't expired yet, give our session a fresh new timestamp.
    $_SESSION["lastmod"] = time();
    if (isset($_SESSION["userlogin"]) && isset($_SESSION["userpwd"])) {
        //Username and password are set, lets try to authenticate.
        $session_pass = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($session_key), base64_decode($_SESSION["userpwd"]), MCRYPT_MODE_CBC, md5(md5($session_key))), "");
        if ($password_encryption == 'md5salt') {
            $result = $db->query("SELECT id, fullname, password FROM users WHERE username="******"userlogin"], 'text') . " AND active=1");
        } else {
            $result = $db->query("SELECT id, fullname, password FROM users WHERE username="******"userlogin"], 'text') . " AND active=1");
        }
        if ($result->numRows() == 1) {
            $rowObj = $result->fetchRow();
            if ($password_encryption == 'md5salt') {
                $session_password = mix_salt(extract_salt($rowObj["password"]), $session_pass);
            } else {
                $session_password = md5($session_pass);
            }
            if ($session_password == $rowObj["password"]) {
                $_SESSION["userid"] = $rowObj["id"];
                $_SESSION["name"] = $rowObj["fullname"];
                if (isset($_POST["authenticate"])) {
                    // Log to syslog if it's enabled
                    if ($syslog_use) {
                        openlog($syslog_ident, LOG_PERROR, $syslog_facility);
                        $syslog_message = sprintf('Successful authentication attempt from [%s] for user \'%s\'', $_SERVER['REMOTE_ADDR'], $_SESSION["userlogin"]);
                        syslog(LOG_INFO, $syslog_message);
                        closelog();
                    }
                    //If a user has just authenticated, redirect him to index with timestamp, so post-data gets lost.
                    session_write_close();
                    clean_page("index.php");
                    exit;
                }
            } else {
                if (isset($_POST['authenticate'])) {
                    //				auth( _('Authentication failed! - <a href="reset_password.php">(forgot password)</a>'),"error");
                    auth(_('Authentication failed!'), "error");
                } else {
                    auth();
                }
            }
        } else {
            if (isset($_POST['authenticate'])) {
                // Log to syslog if it's enabled
                if ($syslog_use) {
                    openlog($syslog_ident, LOG_PERROR, $syslog_facility);
                    $syslog_message = sprintf('Failed authentication attempt from [%s]', $_SERVER['REMOTE_ADDR']);
                    syslog(LOG_WARNING, $syslog_message);
                    closelog();
                }
                //Authentication failed, retry.
                //			auth( _('Authentication failed! - <a href="reset_password.php">(forgot password)</a>'),"error");
                auth(_('Authentication failed!'), "error");
            } else {
                auth();
            }
        }
    } else {
        //No username and password set, show auth form (again).
        auth();
    }
}
function gen_mix_salt($pass)
{
    $salt = generate_salt();
    return mix_salt($salt, $pass);
}
function change_user_pass($details)
{
    global $db;
    global $password_encryption;
    if ($details['newpass'] != $details['newpass2']) {
        error(ERR_USER_MATCH_NEW_PASS);
        return false;
    }
    $query = "SELECT id, password FROM users WHERE username = "******"userlogin"], 'text');
    $response = $db->query($query);
    if (PEAR::isError($response)) {
        error($response->getMessage());
        return false;
    }
    $rinfo = $response->fetchRow();
    if ($password_encryption == 'md5salt') {
        $extracted_salt = extract_salt($rinfo['password']);
        $current_password = mix_salt($extracted_salt, $details['currentpass']);
    } else {
        $current_password = md5($details['currentpass']);
    }
    if ($current_password == $rinfo['password']) {
        if ($password_encryption == 'md5salt') {
            $query = "UPDATE users SET password = "******" WHERE id = " . $db->quote($rinfo['id'], 'integer');
        } else {
            $query = "UPDATE users SET password = "******" WHERE id = " . $db->quote($rinfo['id'], 'integer');
        }
        $response = $db->query($query);
        if (PEAR::isError($response)) {
            error($response->getMessage());
            return false;
        }
        logout(_('Password has been changed, please login.'), 'success');
    } else {
        error(ERR_USER_WRONG_CURRENT_PASS);
        return false;
    }
}