/**
 * 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;
}
 function verify()
 {
     global $serendipity;
     $url = 'https://browserid.org/verify';
     $assert = $_POST['assert'];
     $params = 'assertion=' . $assert . '&audience=' . urlencode($serendipity['baseURL']);
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, $url);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($ch, CURLOPT_POST, 2);
     curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
     $result = curl_exec($ch);
     curl_close($ch);
     $response = json_decode($result);
     if (isset($response) && $response->status == 'okay') {
         $email = $response->email;
         $audience = $response->audience;
         if ($audience != $serendipity['baseURL']) {
             // The login has the wrong host!
             $response->status = 'errorhost';
             $response->message = "Internal error logging you in (wrong host: {$audience})";
             $_SESSION['serendipityAuthedUser'] = false;
             @session_destroy();
         } else {
             // host ist correct, check what we have with this email
             $password = md5($email);
             $query = "SELECT DISTINCT a.email, a.authorid, a.userlevel, a.right_publish, a.realname\r\n                     FROM\r\n                       {$serendipity['dbPrefix']}authors AS a\r\n                     WHERE\r\n                       a.email = '{$email}'";
             $row = serendipity_db_query($query, true, 'assoc');
             if (is_array($row)) {
                 serendipity_setCookie('old_session', session_id());
                 serendipity_setAuthorToken();
                 $_SESSION['serendipityUser'] = $serendipity['serendipityUser'] = $row['realname'];
                 $_SESSION['serendipityPassword'] = $serendipity['serendipityPassword'] = $password;
                 $_SESSION['serendipityEmail'] = $serendipity['serendipityEmail'] = $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'];
                 // Prevent session manupulation:
                 $_SESSION['serendipityBrowserID'] = $this->get_install_token();
                 serendipity_load_configuration($serendipity['authorid']);
             } else {
                 // No user found for that email!
                 $response->status = 's9yunknown';
                 $response->message = "Sorry, we don't have a user for {$email}";
                 $_SESSION['serendipityAuthedUser'] = false;
                 @session_destroy();
             }
         }
         $result = json_encode($response);
     }
     echo $result;
 }
 static function authenticate_openid($getData, $store_path, $returnData = false)
 {
     global $serendipity;
     $trust_root = $serendipity['baseURL'] . 'serendipity_admin.php';
     $path_extra = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'PHP-openid';
     $path = ini_get('include_path');
     $path = $path_extra . PATH_SEPARATOR . $path;
     ini_set('include_path', $path);
     require_once "Auth/OpenID/Consumer.php";
     require_once "Auth/OpenID/FileStore.php";
     require_once "Auth/OpenID/SReg.php";
     require_once "Auth/OpenID/PAPE.php";
     $store = new Auth_OpenID_FileStore($store_path);
     $consumer = new Auth_OpenID_Consumer($store);
     $response = $consumer->complete($trust_root);
     //, $getData);
     if ($response->status == Auth_OpenID_CANCEL) {
         $success = 'Verification cancelled.';
     } else {
         if ($response->status == Auth_OpenID_FAILURE) {
             $success = "OpenID authentication failed: " . $response->message;
         } else {
             if ($response->status == Auth_OpenID_SUCCESS) {
                 // This means the authentication succeeded; extract the
                 // identity URL and Simple Registration data (if it was
                 // returned).
                 $openid = $response->getDisplayIdentifier();
                 $esc_identity = escape($openid);
                 $success = sprintf('You have successfully verified ' . '<a href="%s">%s</a> as your identity.', $esc_identity, $esc_identity);
                 if ($response->endpoint->canonicalID) {
                     $escaped_canonicalID = escape($response->endpoint->canonicalID);
                     $success .= '  (XRI CanonicalID: ' . $escaped_canonicalID . ') ';
                 }
                 $sreg_resp = Auth_OpenID_SRegResponse::fromSuccessResponse($response);
                 $sreg = $sreg_resp->contents();
                 if (@$sreg['email']) {
                     escape($sreg['email']);
                     $success .= "  You also returned '" . escape($sreg['email']) . "' as your email.";
                 }
                 if (@$sreg['nickname']) {
                     $success .= "  Your nickname is '" . escape($sreg['nickname']) . "'.";
                 }
                 if (@$sreg['fullname']) {
                     $success .= "  Your fullname is '" . escape($sreg['fullname']) . "'.";
                 }
             }
         }
     }
     if (!empty($openid)) {
         if ($returnData) {
             return array('realname' => $realname, 'email' => $email, 'openID' => $openid);
         }
         $password = md5($openid);
         $query = "SELECT DISTINCT a.email, a.authorid, a.userlevel, a.right_publish, a.realname\r\n                     FROM\r\n                       {$serendipity['dbPrefix']}authors AS a, {$serendipity['dbPrefix']}openid_authors AS oa\r\n                     WHERE\r\n                       oa.openid_url = '" . serendipity_db_escape_string($openid) . "' and \r\n                       oa.authorid = a.authorid";
         $row = serendipity_db_query($query, true, 'assoc');
         if (is_array($row)) {
             serendipity_setCookie('old_session', session_id());
             serendipity_setAuthorToken();
             $_SESSION['serendipityUser'] = $serendipity['serendipityUser'] = $row['realname'];
             $_SESSION['serendipityPassword'] = $serendipity['serendipityPassword'] = $password;
             $_SESSION['serendipityEmail'] = $serendipity['serendipityEmail'] = $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['serendipityRealname'] = $serendipity['serendipityRealname'] = $row['realname'];
             $_SESSION['serendipityOpenID'] = true;
             serendipity_load_configuration($serendipity['authorid']);
             return true;
         } else {
             $_SESSION['serendipityAuthedUser'] = false;
             @session_destroy();
         }
     }
     return false;
 }