function getsetting($settingname, $default)
{
    global $settings;
    global $DB_USEDATACACHE, $DB_DATACACHEPATH;
    if ($settingname == "usedatacache") {
        return $DB_USEDATACACHE;
    } elseif ($settingname == "datacachepath") {
        return $DB_DATACACHEPATH;
    }
    if (!isset($settings[$settingname])) {
        loadsettings();
    } else {
        return $settings[$settingname];
    }
    if (!isset($settings[$settingname])) {
        savesetting($settingname, $default);
        return $default;
    } else {
        return $settings[$settingname];
    }
}
function getsetting(string $settingname, $default)
{
    global $settings, $DB_USEDATACACHE, $DB_DATACACHEPATH;
    if ($settingname == 'usedatacache') {
        return $DB_USEDATACACHE;
    } else {
        if ($settingname == 'datacachepath') {
            return $DB_DATACACHEPATH;
        }
    }
    if (!isset($settings[$settingname])) {
        loadsettings();
    } else {
        return $settings[$settingname];
    }
    if (!isset($settings[$settingname])) {
        savesetting($settingname, $default);
        return $default;
    } else {
        return $settings[$settingname];
    }
}
function getsetting($settingname, $default)
{
    global $settings;
    loadsettings();
    if (!isset($settings[$settingname])) {
        savesetting($settingname, $default);
        return $default;
    } else {
        if (trim($settings[$settingname]) == "") {
            $settings[$settingname] = $default;
        }
        return $settings[$settingname];
    }
}
/**
 * Returns the current character stats or (if the character isn't logged in) the currently online players
 * Hooks provided:
 *		charstats
 *
 * @return array The current stats for this character or the list of online players
 */
