function registerApp($appInformation)
{
    /***
     *
     *
     * @param bool new_user flag to create a new user
     *
     * These keys are for all new device registrations, including new
     * user creation
     * @key email username
     * @key string password a URL-encoded password
     * @key phone_verify (when asked)
     * @key string key the encryption key
     *
     * These keys are only for new user creation
     * @key string first_name
     * @key string last_name
     * @key int phone
     * @key string handle the display username
     ***/
    $username = $appInformation['username'];
    $device = $appInformation['device'];
    $newUser = boolstr($appInformation['new_user']);
    $return_data = array();
    $validuser_data = array();
    $u = new UserFunctions();
    $password = urldecode($appInformation['password']);
    $encryption_key = $appInformation['key'];
    if (isNull($password) || isNull($username) || isNull($device) || isNull($encryption_key)) {
        return array('status' => false, 'error' => 'Required parameters missing', 'have_username' => !isNull($username), 'have_password' => !isNull($password), 'have_device' => !isNull($device), 'have_encryption_key' => !isNull($encryption_key));
    }
    if ($newUser) {
        # Start the new user creation process
        # The application should have verified password correctness
        $name = array($appInformation['first_name'], $appInformation['last_name']);
        $handle = $appInformation['handle'];
        $phone = $appInformation['phone'];
        if (isNull($appInformation['first_name']) || isNull($appInformation['last_name']) || isNull($phone) || isNull($handle)) {
            return array('status' => false, 'error' => 'Required parameters missing', 'have_name' => !isNull($name), 'have_phone' => !isNull($phone), 'have_handle' => !isNull($handle));
        }
        $result = $u->createUser($username, $password, $name, $handle, $phone);
        if ($result['status'] != true) {
            if (empty($r['human_error'])) {
                $result['human_error'] = $result['error'];
                $result['app_error_code'] = 999;
            }
            return $result;
        }
        $return_data['dblink'] = $result['dblink'];
        $validuser_data['dblink'] = $result['dblink'];
        $validuser_data['secret'] = $result['raw_secret'];
        $validuser_data['hash'] = $result['raw_auth'];
    } else {
        # Verify the user
        # Set up equivalent variables to finish registering the app
        $totp = isset($appInformation['totp']) ? $appInformation['totp'] : false;
        $result = $u->lookupUser($username, $password, true, $totp);
        if ($result['status'] === false && $result['totp'] === true) {
            $u->sendTOTPText();
            return array('status' => false, 'human_error' => $result['human_error'], 'error' => $result['error'], 'app_error_code' => 109);
        }
        # Get the cookie tokens we'll use to validate in registerApp()
        $cookies = $u->createCookieTokens($result['data']);
        $return_data['dblink'] = $result['data']['dblink'];
        $validuser_data['dblink'] = $result['data']['dblink'];
        $validuser_data['secret'] = $cookies['raw_secret'];
        $validuser_data['hash'] = $cookies['raw_auth'];
    }
    # Get the data we need
    $phone_verify_code = $appInformation['phone_verify'];
    $r = $u->registerApp($validuser_data, $encryption_key, $device, $phone_verify_code);
    if ($r['status'] === false) {
        # Phone needs validation. Return the dblink and request
        # validation. Upon validation, re-ping this same target
        if ($r['app_error_code'] == 111) {
            return array_merge($r, array($return_data));
        }
        if (empty($r['human_error'])) {
            $r['human_error'] = $r['error'];
            $r['app_error_code'] = 999;
        }
        # $r["cookies"] = $cookies;
        # $r["lookup_data"] = $result;
        return $r;
    }
    $return_data['secret'] = $r['secret'];
    $return_data = array_merge(array('status' => true, 'message' => "Successful registration of device '{$device}'", 'details' => $r), $return_data);
    return $return_data;
}
function verifyTOTP($get)
{
    $code = $get['code'];
    $user = $get['user'];
    $password = urldecode($get['password']);
    $password = str_replace(' ', '+', $password);
    $secret = $get['secret'];
    $hash = $get['hash'];
    $remote = $get['remote'];
    $is_encrypted = boolstr($get['encrypted']);
    # If it's a good code, pass the cookies back
    $u = new UserFunctions($user);
    /* print_r("bob"."\n\n");
      $e=$u->encryptThis("sally","bob");
      print_r($e."\n\n");
      print_r($u->decryptThis("sally",$e)."\n\n");*/
    $r = $u->lookupUser($user, $password, false, $code);
    if ($r[0] === false) {
        $r['status'] = false;
        $r['human_error'] = $r['message'];
        return $r;
    }
    ## The user and code is valid!
    $return = array('status' => true);
    $userdata = $r[1];
    $cookie_result = $u->createCookieTokens(null, true, $remote);
    $return['cookies'] = $cookie_result;
    $return['string'] = json_encode($cookie_result['raw_cookie']);
    return $return;
}
}
$settings_blob = "<section id='account_settings' class='panel panel-default clearfix'><div class='panel-heading'><h2 class='panel-title'>Settings</h2></div><div class='panel-body'>" . $emailHtml . $alternateEmailHtml . "<ul id='settings_list'><li><a href='#' id='showAdvancedOptions' data-domain='{$domain}' data-user-tfa='" . $has2fa . "' role='button' class='btn btn-default'>More Options</a></li>" . $verifyphone_link . $random . "</ul></div></section>";
$login_output .= "<div id='login_block'>";
$alt_forms = "<div id='alt_logins'>\n<!-- OpenID, Google, Twitter, Facebook -->\n</div>";
$login_preamble = "\n\t    <h2 id='title'>User Login</h2>";
if ($_REQUEST['m'] == 'login_error') {
    $login_preamble .= "<div class='alert alert-warning'><button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'>&times;</span></button><p><strong>There was a problem setting your login credentials</strong>. Please try again.</p></div>";
}
$loginform = "<script src='bower_components/bootstrap/dist/js/bootstrap.min.js' type='text/javascript' charset='utf-8'></script>\n\t    <form id='login' method='post' action='?q=submitlogin' class='form-horizontal'>\n            <fieldset>\n              <legend>Login</legend>\n<div class='form-group col-sm-9 col-md-5'>\n\t      <label for='username' class='control-label'>\n\t\tEmail:\n\t      </label>\n\t      <input class='form-control' type='email' name='username' id='username' placeholder='*****@*****.**' autofocus='autofocus' required='required'/>\n\t      </div>\n<div class='form-group col-sm-9 col-md-5 has-feedback'>\n\t      <label for='password' class='control-label'>\n\t\tPassword:\n\t      </label>\n\t      <input class='form-control' type='password' name='password' id='password' placeholder='Password' class='password-input' required='required'/> <span class='glyphicon glyphicon-question-sign do-password-reset form-control-feedback' style='pointer-events:all;' id='reset-password-icon' data-toggle='tooltip' title='Forgot Password?'></span>\n</div>\n</fieldset>";
$loginform_close = "\t      <br/>\n\t      <button id='login_button' class='btn btn-primary'>Login</button>\n\t    </form>{$alt_forms}<br/><p id='form_create_new_account'><small>Don't have an account yet? <a href='?q=create'>Create one</a>!</small></p>";
$big_login = $login_preamble . $loginform . $loginform_close;
$small_login = $loginform . $loginform_close;
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) {
      </div>
      <div>
        <h3>Show User Data</h3>
<?php 
try {
    if ($u->validateUser()) {
        ?>
        <form action='?t=show' method='post'>
          <p>User: <?php 
        echo $_COOKIE[$cookieuser];
        ?>
</p>
          <input type='password' name='pw' placeholder='password'/><br/>
          <input type='submit'/>
        </form>
        <?php 
    } else {
        echo "Please log in above to test this.";
    }
} catch (Exception $e) {
    echo "You've not logged in. Please log in above to test this.";
}
if ($_REQUEST['t'] == 'show') {
    echo displayDebug($u->lookupUser($_COOKIE[$cookieuser], $_POST['pw']));
}
?>
      </div>
    </article>
  </body>
</html>