if (IS_installed === false) {
    require_once S9Y_INCLUDE_PATH . 'include/functions.inc.php';
} else {
    if (defined('IS_up2date') && IS_up2date === true) {
        serendipity_plugin_api::hook_event('backend_configure', $serendipity);
    }
}
if (isset($serendipity['GET']['adminModule']) && $serendipity['GET']['adminModule'] == 'logout') {
    serendipity_logout();
    header("Location: " . $serendipity['baseURL']);
} else {
    if (IS_installed === true) {
        /* Check author token to insure session not hijacked */
        if (!isset($_SESSION['author_token']) || !isset($serendipity['COOKIE']['author_token']) || $_SESSION['author_token'] !== $serendipity['COOKIE']['author_token']) {
            $_SESSION['serendipityAuthedUser'] = false;
            serendipity_session_destroy();
        }
        if (!serendipity_userLoggedIn()) {
            // Try again to log in, this time with enabled external authentication event hook
            serendipity_login(true);
        }
    }
}
// If we are inside an iframe, halt the script
if (serendipity_is_iframe() !== false) {
    include_once S9Y_INCLUDE_PATH . 'include/functions_entries_admin.inc.php';
    // An iframe may NOT contain <html> and </html> tags, that's why we emit different headers here than on serendipity_admin.php
    // We need to restore GET/POST variables to that depending plugins inside the iframe
    // can still fetch all that variables; and we also tighten security by not allowing
    // to pass any different GET/POST variables to our iframe.
    $iframe_mode = $serendipity['GET']['iframe_mode'];
/**
 * Perform user authentication routine
 *
 * If a user is already authenticated via session data, this bypasses some routines.
 * After a user has ben authenticated, several SESSION variables ar set.
 * If the authentication fails, the session is destroyed.
 *
 * @access public
 * @param   string      The username to check
 * @param   string      The password to check (may contain plaintext or MD5 hash)
 * @param   boolean     Indicates whether the input password is already in MD5 format (TRUE) or not (FALSE).
 * @param   boolean     Indicates whether to query external plugins for authentication
 * @return  boolean     True on success, False on error
 */
function serendipity_authenticate_author($username = '', $password = '', $is_hashed = false, $use_external = true)
{
    global $serendipity;
    static $debug = false;
    static $debugc = 0;
    if ($debug) {
        $fp = fopen('login.log', 'a');
        flock($fp, LOCK_EX);
        $debugc++;
        fwrite($fp, date('Y-m-d H:i') . ' - #' . $debugc . ' Login init [' . $username . ',' . $password . ',' . (int) $is_hashed . ',' . (int) $use_external . ']' . ' (' . $_SERVER['REMOTE_ADDR'] . ',' . $_SERVER['REQUEST_URI'] . ', ' . session_id() . ')' . "\n");
    }
    if (isset($_SESSION['serendipityUser']) && isset($_SESSION['serendipityPassword']) && isset($_SESSION['serendipityAuthedUser']) && $_SESSION['serendipityAuthedUser'] == true) {
        $username = $_SESSION['serendipityUser'];
        $password = $_SESSION['serendipityPassword'];
        // For safety reasons when multiple blogs are installed on the same host, we need to check the current author each time to not let him log into a different blog with the same sessiondata
        #$is_hashed = true;
        if ($debug) {
            fwrite($fp, date('Y-m-d H:i') . ' - Recall from session: ' . $username . ':' . $password . "\n");
        }
    }
    if ($debug) {
        fwrite($fp, date('Y-m-d H:i') . ' - Login ext check' . "\n");
    }
    $is_authenticated = false;
    serendipity_plugin_api::hook_event('backend_login', $is_authenticated, NULL);
    if ($is_authenticated) {
        return true;
    }
    if ($debug) {
        fwrite($fp, date('Y-m-d H:i') . ' - Login username check:' . $username . "\n");
    }
    if ($username != '') {
        if ($use_external) {
            serendipity_plugin_api::hook_event('backend_auth', $is_hashed, array('username' => $username, 'password' => $password));
        }
        $query = "SELECT DISTINCT\n                    email, password, realname, authorid, userlevel, right_publish, hashtype\n                  FROM\n                    {$serendipity['dbPrefix']}authors\n                  WHERE\n                    username   = '******'";
        if ($debug) {
            fwrite($fp, date('Y-m-d H:i') . ' - Login check (' . serialize($is_hashed) . ', ' . $_SESSION['serendipityPassword'] . '):' . $query . "\n");
        }
        $rows =& serendipity_db_query($query, false, 'assoc');
        if (is_array($rows)) {
            foreach ($rows as $row) {
                if ($is_valid_user) {
                    continue;
                }
                $is_valid_user = false;
                // Old MD5 hashing routine. Will convert user.
                if (empty($row['hashtype']) || $row['hashtype'] == 0) {
                    if (isset($serendipity['hashkey']) && time() - $serendipity['hashkey'] >= 15768000) {
                        die('You can no longer login with an old-style MD5 hash to prevent MD5-Hostage abuse. 
                             Please ask the Administrator to set you a new password.');
                    }
                    if ($is_hashed === false && (string) $row['password'] === (string) md5($password) || $is_hashed !== false && (string) $row['password'] === (string) $password) {
                        serendipity_db_query("UPDATE {$serendipity['dbPrefix']}authors\n                                                 SET password = '******',\n                                                     hashtype = 1\n                                               WHERE authorid = '" . $row['authorid'] . "'");
                        if ($debug) {
                            fwrite($fp, date('Y-m-d H:i') . ' - Migrated user:'******'username'] . "\n");
                        }
                        $is_valid_user = true;
                    } else {
                        continue;
                    }
                } else {
                    if ($is_hashed === false && (string) $row['password'] === (string) serendipity_hash($password) || $is_hashed !== false && (string) $row['password'] === (string) $password) {
                        $is_valid_user = true;
                        if ($debug) {
                            fwrite($fp, date('Y-m-d H:i') . ' - Validated ' . $row['password'] . ' == ' . ($is_hashed === false ? 'unhash:' . serendipity_hash($password) : 'hash:' . $password) . "\n");
                        }
                    } else {
                        if ($debug) {
                            fwrite($fp, date('Y-m-d H:i') . ' - INValidated ' . $row['password'] . ' == ' . ($is_hashed === false ? 'unhash:' . serendipity_hash($password) : 'hash:' . $password) . "\n");
                        }
                        continue;
                    }
                }
                // This code is only reached, if the password before is valid.
                if ($is_valid_user) {
                    if ($debug) {
                        fwrite($fp, date('Y-m-d H:i') . ' [sid:' . session_id() . '] - Success.' . "\n");
                    }
                    serendipity_setCookie('old_session', session_id(), false);
                    if (!$is_hashed) {
                        serendipity_setAuthorToken();
                        $_SESSION['serendipityPassword'] = $serendipity['serendipityPassword'] = $password;
                    }
                    $_SESSION['serendipityUser'] = $serendipity['serendipityUser'] = $username;
                    $_SESSION['serendipityRealname'] = $serendipity['serendipityRealname'] = $row['realname'];
                    $_SESSION['serendipityEmail'] = $serendipity['serendipityEmail'] = $row['email'];
                    $_SESSION['serendipityAuthorid'] = $serendipity['authorid'] = $row['authorid'];
                    $_SESSION['serendipityUserlevel'] = $serendipity['serendipityUserlevel'] = $row['userlevel'];
                    $_SESSION['serendipityAuthedUser'] = $serendipity['serendipityAuthedUser'] = true;
                    $_SESSION['serendipityRightPublish'] = $serendipity['serendipityRightPublish'] = $row['right_publish'];
                    $_SESSION['serendipityHashType'] = $serendipity['serendipityHashType'] = $row['hashtype'];
                    serendipity_load_configuration($serendipity['authorid']);
                    serendipity_setCookie('userDefLang', $serendipity['lang'], false);
                    return true;
                }
            }
        }
        // Only reached, when proper login did not yet return true.
        if ($debug) {
            fwrite($fp, date('Y-m-d H:i') . ' - FAIL.' . "\n");
        }
        $_SESSION['serendipityAuthedUser'] = false;
        serendipity_session_destroy();
    }
    if ($debug) {
        fwrite($fp, date('Y-m-d H:i') . ' [sid:' . session_id() . '] - Uninit' . "\n");
        fclose($fp);
    }
    return false;
}