function mountaccessories_run()
{
    global $session;
    $op = httpget('op');
    switch ($op) {
        case "editdefaultaccessories":
            page_header("Editing Mount Accessories");
            $accs = get_default_accs_list();
            output("Here we have the editing screen.  Follow the format you see already, seperating parameters from their values with '=>' and using ';;' to denote a new line.  Leave the last line without the ';;' and everything should be fine.`n`n");
            output("Here are the ID's of all your Mounts, which will come in handy:`n");
            $sql = "SELECT mountid, mountname FROM " . db_prefix("mounts");
            $result = db_query($sql);
            for ($i = 0; $i < db_num_rows($result); $i++) {
                $row = db_fetch_assoc($result);
                output("%s: %s`n", $row['mountid'], $row['mountname']);
            }
            output("`n`nDefault stuff which affects Mount Accessories in core:`n`ndisplayname - shown in stables`ngoldcost`ngemcost`nhidefromstables`nnewdaymsg`nturns`nbuffname`nbuffrounds`nbuffwearoffmsg`nbuffeffectmsg`nbuffnodmgmsg`nbuffeffectfailmsg`nbuffatkmod`nbuffdefmod`nbuffinvulnerable`nbuffregen`nbuffminioncount`nbuffminbadguydamage`nbuffmaxbadguydamage`nbuffmingoodguydamage`nbuffmaxgoodguydamage`nbufflifetap`nbuffdamageshield`nbuffbadguydmgmod`nbuffbadguyatkmod`nbuffbadguydefmod`n`nFormatting:`ndisplayname=>Sexy Accessory;;`ngoldcost=>500;;`nturns=>10`nNote the lack of ;; on the last line.`nHave fun!`n`n");
            rawoutput("<form action='runmodule.php?module=mountaccessories&op=savedefaultaccessories' method='POST'>");
            foreach ($accs as $acc => $details) {
                rawoutput($acc);
                rawoutput("<a href=\"runmodule.php?module=mountaccessories&op=deleteaccessory&acc={$acc}\">Delete</a>");
                addnav("", "runmodule.php?module=mountaccessories&op=deleteaccessory&acc=" . $acc);
                rawoutput("<br /><textarea name='{$acc}' cols='40' rows='12'>");
                $size = count($details);
                $i = 0;
                foreach ($details as $detail => $value) {
                    $textboxoutput = $detail . "=>" . $value;
                    $i++;
                    if ($i != $size) {
                        $textboxoutput .= ";;";
                    }
                    rawoutput($textboxoutput);
                }
                rawoutput("</textarea><br /><br />");
            }
            rawoutput("<input type='submit' class='button' value='" . translate_inline("Save") . "'");
            rawoutput("</form>");
            addnav("", "runmodule.php?module=mountaccessories&op=savedefaultaccessories");
            addnav("Create a new Mount Accessory", "runmodule.php?module=mountaccessories&op=newaccessory");
            addnav("Back to the Grotto", "superuser.php");
            break;
        case "savedefaultaccessories":
            page_header("Editing Mount Accessories");
            $postedaccs = httpallpost();
            function trim_value(&$value)
            {
                $value = trim($value);
            }
            foreach ($postedaccs as $acc => $details) {
                $acc = str_replace("_", " ", $acc);
                $acc = trim($acc);
                $detailsexploded = explode(";;", $details);
                foreach ($detailsexploded as $detail) {
                    $detailandvalue = explode("=>", $detail);
                    $size = count($detailandvalue);
                    for ($i = 0; $i < $size / 2; $i++) {
                        $detailandvalue[$i] = trim($detailandvalue[$i]);
                        $accsarray[$acc][$detailandvalue[$i]] = $detailandvalue[$i + $size / 2];
                    }
                }
            }
            debug("Is this a full, reconstructed Accessories array?");
            debug($accsarray);
            set_module_setting("accessories", serialize($accsarray), "mountaccessories");
            output("Accessories have been saved.");
            addnav("Back to the Grotto", "superuser.php");
            break;
        case "newaccessory":
            page_header("Add a new Mount Accessory");
            output("Now we're going to add a new Mount Accessory.  This has to be parsed so that it can be turned back into an array, so follow the format you'll see below, seperating parameters from their values with '=>' and using ';;' to denote a new line.  Insert an internal name or ID for the mount accessory in the first input box - probably better to keep this value URL-friendly, IE lower-case and no spaces.  Leave the last line without the ';;' and everything should be fine.`n`n");
            output("Here are the ID's of all your Mounts, which will come in handy:`n");
            $sql = "SELECT mountid, mountname FROM " . db_prefix("mounts");
            $result = db_query($sql);
            for ($i = 0; $i < db_num_rows($result); $i++) {
                $row = db_fetch_assoc($result);
                output("%s: %s`n", $row['mountid'], $row['mountname']);
            }
            output("`n`nDefault stuff which affects Mount Accessories in core:`n`ndisplayname - shown in stables`ngoldcost`ngemcost`nhidefromstables`nnewdaymsg`nturns`nbuffname`nbuffrounds`nbuffwearoffmsg`nbuffeffectmsg`nbuffnodmgmsg`nbuffeffectfailmsg`nbuffatkmod`nbuffdefmod`nbuffinvulnerable`nbuffregen`nbuffminioncount`nbuffminbadguydamage`nbuffmaxbadguydamage`nbuffmingoodguydamage`nbuffmaxgoodguydamage`nbufflifetap`nbuffdamageshield`nbuffbadguydmgmod`nbuffbadguyatkmod`nbuffbadguydefmod`n`nFormatting:`ndisplayname=>Sexy Accessory;;`ngoldcost=>500;;`nturns=>10`nNote the lack of ;; on the last line.`nHave fun!`n`n");
            rawoutput("<form action='runmodule.php?module=mountaccessories&op=savenewaccessory' method='POST'>");
            rawoutput("Internal name or ID:<input name='newaccname'>");
            rawoutput("<br /><textarea name='newacc' cols='40' rows='12'>mountid=>0;;</textarea><br /><br />");
            rawoutput("<input type='submit' class='button' value='" . translate_inline("Save") . "'");
            rawoutput("</form>");
            addnav("", "runmodule.php?module=mountaccessories&op=savenewaccessory");
            addnav("Back to the Grotto", "superuser.php");
            break;
        case "savenewaccessory":
            page_header("Editing Mount Accessories");
            $acc = httppost("newacc");
            $accname = httppost("newaccname");
            debug($acc);
            $acc = str_replace("_", " ", $acc);
            $acc = trim($acc);
            $detailsexploded = explode(";;", $acc);
            debug($detailsexploded);
            foreach ($detailsexploded as $detail) {
                $detailandvalue = explode("=>", $detail);
                $size = count($detailandvalue);
                for ($i = 0; $i < $size / 2; $i++) {
                    $detailandvalue[$i] = trim($detailandvalue[$i]);
                    $newacc[$detailandvalue[$i]] = $detailandvalue[$i + $size / 2];
                }
            }
            debug("Is this a full, reconstructed Accessory?");
            debug($accname);
            $allaccs = get_default_accs_list();
            $allaccs[$accname] = $newacc;
            debug("Is this the proper Accessories array?");
            debug($allaccs);
            set_module_setting("accessories", serialize($allaccs), "mountaccessories");
            output("The new accessory has been saved.");
            addnav("Back to the Grotto", "superuser.php");
            addnav("Create a new Mount Accessory", "runmodule.php?module=mountaccessories&op=newaccessory");
            addnav("Edit Mount Accessories", "runmodule.php?module=mountaccessories&op=editdefaultaccessories");
            break;
        case "deleteaccessory":
            page_header("Deleting a Mount Accessory");
            $acc = httpget("acc");
            $accsarray = get_default_accs_list();
            unset($accsarray[$acc]);
            set_module_setting("accessories", serialize($accsarray), "mountaccessories");
            output("Accessory Deleted.");
            addnav("Back to the Grotto", "superuser.php");
            addnav("Create a new Mount Accessory", "runmodule.php?module=mountaccessories&op=newaccessory");
            addnav("Edit Mount Accessories", "runmodule.php?module=mountaccessories&op=editdefaultaccessories");
            break;
        case "browse":
            page_header("Mount Accessories");
            output("Merick directs you to a rack of accessories for your current Mount.`n`n\"Now, I have to be warnin' yer,\" says Merick, \"I'm quite happy to give yer a trade-in on any beasties ye might buy from me, but I don't be takin' no returns on the accessories.  There's nae market in pre-owned add-ons, y'see.\"`n`nYou peruse the accessories on display.");
            output("Here are the accessories available for your Mount:`n`n");
            $stuffavailable = 0;
            $accs = get_mount_accs_list($session['user']['hashorse']);
            debug($accs);
            foreach ($accs as $acc => $details) {
                if (!get_player_acc($acc) && !$details['hidefromstables']) {
                    $stuffavailable++;
                    output("Accessory name: %s`nCost: %s Requisition, %s Cigarettes`n%s`n`n", $details['displayname'], $details['goldcost'], $details['gemcost'], $details['description']);
                    addnav(array("Buy %s", $details['displayname']), "runmodule.php?module=mountaccessories&op=buy&acc=" . $acc);
                }
            }
            if ($stuffavailable == 0) {
                output("There are no upgrades available for your Mount.  Feh.");
            }
            addnav("Return to the Stables", "stables.php");
            break;
        case "buy":
            page_header("Mount Accessories");
            $acc = httpget("acc");
            if (!mountaccessories_takemoney($acc)) {
                output("Merick shakes his head.  \"I dunno, you lot with yer bloody lack of a basic grasp on financial transactions...\"`n`nYou discover with a cringe of embarrassment that you don't actually have enough money to buy that accessory.");
            } else {
                give_accessory($acc);
                apply_accessory($acc);
                output("Merick takes your money, shows you a broad grin, and begins the process of equipping the accessory to your Mount.  Within a few minutes, his work is done, and your Mount is upgraded.");
            }
            addnav("Return to the Stables", "stables.php");
            break;
    }
    page_footer();
    return true;
}
function hunterslodge_avatar_run()
{
    require_once "lib/sanitize.php";
    require_once "lib/names.php";
    global $session;
    $op = httpget("op");
    $free = httpget("free");
    $context = httpget("context");
    switch ($context) {
        case "village":
            $backlink = "village.php";
            break;
        case "forest":
            $backlink = "forest.php";
            break;
        case "worldmap":
            $backlink = "runmodule.php?module=worldmapen&op=continue";
            break;
        case "lodge":
            $backlink = "runmodule.php?module=iitems_hunterslodge&op=start";
            break;
    }
    page_header("Choose your Avatar");
    switch ($op) {
        case "change":
            output("Want to change your Avatar?  No problem.  Upload your avatar via the box below.  Please note that NSFW images, stolen artwork or otherwise dodgy avatars will be erased without refund.  Upload files in .jpg or .png format.  Your limits are 100 pixels wide, 100 pixels tall, with a maximum filesize of 100k.  100px * 100px * 100k, simple!`n`n");
            output("Upload your avatar:`n");
            rawoutput("<form method='POST' enctype='multipart/form-data' name='upload' action='runmodule.php?module=hunterslodge_avatar&op=confirm&free={$free}&context={$context}'><input type='file' name='file'><br><br><input type='submit' class='button' name='Upload' value='Upload!'></form>");
            addnav("", "runmodule.php?module=hunterslodge_avatar&op=confirm&free={$free}&context={$context}");
            addnav("Cancel");
            addnav("Don't set an Avatar, just go back to where I came from", $backlink);
            break;
        case "confirm":
            if (httppost("Upload")) {
                $allowed_types = "(jpg|png)";
                debug(httpallpost());
                debug($_FILES);
                $file = $_FILES["file"];
                debug($file);
                $errors = array(0 => "File Received!", 1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini.", 2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.", 3 => "The uploaded file was only partially uploaded.", 4 => "No file was uploaded.", 6 => "Missing a temporary folder.");
                output_notl("`\$" . $errors[$error] . "`n");
                if (is_uploaded_file($file["tmp_name"])) {
                    if (preg_match("/\\." . $allowed_types . "\$/i", $file["name"])) {
                        if ($file["size"] <= 102400) {
                            $extension = substr($file['name'], strlen($file['name']) - 4, 4);
                            $loginname = str_replace(" ", "", $session['user']['login']);
                            $filename = "images/avatars/" . date("YmdHs") . $loginname . $extension;
                            if (move_uploaded_file($file["tmp_name"], $filename)) {
                                $pic_size = @getimagesize($filename);
                                // GD2 required here - else size always is recognized as 0
                                $pic_width = $pic_size[0];
                                $pic_height = $pic_size[1];
                                if ($pic_height <= 100 && $pic_width <= 100) {
                                    output("So, this is what you want to look like?  Click \"Set Avatar\" to confirm.`n`n");
                                    addnav("Confirm");
                                    addnav("Set Avatar", "runmodule.php?module=hunterslodge_avatar&op=set&free={$free}&context={$context}&avatar=" . rawurlencode($filename));
                                    $image = "<img align='left' src='" . $filename . "'>";
                                    rawoutput("<table><tr><td valign='top'>");
                                    $terms = appoencode(translate_inline("Your Avatar"));
                                    rawoutput("</td><td valign='top'>{$image}</td></tr><td></td><td>{$terms}</td></table>");
                                } else {
                                    output("That picture's too big!  The limit is 100 pixels by 100 pixels.`n`n");
                                }
                            } else {
                                output("The file could not be uploaded.`n`n");
                            }
                        } else {
                            output("You may only have a filesize up to 100 kilobytes!`n`n");
                        }
                    } else {
                        output("That file extension is not supported!`n`n");
                    }
                } else {
                    output("You did not specify a file to upload.`n`n");
                }
            }
            output("`0To try again with a different picture, use the form below.`n`n");
            rawoutput("<form method='POST' enctype='multipart/form-data' name='upload' action='runmodule.php?module=hunterslodge_avatar&op=confirm&free={$free}&context={$context}'><input type='file' name='file'><br><br><input type='submit' class='button' name='Upload' value='Upload!'></form>");
            addnav("", "runmodule.php?module=hunterslodge_avatar&op=confirm&free={$free}&context={$context}");
            addnav("Cancel");
            addnav("Don't set an Avatar, just go back to where I came from", $backlink);
            break;
        case "set":
            $av = httpget("avatar");
            set_module_pref("avatar", $av);
            output("Your Avatar has been changed!`n`n");
            if (!$free) {
                $id = has_item("hunterslodge_avatar");
                delete_item($id);
            }
            addnav("Return");
            addnav("Go back to where I came from", $backlink);
            break;
    }
    page_footer();
}
                 }
             }
             reset($modules);
             while (list($key, $module) = each($modules)) {
                 $content = wizard_scanfile("modules/{$module}.php");
                 wizard_insertfile($content, $languageschema);
             }
         }
     }
     if (get_module_setting("translationdelete")) {
         if (httpget('op') == "uninstall") {
             $get = rawurlencode(serialize(httpallget()));
             require_once "./modules/translationwizard/deleteuninstalled.php";
         } elseif (httpget('op') == "mass" && httppost("uninstall")) {
             $get = rawurlencode(serialize(httpallget()));
             $post = rawurlencode(serialize(httpallpost()));
             require_once "./modules/translationwizard/deleteuninstalled.php";
         }
     }
     break;
     /*case "footer-modules":
     		output_notl("Get:");
     		debug(httpallget());
     	break;
     	*/
 /*case "footer-modules":
 		output_notl("Get:");
 		debug(httpallget());
 	break;
 	*/
 default:
function addcommentary()
{
    global $session, $emptypost, $afk, $dni;
    $section = httppost('section');
    $talkline = httppost('talkline');
    $schema = httppost('schema');
    $comment = trim(httppost('insertcommentary'));
    $counter = httppost('counter');
    $remove = URLDecode(httpget('removecomment'));
    $restore = URLDecode(httpget('restorecomment'));
    //debug(httpallpost());
    if (httpget("bulkdelete")) {
        $everything = httpallpost();
        foreach ($everything as $key => $val) {
            if (substr($key, 0, 14) == "deletecomment_") {
                $del = str_replace("deletecomment_", "", $key);
                removecommentary($del, "Mass deletion by " . $session['user']['name'], $session['user']['acctid']);
            }
        }
    }
    if (!$comment) {
        return false;
    }
    if ($session['user']['chatloc'] == "DNI") {
        $dni = true;
    }
    if ($comment == strtoupper($comment)) {
        //this is an all-uppercase entry.  Do not add this comment to the database; instead, check it for built-in stuff like AFK and GREM, then run it through the commentarycommand hook
        if ($comment == "AFK" || $comment == "BRB") {
            $session['user']['chatloc'] = "AFK";
            $afk = true;
            output("`0`n`c`bYou are Away From the Keyboard until you load another page.`b`c`n");
            return false;
        }
        if ($comment == "DNI") {
            if ($session['user']['chatloc'] == "DNI") {
                $session['user']['chatloc'] = $section;
                $dni = false;
                output("`0`n`c`bYou are no longer in Do Not Interrupt status.`b`c`n");
            } else {
                $session['user']['chatloc'] = "DNI";
                $dni = true;
                output("`0`n`c`bYou are in Do Not Interrupt status.  Type DNI again to leave.`b`nDNI status is used for whenever you're doing or saying something that means other players shouldn't try to interact with you.  For example, when two or more characters are chatting just outside of the main group of characters, and other characters shouldn't be able to hear them.`c`n");
            }
            return false;
        }
        if ($comment == "GREM") {
            //handle deleting the player's last comment
            $sql = "SELECT * FROM " . db_prefix("commentary") . " WHERE author='" . $session['user']['acctid'] . "' ORDER BY commentid DESC LIMIT 1";
            $result = db_query($sql);
            while ($row = db_fetch_assoc($result)) {
                $now = time();
                $then = strtotime($row['postdate']);
                $ago = $now - $then;
                if ($ago < 120) {
                    removecommentary($row['commentid'], "Typo Gremlin", $session['user']['acctid']);
                    output("`0`n`c`bA nearby Typo Gremlin notices the peculiar tastiness of your previous comment.  Within moments, a small horde of them have descended upon your words, and consumed them.`b`c`n");
                } else {
                    output("`0`n`c`bThe Typo Gremlins turn up their nose at your latest comment - it's just too old.  They have no taste for stale words.`b`c`n");
                }
            }
            return false;
        }
        $hookcommand = array('command' => $comment, 'section' => $section);
        $returnedhook = modulehook("commentarycommand", $hookcommand);
        if (!$returnedhook['processed']) {
            debug($returnedhook);
            output("`c`b`JCommand Not Recognized`b`0`nWhen you type in ALL CAPS, the game doesn't think you're talking to other players; it thinks you're trying to perform an action within the game.  For example, typing `#GREM`0 will remove the last comment you posted, as long as you posted it less than two minutes ago.  Typing `#AFK`0 or `#BRB`0 will turn your online status bar grey, so that people know you're `#A`0way `#F`0rom the `#K`0eyboard (or, if you prefer, that you'll `#B`0e `#R`0ight `#B`0ack).  Typing `#DNI`0 will let other players know that you're busy talking to one particular player - maybe somewhere off-camera - and that you don't want to be interrupted right now.`nSome areas have special hidden commands or other easter eggs that you can hunt for.  This time around, you didn't trigger anything special.`c`0`n");
        }
        return false;
    }
    if ($remove > 0) {
        removecommentary($remove, "Moderated by " . $session['user']['name'], $session['user']['acctid']);
    }
    if ($restore > 0) {
        restorecommentary($restore, "Restored by " . $session['user']['name'], $session['user']['acctid']);
    }
    if (array_key_exists('commentcounter', $session) && $session['commentcounter'] == $counter) {
        if ($section || $talkline || $comment) {
            $tcom = color_sanitize($comment);
            if ($tcom == "" || $tcom == ":" || $tcom == "::" || $tcom == "/me") {
                $emptypost = 1;
            } else {
                injectcommentary($section, $talkline, $comment);
            }
        }
    }
}
function textme_dohook($hook, $args)
{
    if (httpget('op') == 'send') {
        require_once 'lib/names.php';
        textme_sendmail(httpallpost(), get_player_basename());
    }
    return $args;
}
function addcommentary()
{
    global $session, $emptypost;
    $info = httpallpost();
    unset($info['section']);
    unset($info['talkline']);
    unset($info['schema']);
    unset($info['insertcommentary']);
    unset($info['counter']);
    unset($info['removecomment']);
    $section = httppost('section');
    $talkline = httppost('talkline');
    $schema = httppost('schema');
    $comment = trim(httppost('insertcommentary'));
    $counter = httppost('counter');
    $remove = URLDecode(httpget('removecomment'));
    if ($remove > 0) {
        $return = '/' . httpget('returnpath');
        $section = httpget('section');
        $sql = "SELECT " . db_prefix("commentary") . ".*," . db_prefix("accounts") . ".name," . db_prefix("accounts") . ".acctid, " . db_prefix("accounts") . ".clanrank," . db_prefix("clans") . ".clanshort FROM " . db_prefix("commentary") . " INNER JOIN " . db_prefix("accounts") . " ON " . db_prefix("accounts") . ".acctid = " . db_prefix("commentary") . ".author LEFT JOIN " . db_prefix("clans") . " ON " . db_prefix("clans") . ".clanid=" . db_prefix("accounts") . ".clanid WHERE commentid={$remove}";
        $row = db_fetch_assoc(db_query($sql));
        $sql = "INSERT LOW_PRIORITY INTO " . db_prefix("moderatedcomments") . " (moderator,moddate,comment) VALUES ('{$session['user']['acctid']}','" . date("Y-m-d H:i:s") . "','" . addslashes(serialize($row)) . "')";
        db_query($sql);
        $sql = "DELETE FROM " . db_prefix("commentary") . " WHERE commentid='{$remove}';";
        db_query($sql);
        invalidatedatacache("comments-{$section}");
        // *** DRAGONBG.COM CORE PATCH START ***
        invalidatedatacache("comments-");
        // *** DRAGONBG.COM CORE PATCH END ***
        $session['user']['specialinc'] == '';
        //just to make sure he was not in a special
        $return = cmd_sanitize($return);
        $return = substr($return, strrpos($return, "/") + 1);
        if (strpos($return, "?") === false && strpos($return, "&") !== false) {
            $x = strpos($return, "&");
            $return = substr($return, 0, $x - 1) . "?" . substr($return, $x + 1);
        }
        debug($return);
        redirect($return);
    }
    if (array_key_exists('commentcounter', $session) && $session['commentcounter'] == $counter) {
        if ($section || $talkline || $comment) {
            $tcom = color_sanitize($comment);
            if ($tcom == "" || $tcom == ":" || $tcom == "::" || $tcom == "/me") {
                $emptypost = 1;
            } else {
                injectcommentary($section, $talkline, $comment, $schema);
            }
        }
    }
}
function changelog_dohook($hook, $args)
{
    switch ($hook) {
        case 'header-modules':
            $module = httppost('module') ?: httpget('module');
            $op = httpget('op');
            if ($module != '') {
                if (substr($op, -1) == 'e') {
                    $op = substr($op, 0, -1);
                } else {
                    if ($op == 'mass') {
                        $method = array_keys(httpallpost())[1];
                        if (substr($method, -1) == 'e') {
                            $method = substr($method, 0, -1);
                        }
                        $op = "mass {$method}";
                        $plural = 's';
                    }
                }
                require_once 'lib/gamelog.php';
                if (is_array($module)) {
                    $lastModule = array_pop($module);
                    $module = implode(', ', $module);
                    $module .= ",`@ and `^{$lastModule}";
                }
                gamelog(sprintf_translate('`Q%sed`@ the `^%s`@ module%s.', $op, $module, $plural), get_module_setting('category'));
            }
            break;
        case 'village':
            if (get_module_setting('infonav')) {
                addnav($args['infonav']);
                addnav('View Changelog', 'runmodule.php?module=changelog&ret=village');
            }
            break;
        case 'header-about':
            addnav('About LoGD');
            addnav('View Changelog', 'runmodule.php?module=changelog&ret=about');
            break;
        case 'newday-runonce':
            $gamelog = db_prefix('gamelog');
            $date = date('Y-m-d H:i:s', strtotime('now'));
            $category = get_module_setting('category');
            db_query("UPDATE {$gamelog} SET date = '{$date}' WHERE category = '{$category}'");
            break;
    }
    return $args;
}
                $textboxoutput .= ";;";
            }
            rawoutput($textboxoutput);
        }
        rawoutput("</textarea><br /><br />");
    }
    rawoutput("<input type='submit' class='button' value='" . translate_inline("Save") . "'");
    rawoutput("</form>");
    addnav("", "runmodule.php?module=staminasystem&op=editplayer&op2=save&id=" . $id . "");
    addnav("Return");
    addnav("Search again", "runmodule.php?module=staminasystem&op=editplayer");
    addnav("Return", "runmodule.php?module=staminasystem&op=superuser");
}
if ($op2 == "save") {
    $userid = httpget('id');
    $postedactions = httpallpost();
    function trim_value(&$value)
    {
        $value = trim($value);
    }
    foreach ($postedactions as $action => $details) {
        $action = str_replace("_", " ", $action);
        $action = trim($action);
        $detailsexploded = explode(";;", $details);
        foreach ($detailsexploded as $detail) {
            $detailandvalue = explode("=>", $detail);
            $size = count($detailandvalue);
            for ($i = 0; $i < $size / 2; $i++) {
                $detailandvalue[$i] = trim($detailandvalue[$i]);
                $actionsarray[$action][$detailandvalue[$i]] = $detailandvalue[$i + $size / 2];
            }
function improbablehousing_secretrooms_run()
{
    global $session;
    page_header("Secret Rooms");
    require_once "modules/improbablehousing/lib/lib.php";
    $hid = httpget("hid");
    $rid = httpget("rid");
    $house = improbablehousing_gethousedata($hid);
    $cost = get_module_setting("cost");
    $roomname = $house['data']['rooms'][$rid]['name'];
    switch (httpget('op')) {
        case "start":
            output("`5Secret Rooms`0 are rooms that exist in your Dwelling and operate just like normal rooms - except that there's no nav link for players to reach them by.  Instead, a player will be instantly transported from the current room to your `5Secret Room`0 by typing a key phrase into their chat box (the phrase itself won't show up in the chat log - it'd be pretty hard to keep it secret otherwise!).`n`nYou as the secret room owner can assign as many key phrases per room as you would like.  For example, you might assign the key phrases \"`#EXAMINE BOOKCASE`0\", \"`&LOOK BEHIND BOOKCASE`0\", and perhaps a few others, to have the player discover a traditional secret passage.  Or, you could assign the phrase \"`#OPEN SESAME`0\" to reveal a cleverly-hidden door.`n`nIn all other aspects, `5Secret Rooms`0 operate exactly like normal rooms - they can be extended, decorated, and can have more rooms branch from them (including other `5Secret Rooms`0).  They can even be locked just like normal rooms - if a player tries to enter a locked `5Secret Room`0 to which he or she doesn't have access, they'll get bounced straight back as usual.`n`n`5Secret Rooms`0 are a donator-only feature, cost %s Donator Points per room, and come pre-assembled.  No construction materials are necessary; `5Secret Rooms`0 arrive ready to decorate.`n`nYou're currently building a `5Secret Room`0 that can be accessed from the room called \"`b%s`b`0\" - are you sure that this is the room you want to build from?`n`n", $cost, $roomname);
            addnav("Want a Secret Room?");
            $donationavailable = $session['user']['donation'] - $session['user']['donationspent'];
            if ($donationavailable >= $cost) {
                addnav(array("Yes, build a Secret Room branching from this one (%s Points)", $cost), "runmodule.php?module=improbablehousing_secretrooms&op=buy&hid={$hid}&rid={$rid}");
            } else {
                addnav("Ah, but you don't have enough points!", "");
            }
            addnav("Cancel and return to the last room", "runmodule.php?module=improbablehousing&op=interior&hid={$hid}&rid={$rid}");
            break;
        case "buy":
            $session['user']['donationspent'] += $cost;
            output("You've bought a `5Secret Room!`0  To enter it, just type \"`#SECRET`0\" into the chat box in the room called \"%s\" (you can delete this trigger phrase and set up some new ones once you're inside the secret room).`n`nHave fun!`n`n", $roomname);
            $newroom = array("name" => "Secret Room", "size" => 1, "enterfrom" => $rid, "desc" => "You're standing in a small, undecorated secret room.", "sleepslots" => array(), "hidden" => 1, "triggers" => array(0 => "SECRET"), "lockreject" => "You do all the right things, but you still can't get in.  Maybe the room is locked?");
            $house['data']['rooms'][] = $newroom;
            improbablehousing_sethousedata($house);
            addnav("Let's get busy!");
            addnav("Back to your Dwelling", "runmodule.php?module=improbablehousing&op=interior&hid={$hid}&rid={$rid}");
            break;
        case "manage":
            if (httpget("save")) {
                $posted = httpallpost();
                $nphrases = array();
                foreach ($posted as $phrase) {
                    $nphrase = stripslashes($phrase);
                    if ($nphrase != "") {
                        $nphrases[] = strtoupper($nphrase);
                    }
                }
                $house['data']['rooms'][$rid]['triggers'] = $nphrases;
                improbablehousing_sethousedata($house);
            }
            $phrases = $house['data']['rooms'][$rid]['triggers'];
            output("You're currently managing the secret room called \"`b%s`b.`0\"  You can set this room's trigger phrases and lock rejection notices below.`n`nRemember, the text that the player inputs must be an exact match.  There's no extra charge for adding more trigger phrases, so more is often better.`n`nTo erase a trigger phrase, just blank the box.`n`n", $roomname);
            rawoutput("<form action='runmodule.php?module=improbablehousing_secretrooms&op=manage&save=true&hid={$hid}&rid={$rid}' method='POST'>");
            rawoutput("<table border='0' cellpadding='2' cellspacing='2'>");
            $phrasecount = 0;
            foreach ($phrases as $phrase) {
                $class = $phrasecount % 2 ? "trlight" : "trdark";
                $phrasecount++;
                rawoutput("<tr class='{$class}'><td><input name=\"phrase{$phrasecount}\" value=\"{$phrase}\"></td></tr>");
            }
            rawoutput("</table>");
            output("`nNow add up to ten new phrases.  Boxes left blank will be ignored.  To add more, just save and you'll get another ten slots.");
            $extracount = $phrasecount + 10;
            rawoutput("<table border='0' cellpadding='2' cellspacing='2'>");
            for ($i = $phrasecount; $i <= $extracount; $i++) {
                $class = $phrasecount % 2 ? "trlight" : "trdark";
                $phrasecount++;
                rawoutput("<tr class='{$class}'><td><input name=\"phrase{$phrasecount}\" value=''></td></tr>");
            }
            rawoutput("</table>");
            rawoutput("<input type='submit' class='button' value='" . translate_inline("Save") . "'");
            rawoutput("</form>");
            addnav("", "runmodule.php?module=improbablehousing_secretrooms&op=manage&save=true&hid={$hid}&rid={$rid}");
            addnav("Return");
            addnav("Back to the Dwelling", "runmodule.php?module=improbablehousing&op=interior&hid={$hid}&rid={$rid}");
            break;
    }
    page_footer();
    return true;
}
function iitems_superuser()
{
    global $session;
    $superop = httpget('superop');
    switch ($superop) {
        case "export":
            page_header("Export an IItem");
            $itemid = httpget("exportitemid");
            $sql = "SELECT id,localname,data FROM " . db_prefix("iitems") . " WHERE localname = '{$itemid}'";
            $result = db_query_cached($sql, "iitems-" . $localname);
            $row = db_fetch_assoc($result);
            $exportcode = $localname . "|BREAK|" . $data;
            rawoutput("<textarea>");
            rawoutput($exportcode);
            rawoutput("</textarea>");
            addnav("Back to the IItem Editor", "runmodule.php?module=iitems&op=superuser&superop=start");
            break;
        case "import":
            page_header("Import an IItem");
            $itemid = httpget("exportitemid");
            $sql = "SELECT id,localname,data FROM " . db_prefix("iitems") . " WHERE localname = '{$itemid}'";
            $result = db_query_cached($sql, "iitems-" . $localname);
            $row = db_fetch_assoc($result);
            $exportcode = $localname . "|BREAK|" . $data;
            rawoutput("<textarea>");
            rawoutput($exportcode);
            rawoutput("</textarea>");
            addnav("Back to the IItem Editor", "runmodule.php?module=iitems&op=superuser&superop=start");
            break;
        case "start":
            page_header("IItems");
            iitems_superuser_item_menu();
            addnav("Return to the Grotto", "superuser.php");
            addnav("Create a new Item", "runmodule.php?module=iitems&op=superuser&superop=create");
            break;
        case "give":
            page_header("Giving IItem");
            output("Giving the item.`n`n");
            $id = httpget('id');
            require_once "modules/iitems/lib/lib.php";
            $success = iitems_give_item($id);
            if (!$success) {
                output("Item could not be given.`n`n");
            } else {
                output("Item given successfully.`n`n");
            }
            iitems_superuser_item_menu();
            addnav("Back to the Item Editor", "runmodule.php?module=iitems&op=superuser&superop=start");
            break;
        case "edit":
            page_header("Editing Item");
            $id = httpget('id');
            if (httpget('subop') == "save") {
                $posted = httpallpost();
                debug($posted);
                $sarray = array();
                $prearray = array();
                foreach ($posted as $ele => $val) {
                    if (substr($ele, 0, 3) == "ele") {
                        $num = substr($ele, 3, 5);
                        // $sarray[$val]=$val;
                        $prearray[$num]['ele'] = $val;
                    } else {
                        if (substr($ele, 0, 3) == "val") {
                            $num = substr($ele, 3, 5);
                            $prearray[$num]['val'] = $val;
                        }
                    }
                }
                foreach ($prearray as $num => $vals) {
                    if ($vals['ele'] != "") {
                        $sarray[$vals['ele']] = $vals['val'];
                    }
                }
                debug($sarray);
                $data = serialize($sarray);
                $data = addslashes($data);
                $sql = "UPDATE " . db_prefix("iitems") . " SET data = '{$data}' WHERE id = {$id}";
                db_query($sql);
                output("Array has been reserialised and saved.");
            }
            $sql = "SELECT id,localname,data FROM " . db_prefix("iitems") . " WHERE id = {$id}";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            debug($row['data']);
            $sarray = unserialize($row['data']);
            if (!is_array($sarray)) {
                $sarray = array();
            }
            output("`bEntries handled by IItems core:`b`n");
            output("`bverbosename`b (REQUIRED): A verbose name for the item that is shown to the player.`n");
            output("`btype`b (REQUIRED): normal, special or inventory.  A 'normal' item is a generic consumable item such as a grenade.  If a player has ten grenades, they will all do the same thing in the same way.  'special' items are disposable items that can have different stats assigned to them - a player might have five throwing knives, but some of them will be rustier than others.`nWhen giving a 'normal' item, the 'quantity' parameter in the player's Inventory array is increased by one for that item.  When giving a 'special' item, if an item of the same verbose name is present in the Inventory array, a fresh one is added with the name 'Verbose Name (x)', where 'x' is an incrementing number.`nWhere an item is given the 'inventory' type `iby an advanced admin`i, adding the item will give the player another Inventory in which to store things.  Use this for things like backpacks, bandoliers, saddle bags, quivers and so forth.`n");
            output("`bimage`b: Specify an image to use in the Inventory here.  All images are stored in images/iitems, so just give the filename.  Example: medkit.png (references yoursite.com/images/iitems/medkit.png)`n");
            output("`bdestroyafteruse`b: When set, the item will be destroyed after a single use.`n");
            output("`bdkpersist`b: When set, this item will be preserved in the player's Inventory across Dragon Kills.`n");
            output("`bdescription`b: Description of the item shown in the player's Inventory.`n");
            output("`busetext`b: Text shown when item is used.  Can be modified by a module when using an item if necessary.`n");
            output("`bdestroytext`b: Text shown when item is destroyed.`n");
            output("`buseatnewday`b: When true, iitem is automatically used at newday.  Useful for things that provide a buff each day.`n");
            output("`bcannotdiscard`b: When true, item cannot be discarded by the player.`n");
            output("`binventorylocation`b: Will place the item in the inventory specified (eg main (for bandolier), fight (for backpack)) upon giving the item.  When combined with an item type set to \"inventory,\" this determines the type of inventory (eg main or fight).  Setting this to \"mount\" has special handling.`n");
            output("`bvillagehooknav`b: When set, the item is usable from the player's Inventory link in the Village.`n");
            output("`bforesthooknav`b: When set, the item is usable from the player's Inventory link in the Forest.`n");
            output("`bworldnavhooknav`b: When set, the item is usable from the player's Inventory link on the World Map, if installed.`n");
            output("`bgoldcost`b: Cost in gold for whatever shop this item is available in.`n");
            output("`bgemcost`b: Cost in gems for whatever shop this item is available in.`n`n");
            output("`bHelp text supplied by other IItems support modules:`b`n");
            modulehook("iitems-superuser");
            output("`n`bInstructions:`b`nTo delete an entry, just blank the boxes.  You can use both single and double quotes in your values, but avoid doing so in your variable names.  Have fun!`n");
            rawoutput("<form action='runmodule.php?module=iitems&op=superuser&superop=edit&subop=save&id={$id}' method='POST'>");
            rawoutput("<table border='0' cellpadding='2' cellspacing='2'>");
            rawoutput("<tr><td>Variable Name</td><td>Value</td></tr>");
            $elementcount = 0;
            $valuecount = 0;
            foreach ($sarray as $element => $value) {
                $class = $elementcount % 2 ? "trlight" : "trdark";
                $elementcount++;
                $valuecount++;
                $element = stripslashes($element);
                $value = stripslashes($value);
                rawoutput("<tr class='{$class}'><td><input name=\"ele{$elementcount}\" value=\"{$element}\"></td><td><textarea class='input' name='val{$valuecount}' cols='20' rows='3'>{$value}</textarea></td></tr>");
            }
            rawoutput("</table>");
            output("`nNow add up to ten new parameters.  Parameters left blank will be ignored.  To add more, just save and you'll get another ten slots.");
            $extracount = $elementcount + 10;
            rawoutput("<table border='0' cellpadding='2' cellspacing='2'>");
            rawoutput("<tr><td>Variable Name</td><td>Value</td></tr>");
            for ($i = $elementcount; $i <= $extracount; $i++) {
                $class = $elementcount % 2 ? "trlight" : "trdark";
                $elementcount++;
                $valuecount++;
                rawoutput("<tr class='{$class}'><td><input name=\"ele{$elementcount}\" value=''></td><td><textarea class='input' name='val{$valuecount}' cols='20' rows='3'></textarea></td></tr>");
            }
            rawoutput("</table>");
            rawoutput("<input type='submit' class='button' value='" . translate_inline("Save") . "'");
            rawoutput("</form>");
            addnav("", "runmodule.php?module=iitems&op=superuser&superop=edit&subop=save&id={$id}");
            addnav("Item Editor Main Page", "runmodule.php?module=iitems&op=superuser&superop=start");
            addnav("Back to the Grotto", "superuser.php");
            break;
        case "create":
            page_header("Create a new Item");
            if (httpget('sub') == "insert") {
                $localname = httppost('localname');
                $sql = "INSERT INTO " . db_prefix("iitems") . " (localname,data) VALUES ('{$localname}','0')";
                db_query($sql);
                output("Item %s Created.`n`n", $localname);
                iitems_superuser_item_menu();
            } else {
                output("Enter a local ID for this item.  Keep it short, memorable, and absent of spaces or special characters.`n");
                rawoutput("<form action='runmodule.php?module=iitems&op=superuser&superop=create&sub=insert' method='POST'>");
                rawoutput("<input name='localname' value='localname'>");
                rawoutput("<input type='submit' class='button' value='" . translate_inline("Save") . "'");
                addnav("", "runmodule.php?module=iitems&op=superuser&superop=create&sub=insert");
            }
            addnav("Item Editor Main Page", "runmodule.php?module=iitems&op=superuser&superop=start");
            break;
        case "copy":
            page_header("Copying an Item");
            $original = httpget('id');
            output("This creates a copy of the previously-selected item, under a new itemid.`n`n");
            if (httpget('sub') == "copy") {
                $localname = httppost('localname');
                $sql = "SELECT data FROM " . db_prefix("iitems") . " WHERE id = {$original}";
                $result = db_query($sql);
                $row = db_fetch_assoc($result);
                $data = $row['data'];
                $data = addslashes($data);
                $sql = "INSERT INTO " . db_prefix("iitems") . " (localname,data) VALUES ('{$localname}','{$data}')";
                db_query($sql);
                output("Item %s Created.`n`n", $localname);
                iitems_superuser_item_menu();
            } else {
                output("Enter an itemid for this item.  Keep it short, memorable, and absent of spaces or special characters.`n");
                rawoutput("<form action='runmodule.php?module=iitems&op=superuser&superop=copy&sub=copy&id=" . $original . "' method='POST'>");
                rawoutput("<input name='localname' value='localname'>");
                rawoutput("<input type='submit' class='button' value='" . translate_inline("Save") . "'");
                addnav("", "runmodule.php?module=iitems&op=superuser&superop=copy&sub=copy&id=" . $original);
            }
            addnav("Item Editor Main Page", "runmodule.php?module=iitems&op=superuser&superop=start");
            break;
        case "delete":
            page_header("You sure about that?");
            $id = httpget('id');
            if (httpget('delete') == "delete") {
                $sql = "DELETE FROM " . db_prefix("iitems") . " WHERE id = '{$id}'";
                db_query($sql);
                output("The item in question has been fed to the Midgets.  I hope you really `iwere`i sure, 'cause it's gonna be a bastard to get it back.`n");
                addnav("Item Editor Main Page", "runmodule.php?module=iitems&op=superuser&superop=start");
                iitems_superuser_item_menu();
            } else {
                output("Now, are you really, really, `ireally`i sure you want to do that?  You're probably used to this sort of thing by now, but I'll still mention that there's no undo, and once an item is deleted it's `ideleted.`i  Like, forever.`n");
                addnav("Yes");
                addnav("Yes, I'm sure, get on with it", "runmodule.php?module=iitems&op=superuser&superop=delete&id=" . $id . "&delete=delete");
                addnav("No");
                addnav("No!  That's not what I wanted to do at all!", "runmodule.php?module=iitems&op=superuser&superop=start");
            }
            break;
    }
    page_footer();
    return true;
}
function jquerycommentary_run()
{
    global $_SERVER, $output, $session;
    require_once 'lib/commentary.php';
    $section = httpget('section');
    $commentary = db_prefix('commentary');
    $accounts = db_prefix('accounts');
    if (($commid = httpget('rmvcmmnt')) != "") {
        $prefix = db_prefix('commentary');
        check_su_access(SU_EDIT_COMMENTS);
        if ($session['user']['superuser'] & SU_EDIT_COMMENTS) {
            db_query("DELETE FROM {$prefix} WHERE commentid = '{$commid}'");
        }
        db_query("INSERT INTO {$commentary} (section, author, comment, postdate) VALUES ('blackhole', '{$session['user']['acctid']}', 'I f****d up', '" . date('Y-m-d H:i:s') . "')");
        invalidatedatacache("comments-{$section}");
        invalidatedatacache("comments-blackhole");
    }
    if (httpget('section') == get_module_pref('current_section') && httpget('section') != '') {
        //echo 'x';
        //var_dump(get_all_module_settings());
        $output = "";
        $_SERVER['REQUEST_URI'] = httpget('r');
        $session['counter'] = httpget('c');
        viewcommentary(get_module_pref('current_section'), get_module_setting('message'), get_module_setting('limit'), get_module_setting('talkline'));
        $output = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $output);
        $output = substr($output, 0, strpos($output, "<jquerycommentaryend>"));
        db_query("UPDATE accounts SET laston = '" . date('Y-m-d H:i:s') . "' WHERE acctid = '{$session['user']['acctid']}'");
        echo trim("{$output}");
        invalidatedatacache("comments-{$section}");
        /*$sql = db_query(
              "SELECT a.name, a.acctid
              FROM accounts AS a
              LEFT JOIN module_userprefs AS m
              ON m.userid = a.acctid
              LEFT JOIN module_userprefs AS u
              ON u.userid = m.userid
              WHERE m.modulename = 'jquerycommentary'
              AND m.setting = 'is_typing'
              AND m.value = '1'
              AND u.modulename = 'jquerycommentary'
              AND u.setting = 'current_section'
              and u.value = '" . get_module_pref('current_section') ."'"
          );
          $typing = [];
          while ($row = db_fetch_assoc($sql)) {
              array_push($typing, [$row['acctid'], $row['name']]);
          }
          $isTyping = appoencode('`@');
          $i = 0;
          echo appoencode('`@Who\'s typing: `n');
          if (count($typing) != 0) {
              foreach ($typing as $key => $val) {
                  $i++;
                  if ($i == 1) {
                      $isTyping .= appoencode($val[1]);
                  }
                  else if ($i > 1 && count($typing) > $i) {
                      $isTyping .= appoencode("`@, {$val[1]}");
                  }
                  else if ($i == count($typing)) {
                      $isTyping .= appoencode("`@ and {$val[1]}");
                  }
              }
              echo $isTyping;
          }
          else {
              echo appoencode('`@No one');
          }*/
    }
    switch (httpget('op')) {
        case 'get_json':
            $sql = db_query("SELECT commentid, author, comment FROM commentary WHERE section = '{$session['current_commentary_area']}' AND deleted = '0' ORDER BY commentid+0 DESC LIMIT 0, 25");
            $json = [];
            while ($row = db_fetch_assoc($sql)) {
                array_push($json, $row);
            }
            echo "<pre>";
            echo json_encode($json, JSON_PRETTY_PRINT);
            echo "</pre>";
            break;
        case 'post':
            $post = httpallpost();
            $post = modulehook('jquery-post-commentary', $post);
            $commentary = db_prefix('commentary');
            if ($post['method'] == 'insertcommentary') {
                require_once 'lib/commentary.php';
                injectcommentary(get_module_pref('current_section'), get_module_setting('talkline'), $post['comment']);
            } else {
                $commentid = explode('_', $post['method']);
                require_once 'lib/systemmail.php';
                require_once 'lib/sanitize.php';
                $post['comment'] = htmlent($post['comment']);
                db_query("UPDATE {$commentary} SET comment = '{$post['comment']}' WHERE commentid = '{$commentid[1]}'");
                db_query("INSERT INTO {$commentary} (section, author, comment, postdate) VALUES ('blackhole', '{$session['user']['acctid']}', 'I f****d up', '" . date('Y-m-d H:i:s') . "')");
                invalidatedatacache("comments-{$session['current_commentary_section']}");
                invalidatedatacache("comments-blackhole");
            }
            break;
        case 'last_comment':
            require_once 'lib/sanitize.php';
            db_query("UPDATE accounts SET laston = '" . date('Y-m-d H:i:s') . "' WHERE acctid = '{$session['user']['acctid']}'");
            //$sql = db_query("SELECT comment, commentid FROM ".db_prefix('commentary')." WHERE author = '{$session['user']['acctid']}' AND section = '{$session['current_commentary_area']}' ORDER BY commentid DESC LIMIT 0,1");
            $sql = db_query("SELECT comment, commentid FROM {$commentary}\n                WHERE author = '{$session['user']['acctid']}'\n                AND (section = 'globalooc'\n                    OR section = '{$session['current_commentary_area']}')\n                ORDER BY commentid DESC\n                LIMIT 0,1");
            $row = db_fetch_assoc($sql);
            $data = $row;
            $sql = db_query("SELECT commentid, section, comment FROM {$commentary}\n                WHERE (section = 'globalooc'\n                OR section = '{$session['current_commentary_area']}'\n                OR section = 'blackhole'\n                )\n                ORDER BY commentid+0 DESC\n                LIMIT 0,1");
            $row = db_fetch_assoc($sql);
            $data['last_section'] = $row['section'];
            $data['last_comment'] = $row['commentid'];
            $data['last_message'] = $row['comment'];
            echo json_encode($data);
            break;
        case 'is_typing':
            $post = httpallpost();
            if ($post['typing'] == 'yes') {
                set_module_pref('is_typing', 1);
            } else {
                set_module_pref('is_typing', 0);
            }
            $sql = db_query("SELECT a.name, a.acctid\n                FROM accounts AS a\n                LEFT JOIN module_userprefs AS m\n                ON m.userid = a.acctid\n                LEFT JOIN module_userprefs AS u\n                ON u.userid = m.userid\n                WHERE m.modulename = 'jquerycommentary'\n                AND m.setting = 'is_typing'\n                AND m.value = '1'\n                AND u.modulename = 'jquerycommentary'\n                AND u.setting = 'current_section'\n                and u.value = '" . get_module_pref('current_section') . "'");
            $typing = [];
            while ($row = db_fetch_assoc($sql)) {
                array_push($typing, [$row['acctid'], $row['name']]);
            }
            $isTyping = appoencode('`@');
            $i = 0;
            if (count($typing) != 0) {
                foreach ($typing as $key => $val) {
                    $i++;
                    if ($i == 1) {
                        $isTyping .= appoencode($val[1]);
                    } else {
                        if ($i > 1 && count($typing) > $i) {
                            $isTyping .= appoencode("`@, {$val[1]}");
                        } else {
                            if ($i == count($typing)) {
                                $isTyping .= appoencode("`@ and {$val[1]}");
                            }
                        }
                    }
                    if ($i == count($typing)) {
                        $isTyping .= appoencode("`@...");
                    }
                }
                echo "✏ {$isTyping}";
            } else {
                echo "<br />";
            }
            break;
        case 'api':
            header('Content-Type: application/json');
            /*$sql = db_query(
                  "SELECT c.*, a.name FROM $commentary AS c
                  LEFT JOIN $accounts AS a
                  ON a.acctid = c.author
                  WHERE (section = '{$session['current_commentary_area']}'
                  OR section = 'global-ooc')
                  AND deleted = 0
                  ORDER BY commentid+0 DESC
                  GROUP BY section
                  LIMIT 0, 25"
              );*/
            $sql = db_query("SELECT comm.*, acc.name FROM\n                (\n                    (SELECT * FROM\n                        (SELECT * FROM commentary\n                        WHERE section = 'globalooc'\n                        AND deleted = '0'\n                        ORDER BY commentid+0 DESC\n                        LIMIT 0, 10)\n                    AS c\n                    ORDER BY c.commentid+0 ASC\n                    LIMIT 0, 10)\n                    UNION (\n                        SELECT * FROM\n                        (SELECT * FROM commentary\n                        WHERE section = 'superuser'\n                        AND deleted = '0'\n                        ORDER BY commentid+0 DESC\n                        LIMIT 0, 25)\n                        AS c\n                        ORDER BY c.commentid+0 ASC\n                        LIMIT 0, 25\n                    )\n                ) AS comm\n                LEFT JOIN accounts AS acc\n                ON acc.acctid = comm.author");
            $json = [];
            while ($row = db_fetch_assoc($sql)) {
                $row['name'] = appoencode($row['name']);
                $row['comment'] = appoencode($row['comment']);
                array_push($json, $row);
            }
            echo json_encode($json, JSON_PRETTY_PRINT);
            break;
    }
}
function drinks_editor()
{
    global $mostrecentmodule;
    if (!get_module_pref("canedit")) {
        check_su_access(SU_EDIT_USERS);
    }
    page_header("Drink Editor");
    require_once "lib/superusernav.php";
    superusernav();
    addnav("Drink Editor");
    addnav("Add a drink", "runmodule.php?module=drinks&act=editor&op=add&admin=true");
    $op = httpget('op');
    $drinkid = httpget('drinkid');
    $header = "";
    if ($op != "") {
        addnav("Drink Editor Main", "runmodule.php?module=drinks&act=editor&admin=true");
        if ($op == 'add') {
            $header = translate_inline("Adding a new drink");
        } else {
            if ($op == 'edit') {
                $header = translate_inline("Editing a drink");
            }
        }
    } else {
        $header = translate_inline("Current drinks");
    }
    output_notl("`&<h3>{$header}`0</h3>", true);
    $drinksarray = array("Drink,title", "drinkid" => "Drink ID,hidden", "name" => "Drink Name", "costperlevel" => "Cost per level,int", "hpchance" => "Chance of modifying HP (see below),range,0,10,1", "turnchance" => "Chance of modifying turns (see below),range,0,10,1", "alwayshp" => "Always modify hitpoints,bool", "alwaysturn" => "Always modify turns,bool", "drunkeness" => "Drunkeness,range,1,100,1", "harddrink" => "Is drink hard alchohol?,bool", "hpmin" => "Min HP to add (see below),range,-20,20,1", "hpmax" => "Max HP to add (see below),range,-20,20,1", "hppercent" => "Modify HP by some percent (see below),range,-25,25,5", "turnmin" => "Min turns to add (see below),range,-5,5,1", "turnmax" => "Max turns to add (see below),range,-5,5,1", "remarks" => "Remarks", "buffname" => "Name of the buff", "buffrounds" => "Rounds buff lasts,range,1,20,1", "buffroundmsg" => "Message each round of buff", "buffwearoff" => "Message when buff wears off", "buffatkmod" => "Attack modifier of buff", "buffdefmod" => "Defense modifier of buff", "buffdmgmod" => "Damage modifier of buff", "buffdmgshield" => "Damage shield modifier of buff", "buffeffectfailmsg" => "Effect failure message (see below)", "buffeffectnodmgmsg" => "No damage message (see below)", "buffeffectmsg" => "Effect message (see below)");
    if ($op == "del") {
        $sql = "DELETE FROM " . db_prefix("drinks") . " WHERE drinkid='{$drinkid}'";
        module_delete_objprefs('drinks', $drinkid);
        db_query($sql);
        $op = "";
        httpset('op', "");
    }
    if ($op == "save") {
        $subop = httpget("subop");
        if ($subop == "") {
            $drinkid = httppost("drinkid");
            list($sql, $keys, $vals) = postparse($drinksarray);
            if ($drinkid > 0) {
                $sql = "UPDATE " . db_prefix("drinks") . " SET {$sql} WHERE drinkid='{$drinkid}'";
            } else {
                $sql = "INSERT INTO " . db_prefix("drinks") . " ({$keys}) VALUES ({$vals})";
            }
            db_query($sql);
            if (db_affected_rows() > 0) {
                output("`^Drink saved!");
            } else {
                $str = db_error();
                if ($str == "") {
                    output("`^Drink not saved: no changes detected.");
                } else {
                    output("`^Drink not saved: `\$%s`0", $sql);
                }
            }
        } elseif ($subop == "module") {
            $drinkid = httpget("drinkid");
            // Save module settings
            $module = httpget("editmodule");
            // This should obey the same rules as the configuration editor
            // So disabling
            //$sql = "DELETE FROM " . db_prefix("module_objprefs") . " WHERE objtype='drinks' AND objid='$drinkid' AND modulename='$module'";
            //db_query($sql);
            $post = httpallpost();
            reset($post);
            while (list($key, $val) = each($post)) {
                set_module_objpref("drinks", $drinkid, $key, $val, $module);
            }
            output("`^Saved.");
        }
        if ($drinkid) {
            $op = "edit";
            httpset("drinkid", $drinkid, true);
        } else {
            $op = "";
        }
        httpset('op', $op);
    }
    if ($op == "activate") {
        $sql = "UPDATE " . db_prefix("drinks") . " SET active=1 WHERE drinkid='{$drinkid}'";
        db_query($sql);
        $op = "";
        httpset('op', "");
    }
    if ($op == "deactivate") {
        $sql = "UPDATE " . db_prefix("drinks") . " SET active=0 WHERE drinkid='{$drinkid}'";
        db_query($sql);
        $op = "";
        httpset('op', "");
    }
    if ($op == "") {
        $op = translate_inline("Ops");
        $id = translate_inline("Id");
        $nm = translate_inline("Name");
        $dkn = translate_inline("Drunkeness");
        $hard = translate_inline("Hard Alchohol?");
        $edit = translate_inline("Edit");
        $deac = translate_inline("Deactivate");
        $act = translate_inline("Activate");
        $conf = translate_inline("Are you sure you wish to delete this drink?");
        $del = translate_inline("Del");
        rawoutput("<table border=0 cellpadding=2 cellspacing=1 bgcolor='#999999'>");
        rawoutput("<tr class='trhead'>");
        rawoutput("<td>{$op}</td><td>{$id}</td><td>{$nm}</td><td>{$dkn}</td><td>{$hard}</td>");
        rawoutput("</tr>");
        $sql = "SELECT drinkid,active,name,drunkeness,harddrink FROM " . db_prefix("drinks") . " ORDER BY drinkid";
        $result = db_query($sql);
        for ($i = 0; $i < db_num_rows($result); $i++) {
            $row = db_fetch_assoc($result);
            $id = $row['drinkid'];
            rawoutput("<tr class='" . ($i % 2 ? "trlight" : "trdark") . "'>");
            rawoutput("<td nowrap>[ <a href='runmodule.php?module=drinks&act=editor&op=edit&drinkid={$id}&admin=true'>{$edit}</a>");
            addnav("", "runmodule.php?module=drinks&act=editor&op=edit&drinkid={$id}&admin=true");
            if ($row['active']) {
                rawoutput(" | <a href='runmodule.php?module=drinks&act=editor&op=deactivate&drinkid={$id}&admin=true'>{$deac}</a>");
                addnav("", "runmodule.php?module=drinks&act=editor&op=deactivate&drinkid={$id}&admin=true");
            } else {
                rawoutput(" | <a href='runmodule.php?module=drinks&act=editor&op=activate&drinkid={$id}&admin=true'>{$act}</a>");
                addnav("", "runmodule.php?module=drinks&act=editor&op=activate&drinkid={$id}&admin=true");
            }
            rawoutput(" | <a href='runmodule.php?module=drinks&act=editor&op=del&drinkid={$id}&admin=true' onClick='return confirm(\"{$conf}\");'>{$del}</a> ]</td>");
            addnav("", "runmodule.php?module=drinks&act=editor&op=del&drinkid={$id}&admin=true");
            output_notl("<td>`^%s</td>`0", $id, true);
            output_notl("<td>`&%s`0</td>", $row['name'], true);
            output_notl("<td>`^%s`0</td>", $row['drunkeness'], true);
            $hard = translate_inline("`^No");
            if ($row['harddrink']) {
                $hard = translate_inline("`\$Yes");
            }
            output_notl("<td>%s`0</td>", $hard, true);
            rawoutput("</tr>");
        }
        rawoutput("</table>");
    }
    $subop = httpget("subop");
    if ($op == "edit") {
        addnav("Drink properties", "runmodule.php?module=drinks&act=editor&op=edit&drinkid={$drinkid}&admin=true");
        module_editor_navs("prefs-drinks", "runmodule.php?module=drinks&act=editor&drinkid={$drinkid}&op=edit&subop=module&editmodule=");
        if ($subop == "module") {
            $module = httpget("editmodule");
            $oldmodule = $mostrecentmodule;
            rawoutput("<form action='runmodule.php?module=drinks&act=editor&op=save&subop=module&editmodule={$module}&drinkid={$drinkid}&admin=true' method='POST'>");
            module_objpref_edit('drinks', $module, $drinkid);
            $mostrecentmodule = $oldmodule;
            rawoutput("</form>");
            addnav("", "runmodule.php?module=drinks&act=editor&op=save&subop=module&editmodule={$module}&drinkid={$drinkid}&admin=true");
        } elseif ($subop == "") {
            $sql = "SELECT * FROM " . db_prefix("drinks") . " WHERE drinkid='" . httpget('drinkid') . "'";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
        }
    } elseif ($op == "add") {
        /* We're adding a new drink, make an empty row */
        $row = array();
        $row['drinkid'] = 0;
    }
    if (($op == "edit" || $op == "add") && $subop == "") {
        rawoutput("<form action='runmodule.php?module=drinks&act=editor&op=save&admin=true' method='POST'>");
        addnav("", "runmodule.php?module=drinks&act=editor&op=save&admin=true");
        showform($drinksarray, $row);
        rawoutput("</form>");
        output("`\$NOTE:`7 Make sure that you know what you are doing when modifying or adding drinks.`n");
        output("Just because the drinks have a lot of options, doesn't mean you have to use all of them`n`n");
        output("`2Drink ID: `7This field is used internally and should be unique.`n");
        output("`2Name: `7The name of the drink the user will see.`n");
        output("`2Cost per level: `7This value times the users level is the drink cost.`n");
        output("`2Chance of modifying HP: `7If set, this is the number of chances out of the total of this and the turn chance for HP getting modified.`n");
        output("`2Chance of modifying turns: `7If set, this is the number of chances out of the total of this and the HP chance for turns getting modified.`n");
        output("`2Always modify HP: `7If set, hitpoints will be modified.  Should not be set alongside HP chance above.`n");
        output("`2Always modify turns: `7If set, turns will be modified.  Should not be set alongside turn chance above.`n");
        output("`2Drunkeness: `7How drunk will this make the player.`n");
        output("`2Hard Drink: `7Users are only allowed a certain number of hard drinks per day regardless of drunkeness.`n");
        output("`2Min HP to add: `7If we are modifying hitpoints, and if HP percent isn't set, use this and the HP max value to pick a random amount of HP to add.  Can be negative.`n");
        output("`2Max HP to add: `7If we are modifying hitpoints and if HP percent isn't set, use this and the HP min value to pick a random amount of HP to add.  Can be negative.`n");
        output("`2HP percent: `7If we are modifying hitpoints and if this is set, the users hitpoints are modified by this percentage.  Can be negative.`n");
        output("`2Min turns to add: `7If we are modifying turns, use this and the turn max value to pick a random amount of turns to add.  Can be negative.`n");
        output("`2Max turns to add: `7If we are modifying turns, use this and the turn min value to pick a random amount of turns to add.  Can be negative.`n");
        output("`2Remarks: `7Text displayed to the user when they order the drink.`n");
        output("`2Buff name: `7What is this buff called.`n");
        output("`2Buff rounds: `7How many rounds this buff lasts.`n");
        output("`2Buff round message: `7What message should show as each round occurs.`n");
        output("`2Buff wearoff: `7What message is shown when this buff wears off.`n");
        output("`2Buff attack modifier: `7Multiplier to modify attack points by? 1.0 is no modification, 2.0 doubles their attack points.`n");
        output("`2Buff defense modifier: `7Multiplier to modify defense points by? 1.0 is no modification, 2.0 doubles their defense points.`n");
        output("`2Buff damage modifier: `7Multiplier to modify damage by? 1.0 is no modification, 2.0 doubles their damage points. This is `\$VERY POTENT`7!`n");
        output("`2Buff damage shield modifier: `7When you are hit, deals damage to your opponent based on damage done to you. 1.0 deals identical damage, 2.0 deals double damage back to the opponent.`n");
        output("`2Effect failure message: Message if this buff fails. (Only used with damage shield)`n");
        output("`2Effect no damage message: Message if no damage is done. (Only used with damage shield)`n");
        output("`2Effect message: What shows when this buff has an effect. (Only used with damage shield)`n`n");
    }
    page_footer();
}
 }
 $dbpass = "";
 if (substr($pass1, 0, 5) == "!md5!") {
     $dbpass = md5(substr($pass1, 5));
 } else {
     $dbpass = md5(md5($pass1));
 }
 $sql = "INSERT INTO " . db_prefix("accounts") . "\r\n\t\t\t\t\t\t(name, superuser, title, password, sex, login, laston, uniqueid, lastip, gold, emailaddress, emailvalidation, referer, regdate)\r\n\t\t\t\t\t\tVALUES\r\n\t\t\t\t\t\t('{$title} {$shortname}', '" . getsetting("defaultsuperuser", 0) . "', '{$title}', '{$dbpass}', '{$sex}', '{$shortname}', '" . date("Y-m-d H:i:s", strtotime("-1 day")) . "', '" . $_COOKIE['lgi'] . "', '" . $_SERVER['REMOTE_ADDR'] . "', " . getsetting("newplayerstartgold", 50) . ", '{$email}', '{$emailverification}', '{$referer}', NOW())";
 db_query($sql);
 if (db_affected_rows(LINK) <= 0) {
     output("`\$Error`^: Your account was not created for an unknown reason, please try again. ");
 } else {
     $sql = "SELECT acctid FROM " . db_prefix("accounts") . " WHERE login='******'";
     $result = db_query($sql);
     $row = db_fetch_assoc($result);
     $args = httpallpost();
     $args['acctid'] = $row['acctid'];
     //insert output
     $sql_output = "INSERT INTO " . db_prefix("accounts_output") . " VALUES ({$row['acctid']},'');";
     db_query($sql_output);
     //end
     modulehook("process-create", $args);
     if ($emailverification != "") {
         $subj = translate_mail("LoGD Account Verification", 0);
         $msg = translate_mail(array("Login name: %s `n`nIn order to verify your account, you will need to click on the link below.`n`n http://%s?op=val&id=%s `n`nThanks for playing!", $shortname, $_SERVER['SERVER_NAME'] . ($_SERVER['SERVER_PORT'] == 80 ? "" : ":" . $_SERVER['SERVER_PORT']) . $_SERVER['SCRIPT_NAME'], $emailverification), 0);
         mail($email, $subj, str_replace("`n", "\n", $msg), "From: " . getsetting("gameadminemail", "*****@*****.**"));
         output("`4An email was sent to `\$%s`4 to validate your address.  Click the link in the email to activate your account.`0`n`n", $email);
     } else {
         rawoutput("<form action='login.php' method='POST'>");
         rawoutput("<input name='name' value=\"{$shortname}\" type='hidden'>");
         rawoutput("<input name='password' value=\"{$pass1}\" type='hidden'>");
function switch_run()
{
    global $session;
    $op = httpget('op');
    $id = httpget('id');
    $accounts = db_prefix('accounts');
    $allAccounts = json_decode(get_module_pref('accounts'), true);
    page_header('Switch Accounts');
    switch ($op) {
        case 'add':
            addnav('Go back', 'runmodule.php?module=switch');
            output("`@Please enter the information of the account you want to add to your switch list. Note that this link is symbolic, meaning it will be added both ways!`n`n`0");
            rawoutput("<form action='runmodule.php?module=switch&op=verify' method='POST'>\n                <input type='text' name='login' placeholder='Login' />\n                <input type='password' name='password' placeholder='Password' />\n                <input type='submit' value='Create Link' />\n                </form>");
            addnav('', 'runmodule.php?module=switch&op=verify');
            break;
        case 'verify':
            $post = httpallpost();
            $post['password'] = md5(md5($post['password']));
            $post['login'] = filter_var($post['login'], FILTER_SANITIZE_STRING);
            $sql = db_query("SELECT acctid, name, uniqueid, lastip\n                FROM {$accounts}\n                WHERE password = '******'password']}'\n                AND login = '******'login']}'");
            if (db_num_rows($sql) == 0) {
                addnav('Go back', 'runmodule.php?module=switch&op=add');
                output("`\$Sorry, no account was found with those credentials!");
                break;
            } else {
                $row = db_fetch_assoc($sql);
                addnav('Go back', 'runmodule.php?module=switch');
                if ($row['acctid'] == $session['user']['acctid']) {
                    output("`\$Sorry, but you cannot add a link to yourself!");
                    break;
                }
                output("`@Success! Adding a link between`^ %s `@and `^%s`@!`0", $session['user']['name'], $row['name']);
                $targetPref = json_decode(get_module_pref('accounts', 'switch', $row['acctid']), true);
                $targetPref = array_merge($targetPref, [$session['user']['acctid']]);
                set_module_pref('accounts', json_encode($targetPref), 'switch', $row['acctid']);
                $userPref = json_decode(get_module_pref('accounts'), true);
                $userPref = array_merge($userPref, [$row['acctid']]);
                set_module_pref('accounts', json_encode($userPref));
            }
            break;
        case 'remove':
            addnav('Go back', 'runmodule.php?module=switch');
            if (!in_array($id, $allAccounts)) {
                output("`\$Woops! That account is not linked to yours!");
                break;
            }
            $unsetId = array_search($id, $allAccounts);
            unset($allAccounts[$unsetId]);
            set_module_pref('accounts', json_encode($allAccounts));
            $targetPref = get_module_pref('accounts', false, $id);
            $targetPref = json_decode($targetPref, true);
            $key = array_search($session['user']['acctid'], $targetPref);
            unset($targetPref[$key]);
            set_module_pref('accounts', json_encode($targetPref), 'switch', $id);
            output("`@The link between your accounts has been destroyed!");
            break;
        case 'switch':
            require_once 'lib/redirect.php';
            require_once 'lib/checkban.php';
            if (!in_array($id, $allAccounts)) {
                addnav('Go back', 'runmodule.php?module=switch');
                output("`\$There was an error. We could not validate your link between these accounts!");
                debuglog('tried to switch into an account they do not have access to!');
                break;
            }
            $sql = db_query("UPDATE {$accounts} SET loggedin = 0 WHERE acctid = '{$session['user']['acctid']}'");
            $sql = db_query("UPDATE {$accounts} SET loggedin = 1 WHERE acctid = '{$id}'");
            $sql = db_query("SELECT * FROM {$accounts} WHERE acctid = '{$id}'");
            $session['user'] = db_fetch_assoc($sql);
            $session['loggedin'] = true;
            $session['laston'] = date('Y-m-d H:i:s');
            $session['user']['laston'] = $session['laston'];
            redirect($session['user']['restorepage'] ?: 'news.php');
            break;
        default:
            require_once 'lib/villagenav.php';
            villagenav();
            addnav('Link an account', 'runmodule.php?module=switch&op=add');
            if (count($allAccounts) > 0) {
                output("`i`@Which account would you like to sign in to?`i`n`n`0");
                rawoutput("<table class='switchAccounts'>\n                        <tr>\n                            <th>\n                                Ops\n                            </th>\n                            <th>\n                                Name\n                            </th>\n                        </tr>\n                    ");
                foreach ($allAccounts as $acctid) {
                    debug($acctid);
                    $sql = db_query("SELECT name\n                        FROM {$accounts}\n                        WHERE acctid = '{$acctid}'");
                    $row = db_fetch_assoc($sql);
                    output("<tr>\n                            <td>\n                                [<a href='runmodule.php?module=switch&op=remove&id=%s'>Del</a>]\n                            </td>\n                            <td>\n                                <a href='runmodule.php?module=switch&op=switch&id=%s'>%s</a>\n                            </td>\n                        </tr>", $acctid, $acctid, $row['name'], true);
                    addnav('', 'runmodule.php?module=switch&op=remove&id=' . $acctid);
                    addnav('', 'runmodule.php?module=switch&op=switch&id=' . $acctid);
                }
                rawoutput("</table>");
            } else {
                output("`@You need to add accounts! Click 'Link an account' to get started!");
            }
            break;
    }
    page_footer();
}
function claneditor_run()
{
    global $session;
    tlschema("claneditor");
    $dt = httpget("dt");
    $op = httpget('op');
    if ($dt != "") {
        $sql = "SELECT * FROM " . db_prefix("clans") . " WHERE clanid='{$dt}'";
        $result = db_query($sql);
        $claninfo = db_fetch_assoc($result);
        if (db_num_rows($result) == 0) {
            $op = "";
        }
    }
    addcommentary();
    $ranks = array(CLAN_APPLICANT => "`!Applicant`0", CLAN_MEMBER => "`#Member`0", CLAN_OFFICER => "`^Officer`0", CLAN_LEADER => "`&Leader`0", CLAN_FOUNDER => "`\$Founder");
    $args = modulehook("clanranks", array("ranks" => $ranks, "clanid" => $dt));
    $ranks = translate_inline($args['ranks'], "clan");
    superusernav();
    addnav("Clans");
    addnav("List Clans", "runmodule.php?module=claneditor&op=list");
    addnav("Create a New Clan", "runmodule.php?module=claneditor&op=new");
    if ($op == "" || $op == "list") {
        page_header("Clan Listing");
        rawoutput("<table border='0' padding='0'><tr><td>");
        $sql = "SELECT MAX(" . db_prefix("clans") . ".clanid) AS clanid, MAX(clanname) AS clanname,count(" . db_prefix("accounts") . ".acctid) AS c FROM " . db_prefix("clans") . " LEFT JOIN " . db_prefix("accounts") . " ON " . db_prefix("clans") . ".clanid=" . db_prefix("accounts") . ".clanid AND clanrank>" . CLAN_APPLICANT . " GROUP BY " . db_prefix("clans") . ".clanid ORDER BY c DESC";
        $result = db_query($sql);
        if (db_num_rows($result) > 0) {
            output("`%Karissa`7 steps in as if by magic, listing the clans for you.`n");
            output("`@`bList of Clans:`b`0`n`n");
            $v = 0;
            $memb_n = translate_inline("(%s members)");
            $memb_1 = translate_inline("(%s member)");
            rawoutput('<table cellspacing="0" cellpadding="2" align="left">');
            output_notl("<tr class='trhead'><td>%s</td><td>%s</td></tr>", translate_inline("`b`&Name of Clan`b"), translate_inline("`&`iNumber of Members`i"), true);
            for ($i = 0; $i < db_num_rows($result); $i++) {
                $row = db_fetch_assoc($result);
                if ($row['c'] == 0) {
                    $sql = "DELETE FROM " . db_prefix("clans") . " WHERE clanid={$row['clanid']}";
                    db_query($sql);
                } else {
                    rawoutput('<tr class="' . ($v % 2 ? "trlight" : "trdark") . '"><td>', true);
                    if ($row['c'] == 1) {
                        $memb = sprintf($memb_1, $row['c']);
                    } else {
                        $memb = sprintf($memb_n, $row['c']);
                    }
                    output_notl("&#149; <a href='runmodule.php?module=claneditor&op=mview&dt=%s'>%s</a></td><td>%s`n", $row['clanid'], full_sanitize(htmlentities($row['clanname']), ENT_COMPAT, getsetting("charset", "ISO-8859-1")), $memb, true);
                    rawoutput('</td></tr>');
                    addnav("", "runmodule.php?module=claneditor&op=mview&dt={$row['clanid']}");
                    $v++;
                }
            }
            rawoutput("</table>", true);
        } else {
            output("`7There are no clans in the database.`n`c");
        }
        rawoutput("</td></tr><tr><td>");
        output_notl("<br>[<a href='runmodule.php?module=claneditor&op=new'>%s</a>]", translate_inline("Create a New Clan"), true);
        addnav("", "runmodule.php?module=claneditor&op=new");
        rawoutput("</td></tr></table>");
        page_footer();
    } elseif ($op == "new") {
        page_header("Clan Creation");
        $apply = httpget('apply');
        if ($apply == 1) {
            $id = httpget("id");
            $ocn = httppost('clanname');
            $ocs = httppost('clanshort');
            $clanname = stripslashes($ocn);
            $clanname = full_sanitize($clanname);
            $clanname = preg_replace("'[^[:alpha:] \\'-]'", "", $clanname);
            $clanname = addslashes($clanname);
            httppostset('clanname', $clanname);
            $clanshort = full_sanitize($ocs);
            $clanshort = preg_replace("'[^[:alpha:]]'", "", $clanshort);
            httppostset('clanshort', $clanshort);
            $sql = "SELECT * FROM " . db_prefix("clans") . " WHERE clanname='{$clanname}'";
            $result = db_query($sql);
            $e = translate_inline("`%Karissa`7 hands you a form to start a clan.");
            $e1 = translate_inline("`%Karissa`7 looks over your form but informs you that your clan name must consist only of letters, spaces, apostrophes, or dashes.  Also, your short name can consist only of letters. She hands you a blank form.");
            $e2 = translate_inline("`%Karissa`7 looks over your form but informs you that you must have at least 5 and no more than 50 characters in your clan's name (and they must consist only of letters, spaces, apostrophes, or dashes), then hands you a blank form.");
            $e3 = translate_inline("`%Karissa`7 looks over your form but informs you that you must have at least 2 and no more than 5 characters in your clan's short name (and they must all be letters), then hands you a blank form.");
            $e4 = translate_inline("`%Karissa`7 looks over your form but informs you that the clan name %s is already taken, and hands you a blank form.");
            $e5 = translate_inline("`%Karissa`7 looks over your form but informs you that the short name %s is already taken, and hands you a blank form.");
            if ($ocs == "" && $ocn == "" && !httppostisset('clanname') && !httppostisset('clanshort')) {
                output_notl($e);
                clanform();
            } elseif ($clanname != $ocn || $clanshort != $ocs) {
                output_notl($e1);
                clanform();
            } elseif (strlen($clanname) < 5 || strlen($clanname) > 50) {
                output_notl($e2);
                clanform();
            } elseif (strlen($clanshort) < 2 || strlen($clanshort) > 5) {
                output_notl($e3);
                clanform();
            } elseif (db_num_rows($result) > 0) {
                output_notl($e4, stripslashes($clanname));
                clanform();
            } else {
                $sql = "SELECT * FROM " . db_prefix("clans") . " WHERE clanshort='{$clanshort}'";
                $result = db_query($sql);
                if (db_num_rows($result) > 0) {
                    output_notl($e5, stripslashes($clanshort));
                    clanform();
                } else {
                    $sql = "INSERT INTO " . db_prefix("clans") . " (clanname,clanshort) VALUES ('{$clanname}','{$clanshort}')";
                    db_query($sql);
                    $clid = db_insert_id();
                    $sql = "UPDATE " . db_prefix("accounts") . " SET clanid='{$clid}',clanrank='" . CLAN_LEADER . "' WHERE acctid='{$id}'";
                    db_query($sql);
                    $subj = "New Clan!";
                    $msg = array("%s`0`^ has made you a new clan!", $session['user']['name']);
                    systemmail($id, $subj, $msg);
                    output("`%Karissa`7 looks over your form, and finding that everything seems to be in order, she takes your fees, stamps the form \"`\$APPROVED`7\" and files it in a drawer.`n`n");
                    output("Congratulations, you've created a new clan named %s!", stripslashes($clanname));
                }
            }
        } elseif ($apply == 0) {
            clanuserform();
        } else {
            output("`7You teleport to the Clan Hall...");
            output("`7You approach `%Karissa`7 and mention that you would like to start a new clan.");
            output("She tells you that there are three requirements to starting a clan.");
            output("First, you have to decide on a full name for your clan.");
            output("Second, you have to decide on an abbreviation for your clan.");
            output("Third you have to decide on the person that should run the clan.");
            $e = translate_inline("`n`n\"`5If you're ok with these three requirements, please fill out the following form,`7\" she says, handing you a sheet of paper.");
            output_notl($e);
            clanuserform();
        }
    } else {
        if ($op != "deleteclan") {
            page_header("The Clan of %s", full_sanitize($claninfo['clanname']));
            output("`n`c`^`bThe Clan of %s`b`c`n`n", full_sanitize($claninfo['clanname']));
        } else {
            page_header("Clan Deletion");
        }
        if ($op == "mview") {
            $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid={$claninfo['motdauthor']}";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            $motdauthname = $row['name'];
            $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid={$claninfo['descauthor']}";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            $descauthname = $row['name'];
            output("`&`bCurrent MoTD:`b `#by %s`2`n", $motdauthname);
            output_notl(nltoappon($claninfo['clanmotd']) . "`n`n");
            commentdisplay("", "clan-{$claninfo['clanid']}", "Speak into their Clan", 25, "projects");
            output_notl("`n`n");
            modulehook("collapse{", array("name" => "collapsedesc"));
            output("`&`bCurrent Description:`b `#by %s`2`n", $descauthname);
            output_notl(nltoappon($claninfo['clandesc']) . "`n");
            modulehook("}collapse");
            $sql = "SELECT count(*) AS c, clanrank FROM " . db_prefix("accounts") . " WHERE clanid={$claninfo['clanid']} GROUP BY clanrank DESC";
            $result = db_query($sql);
            // begin collapse
            modulehook("collapse{", array("name" => "clanmemberdet"));
            output("`n`bMembership Details:`b`n");
            $leaders = 0;
            while ($row = db_fetch_assoc($result)) {
                output_notl($ranks[$row['clanrank']] . ": " . $row['c'] . "`n");
                if ($row['clanrank'] >= CLAN_OFFICER) {
                    $leaders += $row['c'];
                }
            }
            output("`n");
            $noleader = translate_inline("`^There is currently no leader!  Promoting %s`^ to leader as they are the highest ranking member (or oldest member in the event of a tie).`n`n");
            if ($leaders == 0) {
                //There's no leader here, probably because the leader's account
                //expired.
                $sql = "SELECT name,acctid,clanrank FROM " . db_prefix("accounts") . " WHERE clanid={$dt} ORDER BY clanrank DESC, clanjoindate";
                $result = db_query($sql);
                $row = db_fetch_assoc($result);
                $sql = "UPDATE " . db_prefix("accounts") . " SET clanrank=" . CLAN_LEADER . " WHERE acctid='" . $row['acctid'] . "'";
                db_query($sql);
                output_notl($noleader, $row['name']);
            }
            // end collapse
            modulehook("}collapse");
        } elseif ($op == "deleteclan") {
            if (httpget("sop") == "yes") {
                //notify users of the deletion of the clan
                $sql = "SELECT acctid FROM " . db_prefix("accounts") . " WHERE clanid={$dt}";
                $result = db_query($sql);
                $subj = array("Deletion of %s", $claninfo['clanname']);
                $msg = array("The clan you were in, %s, has closed its doors.\nSorry for any inconvenience.", $claninfo['clanname']);
                while ($row = db_fetch_assoc($result)) {
                    systemmail($row['acctid'], $subj, $msg);
                }
                //change the clan if a user is in this clan
                $sql = "UPDATE " . db_prefix("accounts") . " SET clanid=0,clanrank=" . CLAN_APPLICANT . ",clanjoindate='0000-00-00 00:00:00' WHERE clanid={$dt}";
                db_query($sql);
                //change the current users clan if this user was in that clan
                if ($session['user']['clanid'] == $dt) {
                    $session['user']['clanid'] = 0;
                    $session['user']['clanrank'] = CLAN_APPLICANT;
                    $session['user']['clanjoindate'] = '0000-00-00 00:00:00';
                }
                //drop the clan.
                $sql = "DELETE FROM " . db_prefix("clans") . " WHERE clanid={$dt}";
                db_query($sql);
                module_delete_objprefs('clans', $dt);
                $op = "";
                httpset("op", "");
                unset($claninfo);
                $dt = "";
                output("That clan has been wiped.`n");
                output("`@Users within the clan have been notified.");
            } else {
                output("`%`c`bAre you SURE you want to delete this clan?`b`c`n");
                $dc = translate_inline("Delete this clan? Are you sure!");
                rawoutput("[<a href='runmodule.php?module=claneditor&op=deleteclan&sop=yes&dt={$dt}' onClick='return confirm(\"{$dc}\");'>{$dc}</a>]");
                addnav("", "runmodule.php?module=claneditor&op=deleteclan&sop=yes&dt={$dt}");
            }
        } elseif ($op == "editmodule" || $op == "editmodulesave") {
            $mdule = httpget("mdule");
            if ($op == "editmodulesave") {
                // Save module prefs
                $post = httpallpost();
                reset($post);
                while (list($key, $val) = each($post)) {
                    set_module_objpref("clans", $dt, $key, $val, $mdule);
                }
                output("`^Saved!`0`n");
            }
            rawoutput("<form action='runmodule.php?module=claneditor&op=editmodulesave&dt={$dt}&mdule={$mdule}' method='POST'>");
            module_objpref_edit("clans", $mdule, $dt);
            rawoutput("</form>");
            addnav("", "runmodule.php?module=claneditor&op=editmodulesave&dt={$dt}&mdule={$mdule}");
        } elseif ($op == "updinfo") {
            page_header("Update Clan Information");
            $clanmotd = substr(httppost('clanmotd'), 0, 4096);
            if (httppostisset('clanmotd') && $clanmotd != $claninfo['clanmotd']) {
                if ($clanmotd == "") {
                    $mauthor = 0;
                } else {
                    $mauthor = $session['user']['acctid'];
                }
                $sql = "UPDATE " . db_prefix("clans") . " SET clanmotd='{$clanmotd}',motdauthor={$mauthor} WHERE clanid={$claninfo['clanid']}";
                db_query($sql);
                invalidatedatacache("clandata-{$claninfo['clanid']}");
                $claninfo['clanmotd'] = stripslashes($clanmotd);
                output("Updating MoTD`n");
                $claninfo['motdauthor'] = $mauthor;
            }
            $clandesc = httppost('clandesc');
            if (httppostisset('clandesc') && $clandesc != $claninfo['clandesc']) {
                if ($clandesc == "") {
                    $claninfo['descauthor'] = 0;
                    $dauthor = 0;
                } else {
                    $dauthor = $session['user']['acctid'];
                }
                $sql = "UPDATE " . db_prefix("clans") . " SET clandesc='" . addslashes(substr(stripslashes($clandesc), 0, 4096)) . "',descauthor={$dauthor} WHERE clanid={$claninfo['clanid']}";
                db_query($sql);
                invalidatedatacache("clandata-{$claninfo['clanid']}");
                output("Updating description`n");
                $claninfo['clandesc'] = stripslashes($clandesc);
                $claninfo['descauthor'] = $session['user']['acctid'];
            }
            $customsay = httppost('customsay');
            if (httppostisset('customsay') && $customsay != $claninfo['customsay']) {
                $sql = "UPDATE " . db_prefix("clans") . " SET customsay='{$customsay}' WHERE clanid={$claninfo['clanid']}";
                db_query($sql);
                invalidatedatacache("clandata-{$claninfo['clanid']}");
                output("Updating custom say line`n");
                $claninfo['customsay'] = stripslashes($customsay);
            }
            $clanname = httppost('clanname');
            if ($clanname) {
                $clanname = full_sanitize($clanname);
            }
            $clanshort = httppost('clanshort');
            if ($clanshort) {
                $clanshort = full_sanitize($clanshort);
            }
            if (httppostisset('clanname') && $clanname != $claninfo['clanname']) {
                $sql = "UPDATE " . db_prefix("clans") . " SET clanname='{$clanname}' WHERE clanid={$claninfo['clanid']}";
                output("Updating the clan name`n");
                db_query($sql);
                invalidatedatacache("clandata-{$detail}");
                $claninfo['clanname'] = $clanname;
            }
            if (httppostisset('clanshort') && $clanshort != $claninfo['clanshort']) {
                $sql = "UPDATE " . db_prefix("clans") . " SET clanshort='{$clanshort}' WHERE clanid={$claninfo['clanid']}";
                output("Updating the short clan name`n");
                db_query($sql);
                invalidatedatacache("clandata-{$detail}");
                $claninfo['clanshort'] = $clanshort;
            }
            $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid={$claninfo['motdauthor']}";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            $motdauthname = $row['name'];
            $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid={$claninfo['descauthor']}";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            $descauthname = $row['name'];
            output("`&`bCurrent MoTD:`b `#by %s`2`n", $motdauthname);
            output_notl(nltoappon($claninfo['clanmotd']) . "`n");
            output("`&`bCurrent Description:`b `#by %s`2`n", $descauthname);
            output_notl(nltoappon($claninfo['clandesc']) . "`n");
            rawoutput("<form action='runmodule.php?module=claneditor&op=updinfo&dt={$dt}' method='POST'>");
            addnav("", "runmodule.php?module=claneditor&op=updinfo&dt={$dt}");
            output("`&`bMoTD:`b `7(4096 chars)`n");
            rawoutput("<textarea name='clanmotd' cols='50' rows='10'>" . htmlentities($claninfo['clanmotd'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "</textarea><br>");
            output("`bRenaming:`b`n");
            output("`iLong Name:`i ");
            rawoutput("<input name='clanname' value=\"" . htmlentities($claninfo['clanname'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "\" maxlength=50 size=50>");
            output("`n`iShort Name:`i ");
            rawoutput("<input name='clanshort' value=\"" . htmlentities($claninfo['clanshort'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "\" maxlength=5 size=5>");
            output_notl("`n");
            output("`n`&`bDescription:`b `7(4096 chars)`n");
            if (httppost('block') > "") {
                $blockdesc = translate_inline("Description blocked for inappropriate usage.");
                $sql = "UPDATE " . db_prefix("clans") . " SET descauthor=4294967295, clandesc='{$blockdesc}' where clanid='" . $claninfo['clanid'] . "'";
                output("Blocking public description`n");
                db_query($sql);
                invalidatedatacache("clandata-" . $claninfo['clanid'] . "");
                $claninfo['blockdesc'] = "";
                $claninfo['descauthor'] = 4294967295.0;
            } elseif (httppost('unblock') > "") {
                $sql = "UPDATE " . db_prefix("clans") . " SET descauthor=0, clandesc='' where clanid='" . $claninfo['clanid'] . "'";
                output("Unblocking public description`n");
                db_query($sql);
                invalidatedatacache("clandata-" . $claninfo['clanid'] . "");
                $claninfo['clandesc'] = "";
                $claninfo['descauthor'] = 0;
            }
            $blocked = translate_inline("The clan has been blocked from posting a description.`n");
            if ($claninfo['descauthor'] == 4294967295.0) {
                output_notl("`b`%" . $blocked . "`b");
            }
            rawoutput("<textarea name='clandesc' cols='50' rows='10'>" . htmlentities($claninfo['clandesc'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "</textarea><br>");
            output("`n`&`bCustom Talk Line`b `7(blank means \"says\" -- 15 chars max)`n");
            rawoutput("<input name='customsay' value=\"" . htmlentities($claninfo['customsay'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "\" maxlength=\"15\"><br/>");
            $save = translate_inline("Save");
            rawoutput("<input type='submit' class='button' value=\"{$save}\">");
            $snu = htmlentities(translate_inline("Save & Unblock public description"), ENT_COMPAT, getsetting("charset", "ISO-8859-1"));
            $snb = htmlentities(translate_inline("Save & Block public description"), ENT_COMPAT, getsetting("charset", "ISO-8859-1"));
            if ($claninfo['descauthor'] == "4294967295") {
                rawoutput("<input type='submit' name='unblock' value=\"{$snu}\" class='button'>");
            } else {
                rawoutput("<input type='submit' name='block' value=\"{$snb}\" class='button'>");
            }
            rawoutput("</form>");
        } elseif ($op == "membership") {
            output("This is the clans current membership:`n");
            $setrank = httpget('setrank');
            $who = httpget('who');
            if ($setrank > "") {
                $sql = "UPDATE " . db_prefix("accounts") . " SET clanrank={$setrank} WHERE login='******'";
                db_query($sql);
            }
            $remove = httpget('remove');
            if ($remove > "") {
                $sql = "UPDATE " . db_prefix("accounts") . " SET clanrank=" . CLAN_APPLICANT . ",clanid=0,clanjoindate='0000-00-00 00:00:00' WHERE login='******' AND clanrank<={$session['user']['clanrank']}";
                db_query($sql);
                //delete unread application emails from this user.
                //breaks if the applicant has had their name changed via
                //dragon kill, superuser edit, or lodge color change
                $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE login='******'";
                $row = db_fetch_assoc(db_query($sql));
                $subj = serialize(array($apply_short, $row['name']));
                $sql = "DELETE FROM " . db_prefix("mail") . " WHERE msgfrom=0 AND seen=0 AND subject='{$subj}'";
                db_query($sql);
            }
            $sql = "SELECT acctid,name,login,clanrank,laston,clanjoindate,dragonkills,level FROM " . db_prefix("accounts") . " WHERE clanid={$claninfo['clanid']} ORDER BY clanrank DESC,clanjoindate";
            $result = db_query($sql);
            rawoutput("<table border='0' cellpadding='2' cellspacing='0'>");
            $rank = translate_inline("Rank");
            $name = translate_inline("Name");
            $lev = translate_inline("Level");
            $dk = translate_inline("Dragon Kills");
            $jd = translate_inline("Join Date");
            $lo = translate_inline("Last On");
            $ops = translate_inline("Operations");
            $promote = translate_inline("Promote");
            $demote = translate_inline("Demote");
            $remove = translate_inline("Remove From The Clan");
            $confirm = translate_inline("Are you sure you wish to remove this member from the clan?");
            rawoutput("<tr class='trhead'><td>{$rank}</td><td>{$name}</td><td>{$lev}</td><td>{$dk}</td><td>{$jd}</td><td>{$lo}</td>" . ($session['user']['clanrank'] > CLAN_MEMBER ? "<td>{$ops}</td>" : "") . "</tr>", true);
            $i = 0;
            $tot = 0;
            while ($row = db_fetch_assoc($result)) {
                $i++;
                $tot += $row['dragonkills'];
                rawoutput("<tr class='" . ($i % 2 ? "trlight" : "trdark") . "'>");
                rawoutput("<td>");
                output_notl($ranks[$row['clanrank']]);
                rawoutput("</td><td>");
                $link = "bio.php?char=" . $row['acctid'] . "&ret=" . urlencode($_SERVER['REQUEST_URI']);
                rawoutput("<a href='{$link}'>", true);
                addnav("", $link);
                output_notl("`&%s`0", $row['name']);
                rawoutput("</a>");
                rawoutput("</td><td align='center'>");
                output_notl("`^%s`0", $row['level']);
                rawoutput("</td><td align='center'>");
                output_notl("`\$%s`0", $row['dragonkills']);
                rawoutput("</td><td>");
                output_notl("`3%s`0", $row['clanjoindate']);
                rawoutput("</td><td>");
                output_notl("`#%s`0", reltime(strtotime($row['laston'])));
                rawoutput("</td>");
                rawoutput("<td>");
                rawoutput("[ <a href='runmodule.php?module=claneditor&op=membership&dt={$dt}&setrank=" . ($row['clanrank'] + 1) . "&who=" . rawurlencode($row['login']) . "'>{$promote}</a> | ");
                addnav("", "runmodule.php?module=claneditor&op=membership&dt={$dt}&setrank=" . ($row['clanrank'] + 1) . "&who=" . rawurlencode($row['login']));
                rawoutput("<a href='runmodule.php?module=claneditor&op=membership&dt={$dt}&setrank=" . ($row['clanrank'] - 1) . "&who=" . rawurlencode($row['login']) . "'>{$demote}</a> | ");
                addnav("", "runmodule.php?module=claneditor&op=membership&dt={$dt}&setrank=" . ($row['clanrank'] - 1) . "&who=" . rawurlencode($row['login']));
                rawoutput("<a href='runmodule.php?module=claneditor&op=membership&dt={$dt}&remove=" . rawurlencode($row['login']) . "' onClick=\"return confirm('{$confirm}');\">{$remove}</a> ]");
                addnav("", "runmodule.php?module=claneditor&op=membership&dt={$dt}&remove=" . rawurlencode($row['login']));
                rawoutput("</td>");
                rawoutput("</tr>");
            }
            rawoutput("</table>");
            output("`n`n`^This clan has a total of `\$%s`^ dragon kills.", $tot);
        }
        if ($dt != "" && isset($claninfo)) {
            addnav("Clan Options");
            addnav("Main View", "runmodule.php?module=claneditor&op=mview&dt={$dt}");
            addnav("Update Clan Information", "runmodule.php?module=claneditor&op=updinfo&dt={$dt}");
            addnav("Delete this Clan", "runmodule.php?module=claneditor&op=deleteclan&dt={$dt}");
            addnav("Update Members", "runmodule.php?module=claneditor&op=membership&dt={$dt}");
            addnav("Module Prefs");
            module_editor_navs("prefs-clans", "runmodule.php?module=claneditor&op=editmodule&dt=" . $claninfo['clanid'] . "&mdule=");
        }
    }
    page_footer();
}
function mouseracing_run()
{
    global $session;
    page_header("Mouse Racing");
    $jackpot = get_module_setting("jackpot");
    $op = httpget("op");
    switch ($op) {
        case "start":
            output("You wander over to a wall-mounted, glass-fronted wooden box.  Five brightly-coloured metal mouse shapes sit behind the glass, and five coin slots are mounted invitingly to their left.  Each mouse sits across a long, thin channel that runs across the board towards a chequered line.  Beneath each of these channels is another one, angled slightly upwards.  On each mouse is a number that represents how many times your stake each mouse will pay if you win.`n`nA set of numeric reels at the bottom of the machine shows the current payoff for the purple mouse - a handsome `5%s`0 Requisition tokens.`n`nMiu-Miu sees you eyeballing the machine.  \"`2It's ten Req a token, love.  They're right here, behind the bar.`0\"`n`nWill you play?  And if so, how many tokens?  You can bet on any mouse or combination or mice, and each mouse that you bet on will need its own 10-Req token.  Check the boxes and Bet!`n`n", number_format($jackpot));
            addnav("Forget it");
            addnav("Turn away", "runmodule.php?module=pub_kittania&op=continue");
            $mice = array(1 => 1, 2 => 1, 3 => 1, 4 => 1, 5 => 1);
            $bets = array();
            mouseracing_showboard($mice, $bets, $jackpot);
            break;
        case "play":
            $jackpot = httpget("jackpot");
            //get bets
            $bets = array();
            $post = httpallpost();
            foreach ($post as $beton) {
                $bets[$beton] = true;
            }
            $finish = 30;
            $mice = array(1 => 1, 2 => 1, 3 => 1, 4 => 1, 5 => 1);
            $winnings = array(1 => 20, 2 => 40, 3 => 60, 4 => 80, 5 => $jackpot);
            $slidevals = array(1 => 42, 2 => 34, 3 => 30, 4 => 28, 5 => 20);
            $amountbet = count($bets) * 10;
            //check the player made a bet
            if (!$amountbet) {
                output("You didn't bet anything!`n`n");
                mouseracing_showboard($mice, $bets, $jackpot);
                addnav("That's enough");
                addnav("Turn away", "runmodule.php?module=pub_kittania&op=continue");
                break;
            }
            increment_module_setting("played", $amountbet);
            //check the player has enough money to cover the bet
            if ($session['user']['gold'] >= $amountbet) {
                //play the game!
                if ($amountbet == 10) {
                    $cointxt = "token";
                    $slottxt = "slot";
                } else {
                    $cointxt = "tokens";
                    $slottxt = "slots";
                }
                output("You insert your %s into the relevant %s and press the \"Start\" button.  A low hum can be heard, which builds up to a high-pitched whine.  A long arm swipes across the board from right to left, pushing the mice back to their starting positions, before retracting back into its slot on the right-hand side.`n`nYou hear what sounds like a clutch mechanism engaging, and the whine dips in pitch a little, and then there's a ferocious clatter as five little steel ball bearings are violently propelled against plates behind the mice, one ball for each mouse.  After bouncing off the plates, the balls roll back down towards the flywheels that flicked them.  Depending on the position of the flywheel notches in the split-second in which the ball makes contact, the ball sometimes fires out so fast you can't see it move; other times it barely make it to the mouse.`n`nThe mouse at the top seems to be held in place with a little less tension, and the ones below look like they're held increasingly tightly.  The red mouse jerks along the track a few centimeters every time its ball makes contact, while the purple mouse barely seems to notice the impacts.`n`nYou watch the mice scuttle jerkily along the track as the machine clatters away.  It makes a hell of a racket, just like a good arcade machine should.`n`n", $cointxt, $slottxt);
                $session['user']['gold'] -= $amountbet;
                $running = true;
                $wonreq = 0;
                $jackpot += 5;
                while ($running) {
                    $mouse = e_rand(1, 5);
                    $slidenom = $slidevals[$mouse] * 10;
                    $slide = e_rand($slidenom / 2, $slidenom * 2);
                    $slide = $slide / 100;
                    $mice[$mouse] += $slide;
                    if ($mice[$mouse] >= 5 && !$seen5) {
                        $seen5 = true;
                        mouseracing_showboard($mice);
                    }
                    if ($mice[$mouse] >= 10 && !$seen10) {
                        $seen10 = true;
                        mouseracing_showboard($mice);
                    }
                    if ($mice[$mouse] >= 15 && !$seen15) {
                        $seen15 = true;
                        mouseracing_showboard($mice);
                    }
                    if ($mice[$mouse] >= 20 && !$seen20) {
                        $seen20 = true;
                        mouseracing_showboard($mice);
                    }
                    if ($mice[$mouse] >= 25 && !$seen25 && $mice[$mouse] < 30) {
                        $seen25 = true;
                        mouseracing_showboard($mice);
                    }
                    if ($mice[$mouse] >= $finish) {
                        $running = false;
                        if (array_key_exists($mouse, $bets)) {
                            $wonreq += $winnings[$mouse];
                            if ($mouse == 5) {
                                set_module_setting("jackpot", 200, "mouseracing");
                                $jackpot = 200;
                            }
                        }
                        mouseracing_showboard($mice, $bets, $jackpot);
                    }
                }
                if ($wonreq) {
                    output("A bell rings, and tokens clatter into the payout slot.  You won %s Requisition!`n`n", $wonreq);
                    $session['user']['gold'] += $wonreq;
                    increment_module_setting("won", $wonreq, "mouseracing");
                } else {
                    output("You didn't win anything this time...`n`n");
                }
                increment_module_setting("jackpot", 5, "mouseracing");
            } else {
                output("You don't have enough money to cover that bet!`n`n");
                mouseracing_showboard($mice, $bets, $jackpot);
            }
            addnav("That's enough");
            addnav("Turn away", "runmodule.php?module=pub_kittania&op=continue");
            break;
    }
    page_footer();
}
function findthebrain_run()
{
    global $session;
    page_header("Find The Brain");
    $op = httpget("op");
    switch ($op) {
        case "start":
            output("You wander over to a wall-mounted, glass-fronted wooden box.  Behind the glass, six holes are cut into the wood.  Below the glass, six coin slots gape invitingly.  A plate mounted to the bottom of the machine reads:`n`n`3`bINSTRUCTIONS`b`n1) Insert coins into slots`n2) Turn Handle`n3) BRAAAAAINS`n`n`bRULES`b`nWhen the handle is turned, a brain symbol will appear.  If your coin was in the slot corresponding to where the brain appears, the machine will pay five coins back.  You may bet on as many slots as you like.  In each round of play, multiple brains can appear, and multiple prizes can be paid.`0`n`nYou take this to mean that if you bet on all six slots, and all six slots contain brains, you'll win 30 coins back.  Which, given that each token is worth 10 Req, translates to 300 Requisition tokens.  Nice.`n`n");
            addnav("Forget it");
            addnav("Turn away", "runmodule.php?module=pub_newpittsburgh&op=continue");
            $brains = array(1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0);
            $bets = array();
            findthebrain_showboard($brains, $bets);
            break;
        case "play":
            //get bets
            $bets = array();
            $post = httpallpost();
            foreach ($post as $beton) {
                $bets[$beton] = true;
            }
            $brains = array(1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0);
            $amountbet = count($bets) * 10;
            //check the player made a bet
            if (!$amountbet) {
                output("You didn't bet anything!`n`n");
                findthebrain_showboard($brains, $bets);
                addnav("That's enough");
                addnav("Turn away", "runmodule.php?module=pub_newpittsburgh&op=continue");
                break;
            }
            increment_module_setting("played", $amountbet);
            //check the player has enough money to cover the bet
            if ($session['user']['gold'] >= $amountbet) {
                //play the game!
                if ($amountbet == 10) {
                    $cointxt = "token";
                    $slottxt = "slot";
                } else {
                    $cointxt = "tokens";
                    $slottxt = "slots";
                }
                output("You insert your %s into the relevant %s and turn the handle.  There's a series of satisfying clanking and ratcheting sounds, and then a metal plate appears in a window, painted to look like a brain.`n`n", $cointxt, $slottxt);
                $session['user']['gold'] -= $amountbet;
                $choose = 1;
                $bonuschance = e_rand(0, 100);
                while ($bonuschance > 82) {
                    $choose += 1;
                    $bonuschance = e_rand(0, 100);
                }
                for ($i = 0; $i < $choose; $i++) {
                    $chosen = e_rand(1, 6);
                    if (!$brains[$chosen] && $i > 0) {
                        output("There's a quiet sound of a spring straining against pressure, and then another brain shoots into place with a `ikerchunk.`i`n`n");
                    }
                    $brains[$chosen] = 1;
                }
                foreach ($bets as $key => $value) {
                    if ($brains[$key]) {
                        $wonreq += 50;
                    }
                }
                if ($wonreq) {
                    output("A bell rings, and tokens clatter into the payout slot.  You won %s Requisition!`n`n", $wonreq);
                    $session['user']['gold'] += $wonreq;
                    increment_module_setting("won", $wonreq, "findthebrain");
                } else {
                    output("You didn't win anything this time...`n`n");
                }
            } else {
                output("You don't have enough money to cover that bet!`n`n");
            }
            findthebrain_showboard($brains, $bets);
            addnav("That's enough");
            addnav("Turn away", "runmodule.php?module=pub_newpittsburgh&op=continue");
            break;
    }
    page_footer();
}
function settings_run()
{
    global $session;
    $op = httpget('op');
    $category = stripslashes(rawurldecode(httpget('cat'))) ?: 'Account';
    page_header("Settings - {$category}");
    switch ($op) {
        case 'save':
            $accounts = db_prefix('accounts');
            $post = httpallpost();
            unset($post['showFormTabIndex']);
            foreach ($post as $key => $val) {
                $post[$key] = stripcslashes($val);
            }
            $post['oldvalues'] = json_decode($post['oldvalues'], true);
            foreach ($post['oldvalues'] as $key => $val) {
                $post['oldvalues'][$key] = stripslashes($val);
            }
            $post = modulehook('prefs-change', $post);
            if ($post['return'] != '') {
                $return = $post['return'];
                unset($post['return']);
            }
            //Fix template changes.
            if (md5(md5($post['oldpass'])) == $session['user']['password'] && $post['newpass'] != '') {
                require_once 'lib/systemmail.php';
                $newPass = md5(md5($post['newpass']));
                db_query("UPDATE {$accounts}\n                    SET password = '******'\n                    WHERE acctid = '{$session['user']['acctid']}'");
                systemmail($session['user']['acctid'], 'Account Settings', "`@Your password was changed successfully!");
            }
            unset($post['newpass']);
            unset($post['oldpass']);
            foreach ($post as $key => $val) {
                if ($key == 'bio' && $val != $post['oldvalues']['bio']) {
                    $session['user']['bio'] = $val;
                } else {
                    if (!is_array($val) && $val != $post['oldvalues'][$key]) {
                        if (strpos($key, '__user') || strpos($key, '__check')) {
                            $moduleKey = explode('__', $key);
                            set_module_pref($moduleKey[1], $val, $moduleKey[0]);
                            unset($moduleKey);
                        } else {
                            $session['user']['prefs'][$key] = $val;
                        }
                    }
                }
            }
            $prefs = @serialize($session['user']['prefs']);
            db_query("UPDATE {$accounts} SET prefs = '{$prefs}'\n                WHERE acctid = '{$session['user']['acctid']}'");
            redirect("runmodule.php?module=settings&cat={$return}&save=true");
            addnav('Go back', 'runmodule.php?module=settings');
            break;
        default:
            $modules = db_prefix('modules');
            $userprefs = db_prefix('module_userprefs');
            $rewrite = trim(get_module_setting('rewrite'));
            $rewrite = json_decode($rewrite, true);
            $languages = getsetting('serverlanguages', 'en, English');
            $prefs = $session['user']['prefs'];
            $prefs['bio'] = $session['user']['bio'];
            $prefs['template'] = $_COOKIE['template'] ?: getsetting('defaultskin', 'jade.htm');
            $prefs['email'] = $session['user']['emailaddress'];
            $prefsFormat = ['Account' => ['bio' => 'Short biography, textarea', 'newpass' => 'New password, password', 'oldpass' => 'If you are changing your password&comma; type your old one, password', 'email' => 'Email, text'], 'Display' => ['template' => 'Skin, theme', 'language' => 'Which language do you prefer?, enum, ' . $languages, 'timestamp' => 'Show timestamps in commentary?, enum, 0, None, 1, Real Time, 2, Relative Time'], 'Game Behavior' => ['emailonmail' => 'Receive emails when you receive a mail?, bool', 'systemmail' => 'Receive emails for system messages?, bool', 'Be sure to check your email\'s spam folder and add our email as a trusted sender!, note', 'dirtyemail' => 'Allow profanity in mail?, bool', 'timeoffset' => sprintf_translate('Hours to offset time (currently %s)?, int', date($prefs['timeformat'], strtotime('now') + $prefs['timeoffset'] * 3600)), 'ihavenocheer' => 'Disable holiday text?, bool', 'nojump' => 'Disable jumping to the commentary when posting or refreshing?, bool']];
            if (count(explode(',', $languages)) < 3) {
                unset($prefs['Display']['language']);
            }
            $prefsFormat = modulehook('prefs-format', $prefsFormat);
            $prefsTemp = [];
            $modulesFound = [];
            $sql = db_query("SELECT modulename, formalname FROM {$modules}\n                WHERE infokeys LIKE '%|prefs|%'\n                AND active = 1\n                ORDER BY modulename");
            while ($row = db_fetch_assoc($sql)) {
                $formal = $row['formalname'];
                $modulesFound[$row['modulename']] = true;
                if (module_status($row['modulename']) == MODULE_FILE_NOT_PRESENT) {
                    foreach ($rewrite as $key => $moduleName) {
                        if ($moduleName == $formal || strpos($key, $row['modulename']) !== false) {
                            unset($rewrite[$key]);
                        }
                    }
                    set_module_setting('rewrite', json_encode($rewrite));
                } else {
                    $prefsTemp[$formal] = get_module_info($row['modulename'])['prefs'];
                }
                unset($prefsTemp[$formal][0]);
                foreach ($prefsTemp[$formal] as $setting => $description) {
                    $description = explode('|', $description)[0];
                    if (strpos($setting, 'user_') === false) {
                        unset($prefsTemp[$formal][$setting]);
                    } else {
                        $structuredKey = "{$row['modulename']}__{$setting}";
                        if ($rewrite[$structuredKey] != $formal) {
                            $prefsTemp[$rewrite[$structuredKey]][$structuredKey] = $description;
                        } else {
                            $prefsTemp[$formal][$structuredKey] = $description;
                        }
                        unset($prefsTemp[$formal][$setting]);
                    }
                }
                if (count($prefsTemp[$formal]) == 0) {
                    unset($prefsTemp[$formal]);
                    unset($modulesFound[$row['modulename']]);
                }
            }
            foreach ($modulesFound as $name => $true) {
                $sql = db_query("SELECT modulename, setting, value FROM {$userprefs}\n                    WHERE modulename = '{$name}'\n                    AND (setting LIKE 'user_%' OR setting LIKE 'check_%')\n                    AND userid = '{$session['user']['acctid']}'\n                    ");
                while ($row = db_fetch_assoc($sql)) {
                    $prefs["{$row['modulename']}__{$row['setting']}"] = $row['value'];
                }
            }
            $prefsFormat = array_merge_recursive($prefsFormat, $prefsTemp);
            $prefsFormat = modulehook('prefs-format', $prefsFormat);
            require_once 'lib/villagenav.php';
            villagenav();
            addnav('Refresh', 'runmodule.php?module=settings');
            addnav('Categories');
            foreach (array_keys($prefsFormat) as $int => $name) {
                addnav($name, "runmodule.php?module=settings&cat=" . rawurlencode($name));
            }
            output("`c`b`i`Q{$category} Settings`b`i`c");
            if (httpget('save')) {
                output("`@`iYour Settings have been saved!`i`n");
            }
            rawoutput("<form action='runmodule.php?module=settings&op=save' method = 'POST'>");
            require_once 'lib/showform.php';
            showform($prefsFormat[$category], $prefs);
            rawoutput(sprintf("<input type='hidden' name='oldvalues' value='%s' />", json_encode($prefs)));
            rawoutput("<input type='hidden' name='return' value='{$category}' />");
            rawoutput("</form>");
            rawoutput("<script type='text/javascript'>\n                document.getElementsByName('template')[0].onchange = function () {\n                    var index = this.selectedIndex;\n                    var selection = this.children[index].value;\n                    document.cookie = 'template=' + selection + ';expires=86400';\n                }\n\n                </script>");
            addnav('', 'runmodule.php?module=settings&op=save');
            break;
    }
    page_footer();
}
function cityprefs_run()
{
    global $session;
    page_header("City Prefs Editor");
    $op = httpget('op');
    $cityid = httpget('cityid');
    if ($cityid > 0) {
        $cityname = get_cityprefs_cityname("cityid", $cityid);
        page_header("%s Properties", $cityname);
        $modu = get_cityprefs_module("cityid", $cityid);
        if ($modu != "none") {
            addnav("Operations");
            addnav("Module settings", "configuration.php?op=modulesettings&module={$modu}");
        }
        addnav("Navigation");
        if (is_module_active("cities")) {
            addnav(array("Journey to %s", $cityname), "runmodule.php?module=cities&op=travel&city=" . urlencode($cityname) . "&su=1");
        } else {
            addnav(array("Journey to %s", $cityname), "village.php");
        }
    }
    addnav("Navigation");
    addnav("Back to the Grotto", "superuser.php");
    if (is_module_active("modloc")) {
        addnav("Module locations", "runmodule.php?module=modloc");
    }
    if ($op != "su") {
        addnav("Back to city list", "runmodule.php?module=cityprefs&op=su");
    }
    switch ($op) {
        case "su":
            addnav("Operations");
            addnav("Auto-add new cities", "runmodule.php?module=cityprefs&op=update");
            $id = translate_inline("ID");
            $name = translate_inline("City Name");
            $module = translate_inline("Module");
            $edit = translate_inline("Edit");
            $sql = "select * from " . db_prefix("cityprefs");
            $result = db_query($sql);
            rawoutput("<table border='0' cellpadding='3' cellspacing='0' align='center'><tr class='trhead'><td style=\"width:50px\">{$id}</td><td style='width:150px' align=center>{$name}</td><td align=center>{$module}</td><td align=center>{$edit}</td></tr>");
            for ($i = 0; $i < db_num_rows($result); $i++) {
                $row = db_fetch_assoc($result);
                $vloc = array();
                $vname = getsetting("villagename", LOCATION_FIELDS);
                $vloc[$vname] = "village";
                $vloc = modulehook("validlocation", $vloc);
                ksort($vloc);
                reset($vloc);
                foreach ($vloc as $loc => $val) {
                    if ($loc == $row['cityname']) {
                        $area = $val;
                    }
                }
                rawoutput("<tr class='" . ($i % 2 ? "trlight" : "trdark") . "'><td align=center>" . $row['cityid'] . "</td><td align=center>");
                output_notl("%s", $row['cityname']);
                rawoutput("</td><td align=center>");
                output_notl("%s", $row['module']);
                rawoutput("</td><td align=center>");
                rawoutput("<a href='runmodule.php?module=cityprefs&op=editmodule&area=" . htmlentities($val) . "&cityid=" . $row['cityid'] . "'>{$edit}</a></td></tr>");
                addnav("", "runmodule.php?module=cityprefs&op=editmodule&area=" . htmlentities($val) . "&cityid=" . $row['cityid'] . "");
            }
            rawoutput("</table>");
            break;
        case "update":
            $vloc = array();
            $vloc = modulehook("validlocation", $vloc);
            ksort($vloc);
            reset($vloc);
            $out = 0;
            foreach ($vloc as $loc => $val) {
                $sql = "select cityname from " . db_prefix("cityprefs") . " where cityname='" . addslashes($loc) . "'";
                $result = db_query($sql);
                if (db_num_rows($result) == 0) {
                    $sql = "select modulename from " . db_prefix("module_settings") . " where value='" . addslashes($loc) . "' and setting='villagename'";
                    $result = db_query($sql);
                    $row = db_fetch_assoc($result);
                    $sql = "INSERT INTO " . db_prefix("cityprefs") . " (module,cityname) VALUES ('" . $row['modulename'] . "','" . addslashes($loc) . "')";
                    db_query($sql);
                    $out = 1;
                    output("`n`@%s`0 was added.", $loc);
                }
            }
            if ($out == 0) {
                output("There were no new locations found.");
            }
            break;
        case "editmodule":
            //code from clan editor by CortalUX
        //code from clan editor by CortalUX
        case "editmodulesave":
            addnav("Operations");
            addnav("Edit city name and module", "runmodule.php?module=cityprefs&op=editcity&cityid={$cityid}");
            addnav("Delete this city", "runmodule.php?module=cityprefs&op=delcity&cityid={$cityid}");
            $mdule = httpget("mdule");
            if ($mdule == "") {
                output("Select a pref to edit.`n`n");
            } else {
                if ($op == "editmodulesave") {
                    // Save module prefs
                    $post = httpallpost();
                    reset($post);
                    while (list($key, $val) = each($post)) {
                        set_module_objpref("city", $cityid, $key, stripslashes($val), $mdule);
                    }
                    output("`^Saved!`0`n");
                }
                require_once "lib/showform.php";
                rawoutput("<form action='runmodule.php?module=cityprefs&op=editmodulesave&cityid={$cityid}&mdule={$mdule}' method='POST'>");
                module_objpref_edit("city", $mdule, $cityid);
                rawoutput("</form>");
                addnav("", "runmodule.php?module=cityprefs&op=editmodulesave&cityid={$cityid}&mdule={$mdule}");
                //code from clan editor by CortalUX
            }
            addnav("Module Prefs");
            module_editor_navs("prefs-city", "runmodule.php?module=cityprefs&op=editmodule&cityid={$cityid}&mdule=");
            break;
        case "editcity":
            output("Changing these values will not affect the city itself, just what city is associated with the preferences.  This is useful if you want to preserve prefs after removing a city.");
            addnav("Navigation");
            addnav("Back to city properties", "runmodule.php?module=cityprefs&op=editmodule&cityid={$cityid}");
            $sql = "select * from " . db_prefix("cityprefs") . " where cityid={$cityid}";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            $module = $row['module'];
            $city = $row['cityname'];
            $submit = translate_inline("Submit");
            rawoutput("<form action='runmodule.php?module=cityprefs&op=editcity2&cityid={$cityid}' method='POST'>");
            addnav("", "runmodule.php?module=cityprefs&op=editcity2&cityid={$cityid}");
            rawoutput("<input name='cityname' id='cityname' value='{$city}' size='40' maxlength='255'><br>");
            rawoutput("<input name='modulename' id='modulename' value='{$module}' size='40' maxlength='255'><br>");
            rawoutput("<input type='submit' class='button' value='{$submit}'></form>");
            break;
        case "editcity2":
            addnav("Navigation");
            addnav("Back to city properties", "runmodule.php?module=cityprefs&op=editmodule&cityid={$cityid}");
            $cityname = httppost('cityname');
            $modulename = httppost('modulename');
            db_query("update " . db_prefix("cityprefs") . " set cityname='" . $cityname . "',module='" . $modulename . "' where cityid={$cityid}");
            output("The city name is now %s and the module name is %s.", $cityname, $modulename);
            break;
        case "delcity":
            addnav("Navigation");
            $cityid = httpget('cityid');
            addnav("Back to city properties", "runmodule.php?module=cityprefs&op=editmodule&cityid={$cityid}");
            addnav("Options");
            addnav("Yes, delete it", "runmodule.php?module=cityprefs&op=delcity2&cityid={$cityid}");
            output("Are you sure you want to delete this city?  All city prefs will be deleted.  If you would like to retain these settings for a future city, just rename it.");
            break;
        case "delcity2":
            addnav("Navigation");
            addnav("Back to city properties", "runmodule.php?module=cityprefs&op=editmodule&cityid={$cityid}");
            $cityid = httpget('cityid');
            db_query("delete from " . db_prefix("cityprefs") . " where cityid={$cityid}");
            output("The city has been deleted.");
            break;
    }
    page_footer();
}
function module_do_event($type, $module, $allowinactive = false, $baseLink = false)
{
    global $navsection;
    if ($baseLink === false) {
        global $PHP_SELF;
        $baseLink = substr($PHP_SELF, strrpos($PHP_SELF, "/") + 1) . "?";
    } else {
        //debug("Base link was specified as $baseLink");
        //debug(debug_backtrace());
    }
    // Save off the mostrecent module since having that change can change
    // behaviour especially if a module calls modulehooks itself or calls
    // library functions which cause them to be called.
    if (!isset($mostrecentmodule)) {
        $mostrecentmodule = "";
    }
    $mod = $mostrecentmodule;
    $_POST['i_am_a_hack'] = 'true';
    if (injectmodule($module, $allowinactive)) {
        $oldnavsection = $navsection;
        tlschema("module-{$module}");
        $fname = $module . "_runevent";
        $fname($type, $baseLink);
        tlschema();
        //hook into the running event, but only in *this* running event, not in all
        modulehook("runevent_{$module}", array("type" => $type, "baselink" => $baseLink, "get" => httpallget(), "post" => httpallpost()));
        //revert nav section after we're done here.
        $navsection = $oldnavsection;
    }
    $mostrecentmodule = $mod;
}
         }
     }
 } else {
     $session['message'] = translate_inline("`4Error, your login was incorrect`0");
     //now we'll log the failed attempt and begin to issue bans if
     //there are too many, plus notify the admins.
     $sql = "DELETE FROM " . db_prefix("faillog") . " WHERE date<'" . date("Y-m-d H:i:s", strtotime("-" . getsetting("expirecontent", 180) / 4 . " days")) . "'";
     checkban($name, true);
     db_query($sql);
     $sql = "SELECT acctid FROM " . db_prefix("accounts") . " WHERE login='******'";
     $result = db_query($sql);
     if (db_num_rows($result) > 0) {
         // just in case there manage to be multiple accounts on
         // this name.
         while ($row = db_fetch_assoc($result)) {
             $post = httpallpost();
             $sql = "INSERT INTO " . db_prefix("faillog") . " VALUES (0,'" . date("Y-m-d H:i:s") . "','" . addslashes(serialize($post)) . "','{$_SERVER['REMOTE_ADDR']}','{$row['acctid']}','{$_COOKIE['lgi']}')";
             db_query($sql);
             $sql = "SELECT " . db_prefix("faillog") . ".*," . db_prefix("accounts") . ".superuser,name,login FROM " . db_prefix("faillog") . " INNER JOIN " . db_prefix("accounts") . " ON " . db_prefix("accounts") . ".acctid=" . db_prefix("faillog") . ".acctid WHERE ip='{$_SERVER['REMOTE_ADDR']}' AND date>'" . date("Y-m-d H:i:s", strtotime("-1 day")) . "'";
             $result2 = db_query($sql);
             $c = 0;
             $alert = "";
             $su = false;
             while ($row2 = db_fetch_assoc($result2)) {
                 if ($row2['superuser'] > 0) {
                     $c += 1;
                     $su = true;
                 }
                 $c += 1;
                 $alert .= "`3{$row2['date']}`7: Failed attempt from `&{$row2['ip']}`7 [`3{$row2['id']}`7] to log on to `^{$row2['login']}`7 ({$row2['name']}`7)`n";
             }
function addcommentary()
{
    global $session, $emptypost, $afk, $dni;
    $section = httppost('section');
    $talkline = httppost('talkline');
    $schema = httppost('schema');
    $comment = trim(httppost('insertcommentary'));
    $counter = httppost('counter');
    $remove = URLDecode(httpget('removecomment'));
    $restore = URLDecode(httpget('restorecomment'));
    //debug(httpallpost());
    if (httpget("bulkdelete")) {
        $everything = httpallpost();
        foreach ($everything as $key => $val) {
            if (substr($key, 0, 14) == "deletecomment_") {
                $del = str_replace("deletecomment_", "", $key);
                removecommentary($del, "Mass deletion by " . $session['user']['name'], $session['user']['acctid']);
            }
        }
    }
    if ($remove > 0) {
        removecommentary($remove, "Moderated by " . $session['user']['name'], $session['user']['acctid']);
    }
    if ($restore > 0) {
        restorecommentary($restore, "Restored by " . $session['user']['name'], $session['user']['acctid']);
    }
    if (!$comment) {
        return false;
    }
    if ($session['user']['chatloc'] == "DNI") {
        $dni = true;
    }
    $colors = array("1" => "colDkBlue", "2" => "colDkGreen", "3" => "colDkCyan", "4" => "colDkRed", "5" => "colDkMagenta", "6" => "colDkYellow", "7" => "colDkWhite", "~" => "colBlack", "!" => "colLtBlue", "@" => "colLtGreen", "#" => "colLtCyan", "\$" => "colLtRed", "%" => "colLtMagenta", "^" => "colLtYellow", "&" => "colLtWhite", ")" => "colLtBlack", "e" => "colDkRust", "E" => "colLtRust", "g" => "colXLtGreen", "G" => "colXLtGreen", "j" => "colMdGrey", "k" => "colaquamarine", "K" => "coldarkseagreen", "l" => "colDkLinkBlue", "L" => "colLtLinkBlue", "m" => "colwheat", "M" => "coltan", "p" => "collightsalmon", "P" => "colsalmon", "q" => "colDkOrange", "Q" => "colLtOrange", "R" => "colRose", "T" => "colDkBrown", "t" => "colLtBrown", "V" => "colBlueViolet", "v" => "coliceviolet", "x" => "colburlywood", "X" => "colbeige", "y" => "colkhaki", "Y" => "coldarkkhaki");
    if (substr($comment, 0, 9) == "/chatcol ") {
        $ucol = substr($comment, 9, 1);
        if (!isset($colors[$ucol])) {
            output("`c`b`4Invalid default talk colour`b`nYou entered an invalid colour code, please try again.`0`c`n");
            return false;
        } else {
            $session['user']['prefs']['ucol'] = $ucol;
            output_notl("`c`bDefault talk colour changed`b`n`" . $ucol . "This is your new default commentary dialogue colour.  When you type in commentary areas, this colour will show up automatically.  If you're an Extra-Awesome Site Supporter, you can also change the colour of your character's dialogue during quests, monster fights and other in-game areas using the /talkcol switch, in the same way you just used the /chatcol switch.`0`c`n");
            return false;
        }
    } else {
        if (substr($comment, 0, 9) == "/talkcol ") {
            $ucol = substr($comment, 9, 1);
            if (!isset($colors[$ucol])) {
                output("`c`b`4Invalid default talk colour`b`nYou entered an invalid colour code, please try again.`0`c`n");
                return false;
            } else {
                $session['user']['prefs']['ugcol'] = $ucol;
                if ($session['user']['donation'] >= 2000) {
                    output_notl("`c`bDefault talk colour changed`b`n`" . $ucol . "This is your new default in-game dialogue colour.  This is the colour we'll use to represent your character's dialogue during quests, monster encounters, and other in-game things.  If you choose a colour commonly used by monsters or other characters, you might have problems figuring out who's talking - if that's the case, you can reset to the default with \"/talkcol #\".  You can also change your default colour for commentary areas by using the /chatcol switch, in the same way you just used /talkcol.`0`c`n");
                } else {
                    output("`c`bNot enough Supporter Points`b`nSorry, but due to the extra system load that the /talkcol switch uses, this feature is restricted to players with more than 2,000 Supporter Points.`0`c`n");
                }
                return false;
            }
        }
    }
    if ($comment == strtoupper($comment)) {
        //this is an all-uppercase entry.  Do not add this comment to the database; instead, check it for built-in stuff like AFK and GREM, then run it through the commentarycommand hook
        if ($comment == "AFK" || $comment == "BRB") {
            $session['user']['chatloc'] = "AFK";
            $afk = true;
            output("`0`n`c`bYou are Away From the Keyboard until you load another page.`b`c`n");
            return false;
        }
        if ($comment == "DNI") {
            if ($session['user']['chatloc'] == "DNI") {
                $session['user']['chatloc'] = $section;
                $dni = false;
                output("`0`n`c`bYou are no longer in Do Not Interrupt status.`b`c`n");
            } else {
                $session['user']['chatloc'] = "DNI";
                $dni = true;
                output("`0`n`c`bYou are in Do Not Interrupt status.  Type DNI again to leave.`b`nDNI status is used for whenever you're doing or saying something that means other players shouldn't try to interact with you.  For example, when two or more characters are chatting just outside of the main group of characters, and other characters shouldn't be able to hear them.`c`n");
            }
            return false;
        }
        if ($comment == "GREM") {
            //handle deleting the player's last comment
            $sql = "SELECT * FROM " . db_prefix("commentary") . " WHERE author='" . $session['user']['acctid'] . "' ORDER BY commentid DESC LIMIT 1";
            $result = db_query($sql);
            while ($row = db_fetch_assoc($result)) {
                $now = time();
                $then = strtotime($row['postdate']);
                $ago = $now - $then;
                if ($ago < 120) {
                    removecommentary($row['commentid'], "Typo Gremlin", $session['user']['acctid']);
                    output("`0`n`c`bA nearby Typo Gremlin notices the peculiar tastiness of your previous comment.  Within moments, a small horde of them have descended upon your words, and consumed them.`b`c`n");
                } else {
                    output("`0`n`c`bThe Typo Gremlins turn up their nose at your latest comment - it's just too old.  They have no taste for stale words.`b`c`n");
                }
            }
            return false;
        }
        $hookcommand = array('command' => $comment, 'section' => $section);
        $returnedhook = modulehook("commentarycommand", $hookcommand);
        if (!$returnedhook['skipcommand']) {
            //if for some reason you're going to involve a command that can be a mix of upper and lower case, set $args['skipcommand'] and $args['ignore'] to true and handle it in postcomment instead.
            if (!$returnedhook['processed']) {
                output("`c`b`JCommand Not Recognized`b`0`nWhen you type in ALL CAPS, the game doesn't think you're talking to other players; it thinks you're trying to perform an action within the game.  For example, typing `#GREM`0 will remove the last comment you posted, as long as you posted it less than two minutes ago.  Typing `#AFK`0 or `#BRB`0 will turn your online status bar grey, so that people know you're `#A`0way `#F`0rom the `#K`0eyboard (or, if you prefer, that you'll `#B`0e `#R`0ight `#B`0ack).  Typing `#DNI`0 will let other players know that you're busy talking to one particular player - maybe somewhere off-camera - and that you don't want to be interrupted right now.`nSome areas have special hidden commands or other easter eggs that you can hunt for.  This time around, you didn't trigger anything special.`c`0`n");
            }
            return false;
        }
    }
    if ($section || $talkline || $comment) {
        $tcom = color_sanitize($comment);
        if ($tcom == "" || $tcom == ":" || $tcom == "::" || $tcom == "/me") {
            $emptypost = 1;
        } else {
            $comment = comment_sanitize($comment);
            injectcommentary($section, $talkline, $comment);
        }
    }
}
function homepage_run()
{
    require_once "common.php";
    require_once "lib/is_email.php";
    require_once "lib/checkban.php";
    require_once "lib/http.php";
    page_header("Welcome to Improbable Island");
    global $session;
    $r = httpget('r');
    $name = sanitize_name(getsetting("spaceinname", 0), httppost('name'));
    $pass1 = httppost('pass1');
    $pass2 = httppost('pass2');
    $sex = httppost('gender');
    $email = httppost('email');
    $passlen = (int) httppost("passlen");
    if (substr($pass1, 0, 5) != "!md5!" && substr($pass1, 0, 6) != "!md52!") {
        $passlen = strlen($pass1);
    }
    if (!$sex) {
        $outputgender = "man";
    } else {
        $outputgender = "woman";
    }
    switch (httpget('op')) {
        case "changeskin":
            $skin = httpget('skin');
            if ($skin > "") {
                setcookie("template", $skin, strtotime("+45 days"));
                $_COOKIE['template'] = $skin;
            }
            redirect("index.php?r={$r}", "Home page module changing skin");
            break;
        case "gamecredits":
            page_header("Game Credits");
            output("Improbable Island's plot, characters, Stamina system, Item system, ScrapBots system, Races, Implants, Mounts and probably a few other things were created by Dan Hall, AKA Admin CavemanJoe.`nMany monsters were written by Improbable Island's players.`nImprobable Island runs on a modified version of Legend of the Green Dragon 1.1.1, DragonPrime Edition, which was created by the good folks at dragonprime.com.`nThe DragonPrime Edition was based on the original Legend of the Green Dragon, created by Eric Stevens and J.T. Traub as a homage to Legend of the Red Dragon by Seth Able.`n`nPut simply, Improbable Island is a hodgepodged Frankenstein of a game, but we get by.`n`nThe source code to Legend of the Green Dragon 1.1.1 +DP is available at dragonprime.net.`nThe source code to the most recent version of Legend of the Green Dragon written by Stevens and Traub (upon which the DragonPrime edition is based) is available at lotgd.net.`nThe source code of Improbable Island will be made available on Improbable Labs shortly - for now, it is available on request.`n`nFor more information about Improbable Island and Legend of the Green Dragon, check out the links to the left.");
            addnav("Further Reading");
            addnav("Module Credits", "about.php?op=listmodules&r=" . $r);
            addnav("Creative Commons License Info", "about.php?op=license&r=" . $r);
            addnav("Original Legend of the Green Dragon \"About\" page", "about.php?r=" . $r);
            addnav("Back to the Home Page");
            addnav("Back", "home.php?r=" . $r);
            break;
        case 0:
            $tripfilter = 0;
            $sname = strtolower($name);
            if (substr_count($sname, "nigger") || substr_count($sname, "c**t") || substr_count($sname, "dick") && !substr_count($sname, "dicke") || substr_count($sname, "f****t") || substr_count($sname, "v****a") || substr_count($sname, "pussy") || substr_count($sname, "shit") || substr_count($sname, "wank") || substr_count($sname, "bollocks") || substr_count($sname, "clitoris") || substr_count($sname, "f**k") || substr_count($sname, "d***o") || substr_count($sname, "t**s") || substr_count($sname, "piss") || substr_count($sname, "penis")) {
                output("The gatekeeper's biro stops mid-scrawl.  He looks up at you.  \"`6Seriously?`0\" he asks.  \"`6You're gonna walk into a pub, are you, and espy some sweet young thing who puts your heart all aflutter, and when they ask you your name, you're gonna say \"My name's %s, what's yours?\"  Is that right?`0\"`n`nYou shuffle your feet sheepishly.  Let's try this again.`n`n", $name);
                $redoform = 1;
            }
            //todo: redirect when numbers appear in name
            $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE login='******'";
            $result = db_query($sql);
            if (db_num_rows($result) > 0) {
                output("\"`6Oh, dear...`0\" says the gatekeeper.  \"`6See, we've already got a %s drafted in, here.`0\"`n`nYou stare at him for a moment.  \"`#What in the hell difference does `ithat`i make?!`0\"`n`n\"`6Well, you see, it's easier if everyone has different names, and, well, the computer that handles these forms...`0\" he shrugs.  \"`6It's not particularly bright.`0\"`n`nYou nod.  Computers haven't been terribly bright since the EMP wars.`n`n\"`6Just put down any old thing,`0\" says the gatekeeper.  \"`6I doubt it'll matter much.`0\"`n`n", $name);
                $redoform = 1;
            } else {
                if (strlen($name) < 3) {
                    output("\"`6Oh, dear...`0\" says the gatekeeper.  \"`6I'm afraid that name's just too short.`0\"`n`nYou stare at him for a moment.  \"`#What in the hell difference does `ithat`i make?!`0\"`n`n\"`6Well, you see, the computer that handles these forms...`0\" he shrugs.  \"`6It's not particularly bright.`0\"`n`nYou nod.  Computers haven't been terribly bright since the EMP wars.`n`n\"`6Just put down any old thing,`0\" says the gatekeeper.  \"`6I doubt it'll matter much.`0\"`n`n");
                    $redoform = 1;
                } else {
                    if (strlen($name) > 25) {
                        output("\"`6Oh, dear...`0\" says the gatekeeper.  \"`6I'm afraid that name's just too long.`0\"`n`nYou stare at him for a moment.  \"`#What in the hell difference does `ithat`i make?!`0\"`n`n\"`6Well, you see, the computer that handles these forms...`0\" he shrugs.  \"`6It's not particularly bright.`0\"`n`nYou nod.  Computers haven't been terribly bright since the EMP wars.`n`n\"`6Just put down any old thing,`0\" says the gatekeeper.  \"`6I doubt it'll matter much.`0\"`n`n");
                        $redoform = 1;
                    }
                }
            }
            if ($redoform) {
                rawoutput("<form action='runmodule.php?module=homepage&op=0&r={$r}' method='POST'\">\"<span class=\"colLtCyan\">Well then, I suppose you can call me <input name='name' id=\"name\" accesskey='u' size='12'>.</span>\"  Like you're gonna give him your real name anyway.");
                rawoutput("<br /><div align=\"center\"><input type='submit' value='Carry On' class='button'></div><br /><br /></form>");
                addnav("", "runmodule.php?module=homepage&op=0&r=" . $r);
            } else {
                output("The gatekeeper smiles.  \"`6Okay, %s - now, if you don't mind my asking, are you over eighteen?`0\"`n`n", $name);
                output("You grimace.  \"`#Mate, I've been drafted into some sort of war.  If I'm under eighteen, `isomeone's`i in trouble.`0\"`n`n\"`6That as may be,\"`0 says the gatekeeper, \"`6I've got to ask anyway, before we go any further.  Just to make sure.`0\"`n`n`n");
                rawoutput("<table width=80% align=center style=\"border: 1px solid #990000;\"><tr><td class=\"trlight\">");
                output("`c`\$`bWARNING`b`c`7Although most folks would consider Improbable Island to be work-safe by virtue of it being entirely text-based, I should warn you that you probably wouldn't want to invite the vicar over for tea and scones while playing.`n`nImprobable Island contains `bfoetid Midget Brothels`b and other rather adult (but very silly) situations, and is intended for equally silly `badults`b.  If you're not an adult yet, why not check out Kingdom of Loathing, zOMG, Legends of Zork, Puzzle Pirates, Adventure Quest - there's loads of other browser games, really.`n`n");
                output("And if you `iare`i an adult, and want to carry on - knowing that you're about to be subjected to a barrage of sex, drugs and sausage rolls - by all means, continue with the story and have fun.`0");
                rawoutput("</td></tr></table>");
                output("`n`nYou realise you've been staring off into space for a moment, and you blink a couple of times.  \"`#Sorry, I think I spaced out for a minute there.`0\"");
                rawoutput("<form action='runmodule.php?module=homepage&op=1&r={$r}' method='POST'\">");
                rawoutput("<input type='hidden' name='name' value=\"{$name}\">");
                rawoutput("<br /><div align=\"center\"><input type='submit' value='Yes, I am indeed over eighteen.  Now how about some pants?' class='button'></div></form>");
                addnav("", "runmodule.php?module=homepage&op=1&r=" . $r);
            }
            break;
        case 1:
            output("\"`6Yes, yes, we'll sort you out with some pants in just a minute, %s, don't you worry.`0\"  He reaches down out of sight, and pulls up a sheet of paper and a pen.  You see the words \"CONTESTANT REGISTRATION AND PANTS REQUEST FORM 3A\" printed at the top of the page.  Hell, maybe we're getting somewhere.`n`n\"`6Now, might I ask your gender?`0\"`n`nYou hesitate, dumbstruck.  \"`#I'm stood here `istark naked`i, right in front of you.`0\"`n`n\"`6And thanks to all those bloody Zap grenades going off all the time, all I see is a person-shaped blur who won't be getting any pants until they help me fill out this bloody form!`0\" replies the gatekeeper.`n`n", $name);
            rawoutput("<form action='runmodule.php?module=homepage&op=2&r={$r}' method='POST'\"><input type='radio' name='gender' value='0' checked>\"<span class=\"colLtCyan\"><em>Male</em>, thank you very much.</span>\"<br /><input type='radio' name='gender' value='1'>\"<span class=\"colLtCyan\"><em>Female</em>, thank you very much.</span>\"");
            rawoutput("<input type='hidden' name='name' value=\"{$name}\">");
            rawoutput("<br /><div align=\"center\"><input type='submit' value='And is my voice really that androgynous?' class='button'></div><br /><br /></form>");
            addnav("", "runmodule.php?module=homepage&op=2&r=" . $r);
            break;
        case 2:
            output("\"`6No, %s, you `ido`i sound like a %s, but I like a little joke.`0\" the gatekeeper grins.  ", $name, $outputgender);
            output("\"`6Now, can I just take your E-mail address, please?`0\"`n`nMentally, you file the man under \"Nutters.\"  \"`#Hell, we only got `itelevision`i back about a year ago!  You know full well that computers don't work any more.`0\"`n`n\"`6And they haven't done since the EMP bombings years back, yes.  That's the interesting thing -`0\" he leans forward and lowers his voice.  \"`6I've heard tell that there `iare`i some working computers here.  Proper `isilicon`i ones, not these silly relay-and-vacuum-tube monstrosities we use today, where you think you're rich if you've got sixteen bytes of RAM to play with.  We're talking `iterabytes`i, here!  Just `iimagine`i what we could do with that sort of power!`0\"`n`nYou remember what you did with those resources when you had them, only a few years ago.  You played silly browser games on the Internet.`n`n\"`6Anyway - it's an old, old form, from back in the day when it mattered.  Let's take your E-mail address, so we can have something in the space.`0\"  He grins.  \"`6It's not like I'm going to send you any spam, now, is it?`0\"`n`n");
            rawoutput("<form action='runmodule.php?module=homepage&op=3&r={$r}' method='POST'\">\"<span class=\"colLtCyan\">Fine - as far as I remember, it's <input name='email' id=\"email\" accesskey='e' size='25'>.</span>\"");
            rawoutput("<input type='hidden' name='name' value=\"{$name}\">");
            rawoutput("<input type='hidden' name='gender' value=\"{$sex}\">");
            rawoutput("<br /><div align=\"center\"><input type='submit' value='NOW may I have some pants?' class='button'></div></form>");
            rawoutput("<br /><br /><table width=80% align=center style=\"border: 1px solid #990000;\"><tr><td class=\"trlight\">");
            output("`7He ain't kidding - Improbable Island doesn't spam.  Your E-mail address is used to recover your password if you forget it, and (optionally) to let you know if someone sends you a message in-game - that's it.  We don't use it for anything else, and we never let anyone else see it.`n`nOr, you can continue without entering an E-mail address - but you won't be notified of anything, and you won't be able to recover your password if you lose it!`n");
            rawoutput("<form action='runmodule.php?module=homepage&op=3&override=1&r={$r}' method='POST'\"><input name='email' type='hidden' value='not given'>");
            rawoutput("<input type='hidden' name='name' value=\"{$name}\">");
            rawoutput("<input type='hidden' name='gender' value=\"{$sex}\">");
            rawoutput("<br /><div align=\"center\"><input type='submit' value='Continue without an E-mail address' class='button'></div></form>");
            rawoutput("</td></tr></table>");
            addnav("", "runmodule.php?module=homepage&op=3&override=1&r=" . $r);
            break;
        case 3:
            if ($sexdisplay = "Male") {
                $formalgenderdisplay = "man";
            } else {
                $formalgenderdisplay = "lady";
            }
            if (httpget('override') == 1) {
                output("\"`6Fair enough, then, fair enough - I guess it's pretty pointless asking for an E-mail address when they're impossible to use anyway.`0\"`n`n");
                $carryon = 1;
            } else {
                //validate E-mail
                if (!is_email($email)) {
                    output("The gatekeeper frowns.  \"`6That certainly doesn't `isound`i like an E-mail address.  Are you sure that's right?`0\"`n`nLet's try that again.`n");
                } else {
                    //check for duplicates
                    $sql = "SELECT login FROM " . db_prefix("accounts") . " WHERE emailaddress='{$email}'";
                    $result = db_query($sql);
                    if (db_num_rows($result) > 0) {
                        output("The gatekeeper frowns.  \"`6Are you taking the mick, my good %s?  That E-mail is already in my book, here.  You can only sign up once, you know.`0\"`n`nLet's try that again.`n", $formalgenderdisplay);
                    } else {
                        //email is good, request password
                        output("The gatekeeper grins. \"`6I'm sure if you find those computers, you'll be using that address again soon.`0\"`n`n");
                        $carryon = 1;
                    }
                }
            }
            if ($carryon) {
                rawoutput("<script language='JavaScript' src='lib/md5.js'></script>");
                rawoutput("<script language='JavaScript'>\r\n\t\t\t\t<!--\r\n\t\t\t\tfunction md5pass(){\r\n\t\t\t\t\t// encode passwords\r\n\t\t\t\t\tvar plen = document.getElementById('passlen');\r\n\t\t\t\t\tvar pass1 = document.getElementById('pass1');\r\n\t\t\t\t\tplen.value = pass1.value.length;\r\n\r\n\t\t\t\t\tif(pass1.value.substring(0, 5) != '!md5!') {\r\n\t\t\t\t\t\tpass1.value = '!md5!'+hex_md5(pass1.value);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tvar pass2 = document.getElementById('pass2');\r\n\t\t\t\t\tif(pass2.value.substring(0, 5) != '!md5!') {\r\n\t\t\t\t\t\tpass2.value = '!md5!'+hex_md5(pass2.value);\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t}\r\n\t\t\t\t//-->\r\n\t\t\t\t</script>");
                if (httpget('override')) {
                    rawoutput("<form action='runmodule.php?module=homepage&op=4&override=1&r={$r}' method='POST' onSubmit=\"md5pass();\">");
                } else {
                    rawoutput("<form action='runmodule.php?module=homepage&op=4&r={$r}' method='POST' onSubmit=\"md5pass();\">");
                }
                rawoutput("<input type='hidden' name='passlen' id='passlen' value='0'>");
                rawoutput("<input type='hidden' name='name' value=\"{$name}\">");
                rawoutput("<input type='hidden' name='gender' value=\"{$sex}\">");
                rawoutput("<input type='hidden' name='email' value=\"{$email}\">");
                output("You hear a rustling in the bushes behind you, and turn to look.  Branches sway a couple of feet above head-height - there's something there.`n`nYou're suddenly even more aware that you're naked and unarmed.`n`nYou turn back to the gatekeeper.  \"`#Is this going to take long?`0\"`n`n\"`6No, no, we're nearly done now.`0\"  He reaches down beneath his counter, and brings up a stack of shiny silver coins.  \"`6Here's eighty Requisition tokens to get you started.`0\"`n`nYou consider asking him where the hell he thinks you're going to keep them, but a low `4`igrowling`i`0 sound changes your mind very quickly.`n`n\"`#Let me in.  Forget the pants, just let me in.`0\"`n`n\"`6One moment, sunshine, one moment.  I need a password from you.`0\"`n`n\"`#You're kidding me!  Did you `ihear`i that?!`0\"`n`n\"`6Yes, I heard it, and you'll get inside faster if you listen to me.  You need to make up a password - at least four characters in length.  I know, it sounds like a silly thing to ask, but there's a very good reason for it - you see...`0\"  The growling intensifies, and you look back towards the jungle.`n`nThere's a face.  It's looking at you from between the very leafy branches of a tree.  It's eight feet off the ground and shaped like a gas mask, its eyes as big as fists and deep, bright orange, shining against its jet black carapace.`n`n\"`#Don't care,`0\" you say quietly.  \"`#Really, really don't care.  Just put down ");
                rawoutput("<input type='password' name='pass1' id='pass1'>");
                output(".`0\"`n`nThe gatekeeper scribbles on his form.  \"`6Sorry, just run that past me again?`0\"`n`n\"`#I said ");
                rawoutput("<input type='password' name='pass2' id='pass2'>");
                output("!`0\"`n`n");
                rawoutput("<div align=\"center\"><input type='submit' value='Now let me in, damn it!' class='button'></div></form>");
            } else {
                //output the E-mail form again
                rawoutput("<form action='runmodule.php?module=homepage&op=3&r={$r}' method='POST'\">\"<span class=\"colLtCyan\">Fine - as far as I remember, it's <input name='email' id=\"email\" accesskey='e' size='25'>.</span>\"");
                rawoutput("<input type='hidden' name='name' value=\"{$name}\">");
                rawoutput("<input type='hidden' name='gender' value=\"{$sex}\">");
                rawoutput("<br /><div align=\"center\"><input type='submit' value='NOW may I have some pants?' class='button'></div></form>");
                rawoutput("<br /><br /><table width=80% align=center style=\"border: 1px solid #990000;\"><tr><td class=\"trlight\">");
                output("`7He ain't kidding - Improbable Island doesn't spam.  Your E-mail address is used to recover your password if you forget it, and (optionally) to let you know if someone sends you a message in-game - that's it.  We don't use it for anything else, and we never let anyone else see it.`n`nOr, you can continue without entering an E-mail address - but you won't be notified of anything, and you won't be able to recover your password if you lose it!`n");
                rawoutput("<form action='runmodule.php?module=homepage&op=3&override=1&r={$r}' method='POST'\"><input name='email' type='hidden' value='Not Given'>");
                rawoutput("<input type='hidden' name='name' value=\"{$name}\">");
                rawoutput("<input type='hidden' name='gender' value=\"{$sex}\">");
                rawoutput("<br /><div align=\"center\"><input type='submit' value='Continue without an E-mail address' class='button'></div></form>");
                rawoutput("</td></tr></table>");
                addnav("", "runmodule.php?module=homepage&op=3&override=1&r=" . $r);
            }
            break;
        case 4:
            output("`0The thing steps out from behind the trees.  Its chitinous body is thin, shiny, and angular.  There are no hands or feet; its legs and arms terminate in sharp points.  Each time it takes a step, it leaves a deep, round piercing in the ground.  You back up against the gatekeeper's hut, unable to take your eyes off the beast.`n`n");
            if ($passlen <= 3) {
                output("\"`6I'm not sure you heard me right, mate,`0\" says the gatekeeper quietly from behind you.  \"`6I need four characters or more.  No rush.`0\"`n`n");
                $tryagain = true;
            }
            if ($pass1 != $pass2) {
                output("\"`6Sorry, mate, I think I heard two different things,`0\" says the gatekeeper quietly from behind you.  \"`6Wanna repeat that?  No rush.`0\"`n`n");
                $tryagain = true;
            }
            if ($tryagain) {
                rawoutput("<script language='JavaScript' src='lib/md5.js'></script>");
                rawoutput("<script language='JavaScript'>\r\n\t\t\t\t<!--\r\n\t\t\t\tfunction md5pass(){\r\n\t\t\t\t\t// encode passwords\r\n\t\t\t\t\tvar plen = document.getElementById('passlen');\r\n\t\t\t\t\tvar pass1 = document.getElementById('pass1');\r\n\t\t\t\t\tplen.value = pass1.value.length;\r\n\r\n\t\t\t\t\tif(pass1.value.substring(0, 5) != '!md5!') {\r\n\t\t\t\t\t\tpass1.value = '!md5!'+hex_md5(pass1.value);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tvar pass2 = document.getElementById('pass2');\r\n\t\t\t\t\tif(pass2.value.substring(0, 5) != '!md5!') {\r\n\t\t\t\t\t\tpass2.value = '!md5!'+hex_md5(pass2.value);\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t}\r\n\t\t\t\t//-->\r\n\t\t\t\t</script>");
                if (httpget('override')) {
                    rawoutput("<form action='runmodule.php?module=homepage&op=4&override=1&r={$r}' method='POST' onSubmit=\"md5pass();\">");
                } else {
                    rawoutput("<form action='runmodule.php?module=homepage&op=4&r={$r}' method='POST' onSubmit=\"md5pass();\">");
                }
                rawoutput("<input type='hidden' name='passlen' id='passlen' value='0'>");
                rawoutput("<input type='hidden' name='name' value=\"{$name}\">");
                rawoutput("<input type='hidden' name='gender' value=\"{$sex}\">");
                rawoutput("<input type='hidden' name='email' value=\"{$email}\">");
                output("\"`#`iSeriously, mate,`i just put down ");
                rawoutput("<input type='password' name='pass1' id='pass1'>");
                output(".`0\"`n`nThe gatekeeper scribbles on his form.  \"`6Sorry, just run that past me again?`0\"`n`n\"`#I said ");
                rawoutput("<input type='password' name='pass2' id='pass2'>");
                output("!`0\"`n`n");
                rawoutput("<div align=\"center\"><input type='submit' value='Now let me in, damn it!' class='button'></div></form>");
            } else {
                //perform a final test on all supplied information, as in create.php
                //password already checked
                $createaccount = 1;
                //check name
                $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE login='******'";
                $result = db_query($sql);
                //name exists
                if (db_num_rows($result) > 0) {
                    output("name");
                    $createaccount = 0;
                }
                //name too short or too long
                if (strlen($name) < 3 || strlen($name) > 25) {
                    output("name");
                    $createaccount = 0;
                }
                //gender not set
                if ($sex != 1 && $sex != 0) {
                    output("sex is %s", $sex);
                    $createaccount = 0;
                }
                //email
                if (!httpget('override')) {
                    //not overriden
                    //not an E-mail address
                    if (!is_email($email)) {
                        $createaccount = 0;
                        output("email not an email");
                    }
                    //already exists
                    $sql = "SELECT login FROM " . db_prefix("accounts") . " WHERE emailaddress='{$email}'";
                    $result = db_query($sql);
                    if (db_num_rows($result) > 0) {
                        $createaccount = 0;
                        output("email found already");
                    }
                }
                $args = modulehook("check-create", httpallpost());
                if (isset($args['blockaccount']) && $args['blockaccount']) {
                    $msg .= $args['msg'];
                    $createaccount = 0;
                }
                if ($createaccount) {
                    //create the account
                    require_once "lib/titles.php";
                    $title = get_dk_title(0, $sex);
                    $refer = httpget('r');
                    if ($refer > "") {
                        $sql = "SELECT acctid FROM " . db_prefix("accounts") . " WHERE login='******'";
                        $result = db_query($sql);
                        $ref = db_fetch_assoc($result);
                        $referer = $ref['acctid'];
                    } else {
                        $referer = 0;
                    }
                    $dbpass = "";
                    if (substr($pass1, 0, 5) == "!md5!") {
                        $dbpass = md5(substr($pass1, 5));
                    } else {
                        $dbpass = md5(md5($pass1));
                    }
                    $sql = "INSERT INTO " . db_prefix("accounts") . "\r\n\t\t\t\t\t\t(name, superuser, title, password, sex, login, laston, uniqueid, lastip, gold, emailaddress, emailvalidation, referer, regdate, race, location)\r\n\t\t\t\t\t\tVALUES\r\n\t\t\t\t\t\t('{$title} {$name}', '" . getsetting("defaultsuperuser", 0) . "', '{$title}', '{$dbpass}', '{$sex}', '{$name}', '" . date("Y-m-d H:i:s", strtotime("-1 day")) . "', '" . $_COOKIE['lgi'] . "', '" . $_SERVER['REMOTE_ADDR'] . "', " . getsetting("newplayerstartgold", 50) . ", '{$email}', '{$emailverification}', '{$referer}', NOW(), 'Human', 'NewHome')";
                    db_query($sql);
                    if (db_affected_rows(LINK) <= 0) {
                        output("`\$Error`^: Your account was not created for an unknown reason, please try again. ");
                    } else {
                        $sql = "SELECT acctid FROM " . db_prefix("accounts") . " WHERE login='******'";
                        $result = db_query($sql);
                        $row = db_fetch_assoc($result);
                        $args = httpallpost();
                        $args['acctid'] = $row['acctid'];
                        //insert output
                        $sql_output = "INSERT INTO " . db_prefix("accounts_output") . " VALUES ({$row['acctid']},'');";
                        db_query($sql_output);
                        //end
                        modulehook("process-create", $args);
                        //Project Wonderful Conversion Code
                        $pwcode = "<!-- Beginning of Project Wonderful conversion code: -->\r\n\t\t\t\t\t\t<!-- Conversion Track ID: 12 -->\r\n\t\t\t\t\t\t<script type=\"text/javascript\">\r\n\t\t\t\t\t\t<!--var d=document;\r\n\t\t\t\t\t\td.projectwonderful_conversion_id = \"12\";\r\n\t\t\t\t\t\td.projectwonderful_label = \"\";\r\n\t\t\t\t\t\td.projectwonderful_value = \"\";\r\n\t\t\t\t\t\t//-->\r\n\t\t\t\t\t\t</script>\r\n\t\t\t\t\t\t<script type=\"text/javascript\" \r\n\t\t\t\t\t\tsrc=\"http://www.projectwonderfuladservices.com/conversion.js\">\r\n\t\t\t\t\t\t</script>\r\n\t\t\t\t\t\t<!-- End of Project Wonderful ad code. -->";
                        rawoutput($pwcode);
                        if ($emailverification != "") {
                            $subj = translate_mail("LoGD Account Verification", 0);
                            $msg = translate_mail(array("Login name: %s `n`nIn order to verify your account, you will need to click on the link below.`n`n http://%s?op=val&id=%s `n`nThanks for playing!", $shortname, $_SERVER['SERVER_NAME'] . ($_SERVER['SERVER_PORT'] == 80 ? "" : ":" . $_SERVER['SERVER_PORT']) . $_SERVER['SCRIPT_NAME'], $emailverification), 0);
                            mail($email, $subj, str_replace("`n", "\n", $msg), "From: " . getsetting("gameadminemail", "*****@*****.**"));
                            output("`4An email was sent to `\$%s`4 to validate your address.  Click the link in the email to activate your account.`0`n`n", $email);
                        } else {
                            output("\"`#`iLET ME IN!  RIGHT THE HELL NOW!`i`0\"`n`n\"`6Hmm?`0\"  The gatekeeper looks up from his forms.  \"`6Oh!  Yes, I see what you mean.  Wow!`0\" he smiles, as the beast plods closer.  \"`6That's a big one!  Geez, look at the `isize`i of 'im!`0\"`n`n\"`#`iPlease!`i`0\"`n`n\"`6Oh, oh, yes.  Of course.`0\"  He pulls a lever, and the outpost gates swing open.  \"`6In you go, then.`0\"`n`nYou tear through the gates and into the Outpost.`n`nThe gatekeeper chuckles.  \"`6Nice one, Harry!`0\"`n`nGrinning, the monster takes a bow.  \"`4It `inever`i gets old, this,`0\" it says in a broad Yorkshire accent. \"`4You in the pub later?`0\"`n`n\"`6Of course, it's darts night.`0\"`n`n\"`4Right-ho, then.  Ta-raa.`0\"`n`n\"`6See you, Harry.`0\"  The gatekeeper sits back in his chair, lights a cigarette, and carries on with his crossword.`n");
                            rawoutput("<div align='center'><form action='login.php' method='POST'>");
                            rawoutput("<input name='name' value=\"{$name}\" type='hidden'>");
                            rawoutput("<input name='password' value=\"{$pass1}\" type='hidden'>");
                            $click = translate_inline("Venture into Improbable Island!");
                            rawoutput("<input type='submit' class='button' value='{$click}'>");
                            rawoutput("</form></div>");
                            output_notl("`n");
                            savesetting("newestplayer", $row['acctid']);
                        }
                    }
                } else {
                    output("Whoops!  Did you use the back and/or forward buttons?  It looks like your account is already set up.  Head back to the home page and log yourself in!");
                    addnav("D'oh!");
                    addnav("Back to the homepage", "home.php");
                }
            }
            break;
    }
    if ($name) {
        addnav("Character Information");
        addnav(array("Character name: %s", $name), "");
        if (httpget('op') != 1 && httpget('op') != 0) {
            if ($sex) {
                addnav("Gender: Female", "");
            } else {
                if (isset($sex)) {
                    addnav("Gender: Male", "");
                }
            }
            if ($email) {
                addnav(array("E-mail address: %s", $email), "");
            }
        }
    }
    page_footer();
    return true;
}