function charstats()
{
    global $session, $playermount, $companions;
    wipe_charstats();
    $u =& $session['user'];
    if ($session['loggedin']) {
        $u['hitpoints'] = round($u['hitpoints'], 0);
        $u['experience'] = round($u['experience'], 0);
        $u['maxhitpoints'] = round($u['maxhitpoints'], 0);
        // $spirits=array(-6=>"Resurrected",-2=>"Very Low",-1=>"Low","0"=>"Normal",1=>"High",2=>"Very High");
        // if ($u['alive']){ }else{ $spirits[(int)$u['spirits']] = "DEAD"; }
        //calculate_buff_fields();
        reset($session['bufflist']);
        $atk = $u['attack'];
        $def = $u['defense'];
        $buffcount = 0;
        $buffs = "";
        while (list($key, $val) = each($session['bufflist'])) {
            if (isset($val['suspended']) && $val['suspended']) {
                continue;
            }
            if (isset($val['atkmod'])) {
                $atk *= $val['atkmod'];
            }
            if (isset($val['defmod'])) {
                $def *= $val['defmod'];
            }
            // Short circuit if the name is blank
            if ($val['name'] > "" || $session['user']['superuser'] & SU_DEBUG_OUTPUT) {
                tlschema($val['schema']);
                if ($val['name'] == "") {
                    $val['name'] = "DEBUG: {$key}";
                }
                if (is_array($val['name'])) {
                    $val['name'][0] = str_replace("`%", "`%%", $val['name'][0]);
                    $val['name'] = call_user_func_array("sprintf_translate", $val['name']);
                } else {
                    //in case it's a string
                    $val['name'] = translate_inline($val['name']);
                }
                if ($val['rounds'] >= 0) {
                    // We're about to sprintf, so, let's makes sure that
                    // `% is handled.
                    //$n = translate_inline(str_replace("`%","`%%",$val['name']));
                    $b = translate_inline("`#%s `7(%s rounds left)`n", "buffs");
                    $b = sprintf($b, $val['name'], $val['rounds']);
                    $buffs .= appoencode($b, true);
                } else {
                    $buffs .= appoencode("`#{$val['name']}`n", true);
                }
                tlschema();
                $buffcount++;
            }
        }
        if ($buffcount == 0) {
            $buffs .= appoencode(translate_inline("`^None`0"), true);
        }
        $atk = round($atk, 2);
        $def = round($def, 2);
        if ($atk < $u['attack']) {
            $atk = round($u['attack'], 1) . "`\$" . round($atk - $u['attack'], 1);
        } else {
            if ($atk > $u['attack']) {
                $atk = round($u['attack'], 1) . "`@+" . round($atk - $u['attack'], 1);
            } else {
                // They are equal, display in the 1 signifigant digit format.
                $atk = round($atk, 1);
            }
        }
        if ($def < $u['defense']) {
            $def = round($u['defense'], 1) . "`\$" . round($def - $u['defense'], 1);
        } else {
            if ($def > $u['defense']) {
                $def = round($u['defense'], 1) . "`@+" . round($def - $u['defense'], 1);
            } else {
                // They are equal, display in the 1 signifigant digit format.
                $def = round($def, 1);
            }
        }
        addcharstat("Vital Info");
        //health bar
        if ($u['alive']) {
            $cur = $u['hitpoints'];
            $realmax = $u['maxhitpoints'];
            $cur_adjustment = check_temp_stat("hitpoints", 1);
            $max_adjustment = check_temp_stat("maxhitpoints", 1);
        } else {
            $cur = $u['soulpoints'];
            $realmax = $u['level'] * 5 + 50;
            $cur_adjustment = check_temp_stat("soulpoints", 1);
            $max_adjustment = "";
        }
        if ($pct > 60) {
            $ccode = "`@";
        } elseif ($pct > 25) {
            $ccode = "`^";
        } else {
            $ccode = "`\$";
        }
        $hicode = "`&";
        if (!$u['alive']) {
            $ccode = "`7";
        }
        require_once "lib/bars.php";
        $hpbar = fadebar($cur, $realmax);
        $stat = "{$ccode} {$cur} {$cur_adjustment} `0/ {$realmax} {$max_adjustment}<br />" . $hpbar;
        if ($u['alive']) {
            addcharstat("Hitpoints", $stat);
            addcharstat("Attack", $atk . check_temp_stat("attack", 1));
            addcharstat("Defence", $def . check_temp_stat("defense", 1));
        } else {
            addcharstat("Adrenaline", $stat);
            addcharstat("Attack", 10 + round(($u['level'] - 1) * 1.5));
            addcharstat("Defence", 10 + round(($u['level'] - 1) * 1.5));
        }
        // addcharstat("Turns", $u['turns'].check_temp_stat("turns",1));
        // addcharstat("Attack", $atk.check_temp_stat("attack",1));
        // addcharstat("Defence", $def.check_temp_stat("defense",1));
        if (count($companions) > 0) {
            addcharstat("Companions");
            foreach ($companions as $name => $companion) {
                if ($companion['hitpoints'] > 0 || isset($companion['cannotdie']) && $companion['cannotdie'] == true) {
                    if ($companion['hitpoints'] < 0) {
                        $companion['hitpoints'] = 0;
                    }
                    if ($companion['hitpoints'] < $companion['maxhitpoints']) {
                        $color = "`\$";
                    } else {
                        $color = "`@";
                    }
                    if (isset($companion['suspended']) && $companion['suspended'] == true) {
                        $suspcode = "`7 *";
                    } else {
                        $suspcode = "";
                    }
                    addcharstat($companion['name'], $color . $companion['hitpoints'] . "`7/`&" . $companion['maxhitpoints'] . "{$suspcode}`0");
                }
            }
        }
        addcharstat("Personal Info");
        if ($u['alive']) {
            addcharstat("Requisition", number_format($u['gold'] . check_temp_stat("gold", 1)));
            addcharstat("Cigarettes", number_format($u['gems'] . check_temp_stat("gems", 1)));
        } else {
            addcharstat("Cage Fights", $u['gravefights'] . check_temp_stat("gravefights", 1));
            addcharstat("Favour", number_format($u['deathpower'] . check_temp_stat("deathpower", 1)));
        }
        if ($u['alive']) {
            addcharstat("Level", "`b" . $u['level'] . check_temp_stat("level", 1) . "`b");
            //exp bar
            require_once "lib/experience.php";
            $min = exp_for_next_level($u['level'] - 1, $u['dragonkills']);
            $req = exp_for_next_level($u['level'], $u['dragonkills']);
            $exp = round($session['user']['experience'], 0) . check_temp_stat("experience", 1);
            if ($exp < $min) {
                $min = $exp;
            }
            if ($req - $min > 0) {
                $nonpct = floor(($req - $exp) / ($req - $min) * 100);
            } else {
                $nonpct = 0;
            }
            $pct = 100 - $nonpct;
            if ($pct > 100) {
                $pct = 100;
                $nonpct = 0;
            }
            if ($pct < 0) {
                $pct = 0;
                $nonpct = 100;
            }
            if ($exp >= $req) {
                $color = "blue";
                if ($session['user']['level'] == 1 && $session['user']['dragonkills'] == 0) {
                    $expmsg = "<br />You have enough experience to level up!  Challenge your master in the Dojo!";
                }
            } else {
                $color = "white";
            }
            addcharstat("Experience", number_format($u['experience'] . check_temp_stat("experience", 1)) . "/{$req}<br /><table style='border: solid 1px #000000;' bgcolor='red'  cellpadding='0' cellspacing='0' width='70' height='5'><tr><td width='{$pct}%' bgcolor='{$color}'></td><td width='{$nonpct}%'></td></tr></table>{$expmsg}");
            addcharstat("Equipment Info");
            addcharstat("Weapon", $u['weapon']);
            addcharstat("Armor", $u['armor']);
            if ($u['hashorse']) {
                addcharstat("Creature", $playermount['mountname'] . "`0");
            }
        }
        require_once "lib/datetime.php";
        $gt = gametimedetails();
        addcharstat("Game State");
        addcharstat("Game Time", gmdate("g:i a", $gt['gametime']));
        addcharstat("New day in:", date("H:i:s", secondstonextgameday()));
        modulehook("charstats");
        $charstat = getcharstats($buffs);
        if (!is_array($session['bufflist'])) {
            $session['bufflist'] = array();
        }
        return $charstat;
    } else {
        $ret = "";
        if ($ret = datacache("charlisthomepage")) {
        } else {
            $onlinecount = 0;
            // If a module wants to do it's own display of the online chars,
            // let it.
            $list = modulehook("onlinecharlist", array());
            if (isset($list['handled']) && $list['handled']) {
                $onlinecount = $list['count'];
                $ret = $list['list'];
            } else {
                $sql = "SELECT name,alive,location,sex,level,laston,loggedin,lastip,uniqueid 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 level DESC";
                $result = db_query($sql);
                $ret .= appoencode(sprintf(translate_inline("`bOnline Characters (%s players):`b`n"), db_num_rows($result)));
                while ($row = db_fetch_assoc($result)) {
                    $ret .= appoencode("`^{$row['name']}`n");
                    $onlinecount++;
                }
                db_free_result($result);
                if ($onlinecount == 0) {
                    $ret .= appoencode(translate_inline("`iNone`i"));
                }
            }
            savesetting("OnlineCount", $onlinecount);
            savesetting("OnlineCountLast", strtotime("now"));
            updatedatacache("charlisthomepage", $ret);
        }
        return $ret;
    }
}
function rss_run()
{
    if (httpget("op") == "describe") {
        global $session;
        page_header("RSS Feed Information");
        output("This site offers RSS news feeds for periodically updated information about various aspects of the game.");
        output("Click %shere%s for more information about the RSS format.`n`n", "<a href='http://www.google.com/search?q=rss+information' target='_blank'>", "</a>", true);
        output("Feeds offered on this site:`n");
        $format = "`#&#149;`7 %s`n";
        addnav("Get RSS News Feeds");
        if (get_module_setting("do_news")) {
            addnav("Daily News", "runmodule.php?module=rss&feed=news", false, true);
            output($format, "Daily News", true);
        }
        if (get_module_setting("do_online")) {
            addnav("Who's Online", "runmodule.php?module=rss&feed=online", false, true);
            output($format, "Who's Online", true);
        }
        if (get_module_setting("do_motd")) {
            addnav("MoTD", "runmodule.php?module=rss&feed=motd", false, true);
            output($format, "Message of the Day (MoTD)", true);
        }
        addnav("Other");
        addnav("About LoGD", "about.php");
        if ($session['user']['loggedin']) {
            addnav("Return to the news", "news.php");
        } else {
            addnav("Login Page", "index.php");
        }
        page_footer();
        return;
    }
    $items = array();
    $feedtitle = "";
    $pubtime = date("Y-m-d H:i:s");
    $link = getsetting("serverurl", "http://" . $_SERVER['SERVER_NAME'] . ($_SERVER['SERVER_PORT'] == 80 ? "" : ":" . $_SERVER['SERVER_PORT']) . dirname($_SERVER['SCRIPT_NAME']));
    if (!preg_match("/\\/\$/", $link)) {
        $link = $link . "/";
        savesetting("serverurl", $link);
    }
    $feed = httpget("feed");
    //filter out turned-off feeds
    if ($feed == "news" && !get_module_setting("do_news")) {
        $feed = "";
    }
    if ($feed == "motd" && !get_module_setting("do_motd")) {
        $feed = "";
    }
    if ($feed == "online" && !get_module_setting("do_online")) {
        $feed = "";
    }
    switch ($feed) {
        case "news":
            $feedtitle = "LoGD News";
            $sql = "SELECT newstext,arguments,newsdate,now() AS currenttime,tlschema FROM " . db_prefix("news") . " ORDER BY newsid DESC LIMIT 10";
            $result = db_query_cached($sql, "mod_rss_news", get_module_setting("cache_timeout"));
            while ($row = db_fetch_assoc($result)) {
                $pubtime = $row['currenttime'];
                $arguments = array();
                $base_arguments = @unserialize($row['arguments']);
                array_push($arguments, $row['newstext']);
                while ($base_arguments && (list($key, $val) = each($base_arguments))) {
                    array_push($arguments, $val);
                }
                tlschema($row['tlschema']);
                $title = call_user_func_array("sprintf_translate", $arguments);
                tlschema();
                array_push($items, array("title" => $title, "description" => $title, "pubDate" => $row['newsdate'], "link" => $link . "news.php"));
            }
            if (count($items) == 0) {
                $items = array(array("title" => sprintf_translate("There are no news items", array()), "description" => "", "pubDate" => date("Y-m-d H:i:s"), "link" => $link . "news.php"));
            }
            break;
        case "online":
            $feedtitle = "LoGD Who's Online";
            $sql = "SELECT name,alive,location,sex,level,race,now() AS currenttime 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 level DESC";
            $result = db_query_cached($sql, "mod_rss_online", get_module_setting("cache_timeout"));
            while ($row = db_fetch_assoc($result)) {
                $pubtime = $row['currenttime'];
                array_push($items, array("title" => $row['name'], "description" => sprintf_translate("Level %s " . ($row['sex'] ? "female" : "male") . " %s in %s", $row['level'], strtolower($row['race']), $row['location']), "pubDate" => $row['currenttime'], "link" => $link));
            }
            if (count($items) == 0) {
                $items = array(array("title" => sprintf_translate("There are no characters online at this time.", array()), "description" => "", "pubDate" => date("Y-m-d H:i:s"), "link" => $link));
            }
            db_free_result($result);
            if ($onlinecount == 0) {
                $ret .= appoencode("`iNone`i");
            }
            break;
        case "motd":
            $sql = "SELECT motddate,motdbody,motdtitle,name AS motdauthorname,now() AS currenttime FROM " . db_prefix("motd") . " LEFT JOIN " . db_prefix("accounts") . " ON " . db_prefix("accounts") . ".acctid = " . db_prefix("motd") . ".motdauthor ORDER BY motddate DESC limit 10";
            $result = db_query_cached($sql, "mod_rss_motd", get_module_setting("cache_timeout"));
            $feedtitle = "Message of the Day";
            while ($row = db_fetch_assoc($result)) {
                $pubdate = $row['currenttime'];
                array_push($items, array("title" => $row['motdtitle'], "description" => "By {$row['motdauthorname']}\n{$row['motdbody']}", "pubDate" => $row['motddate'], "link" => $link . "motd.php#motd" . date("YmdHis", strtotime($row['motddate']))));
            }
            break;
        default:
            $feedtitle = "No such feed exists";
            $items = array(array("title" => "You have requested a news feed that does not exist.", "desription" => "The news feed you requested does not exist.  This could be because you are using an outdated feed.  Please visit the site at {$link} to try again."), "pubDate" => date("Y-m-d H:i:s"), "link" => $link);
    }
    //build the RSS feed.
    header("Content-Type: text/xml", true);
    echo "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>";
    echo "<rss version=\"2.0\">";
    echo "<channel>";
    echo "<title>" . rss_xmlencode($feedtitle) . "</title>";
    echo "<link>" . rss_xmlencode($link) . "</link>";
    echo "<description>Legend of the Green Dragon -- a browser based text roleplaying game based loosely on the old BBS game Legend of the Red Dragon (LoRD)</description>";
    echo "<language>en-us</language>";
    echo "<copyright>Copyright 2002-" . date("Y") . ", Eric Stevens &amp; JT Traub</copyright>";
    echo "<pubDate>" . date("r", strtotime($pubdate)) . "</pubDate>";
    echo "<lastBuildDate>" . date("r", strtotime($pubdate)) . "</lastBuildDate>";
    echo "<category>LotGD: " . rss_xmlencode($feedtitle) . "</category>";
    echo "<ttl>" . get_module_setting("ttl") . "</ttl>";
    echo "<image>";
    echo "<title>Legend of the Green Dragon</title>";
    echo "<url>" . rss_xmlencode($link) . "images/title.gif</url>";
    echo "<link>" . rss_xmlencode($link) . "</link>";
    echo "</image>";
    reset($items);
    while (list($key, $val) = each($items)) {
        echo "<item>";
        echo "<title>" . rss_xmlencode($val['title']) . "</title>";
        echo "<link>" . rss_xmlencode($val['link']) . "</link>";
        echo "<guid isPermaLink=\"false\">" . rss_xmlencode($val['link']) . "</guid>";
        echo "<description>" . rss_xmlencode($val['description']) . "</description>";
        echo "<pubDate>" . date("r", strtotime($val['pubDate'])) . "</pubDate>";
        echo "</item>";
    }
    echo "</channel>";
    echo "</rss>";
    exit;
}
<?php

