if ($_REQUEST['q'] == 'submitlogin') {
    if (!empty($_POST['username']) && !empty($_POST['password'])) {
        $totp = empty($_POST["totp"]) ? false : $_POST["totp"];
        $res = $user->lookupUser($_POST['username'], $_POST['password'], true, $totp);
        if ($res[0] === false && $res["totp"] === true) {
            # User has two factor authentication. Prompt!
            $totpclass = $res["error"] === false ? "bg-success" : "bg-danger";
            $is_encrypted = empty($res["encrypted_hash"]) || empty($res["encrypted_secret"]);
            $hash = $is_encrypted ? $_COOKIE[$cookieauth] : $res["encrypted_hash"];
            $secret = $is_encrypted ? $_COOKIE[$cookiekey] : $res["encrypted_secret"];
            $current_ip = $_SERVER['REMOTE_ADDR'];
            $ipArray = explode(".", $current_ip);
            array_pop($ipArray);
            $ipTop = implode(".", $ipArray);
            $current_ip = $ipTop;
            $totp_buffer = "<section id='totp_prompt' class='row'>\n  <div class='{$totp_class} alert alert-danger col-xs-12 col-md-6 force-center' id='totp_message'>" . $res["human_error"] . "</div>\n  <form id='totp_submit' onsubmit='event.preventDefault();' class='form-horizontal clearfix col-xs-12'>\n    <fieldset>\n      <legend>Two-Factor Authentication</legend>\n      <input type='number' id='totp_code' name='totp_code' placeholder='Code' pattern='[0-9]{6}' size='6' maxlength='6' required/>\n      <input type='hidden' id='username' name='username' value='" . $_POST['username'] . "'/>\n      <input type='hidden' id='password' name='password' value='" . $res["encrypted_password"] . "'  class='password-input'/>\n      <input type='hidden' id='secret' name='secret' value='" . $secret . "'/>\n      <input type='hidden' id='hash' name='hash' value='" . $hash . "'/>\n      <input type='hidden' id='remote' name='remote' value='" . $current_ip . "'/>\n      <input type='hidden' id='encrypted' name='encrypted' value='" . $user->strbool($is_encrypted) . "'/>\n      <br/>\n      <br/>\n      <button id='verify_totp_button' class='totpbutton btn btn-primary'>Verify</button>\n    </fieldset>\n    <p><small><a href='#' id='alternate_verification_prompt'>I can't use my app</a></small></p>\n  </form>\n</section>";
            $login_output .= $totp_buffer;
        } else {
            if ($res[0] !== false) {
                // Successful login
                $userdata = $res[1];
                $id = $userdata['id'];
                $name_block = $userdata['name'];
                $xml->setXml($name_block);
                echo "<!-- Name block: " . $name_block . " -->";
                # Be sure we get the name from the actual userdata
                $full_name = $xml->getTagContents("<name>");
                $first_name = $xml->getTagContents("<fname>");
                $display_name = $xml->getTagContents("<dname>");
                # Account for possible differnt modes of saving
                if (empty($first_name)) {