function translationconvert_run()
{
    global $session;
    page_header("Translations Convertor Thing");
    output("Outputting all known translations, so that you can do a find-and-replace in the files themselves and we can stop doing this silly translate thing.`n`n");
    if (httpget('delete')) {
        $del = httpget('delete');
        $sql = "UPDATE " . db_prefix("translations") . " SET version='updated' WHERE tid={$del}";
        db_query($sql);
    }
    $sql = "SELECT * FROM " . db_prefix("translations") . " WHERE version='dragonbones' ORDER BY uri";
    $result = db_query($sql);
    $total = 0;
    while ($row = db_fetch_assoc($result)) {
        if ($row['intext'] != $row['outtext']) {
            $total++;
            rawoutput("<a href=\"runmodule.php?module=translationconvert&delete=" . $row['tid'] . "\">MARK</a>");
            addnav("", "runmodule.php?module=translationconvert&delete=" . $row['tid']);
            output_notl("`n`0`b%s`b:", $row['uri']);
            rawoutput("<table width=100%><tr><td width=50% border=1px solid #cccccc>" . $row['intext'] . "</td><td width=50%>" . $row['outtext'] . "</td></tr></table>");
            output_notl("`n`n");
        }
    }
    debug($total);
    addnav("Back to the Grotto", "superuser.php");
    page_footer();
}
function friendlist_search()
{
    global $session;
    $n = httppost("n");
    rawoutput("<form action='runmodule.php?module=friendlist&op=search' method='POST'>");
    addnav("", "runmodule.php?module=friendlist&op=search");
    if ($n != "") {
        $string = "%";
        for ($x = 0; $x < strlen($n); $x++) {
            $string .= substr($n, $x, 1) . "%";
        }
        $sql = "SELECT name,dragonkills,acctid FROM " . db_prefix("accounts") . " WHERE name LIKE '%{$string}%' AND acctid<>" . $session['user']['acctid'] . " AND locked=0 ORDER BY level,dragonkills";
        $result = db_query($sql);
        if (db_num_rows($result) > 0) {
            $ignored = rexplode(get_module_pref('ignored'));
            $friends = rexplode(get_module_pref('friends'));
            $request = rexplode(get_module_pref('request'));
            $iveignored = rexplode(get_module_pref('iveignored'));
            output("`@These users were found:`n");
            rawoutput("<table style='width:60%;text-align:center;' cellpadding='3' cellspacing='0' border='0'>");
            rawoutput("<tr class='trhead'><td>" . translate_inline("Name") . "</td><td>" . translate_inline("Operations") . "</td></tr>");
            for ($i = 0; $i < db_num_rows($result); $i++) {
                $row = db_fetch_assoc($result);
                rawoutput("<tr class='" . ($i % 2 ? "trlight" : "trdark") . "'><td>");
                output_notl($row['name']);
                rawoutput("</td><td>");
                if (in_array($row['acctid'], $ignored)) {
                    $info = translate_inline("This user has ignored you.");
                    $info .= " [<a href='runmodule.php?module=friendlist&op=ignore&ac=" . $row['acctid'] . "' class='colDkGreen'>" . translate_inline("Ignore") . "</a>]";
                    addnav("", "runmodule.php?module=friendlist&op=ignore&ac=" . $row['acctid']);
                } elseif (in_array($row['acctid'], $friends)) {
                    $info = translate_inline("This user is already in your list.");
                } elseif (in_array($row['acctid'], $request)) {
                    $info = translate_inline("This user has already requested to you.");
                } else {
                    if (in_array($row['acctid'], $iveignored)) {
                        $info = "[<a href='runmodule.php?module=friendlist&op=unignore&ac=" . $row['acctid'] . "' class='colLtRed'>" . translate_inline("Unignore") . "</a>]";
                        addnav("", "runmodule.php?module=friendlist&op=unignore&ac=" . $row['acctid']);
                    } else {
                        $info = "[<a href='runmodule.php?module=friendlist&op=ignore&ac=" . $row['acctid'] . "' class='colDkGreen'>" . translate_inline("Ignore") . "</a>]";
                        addnav("", "runmodule.php?module=friendlist&op=ignore&ac=" . $row['acctid']);
                        $info .= " - [<a href='runmodule.php?module=friendlist&op=request&ac=" . $row['acctid'] . "' class='colDkGreen'>" . translate_inline("Request") . "</a>]";
                        addnav("", "runmodule.php?module=friendlist&op=request&ac=" . $row['acctid']);
                    }
                }
                rawoutput("{$info}</td></tr>");
            }
            rawoutput("</table>");
        } else {
            output("`c`@`bA user was not found with that name.`b`c");
        }
        output_notl("`n");
    }
    output("`^`b`cFriend Search...`c`b");
    output("`n`nWho do you want to search for?");
    output("`n`nName of user: "******"<input name='n' maxlength='50' value=\"" . htmlentities(stripslashes(httppost('n'))) . "\">");
    $apply = translate_inline("Search");
    rawoutput("<input type='submit' class='button' value='{$apply}'></form>");
}
function serverloadperpage_run()
{
    global $session;
    page_header("Server Load by Page Execution Times");
    //Show player number table
    $sql = "SELECT * FROM " . db_prefix("performancepage") . " ORDER BY totalpages DESC";
    $result = db_query($sql);
    output("`bAverage Page Generation Times by script request`b`n");
    rawoutput("<table border='0' cellpadding='2' cellspacing='1' align='center' width='100%'>");
    rawoutput("<tr class='trhead'><td>URL</td><td>Total Count</td><td>Total Time</td><td>Average Time / Page</td></tr>");
    for ($i = 0; $i < db_num_rows($result); $i++) {
        $row = db_fetch_assoc($result);
        if ($row['totalpages'] >= 1) {
            $avg = $row['totaltime'] / $row['totalpages'];
            $max = 100;
            $bwidth = round($avg * 100);
            $bnonwidth = $max - $bwidth;
            if ($bnonwidth > 0) {
                $bar = "<table style='border: solid 1px #000000' width='{$max}' height='7' bgcolor='#333333' cellpadding=0 cellspacing=0><tr><td width='{$bwidth}' bgcolor='#00ff00'></td><td width='{$bnonwidth}'></td></tr></table>";
            } else {
                $over = $bwidth - $max;
                $total = $max + $over;
                $bar = "<table style='border: solid 1px #000000' height='7' width='{$total}' cellpadding=0 cellspacing=0><tr><td width='{$max}' bgcolor='#990000'></td><td width='{$over}' bgcolor='#ff0000'></td></tr></table>";
            }
            rawoutput("<tr class='" . ($i % 2 ? "trdark" : "trlight") . "'>");
            rawoutput("<td>" . $row['page'] . "</td><td>" . number_format($row['totalpages']) . "</td><td>" . $row['totaltime'] . "</td><td>" . $bar . round($row['totaltime'] / $row['totalpages'], 4) . "</td></tr>");
        }
    }
    rawoutput("</table>");
    page_footer();
}
function creatureaddon_dohook($hookname, $args)
{
    global $session;
    switch ($hookname) {
        case "gravefight-start":
            if (get_module_objpref("creatures", $args['creatureid'], "description")) {
                output(stripslashes(get_module_objpref("creatures", $args['creatureid'], "description")));
            }
            break;
        case "creatureencounter":
            $args['creaturegold'] += get_module_objpref("creatures", $args['creatureid'], "addgold");
            $args['creaturehealth'] += get_module_objpref("creatures", $args['creatureid'], "addhit");
            $args['creatureattack'] += get_module_objpref("creatures", $args['creatureid'], "addattack");
            $args['creaturedefense'] += get_module_objpref("creatures", $args['creatureid'], "adddefense");
            if (get_module_objpref("creatures", $args['creatureid'], "image")) {
                rawoutput("<table width = \"100%\"><tr><td width=\"100%\" align = \"center\"><img src=\"./images/" . get_module_objpref("creatures", $args['creatureid'], "image") . "\"></td></tr></table>");
            }
            if (get_module_objpref("creatures", $args['creatureid'], "description") && !httpget("nodesc")) {
                output(stripslashes(get_module_objpref("creatures", $args['creatureid'], "description")));
            }
            break;
        case "battle-victory":
            if ($session['user']['level'] < 15 && e_rand(1, 100) <= get_module_objpref("creatures", $args['creatureid'], "gemchance") && get_module_objpref("creatures", $args['creatureid'], "gemmessage")) {
                $message = get_module_objpref("creatures", $args['creatureid'], "gemmessage");
                output($message);
                debug("Creature Addon module is awarding a gem.");
                $session['user']['gems']++;
                debuglog("found a gem when slaying a " . $args['creaturename']);
            }
            break;
    }
    return $args;
}
function monsterkills_run()
{
    page_header("Most Monster Kills");
    $acc = db_prefix("accounts");
    $mp = db_prefix("module_userprefs");
    $sql = "SELECT {$acc}.name AS name,\r\n\t\t{$acc}.acctid AS acctid,\r\n\t\t{$mp}.value AS kills,\r\n\t\t{$mp}.userid FROM {$mp} INNER JOIN {$acc}\r\n\t\tON {$acc}.acctid = {$mp}.userid \r\n\t\tWHERE {$mp}.modulename = 'monsterkills' \r\n\t\tAND {$mp}.setting = 'kills' \r\n\t\tAND {$mp}.value > 0 ORDER BY ({$mp}.value+0)\t\r\n\t\tDESC limit " . get_module_setting("list") . "";
    $result = db_query($sql);
    $rank = translate_inline("Kills");
    $name = translate_inline("Name");
    output("`n`b`c`@Most`\$ Monster `@Kills`n`n`c`b");
    rawoutput("<table border='0' cellpadding='2' cellspacing='1' align='center'>");
    rawoutput("<tr class='trhead'><td align=center>{$name}</td><td align=center>{$rank}</td></tr>");
    for ($i = 0; $i < db_num_rows($result); $i++) {
        $row = db_fetch_assoc($result);
        if ($row['name'] == $session['user']['name']) {
            rawoutput("<tr class='trhilight'><td>");
        } else {
            rawoutput("<tr class='" . ($i % 2 ? "trdark" : "trlight") . "'><td align=left>");
        }
        output_notl("%s", $row['name']);
        rawoutput("</td><td align=right>");
        output_notl("%s", $row['kills']);
        rawoutput("</td></tr>");
    }
    rawoutput("</table>");
    addnav("Back to HoF", "hof.php");
    villagenav();
    page_footer();
}
function medals_show_medals($acctid = false)
{
    global $session;
    if (!$acctid) {
        $acctid = $session['user']['acctid'];
    }
    $info = unserialize(get_module_pref("medals", "medals", $acctid));
    if (!is_array($info)) {
        $info = array();
        set_module_pref("medals", serialize($info), "medals", $acctid);
    }
    $count = 0;
    $rc = 0;
    rawoutput("<table border=0 cellpadding=9 cellspacing=0><tr>");
    foreach ($info as $key => $vals) {
        $count++;
        $finalrow = false;
        output_notl("<td><img src=\"images/medals/" . $vals['icon'] . "\" alt=\"" . $vals['name'] . "\" title=\"" . $vals['name'] . "\"></td>", true);
        if ($count == 5) {
            rawoutput("</tr><tr>");
            $count = 0;
            $finalrow = true;
        }
    }
    if ($finalrow) {
        rawoutput("</table>");
    } else {
        for ($i = 0; $i < 5 - $count; $i++) {
            rawoutput("<td>&nbsp;</td>");
        }
        rawoutput("</tr></table>");
    }
    //rawoutput("<img src=\"images/medals/background-bottom.png\">");
    output_notl("`n");
}
function bioextension_dohook($hookname, $args)
{
    global $session;
    if ($hookname == "bioinfo") {
        $sql = "SELECT donation FROM " . db_prefix("accounts") . " WHERE acctid = '" . $args['acctid'] . "'";
        $result = db_query($sql);
        $row = db_fetch_assoc($result);
        if ($row['donation'] >= get_module_setting("threshhold")) {
            $bio = get_module_pref("user_extendedbio", "bioextension", $args['acctid']);
            $link = get_module_pref("user_extlink", "bioextension", $args['acctid']);
            $bio = str_replace(chr(13), "`n", $bio);
            $bio = stripslashes($bio);
            output("`0%s`n`n", $bio);
            if (substr($link, 0, 5) == "http:") {
                rawoutput("<a href=\"" . $link . "\">Player's webpage</a><br /><br />");
            }
        }
    } else {
        if ($hookname == "footer-prefs") {
            $bio = get_module_pref("user_extendedbio");
            $limit = get_module_setting("charlimit");
            if (strlen($bio) > $limit) {
                output("`c`4`bWARNING`b`0`c`nYour Extended Bio is oversized by %s characters.  If you navigate away from this page, your Extended Bio will have %s characters indiscriminately cut from the end.  Please edit and re-save your Extended Bio to avoid cuts.", strlen($bio) - $limit, strlen($bio) - $limit);
                $bio = substr($bio, 0, $limit);
                set_module_pref("user_extendedbio", $bio);
            }
        }
    }
    return $args;
}
function dwshacks_dohook($hookname, $args)
{
    global $session;
    switch ($hookname) {
        case "dwellings-list-type":
            addnav("Show Only Types");
            addnav(array("%s", translate_inline(ucfirst(get_module_setting("dwnameplural", "dwshacks")))), "runmodule.php?module=dwellings&op=list&showonly=dwshacks&ref={$args['ref']}&sortby={$args['sortby']}&order={$args['order']}");
            break;
        case "dwellings-list-interact":
            if ($args['type'] == "dwshacks" && $args['status'] == 1 && get_module_setting("maxkeys") == 123456789) {
                addnav("", "runmodule.php?module=dwellings&op=enter&dwid={$args['dwid']}");
                $tress = translate_inline("Tresspass");
                rawoutput("<a href='runmodule.php?module=dwellings&op=enter&dwid={$args['dwid']}'>{$tress}</a>");
            }
            break;
        case "dwellings-manage":
            $dwid = $args['dwid'];
            if (get_module_setting("maxkeys") == 123456789 && $args['type'] == "dwshacks") {
                blocknav("runmodule.php?module=dwellings&op=keys&dwid={$dwid}");
            }
            break;
        case "dwellings":
            if (get_module_objpref("city", $args['cityid'], "showdwshacks")) {
                output("  Along the narrow pathway, precariously placed wood planks are nailed and leaning on each other in a fashion that only leaves you to assume they are supposed to be %s.`0", translate_inline(get_module_setting("dwnameplural")));
                if ($args['allowbuy'] == 1 && $session['user']['dragonkills'] >= get_module_setting("dkreq")) {
                    $cityid = $args['cityid'];
                    addnav("Options");
                    addnav(array("Establish a %s", translate_inline(ucfirst(get_module_setting("dwname", "dwshacks")))), "runmodule.php?module=dwellings&op=buy&type=dwshacks&subop=presetup&cityid={$cityid}");
                }
            }
            break;
    }
    return $args;
}
function binarypuzzle_show($switches = 0, $goal)
{
    global $session;
    if (!$switches) {
        $switches = unserialize(get_module_pref("switches", "binarypuzzle"));
    }
    $total = 0;
    foreach ($switches as $switch => $vals) {
        $sw = $switch;
        if ($vals['status']) {
            $total += $vals['val'];
        }
        rawoutput("<a href=\"runmodule.php?module=binarypuzzle&op=switch&switch=" . $sw . "&goal=" . $goal . "\">" . $vals['status'] . "</a>");
        addnav("", "runmodule.php?module=binarypuzzle&op=switch&switch={$sw}&goal={$goal}");
    }
    output("`nGoal number: %s`n", $goal);
    //Now check to see if any of the clues are active
    $clues = unserialize(get_module_pref("clues", "binarypuzzle"));
    foreach ($clues as $clue) {
        if ($clue == $total) {
            output("`@Clue number: %s`n", $clue);
        } else {
            output("`0Clue number: %s`n", $clue);
        }
    }
}
function avatar_showimages($set)
{
    $races = modulehook("racenames");
    rawoutput("<table cellpadding='0' cellspacing='0' border='0' bgcolor='#999999'>");
    $r = translate_inline("Race");
    $m = translate_inline("Male Image");
    $f = translate_inline("Female Image");
    rawoutput("<tr class='trhead'><th>{$r}</th><th>{$m}</th><th>{$f}</th></tr>");
    $i = 0;
    foreach ($races as $key => $race) {
        $r = strtolower($race);
        $imm = avatar_getimage($r, "male", $set);
        $imf = avatar_getimage($r, "female", $set);
        rawoutput("<tr class='" . ($i % 2 ? "trlight" : "trdark") . "'>");
        rawoutput("<th>");
        output_notl('`^');
        output($race);
        output_notl("`0");
        rawoutput("</th><td>");
        rawoutput($imm);
        rawoutput("</td><td>");
        rawoutput($imf);
        rawoutput("</td>");
        rawoutput("</tr>");
        $i++;
    }
    rawoutput("</table>");
}
function relativedate(string $indate) : string
{
    $lastOn = round((strtotime('now') - strtotime($indate)) / 86400, 0) . 'days';
    tlschema('datetime');
    if (substr($lastOn, 0, 2) == '1 ') {
        $lastOn = translate_inline('1 day');
    } else {
        if (date('Y-m-d', strtotime($lastOn)) == date('Y-m-d')) {
            $lastOn = translate_inline('Today');
        } else {
            if (date('Y-m-d', strtotime($lastOn)) == date('Y-m-d', strtotime('-1 day'))) {
                $lastOn = translate_inline('Yesterday');
            } else {
                if (strpos($indate, '0000-00-00') !== false) {
                    $lastOn = translate_inline('Never');
                } else {
                    $lastOn = sprintf_translate('%s days', round((strtotime('now') - strtotime($indate)) / 86400, 0));
                    rawoutput(tlbutton_clear());
                }
            }
        }
    }
    tlschema();
    return $lastOn;
}
function clannews_outputseparator()
{
    // the line below is the output used to separate news events in
    // news.php.  however, it doesn't work well with the page layout
    // of clan.php, since it takes up a bit more vertical space than
    // the style of the other elements on the page does.
    // output_notl("`c`2-=-`@=-=`2-=-`@=-=`2-=-`@=-=`2-=-`0`c");
    rawoutput("<table cellspacing=0><tr><td height=5></td></tr></table>");
}
function hunterslodge_customarmour_run()
{
    require_once "lib/sanitize.php";
    require_once "lib/names.php";
    global $session;
    $op = httpget("op");
    $free = httpget("free");
    page_header("Choose your Custom Armour");
    switch ($op) {
        case "change":
            output("Want to change your Custom Armour?  No problem.  Enter your desired armour in the box below.  You've got 25 characters to play around with.`n(leave this blank to disable custom armour naming and return to default, game-supplied armour names)`n`n");
            rawoutput("<form action='runmodule.php?module=hunterslodge_customarmour&op=confirm&free=" . $free . "' method='POST'>");
            $armour = get_module_pref("customarmour");
            rawoutput("<input id='input' name='newarmour' width='25' maxlength='25' value='" . htmlentities($armour, ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "'>");
            rawoutput("<input type='submit' class='button' value='Preview'>");
            rawoutput("</form>");
            addnav("", "runmodule.php?module=hunterslodge_customarmour&op=confirm&free=" . $free);
            addnav("Cancel");
            addnav("Don't set custom armour, just go back to the Lodge", "runmodule.php?module=iitems_hunterslodge&op=start");
            break;
        case "confirm":
            $newarmour = httppost("newarmour");
            $sub = httpget("sub");
            $newarmour = str_replace("`", "", $newarmour);
            $newarmour = comment_sanitize($newarmour);
            $newarmour = substr($newarmour, 0, 25);
            if ($newarmour) {
                output("Your new custom armour is:`n%s`nWould you like to set your new armour now?`n`n", $newarmour);
            } else {
                output("You've chosen to go back to the default, game-supplied armours.  Are you sure that's what you want?`n`n");
            }
            addnav("Confirm");
            addnav("Set custom armour", "runmodule.php?module=hunterslodge_customarmour&op=set&free={$free}&newarmour=" . rawurlencode($newarmour));
            addnav("Cancel");
            addnav("Don't set custom armour, just go back to the Lodge", "runmodule.php?module=iitems_hunterslodge&op=start");
            break;
        case "set":
            $newarmour = rawurldecode(httpget("newarmour"));
            if ($newarmour == "") {
                output("Your custom armour name has been removed.  The next time you change your armour, you'll return to game-supplied armour names.`n`n");
            } else {
                output("Your custom armour has been set to %s!`n`n", $newarmour);
                $session['user']['armor'] = $newarmour;
            }
            set_module_pref("customarmour", $newarmour);
            if (!$free) {
                require_once "modules/iitems/lib/lib.php";
                $id = has_item("hunterslodge_customarmour");
                delete_item($id);
            }
            addnav("Return");
            addnav("Return to the Lodge", "runmodule.php?module=iitems_hunterslodge&op=start");
            break;
    }
    page_footer();
}
function logd_error_handler($errno, $errstr, $errfile, $errline)
{
    global $session;
    static $in_error_handler = 0;
    // If we have used the @ operator, just don't report anything!
    if (!error_reporting()) {
        return;
    }
    $in_error_handler++;
    if ($in_error_handler > 1) {
        //prevents the error handler from being re-called when we're already within a call of it.
        if ($errno & (E_USER_WARNING | E_WARNING)) {
            echo "PHP Warning: \"{$errstr}\"<br>in <b>{$errfile}</b> at <b>{$errline}</b>.  Additionally this occurred while within logd_error_handler().<br>";
        } elseif ($errno & (E_USER_ERROR | E_ERROR)) {
            echo "PHP ERROR: \"{$errstr}\"<br>in <b>{$errfile}</b> at <b>{$errline}</b>.  Additionally this occurred while within logd_error_handler().<br>";
        }
        $in_error_handler--;
        return;
    }
    switch ($errno) {
        case E_NOTICE:
        case E_USER_NOTICE:
            if (getsetting('show_notices', 0) && $session['user']['superuser'] & SU_SHOW_PHPNOTICE) {
                debug("PHP Notice: \"{$errstr}\"<br>in <b>{$errfile}</b> at <b>{$errline}</b>.");
            }
            break;
        case E_WARNING:
        case E_USER_WARNING:
            require_once "show_backtrace.php";
            tlschema("errorhandler");
            output("PHP Warning: \"%s\"`nin `b%s`b at `b%s`b.`n", $errstr, $errfile, $errline, true);
            tlschema();
            $backtrace = show_backtrace();
            rawoutput($backtrace);
            if (getsetting("notify_on_warn", 0) > "") {
                //$args = func_get_args();
                //call_user_func_array("logd_error_notify",$args);
                logd_error_notify($errno, $errstr, $errfile, $errline, $backtrace);
            }
            break;
        case E_ERROR:
        case E_USER_ERROR:
            require_once "lib/show_backtrace.php";
            echo sprintf("PHP ERROR: \"%s\"<br>in <b>%s</b> at <b>%s</b>.<br>", $errstr, $errfile, $errline);
            $backtrace = show_backtrace();
            echo $backtrace;
            if (getsetting("notify_on_error", 0) > "") {
                //$args = func_get_args();
                //call_user_func_array("logd_error_notify",$args);
                logd_error_notify($errno, $errstr, $errfile, $errline, $backtrace);
            }
            die;
            break;
    }
    $in_error_handler--;
}
function namecolor_form()
{
    $regname = get_player_basename();
    output("Your name currently is this:");
    rawoutput($regname);
    output(", which looks like %s`7`n`n", $regname);
    output("How would you like your name to look?`n");
    rawoutput("<form action='runmodule.php?module=namecolor&op=namepreview' method='POST'><input name='newname' value=\"" . HTMLEntities($regname, ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "\"> <input type='submit' class='button' value='Preview'></form>");
    addnav("", "runmodule.php?module=namecolor&op=namepreview");
}
function iitems_eboy_gypsy_run()
{
    global $session;
    page_header("eBoy's Price Chart");
    require_once "modules/iitems/lib/lib.php";
    $cost = get_module_setting("cost", "iitems_eboy_gypsy");
    if ($cost == 1) {
        $p = "Cigarette";
    } else {
        $p = "Cigarettes";
    }
    if ($session['user']['gems'] >= $cost) {
        $session['user']['gems'] -= $cost;
        output("`5You hand over the %s and the old man chuckles.  \"`!Aaah, thank ye kindly.  Now, here we are!  I'd recommend you write these down.  Now mark my words - these prices fluctuate by the `iminute`i!  That eBoy, he's a crafty bastard, y'see.  He sells things for whatever people are willing to buy them for, and not one penny less!  Even if that means putting his prices up the `isecond`i someone buys something!`5\"`n`nHe reaches under his desk and brings up a clattering rectangular machine made out of wood and brass, about the size of a fat telephone directory.  A radio antenna protrudes from one corner.`n`nTrue to his word, the spinning reels show the prices of every commodity in every outpost.  You spend a few minutes studying the readout.`n`n", $p);
        $sql = "select * from " . db_prefix("cityprefs");
        $result = db_query($sql);
        for ($i = 0; $i < db_num_rows($result); $i++) {
            $row = db_fetch_assoc($result);
            $cid = $row['cityid'];
            $name = $row['cityname'];
            $eboy = unserialize(get_module_objpref("city", $cid, "eboytrades-intelligent", "iitems_eboy_intelligent"));
            output("`b`0%s`b`n", $name);
            rawoutput("<table border=0 cellpadding=3 cellspacing=2><tr class=\"trdark\"><td>Item</td><td>Buying at</td><td>Selling at</td><td>Stock</td></tr>");
            $classcount = 1;
            foreach ($eboy as $key => $details) {
                $itemdetails = iitems_get_item_details($key);
                if ($details['price'] < 10) {
                    $details['price'] = 10;
                }
                $eboy[$key]['price'] = $details['price'];
                if ($details['stock'] < 3) {
                    $buy = round($details['price'] * 0.5);
                } else {
                    $buy = round($details['price'] * 0.7);
                }
                $classcount++;
                $class = $classcount % 2 ? "trdark" : "trlight";
                $dname = $itemdetails['verbosename'];
                $dsell = number_format($details['price']);
                $dbuy = number_format($buy);
                $dstock = number_format($details['stock']);
                rawoutput("<tr class='{$class}'><td>{$dname}</td><td align=\"center\">{$dbuy}</td><td align=\"center\">{$dsell}</td><td align=\"center\">{$dstock}</td></tr>");
            }
            rawoutput("</table>");
            output("`n`n");
        }
    } else {
        output("`5You enthusiastically agree to the price, before realising that you don't actually have that many cigarettes.  Whoops.");
    }
    addnav("Leave");
    addnav("Return to the Outpost", "village.php");
    page_footer();
    return true;
}
function do_forced_nav($anonymous, $overrideforced)
{
    global $baseaccount, $session, $REQUEST_URI;
    rawoutput("<!--\nAllowAnonymous: " . ($anonymous ? "True" : "False") . "\nOverride Forced Nav: " . ($overrideforced ? "True" : "False") . "\n-->");
    if (isset($session['loggedin']) && $session['loggedin']) {
        $sql = "SELECT *  FROM " . db_prefix("accounts") . " WHERE acctid = '" . $session['user']['acctid'] . "'";
        $result = db_query($sql);
        if (db_num_rows($result) == 1) {
            $session['user'] = db_fetch_assoc($result);
            $baseaccount = $session['user'];
            $session['bufflist'] = unserialize($session['user']['bufflist']);
            if (!is_array($session['bufflist'])) {
                $session['bufflist'] = array();
            }
            $session['user']['dragonpoints'] = unserialize($session['user']['dragonpoints']);
            $session['user']['prefs'] = unserialize($session['user']['prefs']);
            if (!is_array($session['user']['dragonpoints'])) {
                $session['user']['dragonpoints'] = array();
            }
            if (is_array(unserialize($session['user']['allowednavs']))) {
                $session['allowednavs'] = unserialize($session['user']['allowednavs']);
            } else {
                $session['allowednavs'] = array($session['user']['allowednavs']);
            }
            if (!$session['user']['loggedin'] || date("U") - strtotime($session['user']['laston']) > getsetting("LOGINTIMEOUT", 900)) {
                $session = array();
                redirect("index.php?op=timeout", "Account not logged in but session thinks they are.");
            }
        } else {
            $session = array();
            $session['message'] = translate_inline("`4Error, your login was incorrect`0", "login");
            redirect("index.php", "Account Disappeared!");
        }
        db_free_result($result);
        //check the nav exists in the session's allowednavs array
        if (isset($session['allowednavs'][$REQUEST_URI]) && $session['allowednavs'][$REQUEST_URI] && $overrideforced !== true) {
            //The nav is fine
            //clear the navs - more navs will be added as the script the player is currently viewing loads and executes
            $session['allowednavs'] = array();
        } else {
            if ($overrideforced !== true) {
                //This nav is not fine at all.  Redirect the player to badnav.php.
                $session['badnav'] = 1;
                redirect("badnav.php", "Navigation not allowed to {$REQUEST_URI}");
            }
        }
    } else {
        if (!$anonymous) {
            $session['message'] = translate_inline("You are not logged in, this may be because your session timed out.", "login");
            redirect("index.php?op=timeout&nli=true", "Not logged in: {$REQUEST_URI}");
        }
    }
}
function topoutput_dohook($hookname, $args)
{
    global $session;
    if ($hookname == "everyheader-loggedin") {
        rawoutput("!!!TOP!!!");
    }
    if ($hookname == "everyfooter-loggedin") {
        debug($output);
        str_replace("!!!TOP!!!", "Woo yay!", $output);
    }
    return $args;
}
function tip()
{
    global $tipid;
    $tip = translate_inline("Tip");
    output_notl("<div style='cursor: pointer; cursor: hand; display: inline;' onMouseOver=\"tip{$tipid}.style.visibility='visible'; tip{$tipid}.style.display='inline';\" onMouseOut=\"tip{$tipid}.style.visibility='hidden'; tip{$tipid}.style.display='none';\">`i[ `b{$tip}`b ]`i", true);
    rawoutput("<div class='debug' id='tip{$tipid}' style='position: absolute; width: 200px; max-width: 200px; float: right;'>");
    $args = func_get_args();
    call_user_func_array("output", $args);
    rawoutput("</div></div>");
    rawoutput("<script language='JavaScript'>var tip{$tipid} = document.getElementById('tip{$tipid}'); tip{$tipid}.style.visibility='hidden'; tip{$tipid}.style.display='none';</script>");
    $tipid++;
}
function dwellingscostsp_dohook($hookname, $args)
{
    global $session;
    switch ($hookname) {
        case "dwellings-buy-valuecheck":
            $typeid = get_module_setting("typeid", $args['type']);
            $paidsp = abs((int) httppost('paidsp'));
            if ($paidsp < 0) {
                $paidsp = 0;
            }
            $pointsavailable = $session['user']['donation'] - $session['user']['donationspent'];
            if ($pointsavailable < $paidsp) {
                $args['allowpay'] = 0;
                blocknav("runmodule.php?module=dwellings&op=build&type=" . $args['type'] . "&dwid=" . $args['dwid'] . "");
                output("`nYou do not have that many site points.");
            } elseif ($paidsp > get_module_objpref("dwellingtypes", $typeid, "spcost") - get_module_objpref("dwellings", $args['dwid'], "spspent")) {
                $args['allowpay'] = 0;
                blocknav("runmodule.php?module=dwellings&op=build&type=" . $args['type'] . "&dwid=" . $args['dwid'] . "");
                output("`nYou have tried to spend more site points than you need to.");
            }
            break;
        case "dwellings-buy-setup":
            $typeid = get_module_setting("typeid", $args['type']);
            $paidsp = abs((int) httppost('paidsp'));
            if ($paidsp < 0) {
                $paidsp = 0;
            }
            $spent = get_module_objpref("dwellings", $args['dwid'], "spspent") + $paidsp;
            set_module_objpref("dwellings", $args['dwid'], "spspent", $spent);
            $session['user']['donationspent'] += $paidsp;
            if ($spent != get_module_objpref("dwellingtypes", $typeid, "spcost")) {
                $args['finished'] = 0;
            }
            break;
        case "dwellings-pay-costs":
            $typeid = get_module_setting("typeid", $args['type']);
            $costsp = get_module_objpref("dwellingtypes", $typeid, "spcost") - get_module_objpref("dwellings", $args['dwid'], "spspent");
            if ($costsp) {
                output("`#%s Site Points`0`n", $costsp);
            }
            break;
        case "dwellings-pay-input":
            $typeid = get_module_setting("typeid", $args['type']);
            $costsp = get_module_objpref("dwellingtypes", $typeid, "spcost") - get_module_objpref("dwellings", $args['dwid'], "spspent");
            $sp = translate_inline("Site Points");
            if ($costsp) {
                rawoutput("{$sp}: <input id='input' name='paidsp' width=5><br>");
            }
            break;
    }
    return $args;
}
function clanform()
{
    rawoutput("<form action='clan.php?op=new&apply=1' method='POST'>");
    addnav("", "clan.php?op=new&apply=1");
    output("`b`cNew Clan Application Form`c`b");
    output("Clan Name: ");
    rawoutput("<input name='clanname' maxlength='50' value=\"" . htmlentities(stripslashes(httppost('clanname')), ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "\">");
    output("`nShort Name: ");
    rawoutput("<input name='clanshort' maxlength='5' size='5' value=\"" . htmlentities(stripslashes(httppost('clanshort')), ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "\">");
    output("`nNote, color codes are permitted in neither clan names nor short names.");
    output("The clan name is shown on player bios and on clan overview pages while the short name is displayed next to players' names in comment areas and such.`n");
    $apply = translate_inline("Apply");
    rawoutput("<input type='submit' class='button' value='{$apply}'></form>");
}
function clancommentaryoverview_run()
{
    page_header("Clan Commentary Overview");
    $numcomments = get_module_setting("numcomments");
    require_once "lib/superusernav.php";
    superusernav();
    addnav("C?Commentary Overview", "moderate.php");
    addnav("Clan Halls");
    $sql = "SELECT clanid, clanname, clanshort FROM " . db_prefix("clans") . " ORDER BY clanid";
    $res = db_query($sql);
    // since these are proper names, they shouldn't be translated
    tlschema("notranslate");
    while ($row = db_fetch_assoc($res)) {
        addnav(array("<%s> %s", $row['clanshort'], $row['clanname']), "moderate.php?area=clan-{$row['clanid']}");
    }
    tlschema();
    $sql = "SELECT clanid, clanname FROM " . db_prefix("clans") . " ORDER BY clanid";
    $res = db_query($sql);
    $firstclan = 1;
    while ($clan = db_fetch_assoc($res)) {
        $cid = $clan['clanid'];
        $csql = "SELECT * FROM " . db_prefix("commentary") . " WHERE section='clan-" . $cid . "' ORDER BY postdate DESC LIMIT " . $numcomments;
        $cres = db_query($csql);
        if (db_num_rows($cres) > 0) {
            if ($firstclan == 1) {
                $firstclan = 0;
                addnav("", "runmodule.php?module=clancommentaryoverview");
                $buttonrefresh = translate_inline("Refresh");
                rawoutput("<form action='runmodule.php?module=clancommentaryoverview' method='post'>");
                rawoutput("<input type='submit' class='button' value='{$buttonrefresh}'>");
                rawoutput("</form>");
            }
            rawoutput("<hr>");
            $cname = $clan['clanname'];
            addnav("", "moderate.php?area=clan-" . $cid);
            rawoutput("<a href='moderate.php?area=clan-" . $cid . "'>");
            output_notl("`b`^%s`b`0", $cname);
            rawoutput("</a>");
            output_notl("`n");
            $carray = array();
            while ($ccomment = db_fetch_assoc($cres)) {
                array_push($carray, $ccomment);
            }
            while ($ccomment = array_pop($carray)) {
                clancommentaryoverview_displaycomment($ccomment);
            }
        }
    }
    page_footer();
}
function hunterslodge_namedmount_run()
{
    require_once "lib/sanitize.php";
    require_once "lib/names.php";
    global $session;
    global $playermount;
    $op = httpget("op");
    $free = httpget("free");
    page_header("Name your Mount");
    switch ($op) {
        case "change":
            output("Want to change your Mount's name?  No problem.  Enter your desired name in the box below.  You've got 25 characters to play around with.`n(leave this blank to disable mount naming)`n`n");
            rawoutput("<form action='runmodule.php?module=hunterslodge_namedmount&op=confirm&free=" . $free . "' method='POST'>");
            rawoutput("<input id='input' name='newname' width='25' maxlength='25' value='" . htmlentities($race, ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "'>");
            rawoutput("<input type='submit' class='button' value='Preview'>");
            rawoutput("</form>");
            addnav("", "runmodule.php?module=hunterslodge_namedmount&op=confirm&free=" . $free);
            addnav("Cancel");
            addnav("Don't set a mount name, just go back to the Lodge", "runmodule.php?module=iitems_hunterslodge&op=start");
            break;
        case "confirm":
            $newname = httppost("newname");
            $sub = httpget("sub");
            $newname = comment_sanitize($newname);
            $newname = substr($newname, 0, 25);
            if ($newname) {
                output("Your Mount's name is now:`n%s`0 the %s`nWould you like to set your mount's name now?`n`n", $newname, $playermount['mountname']);
            } else {
                output("You've chosen to go back to having an unnamed Mount.  Are you sure that's what you want?`n`n");
            }
            addnav("Confirm");
            addnav("Set mount name", "runmodule.php?module=hunterslodge_namedmount&op=set&free={$free}&newname=" . rawurlencode($newname));
            addnav("Cancel");
            addnav("Don't set a custom mount name, just go back to the Lodge", "runmodule.php?module=iitems_hunterslodge&op=start");
            break;
        case "set":
            $newname = rawurldecode(httpget("newname"));
            output("You now ride %s`0 the %s!`n`n", $newname, $playermount['mountname']);
            set_module_pref("mountname", $newname);
            if (!$free) {
                $id = has_item("hunterslodge_namedmount");
                delete_item($id);
            }
            addnav("Return");
            addnav("Return to the Lodge", "runmodule.php?module=iitems_hunterslodge&op=start");
            break;
    }
    page_footer();
}
function colourtest_run()
{
    global $session;
    $teststring = "ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 1234567890 !@#\$%%^&*()`n";
    $colours = 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", "J" => "colMdBlue", "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");
    page_header("Colour Test");
    output("`b`cPlease ensure that your monitor is correctly calibrated before making any changes to your templates.`b  It also helps a lot to have a friend do this with you - people's eyes are very different.`c`n`n");
    rawoutput("An excellent resource for monitor calibration, including test images and tutorials, can be found <a href=\"http://www.normankoren.com/makingfineprints1A.html\"> here.</a>");
    output("`n`n`0We are now testing each colour, to see how it looks against the background for this template.`n`nMake sure that each colour is clear and easily-readable.  It's a good idea to test on a variety of monitors, both CRT and LCD, at different colour depths and resolutions, and in different ambient light.  The ColorZilla and FireBug extensions for FireFox are invaluable for determining appropriate colours.`n`n");
    foreach ($colours as $code => $colour) {
        output_notl("`0CCode " . $code . ", CSS code " . $colour . ": `" . $code . "" . $teststring);
    }
    addnav("Back to the Superuser grotto", "superuser.php");
    addnav("Reload this page", "runmodule.php?module=colourtest");
    page_footer();
}
function friends_run()
{
    global $session;
    popup_header("Who's Online");
    //Output online characters list
    $sql = "SELECT name,laston,loggedin FROM " . db_prefix("accounts") . " WHERE locked=0 AND loggedin=1 AND laston>'" . date("Y-m-d H:i:s", strtotime("-" . getsetting("LOGINTIMEOUT", 900) . " seconds")) . "' ORDER BY laston DESC";
    $result = db_query($sql);
    rawoutput("<table>");
    while ($row = db_fetch_assoc($result)) {
        rawoutput("<tr><td>");
        output("%s", $row['name']);
        rawoutput("</td><td>");
        output("%s", $row['laston']);
        rawoutput("</td></tr>");
    }
    rawoutput("</table>");
    popup_footer();
}
function mementos_feelgood_run()
{
    global $session;
    page_header("Memento Attributes");
    $mould = httpget('mould');
    $itemname = get_item_pref("verbosename", $mould);
    require_once "modules/mementos_feelgood/attributes.php";
    $attributes = mementos_feelgood_getattributes();
    switch (httpget('op')) {
        case "choosestat":
            output("`bWhat are Memento Attributes for?`b`nLet someone know how you feel about them by giving them a special Memento with a stat enhancement.  Like Mementos in themselves, these stat enhancements don't do anything to your character's abilities - they're intended only as trifles to flatter and delight.`n`nSee someone engage in a particularly special bit of rhyming roleplay?  Give them a Red Music Box of +1 Musical Mastery.  If someone else gives the player another Memento with the Musical Mastery stat attached, then their Bio will show that they have two points in Musical Mastery.  You get the idea, I'm sure - it's a tool for showing your appreciation or admiration in a playful way.`n`n`bNo really, what are Memento Attributes `ifor?`i  What do they `ido?`i`b`nThey make people feel good.  That's it!`n`n`bHow much do they cost?`b`nNothing!  They're free!  You can only apply one Attribute to any given Memento type, mind - and you can't change your mind afterwards, so choose carefully.`n`n`bHow to use them`b`nFigure out what you want your Memento to mean, and look for something in the list below that's a good match.  When you click, that Attribute will be applied to all the Mementos that came out of this Mould, and all the Mementos that will ever come out of it in the future.`n`n");
            foreach ($attributes as $key => $vals) {
                rawoutput("<strong><a href='runmodule.php?module=mementos_feelgood&op=confirm&assignstat=" . $key . "&mould=" . $mould . "'></strong>" . stripslashes(appoencode($vals['name'])) . "</a>: " . stripslashes(appoencode($vals['description'])) . "<br />");
                addnav("", "runmodule.php?module=mementos_feelgood&op=confirm&assignstat=" . $key . "&mould=" . $mould);
            }
            break;
        case "confirm":
            $assignstat = httpget('assignstat');
            $statname = $attributes[$assignstat]['name'];
            output("You're about to assign the Attribute \"%s\" to the Memento mould \"%s\".  Are you sure you want to do that?", $statname, $itemname);
            addnav("Yes!");
            addnav("Do it!", "runmodule.php?module=mementos_feelgood&op=confirmfinal&assignstat=" . $assignstat . "&mould=" . $mould);
            addnav("No wait hang on");
            addnav("That's not what I want to do AT ALL.", "runmodule.php?module=mementos_feelgood&op=choosestat&mould=" . $mould);
            break;
        case "confirmfinal":
            $assignstat = httpget('assignstat');
            output("Attribute applied!");
            //get all the items like this and apply the pref to all of them
            $sql = "SELECT * FROM " . db_prefix("items_prefs") . " WHERE setting='memento_originalitem' AND value='" . $mould . "'";
            $result = db_query($sql);
            while ($row = db_fetch_assoc($result)) {
                debug("Setting pref for itemid " . $row['id']);
                set_item_pref("memento_feelgood_attribute", $assignstat, $row['id']);
            }
            set_item_pref("memento_feelgood_attribute", $assignstat, $mould);
            break;
    }
    addnav("Return");
    addnav("Memento Forge", "runmodule.php?module=mementos&op=start");
    page_footer();
    return true;
}
function jquerycommentary_dohook($hook, $args)
{
    global $jQueryDiv, $jQueryScript, $session, $output, $_SERVER, $SCRIPT_NAME;
    switch ($hook) {
        case "viewcommentary":
            if ($SCRIPT_NAME != 'moderate.php' && $session['user']['superuser'] & SU_EDIT_COMMENTS && get_module_pref('user_disable') != 1) {
                if (httpget('ajax') != '1' && $jQueryDiv == 0) {
                    rawoutput("<div class='live-commentary'>");
                    $jQueryDiv++;
                }
                preg_match_all("/\\[([^\\]]*)\\]/", $args['commentline'], $matches);
                $text = $matches[1][0];
                preg_match_all("/removecomment=(\\d*)/", $text, $matches);
                $commid = $matches[1][0];
                $args['commentline'] = str_replace($text, "<a href='#live-commentary' class='deleteCommentary' data-comment-id='{$commid}'>Del</a>", $args['commentline']);
            }
            break;
        case "insertcomment":
            $session['current_commentary_area'] = $args['section'];
            set_module_pref('current_section', $args['section']);
            $sql = db_query("SELECT * FROM commentary WHERE author = '{$session['user']['acctid']}' AND deleted = 0 AND (section = 'globalooc' OR section = '{$args['section']}') ORDER BY commentid DESC LIMIT 0,1");
            $row = db_fetch_assoc($sql);
            $r = urlencode($_SERVER['REQUEST_URI']);
            $refresh = get_module_pref('user_refresh');
            $enableSounds = get_module_pref('user_sounds');
            $ninja = get_module_pref('user_ninja');
            $timeout = get_module_setting('timeout');
            if (get_module_pref('user_jumpto') == 1) {
                $autoscroll = "\n                        \$('html, body').animate({\n                            scrollTop: \$('.live-commentary').delay(500).offset().top\n                        }, 400);";
            }
            rawoutput("<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js'></script>");
            if ((httpget('comscroll') == '' || httpget('comscroll') == '0') && $args['section'] != ' OR 1=1 ' && $jQueryScript == 0 && get_module_pref('user_disable') != 1) {
                rawoutput("<script type='text/javascript'>\n                    var currentTimeout = 0;\n                    var lastKeyUp = 0;\n                    var myComment = 'test';\n                    var myCommentID = 0;\n                    var lastCommentID = 0;\n                    var messageid = 0;\n                    var whosTyping = '<br />';\n                    var isInputEmpty = 0;\n                    \$(document).ready(function(){\n                        \$('#inputinsertcommentary').val(localStorage['commentaryForm']);\n                        \$('#commentaryform .button').hide();\n                        if (typeof renewWhosHere == 'function') {\n                            renewWhosHere();\n                        }\n                        {$autoscroll}\n                        reloadCommentary(true);\n                        setInterval(function() {\n                            currentTimeout += {$refresh};\n                            if(currentTimeout > {$timeout}) {\n                                \$('.live-commentary').html('Please click \\'Refresh\\' to reload the commentary!');\n                                \$('.whoshere').html('...');\n                            }\n                            else {\n                                if ((currentTimeout - lastKeyUp) > 0) {\n                                    notTyping();\n                                    isInputEmpty = 0;\n                                }\n                                reloadCommentary();\n                            }\n                        }, {$refresh}*1000);\n                        \$('#inputinsertcommentary').keypress(function(e) {\n                            var lastKeyUp = currentTimeout;\n                            var input = \$(this).val();\n                            localStorage.setItem('commentaryForm', input);\n                            \$('#charsleftinsertcommentary').hide();\n                            if (isInputEmpty == 0 && input.length != 0 && {$ninja} != 1) {\n                                isTyping();\n                                isInputEmpty++;\n                            }\n                            if (input.length == 0) {\n                                \$('#previewtextinsertcommentary').hide();\n                            }\n                            else if (input.length != 0) {\n                                \$('#previewtextinsertcommentary').show();\n                            }\n                            if (input == '/edit' || (e.keyCode == '38' && input.length < 1)) {\n                                \$(this).val(myComment.replace(/(\\<.*?\\>)/ig, '').replace(/\\`\\`/ig, '`')).attr('name','updatecommentary_' + myCommentID);\n                            }\n                            if (e.keyCode == 13) {\n                                e.preventDefault();\n                                jquerypostcommentary();\n                                return false;\n                            }\n                            currentTimeout = 0;\n                        });\n                    \$('.live-commentary').on('click', '.deleteCommentary', function(event) {\n                        \$('.live-commentary').load('runmodule.php?module=jquerycommentary&ajax=1&section={$args['section']}&c={$session['counter']}&r={$r}&rmvcmmnt='+\$(this).attr('data-comment-id'));\n                    });\n                    });\n                    function jquerypostcommentary() \n                    {\n                        var postData = \$('#inputinsertcommentary').val().replace('/(\\<.*?\\>)/', ' ');\n                        var nameData = \$('#inputinsertcommentary').attr('name');\n                        var formURL = \$('#jquerycommentaryform').attr('action');\n                        \$.ajax({\n                            url : 'runmodule.php?module=jquerycommentary&op=post',\n                            type: 'POST',\n                            data : {method: nameData, comment: postData},\n                            success: function (data){\n                                localStorage.setItem('commentaryForm', '');\n                                \$('#inputinsertcommentary').val('').attr('name','insertcommentary');\n                                notTyping();\n                                \$('#charsleftinsertcommentary, #previewtextinsertcommentary').hide();\n                            },\n                            error: function(){\n                                alert('We could not successfully post. Check your internet connection, or wait a minute.');\n                            }\n                        });\n                        reloadCommentary(true);\n                        return false;\n                    }\n                    function reloadCommentary(force)\n                    {\n                        \$('.is_typing').html(whosTyping);\n                        \$.getJSON('runmodule.php?module=jquerycommentary&op=last_comment', function(comments) {\n                            console.log(comments);\n                                myComment = comments.comment;\n                                myCommentID = comments.commentid;\n                                lastMessage = comments.last_message;\n                                if ((comments.last_comment != lastCommentID && lastCommentID != 0 && comments.last_section != 'blackhole' && {$enableSounds} == 1) || force == true) {\n                                    \$('.live-commentary').load('runmodule.php?module=jquerycommentary&ajax=1&section={$args['section']}&c={$session['counter']}&r={$r}');\n                                    \$.getJSON('runmodule.php?module=api&modulename=checkmail', function(messages) {\n                                        if (messages.length > 0) {\n                                            if (messages[0].seen == 1) {\n                                                newMail();\n                                            }\n                                            else {\n                                                clearMail();\n                                            }\n                                        }\n                                        else {\n                                            clearMail();\n                                        }\n                                    });\n                                    if (!force) {\n                                        notifyNewComment(lastCommentID);\n                                    }\n                                }\n                                else if (comments.last_comment < lastCommentID || (comments.last_section == 'blackhole' && comments.last_comment != lastCommentID)) {\n                                    \$('.live-commentary').load('runmodule.php?module=jquerycommentary&ajax=1&section={$args['section']}&c={$session['counter']}&r={$r}');\n                                    if (typeof renewWhosHere == 'function') {\n                                        renewWhosHere();\n                                    }\n                                    \$.getJSON('runmodule.php?module=api&modulename=checkmail', function(messages) {\n                                        if (messages.length > 0) {\n                                            if (messages[0].seen == 1) {\n                                                newMail();\n                                            }\n                                            else {\n                                                clearMail();\n                                            }\n                                        }\n                                        else {\n                                            clearMail();\n                                        }\n                                    });\n                                }\n                                lastCommentID = comments.last_comment;\n                        });\n                    }\n                    function notifyNewComment(ID)\n                    {\n                        notification = new Audio('templates/assets/newMessage.mp3');\n                        notification.volume = .4;\n                        notification.play();\n                    }\n                    function isTyping()\n                    {\n                        \$.ajax({\n                            type: 'POST',\n                            url: 'runmodule.php?module=jquerycommentary&op=is_typing',\n                            data: {typing: 'yes'},\n                            success: function (message, status, jqXHR) {\n                                whosTyping = message;\n                            }\n                        });\n                    }\n                    function notTyping()\n                    {\n                        \$.ajax({\n                            type: 'POST',\n                            url: 'runmodule.php?module=jquerycommentary&op=is_typing',\n                            data: {typing: 'no'},\n                            success: function (message, status, jqXHR) {\n                                whosTyping = message;\n                            }\n                        });\n                    }\n                    function newMail()\n                    {\n                        \$('a[name=maillink]').html('Mailbox').removeClass('motd').addClass('unreadmotd');\n                        \$('.alerts').html('You have a new mail!').animate({\n                            height: '1.25em'\n                        }, 500);\n                    }\n                    function clearMail()\n                    {\n                        \$('a[name=maillink]').html('Mailbox').removeClass('unreadmotd').addClass('motd');\n                        \n                    \$('.alerts').html('').animate({\n                        height: '0em'\n                    }, 500);\n                    }\n                </script>");
                $jQueryScript++;
                rawoutput("</div>\n                        <jquerycommentaryend></jquerycommentaryend>\n                        <div class='is_typing' style='display: inline-block;'></div>\n                        <div class='commentary_sound'></div>");
            } elseif (httpget('comscroll') != '' && httpget('comscroll') != '0') {
                rawoutput("<script type='text/javascript'>\n                    \$(document).ready(function(){\n                        \$('#commentaryform').hide();\n                    });\n                    </script>");
            }
            break;
    }
    return $args;
}
function friendlist_faq()
{
    $c = translate_inline("Return to the Contents");
    output_notl("`#<strong><center><a href='petition.php?op=faq'>{$c}</a></center></strong>`0", true);
    addnav("", "petition.php?op=faq");
    rawoutput("<hr>");
    output("`c`&`bQuestions about Friend Lists`b`c`n");
    output("`^1. Where is it?`n");
    output("`@Just click the link at the top of the mail page.`n`n");
    output("`^2. What is it for?`n");
    output("`@You can send requests to add someone to both of your lists.`nIf the other user accepts, you will be able to see their status, location, and whether or not they are logged in.`n`n");
    output("`^3. Anything else?`n");
    output("`@You can ignore players that harass you, to prevent them from sending you mail.`nYou can ignore Admin, however their mails will still come through.`n`n");
    if (get_module_setting('allowStat')) {
        output("`^4. Sure that's it?`n");
        output("`@Oh, I forgot!;) You can turn on a preference to see how many of your friends are online.");
    }
    rawoutput("<hr>");
    output_notl("`#<strong><center><a href='petition.php?op=faq'>{$c}</a></center></strong>`0", true);
}
function module_display_events($eventtype, $forcescript = false)
{
    global $PHP_SELF, $session;
    if (!($session['user']['superuser'] & SU_DEVELOPER)) {
        return;
    }
    if ($forcescript === false) {
        $script = substr($PHP_SELF, strrpos($PHP_SELF, "/") + 1);
    } else {
        $script = $forcescript;
    }
    $events = module_collect_events($eventtype, true);
    if (!is_array($events) || count($events) == 0) {
        return;
    }
    usort($events, "event_sort");
    tlschema("events");
    output("`n`nSpecial event triggers:`n");
    $name = translate_inline("Name");
    $rchance = translate_inline("Raw Chance");
    $nchance = translate_inline("Normalized Chance");
    rawoutput("<table cellspacing='1' cellpadding='2' border='0' bgcolor='#999999'>");
    rawoutput("<tr class='trhead'>");
    rawoutput("<td>{$name}</td><td>{$rchance}</td><td>nchance</td>");
    rawoutput("</tr>");
    $i = 0;
    foreach ($events as $event) {
        // Each event is an associative array of 'modulename',
        // 'rawchance' and 'normchance'
        rawoutput("<tr class='" . ($i % 2 == 0 ? "trdark" : "trlight") . "'>");
        $i++;
        if ($event['modulename']) {
            $link = "module-{$event['modulename']}";
            $name = $event['modulename'];
        }
        $rlink = "{$script}?eventhandler={$link}";
        $rlink = str_replace("?&", "?", $rlink);
        $first = strpos($rlink, "?");
        $rl1 = substr($rlink, 0, $first + 1);
        $rl2 = substr($rlink, $first + 1);
        $rl2 = str_replace("?", "&", $rl2);
        $rlink = $rl1 . $rl2;
        rawoutput("<td><a href='{$rlink}'>{$name}</a></td>");
        addnav("", "{$rlink}");
        rawoutput("<td>{$event['rawchance']}</td>");
        rawoutput("<td>{$event['normchance']}</td>");
        rawoutput("</tr>");
    }
    rawoutput("</table>");
}
    rawoutput("</td><td>");
    // "43200" used so will basically round to nearest day rather than floor number of days
    $expire = sprintf_translate("%s days", round((strtotime($row['banexpire']) + 43200 - strtotime("now")) / 86400, 0));
    if (substr($expire, 0, 2) == "1 ") {
        $expire = translate_inline("1 day");
    }
    if (date("Y-m-d", strtotime($row['banexpire'])) == date("Y-m-d")) {
        $expire = translate_inline("Today");
    }
    if (date("Y-m-d", strtotime($row['banexpire'])) == date("Y-m-d", strtotime("1 day"))) {
        $expire = translate_inline("Tomorrow");
    }
    if ($row['banexpire'] == "0000-00-00") {
        $expire = translate_inline("Never");
    }
    output_notl("%s", $expire);
    rawoutput("</td><td>");
    output_notl("%s", $row['banreason']);
    rawoutput("</td><td>");
    $file = "user.php?op=removeban&subop=xml&ip={$row['ipfilter']}&id={$row['uniqueid']}";
    rawoutput("<div id='user{$i}'><a href='{$file}' target='_blank' onClick=\"getUserInfo('{$row['ipfilter']}','{$row['uniqueid']}',{$i}); return false;\">");
    output_notl("%s", $showuser, true);
    rawoutput("</a></div>");
    addnav("", $file);
    rawoutput("</td><td>");
    output_notl("%s", relativedate($row['lasthit']));
    rawoutput("</td></tr>");
    $i++;
}
rawoutput("</table>");