// translator ready
// addnews ready
// mail ready
require_once "lib/constants.php";
$lastexpire = strtotime(getsetting("last_char_expire", "0000-00-00 00:00:00"));
$needtoexpire = strtotime("-23 hours");
if ($lastexpire < $needtoexpire) {
    savesetting("last_char_expire", date("Y-m-d H:i:s"));
    $old = getsetting("expireoldacct", 45);
    $new = getsetting("expirenewacct", 10);
    $trash = getsetting("expiretrashacct", 1);
    # First, get the account ids to delete the user prefs.
    $sql1 = "SELECT login,acctid,dragonkills,level FROM " . db_prefix("accounts") . " WHERE (superuser&" . NO_ACCOUNT_EXPIRATION . ")=0 AND (1=0\n" . ($old > 0 ? "OR (laston < \"" . date("Y-m-d H:i:s", strtotime("-{$old} days")) . "\")\n" : "") . ($new > 0 ? "OR (laston < \"" . date("Y-m-d H:i:s", strtotime("-{$new} days")) . "\" AND level=1 AND dragonkills=0)\n" : "") . ($trash > 0 ? "OR (laston < \"" . date("Y-m-d H:i:s", strtotime("-" . ($trash + 1) . " days")) . "\" AND level=1 AND experience < 10 AND dragonkills=0)\n" : "") . ")";
    $result1 = db_query($sql1);
    $acctids = array();
    $pinfo = array();
    $dk0lvl = 0;
    $dk0ct = 0;
    $dk1lvl = 0;
    $dk1ct = 0;
    $dks = 0;
    while ($row1 = db_fetch_assoc($result1)) {
        require_once "lib/charcleanup.php";
        if (!char_cleanup($row1['acctid'], CHAR_DELETE_AUTO)) {
            continue;
        }
        array_push($acctids, $row1['acctid']);
        array_push($pinfo, "{$row1['login']}:dk{$row1['dragonkills']}-lv{$row1['level']}");
        if ($row1['dragonkills'] == 0) {
if ($session['user']['superuser'] & SU_MEGAUSER) {
    $session['user']['superuser'] = $session['user']['superuser'] | SU_EDIT_USERS;
}
translator_setup();
//set up the error handler after the intial setup (since it does require a
//db call for notification)
require_once "lib/errorhandler.php";
// WARNING:
// do not hook on these modulehooks unless you really need your module to run
// on every single page hit.  This is called even when the user is not
// logged in!!!
// This however is the only context where blockmodule can be called safely!
// You should do as LITTLE as possible here and consider if you can hook on
// a page header instead.
modulehook("everyhit");
if ($session['user']['loggedin']) {
    modulehook("everyhit-loggedin");
}
// This bit of code checks the current system load, so that high-intensity operations can be disabled or postponed during times of exceptionally high load.  Since checking system load can in itself be resource intensive, we'll only check system load once per thirty seconds, checking it against time retrieved from the database at the first load of getsetting().
global $fiveminuteload;
$lastcheck = getsetting("systemload_lastcheck", 0);
$fiveminuteload = getsetting("systemload_lastload", 0);
$currenttime = time();
if ($currenttime - $lastcheck > 30) {
    $load = exec("uptime");
    $load = split("load average:", $load);
    $load = split(", ", $load[1]);
    $fiveminuteload = $load[1];
    savesetting("systemload_lastload", $fiveminuteload);
    savesetting("systemload_lastcheck", $currenttime);
}
/**
 * Returns the current character stats or (if the character isn't logged in) the currently online players
 * Hooks provided:
 *		charstats
 *
 * @return array The current stats for this character or the list of online players
 */
function charstats()
{
    global $session, $playermount, $companions;
    wipe_charstats();
    $u =& $session['user'];
    if ($session['loggedin']) {
        $u['hitpoints'] = round($u['hitpoints'], 0);
        $u['experience'] = round($u['experience'], 0);
        $u['maxhitpoints'] = round($u['maxhitpoints'], 0);
        $spirits = array(-6 => "Resurrected", -2 => "Very Low", -1 => "Low", "0" => "Normal", 1 => "High", 2 => "Very High");
        if ($u['alive']) {
        } else {
            $spirits[(int) $u['spirits']] = "DEAD";
        }
        //calculate_buff_fields();
        reset($session['bufflist']);
        $atk = $u['attack'];
        $def = $u['defense'];
        $buffcount = 0;
        $buffs = "";
        while (list($key, $val) = each($session['bufflist'])) {
            if (isset($val['suspended']) && $val['suspended']) {
                continue;
            }
            if (isset($val['atkmod'])) {
                $atk *= $val['atkmod'];
            }
            if (isset($val['defmod'])) {
                $def *= $val['defmod'];
            }
            // Short circuit if the name is blank
            if ($val['name'] > "" || $session['user']['superuser'] & SU_DEBUG_OUTPUT) {
                tlschema($val['schema']);
                if ($val['name'] == "") {
                    $val['name'] = "DEBUG: {$key}";
                }
                if (is_array($val['name'])) {
                    $val['name'][0] = str_replace("`%", "`%%", $val['name'][0]);
                    $val['name'] = call_user_func_array("sprintf_translate", $val['name']);
                } else {
                    //in case it's a string
                    $val['name'] = translate_inline($val['name']);
                }
                if ($val['rounds'] >= 0) {
                    // We're about to sprintf, so, let's makes sure that
                    // `% is handled.
                    //$n = translate_inline(str_replace("`%","`%%",$val['name']));
                    $b = translate_inline("`#%s `7(%s rounds left)`n", "buffs");
                    $b = sprintf($b, $val['name'], $val['rounds']);
                    $buffs .= appoencode($b, true);
                } else {
                    $buffs .= appoencode("`#{$val['name']}`n", true);
                }
                tlschema();
                $buffcount++;
            }
        }
        if ($buffcount == 0) {
            $buffs .= appoencode(translate_inline("`^None`0"), true);
        }
        $atk = round($atk, 2);
        $def = round($def, 2);
        if ($atk < $u['attack']) {
            $atk = round($u['attack'], 1) . "`\$" . round($atk - $u['attack'], 1);
        } else {
            if ($atk > $u['attack']) {
                $atk = round($u['attack'], 1) . "`@+" . round($atk - $u['attack'], 1);
            } else {
                // They are equal, display in the 1 signifigant digit format.
                $atk = round($atk, 1);
            }
        }
        if ($def < $u['defense']) {
            $def = round($u['defense'], 1) . "`\$" . round($def - $u['defense'], 1);
        } else {
            if ($def > $u['defense']) {
                $def = round($u['defense'], 1) . "`@+" . round($def - $u['defense'], 1);
            } else {
                // They are equal, display in the 1 signifigant digit format.
                $def = round($def, 1);
            }
        }
        addcharstat("Vital Info");
        addcharstat("Name", $u['name']);
        addcharstat("Level", "`b" . $u['level'] . check_temp_stat("level", 1) . "`b");
        if ($u['alive']) {
            addcharstat("Hitpoints", $u['hitpoints'] . check_temp_stat("hitpoints", 1) . "`0/" . $u['maxhitpoints'] . check_temp_stat("maxhitpoints", 1));
            addcharstat("Turns", $u['turns'] . check_temp_stat("turns", 1));
            addcharstat("Attack", $atk . check_temp_stat("attack", 1));
            addcharstat("Defense", $def . check_temp_stat("defense", 1));
        } else {
            $maxsoul = $u['level'] * 5 + 50;
            addcharstat("Soulpoints", $u['soulpoints'] . check_temp_stat("soulpoints", 1) . "`0/" . $maxsoul);
            addcharstat("Torments", $u['gravefights'] . check_temp_stat("gravefights", 1));
            addcharstat("Psyche", 10 + round(($u['level'] - 1) * 1.5));
            addcharstat("Spirit", 10 + round(($u['level'] - 1) * 1.5));
        }
        addcharstat("Spirits", translate_inline("`b" . $spirits[(int) $u['spirits']] . "`b"));
        if ($u['race'] != RACE_UNKNOWN) {
            addcharstat("Race", translate_inline($u['race'], "race"));
        } else {
            addcharstat("Race", translate_inline(RACE_UNKNOWN, "race"));
        }
        if (count($companions) > 0) {
            addcharstat("Companions");
            foreach ($companions as $name => $companion) {
                if ($companion['hitpoints'] > 0 || isset($companion['cannotdie']) && $companion['cannotdie'] == true) {
                    if ($companion['hitpoints'] < 0) {
                        $companion['hitpoints'] = 0;
                    }
                    if ($companion['hitpoints'] < $companion['maxhitpoints']) {
                        $color = "`\$";
                    } else {
                        $color = "`@";
                    }
                    if (isset($companion['suspended']) && $companion['suspended'] == true) {
                        $suspcode = "`7 *";
                    } else {
                        $suspcode = "";
                    }
                    addcharstat($companion['name'], $color . $companion['hitpoints'] . "`7/`&" . $companion['maxhitpoints'] . "{$suspcode}`0");
                }
            }
        }
        addcharstat("Personal Info");
        if ($u['alive']) {
            addcharstat("Gold", $u['gold'] . check_temp_stat("gold", 1));
        } else {
            addcharstat("Favor", $u['deathpower'] . check_temp_stat("deathpower", 1));
        }
        addcharstat("Gems", $u['gems'] . check_temp_stat("gems", 1));
        addcharstat("Experience", $u['experience'] . check_temp_stat("experience", 1));
        addcharstat("Equipment Info");
        addcharstat("Weapon", $u['weapon']);
        addcharstat("Armor", $u['armor']);
        if ($u['hashorse']) {
            addcharstat("Creature", $playermount['mountname'] . "`0");
        }
        modulehook("charstats");
        $charstat = getcharstats($buffs);
        if (!is_array($session['bufflist'])) {
            $session['bufflist'] = array();
        }
        return $charstat;
    } else {
        $ret = "";
        if ($ret = datacache("charlisthomepage")) {
        } else {
            $onlinecount = 0;
            // If a module wants to do it's own display of the online chars,
            // let it.
            $list = modulehook("onlinecharlist", array());
            if (isset($list['handled']) && $list['handled']) {
                $onlinecount = $list['count'];
                $ret = $list['list'];
            } else {
                $sql = "SELECT name,alive,location,sex,level,laston,loggedin,lastip,uniqueid 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 level DESC";
                $result = db_query($sql);
                $ret .= appoencode(sprintf(translate_inline("`bOnline Characters (%s players):`b`n"), db_num_rows($result)));
                while ($row = db_fetch_assoc($result)) {
                    $ret .= appoencode("`^{$row['name']}`n");
                    $onlinecount++;
                }
                db_free_result($result);
                if ($onlinecount == 0) {
                    $ret .= appoencode(translate_inline("`iNone`i"));
                }
            }
            savesetting("OnlineCount", $onlinecount);
            savesetting("OnlineCountLast", strtotime("now"));
            updatedatacache("charlisthomepage", $ret);
        }
        return $ret;
    }
}
		if (substr($laston,0,2)=="1 ") $laston="1 day";
		if (date("Y-m-d",strtotime($row[laston])) == date("Y-m-d")) $laston="Today";
		if (date("Y-m-d",strtotime($row[laston])) == date("Y-m-d",strtotime("-1 day"))) $laston="Yesterday";
		if ($loggedin) $laston="Now";
		output($laston);
		output("</td></tr>",true);
	}
	output("</table>",true);
}else if ($HTTP_GET_VARS['op']=="addbounty"){
	if ($session['user']['bounties'] >= getsetting("maxbounties",5)) {
		output("Dag gives you a piercing look. `7\"Ye be thinkin' I be an assassin or somewhat?  Ye already be placin' more than 'nuff bounties for t'day.  Now, be ye gone before I stick a bounty on yer head fer annoyin' me.`n`n");
	} else {
		$fee = getsetting("bountyfee",10);
		if ($fee < 0 || $fee > 100) {
			$fee = 10;
			savesetting("bountyfee",$fee);
		}
		$min = getsetting("bountymin",50);
		$max = getsetting("bountymax",400);
		output("Dag Durnick glances up at you and adjusts the pipe in his mouth with his teeth.`n`7\"So, who ye be wantin' to place a hit on? Just so ye be knowing, they got to be legal to be killin', they got to be at least level " . getsetting("bountylevel",3) . ", and they can't be having too much outstandin' bounty nor be getting hit to frequent like, so if they ain't be listed, they can't be contracted on!  We don't run no slaughterhouse here, we run a.....business.  Also, there be a " . getsetting("bountyfee",10) . "% listin' fee fer any hit ye be placin'.\"`n`n");
		output("<form action='dag.php?op=finalize' method='POST'>",true);
		output("`2Target: <input name='contractname'>`n", true);
		output("`2Amount to Place: <input name='amount' id='amount' width='5'>`n`n",true);
		output("<input type='submit' class='button' value='Finalize Contract'></form>",true);
		addnav("","dag.php?op=finalize");
	}
}elseif ($HTTP_GET_VARS['op']=="finalize") {
	//$name = "%" . rawurldecode($_POST['contractname']) . "%";
	if ($_GET['subfinal']==1){
		$sql = "SELECT acctid,name,login,level,locked,age,dragonkills,pk,experience,bounty FROM accounts WHERE name='".addslashes(rawurldecode(stripslashes($_POST['contractname'])))."' AND locked=0";
		//output($sql);
 output("&#149; Not linking back to LoGDnet`n", true);
 output("Or really, any other reason that we want.`n");
 output("If you've been banned already, chances are you know why, and chances are we've got no interest in removing the ban.");
 output("We provide this free of charge, at the expense of considerable bandwidth and server load, so if you've had the gall to abuse our charity, don't expect it to be won back very easily.`n`n");
 output("If you are well behaved, we don't have an interest in blocking you from this listing. `0`n");
 rawoutput("<table border='0' cellpadding='1' cellspacing='0'>");
 rawoutput("<tr class='trhead'><td>");
 output("Server");
 rawoutput("</td><td>");
 output("Version");
 rawoutput("</td>");
 require_once "lib/pullurl.php";
 $u = getsetting("logdnetserver", "http://logdnet.logd.com/");
 if (!preg_match("/\\/\$/", $u)) {
     $u = $u . "/";
     savesetting("logdnetserver", $u);
 }
 $servers = pullurl($u . "logdnet.php?op=net");
 if (!$servers) {
     $servers = array();
 }
 $i = 0;
 while (list($key, $val) = each($servers)) {
     $row = unserialize($val);
     // If we aren't given an address, continue on.
     if (substr($row['address'], 0, 7) != "http://" && substr($row['address'], 0, 8) != "https://") {
         continue;
     }
     // Give undescribed servers a boring descriptionn
     if (trim($row['description']) == "") {
         $row['description'] = "Another boring and undescribed LotGD server";
function iitems_hunterslodge_run()
{
    global $session;
    page_header("Hunter's Lodge");
    $op = httpget('op');
    $pointsleft = $session['user']['donation'] - $session['user']['donationspent'];
    $pointstotal = $session['user']['donation'];
    $pointsspent = $session['user']['donationspent'];
    switch ($op) {
        case "superuser":
            $sql = "SELECT * FROM " . db_prefix("purchaselog");
            $result = db_query($sql);
            $peritem = array();
            $now = time();
            while ($row = db_fetch_assoc($result)) {
                $item = $row['purchased'];
                $peritem[$item]['sold'] += 1;
                $peritem[$item]['income'] += $row['amount'];
                $time = strtotime($row['timestamp']);
                if (isset($peritem[$item]['firstpurchase']) && $peritem[$item]['firstpurchase'] > $time) {
                    $peritem[$item]['firstpurchase'] = $time;
                } else {
                    if (!isset($peritem[$item]['firstpurchase'])) {
                        $peritem[$item]['firstpurchase'] = $time;
                    }
                }
            }
            foreach ($peritem as $item => $data) {
                $timesincefirst = $now - $data['firstpurchase'];
                $incomeperday = round($data['income'] / ($timesincefirst / 86400) / 100, 2);
                $peritem[$item]['incomeperday'] = $incomeperday;
                $peritem[$item]['item'] = $item;
            }
            function sortbysold($a, $b)
            {
                if ($b['sold'] > $a['sold']) {
                    return true;
                } else {
                    return false;
                }
            }
            function sortbyincome($a, $b)
            {
                if ($b['income'] > $a['income']) {
                    return true;
                } else {
                    return false;
                }
            }
            function sortbydailyincome($a, $b)
            {
                if ($b['incomeperday'] > $a['incomeperday']) {
                    return true;
                } else {
                    return false;
                }
            }
            rawoutput("<table width=100% border=0 cellpadding=0 cellspacing=0><tr class='trhead'><td>Item</td><td>Item Verbose Name</td><td><a href='runmodule.php?module=iitems_hunterslodge&op=superuser&sort=sortbysold'>Units sold</a></td><td><a href='runmodule.php?module=iitems_hunterslodge&op=superuser&sort=sortbyincome'>Profit total</a></td><td><a href='runmodule.php?module=iitems_hunterslodge&op=superuser&sort=sortbydailyincome'>Profit per day</a></td></tr>");
            $classcount = 1;
            addnav("", "runmodule.php?module=iitems_hunterslodge&op=superuser&sort=sortbysold");
            addnav("", "runmodule.php?module=iitems_hunterslodge&op=superuser&sort=sortbyincome");
            addnav("", "runmodule.php?module=iitems_hunterslodge&op=superuser&sort=sortbydailyincome");
            if (httpget('sort')) {
                usort($peritem, httpget('sort'));
            }
            foreach ($peritem as $item => $data) {
                $classcount++;
                $class = $classcount % 2 ? "trdark" : "trlight";
                $vname = get_item_setting("verbosename", $data['item']);
                if (!$vname) {
                    $vname = $data['item'];
                }
                rawoutput("<tr class='{$class}'><td>" . $data['item'] . "</td><td>" . $vname . "</td><td>" . number_format($data['sold']) . "</td><td>\$" . number_format($data['income'] / 100, 2) . "</td><td>\$" . number_format($data['incomeperday'], 2) . "</td></tr>");
            }
            rawoutput("</table>");
            addnav("Return");
            addnav("Back to the Grotto", "superuser.php");
            break;
        case "explain":
            output("You give a friendly nod to the proprietor, and open your mouth to ask him a question.`n`nHe grins back at you.`n`nThere's a small `ipop`iping sensation in the centre of your skull, like a muscle abruptly shifting - and you suddenly realise what this place is all about.`n`n`bAbout Supporter Points`b`nImprobable Island is entirely funded by donations from its players.  When you donate, you get Supporter Points, which you can use on items in the Hunter's Lodge.  You get one hundred Supporter Points per US Dollar, and donations are accepted through PayPal.  To donate, click the coin slot to the lower right of your screen.  Always use the \"Site Admin\" PayPal button when donating if you wish to receive Supporter Points (donations made through the \"Author\" button go to Eric Stevens, the author of the game engine on which Improbable Island was originally based - you don't get any Supporter Points for donating through this button).  You can also get Supporter Points by referring new players to the site (click the Referrals link to the left) or sometimes in `4Other Ways`0 which will be announced from time to time.`n`n`bTo give presents`b`nAll Hunter's Lodge items (and most other in-game items) can be given as gifts to other players.  Visit the Gifting Station in Common Ground to do so.  Some items can be gifted for free - others cost one Supporter Point each to gift.  Hunter's Lodge items that bestow permanent benefits (IE unlimited title change documents) can only be gifted if they're unused.  In all cases, you'll get to choose your gift-wrap and whether to give anonymously or not.`n`n`bHey, it's my birthday soon.  Can I ask my non-Island-playing mates to buy me points on the Island?`b`nYes!  Just send them to this link:`nhttp://www.improbableisland.com/runmodule.php?module=giftpoints&acctid=%s`n`n", $session['user']['acctid']);
            addnav("Okay");
            addnav("Back to the Hunter's Lodge", "runmodule.php?module=iitems_hunterslodge&op=start");
            addnav("Referrals", "runmodule.php?module=iitems_hunterslodge&op=referrals");
            break;
        case "referrals":
            output("If you help bring new players to Improbable Island, you'll earn one Supporter Point every time those players hit a new Game Day.  To refer players, use this address:`n`n");
            $url = getsetting("serverurl", "http://" . $_SERVER['SERVER_NAME'] . ($_SERVER['SERVER_PORT'] == 80 ? "" : ":" . $_SERVER['SERVER_PORT']) . dirname($_SERVER['REQUEST_URI']));
            if (!preg_match("/\\/\$/", $url)) {
                $url = $url . "/";
                savesetting("serverurl", $url);
            }
            output_notl("%shome.php?r=%s`n`n", $url, rawurlencode($session['user']['login']));
            $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE referer={$session['user']['acctid']} ORDER BY dragonkills,level";
            $result = db_query($sql);
            $number = db_num_rows($result);
            if ($number) {
                output("Accounts you've referred:`n");
                for ($i = 0; $i < $number; $i++) {
                    $row = db_fetch_assoc($result);
                    output_notl("%s`0`n", $row['name']);
                }
            }
            addnav("Okay");
            addnav("Back to the Hunter's Lodge", "runmodule.php?module=iitems_hunterslodge&op=start");
            break;
        case "start":
            output("You head into the Hunter's Lodge.  It's a bright, shiny place, with many expensive-looking items arranged inside glass cabinets.  The proprietor, a snappily-dressed male Joker, grins at you from behind the counter.`n`n");
            if (!has_item("lodgebag")) {
                output("The joker silently hands you a small bag, with a look that suggests you put your purchases inside.`n`n");
                give_item("lodgebag");
            }
            output("`0You have `b`5%s`0`b Supporter Points left, out of `5%s`0 accumulated in total.`n`n", number_format($pointsleft), number_format($pointstotal));
            addnav("What's all this about, then?");
            addnav("How do I get supporter points, or give presents to people?", "runmodule.php?module=iitems_hunterslodge&op=explain");
            $lodgeitems = get_items_with_settings("lodge");
            //debug($lodgeitems);
            rawoutput("<table width=100% style='border: dotted 1px #000000;'>");
            $boughtitems = array();
            $sql = "SELECT * FROM " . db_prefix("purchaselog") . " WHERE acctid = '" . $session['user']['acctid'] . "'";
            $result = db_query($sql);
            while ($row = db_fetch_assoc($result)) {
                $boughtitems[$row['purchased']] = 1;
            }
            foreach ($lodgeitems as $key => $vals) {
                if (!$vals['lodge']) {
                    continue;
                }
                $classcount += 1;
                $class = $classcount % 2 ? "trdark" : "trlight";
                rawoutput("<tr class='{$class}'><td>");
                if ($vals['image']) {
                    rawoutput("<table width=100% cellpadding=0 cellspacing=0><tr><td width=100px align=center><img src=\"images/items/" . $vals['image'] . "\"></td><td>");
                }
                output("`b%s`b`n", stripslashes($vals['verbosename']));
                output("%s`0`n", stripslashes($vals['description']));
                if ($vals['weight']) {
                    output("Weight: %s kg`n`0", $vals['weight']);
                }
                rawoutput("<table width=100%><tr><td width=50%>");
                if ($vals['tradable']) {
                    output("`5Giftable Item`0`n");
                }
                if ($vals['lodge_cost']) {
                    $disp = "`b`5" . number_format($vals['lodge_cost']) . "`0`b Supporter Points";
                    $sdisp = $vals['lodge_cost'] . " Points";
                    output("Price: %s`n", $disp);
                    if ($vals['lodge_limited']) {
                        output("`4Limited Item`0: %s available`n", $vals['lodge_stock']);
                    }
                }
                if ($vals['lodge_limited'] && $vals['lodge_stock'] > 0 || !$vals['lodge_limited']) {
                    if ($vals['lodge_singlebuy'] && $boughtitems[$key]) {
                        output("`7You've already obtained and used this item.  No need to get it again!`n");
                    } else {
                        if ($pointstotal >= $vals['lodge_freebie_threshold'] && $vals['lodge_freebie_threshold']) {
                            output("`2This item is now `bfree`b!`0`n");
                            addnav("", "runmodule.php?module=iitems_hunterslodge&op=buy&item=" . $key . "&freebie=true");
                            rawoutput("<a href=\"runmodule.php?module=iitems_hunterslodge&op=buy&item=" . $key . "&freebie=true\">Get it!</a><br />");
                        } else {
                            if ($vals['lodge_freebie_threshold']) {
                                output("`2This item becomes free once you have accumulated more than %s Supporter Points, spent or unspent.`0`n", $vals['lodge_freebie_threshold']);
                            }
                            if ($pointsleft >= $vals['lodge_cost']) {
                                addnav("Buy Items");
                                addnav(array("%s (%s)", stripslashes($vals['verbosename']), $sdisp), "runmodule.php?module=iitems_hunterslodge&op=buy&item=" . $key, true);
                                addnav("", "runmodule.php?module=iitems_hunterslodge&op=buy&item=" . $key);
                                rawoutput("<a href=\"runmodule.php?module=iitems_hunterslodge&op=buy&item=" . $key . "\">More Details / Buy for " . appoencode($disp) . "</a><br />");
                            } else {
                                output("`&You need another %s Supporter Points for this item.`0`n", number_format($vals['lodge_cost'] - $pointsleft));
                                addnav("", "runmodule.php?module=iitems_hunterslodge&op=buy&item=" . $key . "&cannotafford=1");
                                rawoutput("<a href=\"runmodule.php?module=iitems_hunterslodge&op=buy&item=" . $key . "&cannotafford=1\">More Details</a><br />");
                            }
                        }
                    }
                } else {
                    output("`&Sold out!`0`n");
                }
                rawoutput("</td></tr></table>");
                if ($vals['image']) {
                    rawoutput("</td></tr></table>");
                }
                rawoutput("</td></tr>");
            }
            rawoutput("</td></tr></table>");
            modulehook("hunterslodge");
            break;
        case "buy":
            $itemid = httpget("item");
            $item = get_item_settings($itemid);
            $free = httpget("freebie");
            $cannotafford = httpget("cannotafford");
            //debug($item);
            if ($item['lodge_longdesc']) {
                output_notl("`0%s`0`n`n", stripslashes($item['lodge_longdesc']));
            }
            if (!$cannotafford) {
                if (!$free) {
                    output("You're about to buy a %s for %s Supporter Points, leaving you with %s points available to spend afterwards.`n`n", $item['verbosename'], number_format($item['lodge_cost']), number_format($pointsleft - $item['lodge_cost']));
                    addnav("Confirm");
                    addnav(array("Buy %s for %s Points", stripslashes($item['verbosename']), $item['lodge_cost']), "runmodule.php?module=iitems_hunterslodge&op=buyconfirm&item={$itemid}");
                    addnav("No, I don't want to do that!");
                    addnav("Back to the Lodge", "runmodule.php?module=iitems_hunterslodge&op=start");
                } else {
                    redirect("runmodule.php?module=iitems_hunterslodge&op=buyconfirm&item={$itemid}&freebie=true");
                }
            } else {
                output("`0You need another %s Supporter Points to get this item.`0`n`n", number_format($item['lodge_cost'] - $pointsleft));
                addnav("Okay");
                addnav("Back to the Lodge", "runmodule.php?module=iitems_hunterslodge&op=start");
                addnav("How do I get supporter points?", "runmodule.php?module=iitems_hunterslodge&op=explain");
            }
            break;
        case "buyconfirm":
            $itemid = httpget("item");
            $iteminside = httpget("item_inside");
            $item = get_item_settings($itemid);
            $free = httpget("freebie");
            if (!$free) {
                $cost = $item['lodge_cost'];
                output("You have purchased a %s for %s Supporter Points.  You can find the item in your Inventory.  Thank you for your support!`n`n", $item['verbosename'], $item['lodge_cost']);
                give_item($itemid);
                $session['user']['donationspent'] += $item['lodge_cost'];
            } else {
                //handle freebie items
                give_item($itemid);
                output("`0You now have a %s`0!  Thank you for your support!`n`n", $item['verbosename']);
                $cost = 0;
            }
            if ($item['lodge_limited']) {
                increment_item_setting("lodge_stock", -1, $itemid);
            }
            //log purchase
            $sql = "INSERT INTO " . db_prefix("purchaselog") . " (acctid,purchased,amount,data,giftwrap,timestamp) VALUES ('" . $session['user']['acctid'] . "','" . $itemid . "','" . $cost . "','" . addslashes(serialize($item)) . "','" . $wrap . "','" . date("Y-m-d H:i:s") . "')";
            //debug($sql);
            db_query($sql);
            addnav("Yay!");
            addnav("Back to the Hunter's Lodge", "runmodule.php?module=iitems_hunterslodge&op=start");
            break;
    }
    addnav("Leave");
    addnav("Return to the Outpost", "village.php");
    addnav("Inventory");
    addnav("View your Inventory", "inventory.php?items_context=lodge");
    page_footer();
    return true;
}
                         rawoutput("<input name='password' value=\"{$pass1}\" type='hidden'>");
                         output("Your account was created, your login name is `^%s`0.`n`n", $shortname);
                         $click = translate_inline("Click here to log in");
                         rawoutput("<input type='submit' class='button' value='{$click}'>");
                         rawoutput("</form>");
                         output_notl("`n");
                         if ($trash > 0) {
                             output("`^Characters that have never been logged into will be deleted after %s day(s) of no activity.`n`0", $trash);
                         }
                         if ($new > 0) {
                             output("`^Characters that have never reached level 2 will be deleted after %s days of no activity.`n`0", $new);
                         }
                         if ($old > 0) {
                             output("`^Characters that have reached level 2 at least once will be deleted after %s days of no activity.`n`0", $old);
                         }
                         savesetting("newestplayer", $row['acctid']);
                     }
                 }
             }
         } else {
             output("`\$Error`^:`n%s", $msg);
             $op = "";
         }
     }
 }
 if ($op == "") {
     output("`&`c`bCreate a Character`b`c`0");
     $refer = httpget('r');
     if ($refer) {
         $refer = "&r=" . htmlentities($refer, ENT_COMPAT, getsetting("charset", "ISO-8859-1"));
     }
<?php

output("`@`c`bAll Done!`b`c");
output("Your install of Legend of the Green Dragon has been completed!`n");
output("`nRemember us when you have hundreds of users on your server, enjoying the game.");
output("Eric, JT, and a lot of others put a lot of work into this world, so please don't disrespect that by violating the license.");
if ($session['user']['loggedin']) {
    addnav("Continue", $session['user']['restorepage']);
} else {
    addnav("Login Screen", "./");
}
savesetting("installer_version", $logd_version);
$noinstallnavs = true;
        if ($session['user']['location'] == $settings['innname']) {
            $session['user']['location'] = stripslashes(httppost('innname'));
        }
    }
    if (stripslashes(httppost("motditems")) != $settings['motditems']) {
        invalidatedatacache("motd");
    }
    $post = httpallpost();
    reset($post);
    $old = $settings;
    while (list($key, $val) = each($post)) {
        if (!isset($settings[$key]) || stripslashes($val) != $settings[$key]) {
            if (!isset($old[$key])) {
                $old[$key] = "";
            }
            savesetting($key, stripslashes($val));
            output("Setting %s to %s`n", $key, stripslashes($val));
            gamelog("`@changed core setting `^{$key}`@ from `3{$old[$key]}`@ to `#{$val}`0", "settings");
            // Notify every module
            modulehook("changesetting", array("module" => "core", "setting" => $key, "old" => $old[$key], "new" => $val), true);
        }
    }
    output("`^Settings saved.`0");
    $op = "";
    httpset($op, "");
} elseif ($op == "modulesettings") {
    include_once "lib/gamelog.php";
    if (injectmodule($module, true)) {
        $save = httpget('save');
        if ($save != "") {
            load_module_settings($module);
 $post = modulehook("addpetition", $post);
 if (!$post['cancelpetition']) {
     unset($post['cancelpetition'], $post['cancelreason']);
     $sql = "INSERT INTO " . db_prefix("petitions") . " (author,date,body,pageinfo,ip,id) VALUES (" . (int) $session['user']['acctid'] . ",'{$date}',\"" . addslashes(output_array($post)) . "\",\"" . addslashes(output_array($session, "Session:")) . "\",'{$_SERVER['REMOTE_ADDR']}','" . addslashes($_COOKIE['lgi']) . "')";
     db_query($sql);
     // Fix the counter
     invalidatedatacache("petition_counts");
     // If the admin wants it, email the petitions to them.
     if (getsetting("emailpetitions", 0)) {
         // Yeah, the format of this is ugly.
         require_once "lib/sanitize.php";
         $name = color_sanitize($session['user']['name']);
         $url = getsetting("serverurl", "http://" . $_SERVER['SERVER_NAME'] . ($_SERVER['SERVER_PORT'] == 80 ? "" : ":" . $_SERVER['SERVER_PORT']) . dirname($_SERVER['REQUEST_URI']));
         if (!preg_match("/\\/\$/", $url)) {
             $url = $url . "/";
             savesetting("serverurl", $url);
         }
         $tl_server = translate_inline("Server");
         $tl_author = translate_inline("Author");
         $tl_date = translate_inline("Date");
         $tl_body = translate_inline("Body");
         $tl_subject = sprintf_translate("New LoGD Petition at %s", $url);
         $msg = "{$tl_server}: {$url}\n";
         $msg .= "{$tl_author}: {$name}\n";
         $msg .= "{$tl_date} : {$date}\n";
         $msg .= "{$tl_body} :\n" . output_array($post) . "\n";
         mail(getsetting("gameadminemail", "*****@*****.**"), $tl_subject, $msg);
     }
     $session['user']['password'] = $p;
     output("Your petition has been sent to the server admin.");
     output("Please be patient, most server admins have jobs and obligations beyond their game, so sometimes responses will take a while to be received.");
    unsuspend_companions("allowinshades");
    if (!getsetting("newdaycron", 0)) {
        //check last time we did this vs now to see if it was a different game day.
        $lastnewdaysemaphore = convertgametime(strtotime(getsetting("newdaySemaphore", "0000-00-00 00:00:00") . " +0000"));
        $gametoday = gametime();
        if (gmdate("Ymd", $gametoday) != gmdate("Ymd", $lastnewdaysemaphore)) {
            // it appears to be a different game day, acquire semaphore and
            // check again.
            $sql = "LOCK TABLES " . db_prefix("settings") . " WRITE";
            db_query($sql);
            clearsettings();
            $lastnewdaysemaphore = convertgametime(strtotime(getsetting("newdaySemaphore", "0000-00-00 00:00:00") . " +0000"));
            $gametoday = gametime();
            if (gmdate("Ymd", $gametoday) != gmdate("Ymd", $lastnewdaysemaphore)) {
                //we need to run the hook, update the setting, and unlock.
                savesetting("newdaySemaphore", gmdate("Y-m-d H:i:s"));
                $sql = "UNLOCK TABLES";
                db_query($sql);
                require "lib/newday/newday_runonce.php";
            } else {
                //someone else beat us to it, unlock.
                $sql = "UNLOCK TABLES";
                db_query($sql);
            }
        }
    }
    $args = modulehook("newday", array("resurrection" => $resurrection, "turnstoday" => $turnstoday));
    $turnstoday = $args['turnstoday'];
    debuglog("New Day Turns: {$turnstoday}");
}
page_footer();
addnav("Game Functions");
addnav("Forgotten Password", "create.php?op=forgot");
addnav("List Warriors", "list.php");
addnav("Daily News", "news.php");
addnav("Other Info");
addnav("About LoGD", "about.php");
addnav("Game Setup Info", "about.php?op=setup");
addnav("LoGD Net", "logdnet.php?op=list");
modulehook("index", array());
if (abs(getsetting("OnlineCountLast", 0) - strtotime("now")) > 60) {
    $sql = "SELECT count(acctid) as onlinecount FROM " . db_prefix("accounts") . " WHERE locked=0 AND loggedin=1 AND laston>'" . date("Y-m-d H:i:s", strtotime("-" . getsetting("LOGINTIMEOUT", 900) . " seconds")) . "'";
    $result = db_query($sql);
    $onlinecount = db_fetch_assoc($result);
    $onlinecount = $onlinecount['onlinecount'];
    savesetting("OnlineCount", $onlinecount);
    savesetting("OnlineCountLast", strtotime("now"));
} else {
    $onlinecount = getsetting("OnlineCount", 0);
}
if ($onlinecount < getsetting("maxonline", 0) || getsetting("maxonline", 0) == 0) {
    output("Enter your name and password to enter the realm.`n");
    if ($op == "timeout") {
        $session['message'] .= translate_inline(" Your session has timed out, you must log in again.`n");
    }
    if (!isset($_COOKIE['lgi'])) {
        $session['message'] .= translate_inline("It appears that you may be blocking cookies from this site.  At least session cookies must be enabled in order to use this site.`n");
        $session['message'] .= translate_inline("`b`#If you are not sure what cookies are, please <a href='http://en.wikipedia.org/wiki/WWW_browser_cookie'>read this article</a> about them, and how to enable them.`b`n");
    }
    if (isset($session['message']) && $session['message'] > "") {
        output_notl("`b`\$%s`b`n", $session['message'], true);
    }
                }
                if ($config['healer'] > 0) {
                    $config['healer']--;
                    if ($config['healer'] > 0) {
                        output("`n`@Golinda will be willing to see you for {$config['healer']} more day" . ($config['healer'] > 1 ? "s." : "."));
                    } else {
                        output("`n`@Golinda will no longer treat you.");
                        unset($config['healer']);
                    }
                }
                $session['user']['donationconfig'] = serialize($config);
                if ($session['user']['hauntedby'] > "") {
                    output("`n`n`)You have been haunted by {$session['user']['hauntedby']}`), as a result, you lose a forest fight!");
                    $session['user']['turns']--;
                    $session['user']['hauntedby'] = "";
                }
                $session['user']['drunkenness'] = 0;
                $session['user']['bounties'] = 0;
            }
            if (strtotime(getsetting("lastdboptimize", date("Y-m-d H:i:s", strtotime("-1 day")))) < strtotime("-1 day")) {
                savesetting("lastdboptimize", date("Y-m-d H:i:s"));
                $result = db_query("SHOW TABLES");
                for ($i = 0; $i < db_num_rows($result); $i++) {
                    list($key, $val) = each(db_fetch_assoc($result));
                    db_query("OPTIMIZE TABLE {$val}");
                }
            }
        }
    }
}
page_footer();
function translator_check_collect_texts()
{
    $tlmax = getsetting("tl_maxallowed", 0);
    if (getsetting("permacollect", 0)) {
        savesetting("collecttexts", 1);
    } elseif ($tlmax && getsetting("OnlineCount", 0) <= $tlmax) {
        savesetting("collecttexts", 1);
    } else {
        savesetting("collecttexts", 0);
    }
}
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;
}