function handle_event($location, $baseLink = false, $needHeader = false)
{
    if ($baseLink === false) {
        global $PHP_SELF;
        $baseLink = substr($PHP_SELF, strrpos($PHP_SELF, "/") + 1) . "?";
    } else {
        //debug("Base link was specified as $baseLink");
        //debug(debug_backtrace());
    }
    global $session, $playermount, $badguy;
    $skipdesc = false;
    tlschema("events");
    $allowinactive = false;
    $eventhandler = httpget('eventhandler');
    if ($session['user']['superuser'] & SU_DEVELOPER && $eventhandler != "") {
        $allowinactive = true;
        $array = preg_split("/[:-]/", $eventhandler);
        if ($array[0] == "module") {
            $session['user']['specialinc'] = "module:" . $array[1];
        } else {
            $session['user']['specialinc'] = "";
        }
    }
    $_POST['i_am_a_hack'] = 'true';
    if ($session['user']['specialinc'] != "") {
        $specialinc = $session['user']['specialinc'];
        $session['user']['specialinc'] = "";
        if ($needHeader !== false) {
            page_header($needHeader);
        }
        output("`^`c`bSomething Special!`c`b`0");
        if (strchr($specialinc, ":")) {
            $array = split(":", $specialinc);
            $starttime = getmicrotime();
            module_do_event($location, $array[1], $allowinactive, $baseLink);
            $endtime = getmicrotime();
            if ($endtime - $starttime >= 1.0 && $session['user']['superuser'] & SU_DEBUG_OUTPUT) {
                debug("Slow Event (" . round($endtime - $starttime, 2) . "s): {$hookname} - {$row['modulename']}`n");
            }
        }
        if (checknavs()) {
            // The page rendered some linkage, so we just want to exit.
            page_footer();
        } else {
            $skipdesc = true;
            $session['user']['specialinc'] = "";
            $session['user']['specialmisc'] = "";
            httpset("op", "");
        }
    }
    tlschema();
    return $skipdesc;
}
            }
        } elseif ($key == "oldvalues") {
            //donothing.
        } elseif ($oldvalues[$key] != stripslashes($val) && isset($oldvalues[$key])) {
            $sql .= "{$key} = \"{$val}\",";
            $updates++;
            output("%s has changed to %s.`n", $key, stripslashes($val));
            debuglog($session['user']['name'] . "`0 changed {$key} to {$val}", $userid);
            if ($session['user']['acctid'] == $userid) {
                $session['user'][$key] = stripslashes($val);
            }
        }
    }
}
$sql = substr($sql, 0, strlen($sql) - 1);
$sql = "UPDATE " . db_prefix("accounts") . " SET " . $sql . " WHERE acctid=\"{$userid}\"";
$petition = httpget("returnpetition");
if ($petition != "") {
    addnav("", "viewpetition.php?op=view&id={$petition}");
}
addnav("", "user.php");
if ($updates > 0) {
    db_query($sql);
    debug("Updated {$updates} fields in the user record with:\n{$sql}");
    output("%s fields in the user's record were updated.", $updates);
} else {
    output("No fields were changed in the user's record.");
}
$op = "edit";
httpset($op, "edit");
function darkhorse_run()
{
    $op = httpget('op');
    if ($op == "enter") {
        httpset("op", "tavern");
        page_header(get_module_setting("tavernname"));
        darkhorse_runevent("forest", "forest.php?");
        // Clear the specialinc, just in case.
        $session['user']['specialinc'] = "";
        page_footer();
    }
}
function riddles_editor()
{
    global $session;
    require_once "lib/nltoappon.php";
    if (!get_module_pref("canedit")) {
        check_su_access(SU_EDIT_RIDDLES);
    }
    $op = httpget('op');
    $id = httpget('id');
    page_header("Riddle Editor");
    require_once "lib/superusernav.php";
    superusernav();
    addnav("Riddle Editor");
    addnav("Riddle Editor Home", "runmodule.php?module=riddles&act=editor&admin=true");
    addnav("Add a riddle", "runmodule.php?module=riddles&act=editor&op=edit&admin=true");
    if ($op == "save") {
        $id = httppost('id');
        $riddle = trim(httppost('riddle'));
        $answer = trim(httppost('answer'));
        if ($id > "") {
            $sql = "UPDATE " . db_prefix("riddles") . " SET riddle='" . nltoappon($riddle) . "', answer='{$answer}' WHERE id='{$id}'";
        } else {
            $sql = "INSERT INTO " . db_prefix("riddles") . " (riddle,answer,author) VALUES('" . nltoappon($riddle) . "','{$answer}','{$session['user']['login']}')";
        }
        db_query($sql);
        if (db_affected_rows() > 0) {
            $op = "";
            httpset("op", "");
            output("Riddle saved.");
        } else {
            output("The query was not executed for some reason I can't fathom.");
            output("Perhaps you didn't actually make any changes to the riddle.");
        }
    } elseif ($op == "del") {
        $sql = "DELETE FROM " . db_prefix("riddles") . " WHERE id='{$id}'";
        db_query($sql);
        $op = "";
        httpset("op", "");
        output("Riddle deleted.");
    }
    if ($op == "") {
        $sql = "SELECT * FROM " . db_prefix("riddles");
        $result = db_query($sql);
        $i = translate_inline("Id");
        $ops = translate_inline("Ops");
        $rid = translate_inline("Riddle");
        $ans = translate_inline("Answer");
        $auth = translate_inline("Author");
        rawoutput("<table border=0 cellpadding=2 cellspacing=1 bgcolor='#999999'><tr class='trhead'><td>{$i}</td><td>{$ops}</td><td>{$rid}</td><td>{$ans}</td><td>{$auth}</td></tr>");
        for ($i = 0; $i < db_num_rows($result); $i++) {
            $row = db_fetch_assoc($result);
            rawoutput("<tr class='" . ($i % 2 ? "trlight" : "trdark") . "'>");
            rawoutput("<td valign='top'>");
            output_notl("%s", $row['id']);
            rawoutput("</td><td valign='top'>");
            $conf = translate_inline("Are you sure you wish to delete this riddle?");
            $edit = translate_inline("Edit");
            $del = translate_inline("Delete");
            $elink = "runmodule.php?module=riddles&act=editor&op=edit&id=" . $row['id'] . "&admin=true";
            $dlink = "runmodule.php?module=riddles&act=editor&op=del&id=" . $row['id'] . "&admin=true";
            output_notl("[");
            rawoutput("<a href='{$elink}'>{$edit}</a>");
            output_notl("|");
            rawoutput("<a href='{$dlink}' onClick='return confirm(\"{$conf}\");'>{$del}</a>");
            output_notl("]");
            addnav("", $elink);
            addnav("", $dlink);
            rawoutput("</td><td valign='top'>");
            output_notl("`&%s`0", $row['riddle']);
            rawoutput("</td><td valign='top'>");
            output_notl("`#%s`0", $row['answer']);
            rawoutput("</td><td valign='top'>");
            output_notl("`^%s`0", $row['author']);
            rawoutput("</td></tr>");
        }
        rawoutput("</table>");
    } elseif ($op == "edit") {
        $sql = "SELECT * FROM " . db_prefix("riddles") . " WHERE id='{$id}'";
        $result = db_query($sql);
        rawoutput("<form action='runmodule.php?module=riddles&act=editor&op=save&admin=true' method='POST'>", true);
        addnav("", "runmodule.php?module=riddles&act=editor&op=save&admin=true");
        if ($row = db_fetch_assoc($result)) {
            output("`bEdit a riddle`b`n");
            $title = "Edit a riddle";
            $i = $row['id'];
            rawoutput("<input type='hidden' name='id' value='{$i}'>");
        } else {
            output("`bAdd a riddle`b`n");
            $title = "Add a riddle";
            $row = array("riddle" => "", "answer" => "", "author" => $session['user']['login']);
        }
        $form = array("Riddle,title", "riddle" => "Riddle text,textarea", "answer" => "Answer", "author" => "Author,viewonly");
        require_once "lib/showform.php";
        showform($form, $row);
        rawoutput("</form>");
        output("`^NOTE:`& Separate multiple correct answers with semicolons (;)`n`n");
        output("`7The following are ignored at the start of answers: `&a, an, and, the, my, your, someones, someone's, someone, his, hers`n");
        output("`7The following are ignored at the end of answers: `&s, ing, ed`0`n`n");
        output("`\$NOTE:  Riddles are displayed in the language they are stored in the database.");
        output("Similarly, answers are expected in the language stored in the database.");
    }
    page_footer();
}
function worldmapen_run_real()
{
    global $session, $badguy, $pvptimeout, $options, $outdoors, $shady;
    $outdoors = true;
    $op = httpget("op");
    $battle = false;
    if ($op == 'move' && rawurldecode(httpget('oloc')) != get_module_pref('worldXYZ')) {
        debug(get_module_pref('worldXYZ'));
        $op = 'continue';
        httpset('op', $op);
    }
    //	debug("Worldmap running op={$op} ...");
    // handle the admin editor first
    if ($op == "edit") {
        if (!get_module_pref("canedit")) {
            check_su_access(SU_EDIT_USERS);
        }
        if (get_module_setting("worldmapenInstalled") != 1) {
            set_module_setting('worldmapenInstalled', "1");
            worldmapen_defaultcityloc();
        }
        worldmapen_editor();
    }
    if ($op == "destination") {
        $cname = httpget("cname");
        $session['user']['location'] = $cname;
        addnav(array("Enter %s", $cname), "village.php");
        output("`c`4`bYou've Arrived in %s.`b`0`c`n", $cname);
        output("`cYou have reached the outer gates of the city.`c");
    }
    if (!get_module_setting("worldmapenInstalled")) {
        page_header("A rip in the fabric of space and time");
        require_once "lib/villagenav.php";
        villagenav();
        output("`^The admins of this game haven't yet finished installing the worldmapen module.");
        output("You should send them a petition and tell them that they forgot to generate the initial locations of the cities.");
        output("Until then, you are kind of stuck here, so I hope you like where you are.`n`n");
        output("After all, remember:`nWherever you go, there you are.`0");
        page_footer();
    }
    $subop = httpget("subop");
    $act = httpget("act");
    $type = httpget("type");
    $name = httpget("name");
    $direction = httpget("dir");
    $su = httpget("su");
    $buymap = httpget("buymap");
    $worldmapCostGold = get_module_setting("worldmapCostGold");
    $pvp = httpget('pvp');
    require_once "lib/events.php";
    if ($session['user']['specialinc'] != "" || httpget("eventhandler")) {
        $in_event = handle_event(get_module_setting("randevent"), "runmodule.php?module=worldmapen&op=continue&", "Travel");
        if ($in_event) {
            addnav("Continue", "runmodule.php?module=worldmapen&op=continue");
            module_display_events(get_module_setting("randevent"), "runmodule.php?module=worldmapen&op=continue");
            page_footer();
        }
    }
    page_header("Journey");
    //is the player looking at chat?
    if (httpget('comscroll') || httpget('comscroll') === 0 || httpget('comment') || httpget('refresh')) {
        $chatoverride = 1;
        require_once "lib/commentary.php";
        addcommentary();
        $loc = get_module_pref("worldXYZ", "worldmapen");
        viewcommentary("mapchat-" . $loc, "Chat with others who walk this path...", 25);
    }
    if ($op == "beginjourney") {
        $loc = $session['user']['location'];
        $x = get_module_setting($loc . "X");
        $y = get_module_setting($loc . "Y");
        $z = get_module_setting($loc . "Z");
        $xyz = $x . "," . $y . "," . $z;
        set_module_pref("worldXYZ", $xyz);
        output("`b`&The gates of %s`& stand closed behind you.`0`b`n`n", $session['user']['location']);
        $num = e_rand(1, 5);
        $msg = get_module_setting("leaveGates{$num}");
        output("`c`n`^%s`0`n`c`n", $msg);
        worldmapen_determinenav();
        if (get_module_setting("smallmap")) {
            worldmapen_viewsmallmap();
        }
        if (!$chatoverride) {
            require_once "lib/commentary.php";
            addcommentary();
            $loc = get_module_pref("worldXYZ", "worldmapen");
            viewcommentary("mapchat-" . $loc, "Chat with others who walk this path...", 25);
        }
        worldmapen_viewmapkey(true, false);
        module_display_events(get_module_setting("randevent"), "runmodule.php?module=worldmapen&op=continue");
        $loc = get_module_pref('worldXYZ');
        list($x, $y, $z) = explode(",", $loc);
        $t = worldmapen_getTerrain($x, $y, $z);
        //debug($t);
        if ($t['type'] == "Forest") {
            $shady = true;
        }
    } elseif ($op == "continue") {
        checkday();
        worldmapen_determinenav();
        if (get_module_setting("smallmap")) {
            worldmapen_viewsmallmap();
        }
        if (!$chatoverride) {
            require_once "lib/commentary.php";
            addcommentary();
            $loc = get_module_pref("worldXYZ", "worldmapen");
            viewcommentary("mapchat-" . $loc, "Chat with others who walk this path...", 25);
        }
        worldmapen_viewmapkey(true, false);
        $loc = get_module_pref('worldXYZ');
        list($x, $y, $z) = explode(",", $loc);
        $t = worldmapen_getTerrain($x, $y, $z);
        //debug($t);
        if ($t['type'] == "Forest") {
            $shady = true;
        }
        //Turns Trading bit, added by CavemanJoe
    } elseif ($op == "tradeturn") {
        checkday();
        $pointstrade = get_module_setting("turntravel");
        output("You can trade one Turn for %s Travel Points.  Do you want to do this now?", $pointstrade);
        addnav("Yes, use a turn", "runmodule.php?module=worldmapen&op=tradeturnconfirm");
        addnav("No, cancel and return to the map", "runmodule.php?module=worldmapen&op=continue");
    } elseif ($op == "tradeturnconfirm") {
        $pointstrade = get_module_setting("turntravel");
        output("By conserving energy that you would have otherwise used for fighting creatures, you have gained %s Travel Points.", $pointstrade);
        $session['user']['turns']--;
        $ttoday = get_module_pref("traveltoday", "cities");
        set_module_pref("traveltoday", $ttoday - $pointstrade, "cities");
        addnav("Continue", "runmodule.php?module=worldmapen&op=continue");
    } elseif ($op == "move" && !$chatoverride) {
        checkday();
        if ($session['user']['location'] != 'World') {
            set_module_pref("lastCity", $session['user']['location']);
            $session['user']['location'] = "World";
        }
        $session['user']['restorepage'] = "runmodule.php?module=worldmapen&op=continue";
        $loc = get_module_pref('worldXYZ');
        list($x, $y, $z) = explode(",", $loc);
        if ($direction == "north") {
            $y += 1;
        }
        if (get_module_setting("compasspoints") == "1" and $direction == "northeast") {
            $y += 1;
            $x += 1;
        }
        if (get_module_setting("compasspoints") == "1" and $direction == "northwest") {
            $y += 1;
            $x -= 1;
        }
        if ($direction == "east") {
            $x += 1;
        }
        if ($direction == "south") {
            $y -= 1;
        }
        if (get_module_setting("compasspoints") == "1" and $direction == "southeast") {
            $y -= 1;
            $x += 1;
        }
        if (get_module_setting("compasspoints") == "1" and $direction == "southwest") {
            $y -= 1;
            $x -= 1;
        }
        if ($direction == "west") {
            $x -= 1;
        }
        $terraincost = worldmapen_terrain_cost($x, $y, $z);
        $encounterbase = worldmapen_encounter($x, $y, $z);
        $encounterchance = get_module_pref("encounterchance");
        $encounter = $encounterbase * $encounterchance / 100;
        debug($encounterbase . " * " . $encounterchance . " / 100 = " . $encounter);
        $ttoday = get_module_pref("traveltoday", "cities");
        set_module_pref("traveltoday", $ttoday + $terraincost, "cities");
        worldmapen_terrain_takestamina($x, $y, $z);
        $xyz = $x . "," . $y . "," . $z;
        set_module_pref("worldXYZ", $xyz);
        // $randchance = get_module_setting("randchance");
        // if (e_rand(0,100) < $randchance){
        // $eventravel = "travel";
        // set_module_setting("randevent", $eventravel);
        // }else{
        // $eventravel = "forest";
        // set_module_setting("randevent", $eventravel);
        // }
        //Extra Gubbins pertaining to trading Turns for Travel, added by Caveman Joe
        $useturns = get_module_setting("useturns");
        $allowzeroturns = get_module_setting("allowzeroturns");
        $playerturns = $session['user']['turns'];
        $proceed = 1;
        //the Proceed value is used when the player has hit a monster, to make sure it's okay to actually run the event/monster.
        if ($playerturns == 0 && $allowzeroturns == 0) {
            $proceed = 0;
        }
        if (e_rand(0, 100) < $encounter && $su != '1' && $proceed == 1 && !$chatoverride) {
            // They've hit a monster!
            if (module_events(get_module_setting("randevent"), get_module_setting("wmspecialchance"), "runmodule.php?module=worldmapen&op=continue&") != 0) {
                page_header("Something Special!");
                if (checknavs()) {
                    page_footer();
                } else {
                    // Reset the special for good.
                    $session['user']['specialinc'] = "";
                    $session['user']['specialmisc'] = "";
                    $skipvillagedesc = true;
                    $op = "";
                    httpset("op", "");
                    addnav("Continue", "runmodule.php?module=worldmapen&op=continue&");
                    module_display_events(get_module_setting("randevent"), "runmodule.php?module=worldmapen&op=continue");
                    page_footer();
                }
            }
            //Check if we're removing a turn when the player encounters a monster, and if so, do it
            if ($useturns == 1) {
                $session['user']['turns']--;
            }
            //Fix to only search for Forest type creatures, added by CavemanJoe
            $sql = "SELECT * FROM " . db_prefix("creatures") . " WHERE creaturelevel = '{$session['user']['level']}' AND forest = 1 ORDER BY rand(" . e_rand() . ") LIMIT 1";
            $result = db_query($sql);
            restore_buff_fields();
            if (db_num_rows($result) == 0) {
                // There is nothing in the database to challenge you,
                // let's give you a doppleganger.
                $badguy = array();
                $badguy['creaturename'] = "An evil doppleganger of " . $session['user']['name'];
                $badguy['creatureweapon'] = $session['user']['weapon'];
                $badguy['creaturelevel'] = $session['user']['level'];
                $badguy['creaturegold'] = rand($session['user']['level'] * 15, $session['user']['level'] * 30);
                $badguy['creatureexp'] = round($session['user']['experience'] / 10, 0);
                $badguy['creaturehealth'] = $session['user']['maxhitpoints'];
                $badguy['creatureattack'] = $session['user']['attack'];
                $badguy['creaturedefense'] = $session['user']['defense'];
            } else {
                $badguy = db_fetch_assoc($result);
                require_once "lib/forestoutcomes.php";
                $badguy = buffbadguy($badguy);
            }
            calculate_buff_fields();
            $badguy['playerstarthp'] = $session['user']['hitpoints'];
            $badguy['diddamage'] = 0;
            $badguy['type'] = 'world';
            //debug("Worldmap run.php is debugging badguy");
            //debug($badguy);
            $session['user']['badguy'] = createstring($badguy);
            $battle = true;
        } else {
            // $args = modulehook("count-travels", array('available'=>0, 'used'=>0));
            // $free = max(0, $args['available'] - $args['used']);
            // if (get_module_setting("usestamina")==1){
            // output("`c`nYou think to yourself what a nice day it is.`c`n");
            // } else {
            // output("`c`nYou think to yourself what a nice day it is.`nYou have %s Travel Points remaining.%s`c`n",$free);
            // }
            $free = 100;
            worldmapen_determinenav();
            if (get_module_setting("smallmap")) {
                worldmapen_viewsmallmap();
            }
            if (!$chatoverride) {
                require_once "lib/commentary.php";
                addcommentary();
                $loc = get_module_pref("worldXYZ", "worldmapen");
                viewcommentary("mapchat-" . $loc, "Chat with others who walk this path...", 25);
            }
            worldmapen_viewmapkey(true, false);
            module_display_events(get_module_setting("randevent"), "runmodule.php?module=worldmapen&op=continue");
        }
        $loc = get_module_pref('worldXYZ');
        list($x, $y, $z) = explode(",", $loc);
        $t = worldmapen_getTerrain($x, $y, $z);
        //debug($t);
        if ($t['type'] == "Forest") {
            $shady = true;
        }
    } elseif ($op == "gypsy") {
        $outdoors = false;
        if ($buymap == '') {
            output("`5\"`!Ah, yes.  An adventurer.  I could tell by looking into your eyes,`5\" the gypsy says.`n");
            output("\"`!Many people have lost their way while journeying without a guide such as this.");
            output("It will let you see all the world.`5\"`n");
            output("\"`!Yes, yes.  Let's see...  What sort of price should we put on this?");
            output("Hmm.  How about `^%s`! gold?`5\"", $worldmapCostGold);
            addnav(array("Buy World Map `0(`^%s gold`0)", $worldmapCostGold), "runmodule.php?module=worldmapen&op=gypsy&buymap=yes");
            addnav("Forget it", "village.php");
        } elseif ($buymap == 'yes') {
            if ($session['user']['gold'] < $worldmapCostGold) {
                output("`5\"`!What do you take me for?  A blind hag?  Come back when you have the money`5\"");
                addnav("Leave quickly", "village.php");
            } else {
                output("`5\"`!Enjoy your newfound sight,`5\"  the gypsy says as she walks away to greet some patrons that have just strolled in.");
                $session['user']['gold'] -= $worldmapCostGold;
                set_module_pref("worldmapbuy", 1);
                require_once "lib/villagenav.php";
                villagenav();
            }
        }
    } elseif ($op == "viewmap") {
        worldmapen_determinenav();
        worldmapen_viewmap(true);
        if (is_module_active("medals")) {
            require_once "modules/medals.php";
            medals_award_medal("boughtmap", "Bearer of the Map", "This player purchased the World Map from the Comms Tent!", "medal_islandmap.png");
        }
    } elseif ($op == "camp") {
        if ($session['user']['loggedin']) {
            $session['user']['loggedin'] = 0;
            $session['user']['restorepage'] = "runmodule.php?module=worldmapen&op=wake";
            saveuser();
            invalidatedatacache("charlisthomepage");
            invalidatedatacache("list.php-warsonline");
        }
        $session = array();
        redirect("index.php", "Redirected to Index from World Map");
    } elseif ($op == "wake") {
        if ($session['user']['hitpoints'] > 0) {
            // runmodule.php calls do_forced_nav,
            $session['user']['alive'] = true;
            // and that resets ['alive'], so
        } else {
            // this is from common.php to make sure
            $session['user']['alive'] = false;
            // the player is not half-dead after log-in.
        }
        output("You yawn and stretch and look around your campsite.`n`n");
        output("Ah, how wonderful it is to sleep in the open air!`n");
        output("The world seems full of possibilities today.`n`n");
        checkday();
        worldmapen_determinenav();
        if (get_module_setting("smallmap")) {
            worldmapen_viewsmallmap();
        }
        if (!$chatoverride) {
            require_once "lib/commentary.php";
            addcommentary();
            $loc = get_module_pref("worldXYZ", "worldmapen");
            viewcommentary("mapchat-" . $loc, "Chat with others who walk this path...", 25);
        }
        worldmapen_viewmapkey(true, false);
        $loc = get_module_pref('worldXYZ');
        list($x, $y, $z) = explode(",", $loc);
        $t = worldmapen_getTerrain($x, $y, $z);
        //debug($t);
        if ($t['type'] == "Forest") {
            $shady = true;
        }
    } elseif ($op == "combat") {
        // Okay, we've picked a person to fight.
        require_once "lib/pvpsupport.php";
        $name = httpget("name");
        $badguy = setup_target($name);
        $failedattack = false;
        if ($badguy === false) {
            output("`0`n`nYou survey the area again.`n");
            worldmapen_determinenav();
        } else {
            $battle = true;
            $badguy['type'] = 'pvp';
            //$options['type'] = 'pvp';
            $session['user']['badguy'] = createstring($badguy);
            $session['user']['playerfights']--;
        }
    } elseif ($op == "fight" || $op == "run") {
        if (!$chatoverride && !httpget("frombio")) {
            $battle = true;
        } else {
            worldmapen_determinenav();
            if (get_module_setting("smallmap")) {
                worldmapen_viewsmallmap();
            }
            worldmapen_viewmapkey(true, false);
        }
        // $args = modulehook("count-travels", array('available'=>0,'used'=>0));
        // $free = max(0, $args['available'] - $args['used']);
        // if (get_module_setting("usestamina")==1){
        $free = 100;
        // }
        if ($op == "run" && !$pvp) {
            if (!$chatoverride) {
                if (e_rand(1, 5) < 3 && $free) {
                    // They managed to get away.
                    output("You set off running at a breakneck pace!`n`n");
                    output("A short time later, you have managed to avoid your opponent, so you stop to catch your breath.");
                    $ttoday = get_module_pref("traveltoday", "cities");
                    set_module_pref("traveltoday", $ttoday + 1, "cities");
                    output("As you look around, you realize that all you really managed was to run in circles.");
                    $battle = false;
                    worldmapen_determinenav();
                    if (get_module_setting("smallmap")) {
                        worldmapen_viewsmallmap();
                    }
                    require_once "lib/commentary.php";
                    addcommentary();
                    $loc = get_module_pref("worldXYZ", "worldmapen");
                    viewcommentary("mapchat-" . $loc, "Chat with others who walk this path...", 25);
                    worldmapen_viewmapkey(true, false);
                } else {
                    output("You try to run, but you don't manage to get away!`n");
                    $op = "fight";
                    httpset('op', $op);
                }
            } else {
                if (get_module_setting("smallmap")) {
                    worldmapen_viewsmallmap();
                }
                require_once "lib/commentary.php";
                addcommentary();
                $loc = get_module_pref("worldXYZ", "worldmapen");
                viewcommentary("mapchat-" . $loc, "Chat with others who walk this path...", 25);
                worldmapen_determinenav();
                worldmapen_viewmapkey(true, false);
            }
        } elseif ($op == "run" && $pvp) {
            output("Your pride prevents you from running");
            $op = "fight";
            httpset('op', $op);
        }
        $loc = get_module_pref('worldXYZ');
        list($x, $y, $z) = explode(",", $loc);
        $t = worldmapen_getTerrain($x, $y, $z);
        //debug($t);
        if ($t['type'] == "Forest") {
            $shady = true;
        }
    }
    if ($battle) {
        include_once "battle.php";
        if (isset($enemies) && !$pvp) {
            $badguy =& $enemies;
        }
        if ($victory) {
            if ($pvp) {
                require_once "lib/pvpsupport.php";
                $aliveloc = $badguy['location'];
                pvpvictory($badguy, $aliveloc, $options);
                addnews("`4%s`3 defeated `4%s`3 while they were camped in the wilderness.`0", $session['user']['name'], $badguy['creaturename']);
                $badguy = array();
            } else {
                if (!$chatoverride && !httpget('frombio')) {
                    //is talking
                    require_once "lib/forestoutcomes.php";
                    forestvictory($badguy, false);
                }
            }
            //has just beaten a badguy
            worldmapen_determinenav();
            if (get_module_setting("smallmap")) {
                worldmapen_viewsmallmap();
            }
            if (!$chatoverride) {
                require_once "lib/commentary.php";
                addcommentary();
                $loc = get_module_pref("worldXYZ", "worldmapen");
                viewcommentary("mapchat-" . $loc, "Chat with others who walk this path...", 25);
            }
            worldmapen_viewmapkey(true, false);
        } elseif ($defeat) {
            // Reset the players body to the last city they were in
            $session['user']['location'] = get_module_pref('lastCity');
            if ($pvp) {
                require_once "lib/pvpsupport.php";
                require_once "lib/taunt.php";
                $killedloc = $badguy['location'];
                $taunt = select_taunt();
                pvpdefeat($badguy, $killedloc, $taunt, $options);
                addnews("`4%s`3 was defeated while attacking `4%s`3 as they were camped in the wilderness.`0`n%s", $session['user']['name'], $badguy['creaturename'], $taunt);
            } else {
                require_once "lib/forestoutcomes.php";
                forestdefeat($badguy, "in the wild");
            }
            output("`n`n`&You are sure that someone, sooner or later, will stumble over your corpse and return it to %s`& for you.`0", $session['user']['location']);
        } else {
            require_once "lib/fightnav.php";
            $allow = true;
            $extra = "";
            if ($pvp) {
                $allow = false;
                $extra = "pvp=1&";
            }
            fightnav($allow, $allow, "runmodule.php?module=worldmapen&{$extra}");
        }
    }
    page_footer();
}
            $body = str_replace("\r", "\n", $body);
            $body = addslashes(substr(stripslashes($body), 0, (int) getsetting("mailsizelimit", 1024)));
            systemmail($row1['acctid'], $subject, $body, $session['user']['acctid']);
            output("Your message was sent!`n");
        }
    } else {
        output("Could not find the recipient, please try again.`n");
    }
    if (httppost("returnto") > "") {
        $op = "read";
        httpset('op', 'read');
        $id = httppost('returnto');
        httpset('id', $id);
    } else {
        $op = "";
        httpset('op', "");
    }
}
if ($op == "") {
    output("`b`iMail Box`i`b");
    if (isset($session['message'])) {
        output($session['message']);
    }
    $session['message'] = "";
    $sql = "SELECT subject,messageid," . db_prefix("accounts") . ".name,msgfrom,seen,sent FROM " . db_prefix("mail") . " LEFT JOIN " . db_prefix("accounts") . " ON " . db_prefix("accounts") . ".acctid=" . db_prefix("mail") . ".msgfrom WHERE msgto=\"" . $session['user']['acctid'] . "\" ORDER BY sent DESC";
    $result = db_query($sql);
    if (db_num_rows($result) > 0) {
        output_notl("<form action='mail.php?op=process' method='POST'><table>", true);
        for ($i = 0; $i < db_num_rows($result); $i++) {
            $row = db_fetch_assoc($result);
            if ((int) $row['msgfrom'] == 0) {
        $op = "";
        httpset("op", $op);
    } else {
        if ($op == "save") {
            $weaponid = (int) httppost("weaponid");
            $damage = httppost("damage");
            $weaponname = httppost("weaponname");
            if ($weaponid > 0) {
                $sql = "UPDATE " . db_prefix("weapons") . " SET weaponname=\"{$weaponname}\",damage=\"{$damage}\",value=" . $values[$damage] . " WHERE weaponid='{$weaponid}'";
            } else {
                $sql = "INSERT INTO " . db_prefix("weapons") . " (level,damage,weaponname,value) VALUES ({$weaponlevel},\"{$damage}\",\"{$weaponname}\"," . $values[$damage] . ")";
            }
            db_query($sql);
            //output($sql);
            $op = "";
            httpset("op", $op);
        }
    }
}
if ($op == "") {
    $sql = "SELECT max(level+1) as level FROM " . db_prefix("weapons");
    $res = db_query($sql);
    $row = db_fetch_assoc($res);
    $max = $row['level'];
    for ($i = 0; $i <= $max; $i++) {
        if ($i == 1) {
            addnav("Weapons for 1 DK", "weaponeditor.php?level={$i}");
        } else {
            addnav(array("Weapons for %s DKs", $i), "weaponeditor.php?level={$i}");
        }
    }
<?php

//save module settings.
$userid = httpget('userid');
$module = httpget('module');
$post = httpallpost();
$post = modulehook("validateprefs", $post, true, $module);
if (isset($post['validation_error']) && $post['validation_error']) {
    tlschema("module-{$module}");
    $post['validation_error'] = translate_inline($post['validation_error']);
    tlschema();
    output("Unable to change settings: `\$%s`0", $post['validation_error']);
} else {
    reset($post);
    while (list($key, $val) = each($post)) {
        output("Setting %s to %s`n", $key, stripslashes($val));
        $sql = "REPLACE INTO " . db_prefix("module_userprefs") . " (modulename,userid,setting,value) VALUES ('{$module}','{$userid}','{$key}','{$val}')";
        db_query($sql);
    }
    output("`^Preferences for module %s saved.`n", $module);
}
$op = "edit";
httpset("op", "edit");
httpset("subop", "module", true);
    db_query($sql);
    output('`6The item "`^%s`6" has been successfully edited.`n`n', $displayname);
    if (getsetting('usedatacache', false) && $cat != $postcat) {
        $cat = (int) $cat;
        require_once './modules/mysticalshop/libcoredup.php';
        invalidatedatacache('modules-mysticalshop-view-' . $cat);
        mysticalshop_massinvalidate('modules-mysticalshop-viewgoods-' . $cat);
    }
} else {
    $sql = 'LOCK TABLES ' . db_prefix('magicitems') . ' WRITE;';
    db_query($sql);
    $sql = "INSERT INTO " . db_prefix("magicitems") . "\r\n\t(category,name,description,gold,gems,dk,attack,defense,charm,hitpoints,turns,favor,bigdesc,rare,rarenum)\r\n\tVALUES ({$postcat},'{$name}','{$describe}',{$gold},{$gems},{$dk},{$attack},{$defense},{$charm},{$hitpoints},{$turns},{$favor},'{$bigdesc}',{$rare},{$rarenum})";
    db_query($sql);
    $itemid = db_insert_id();
    $sql = 'UNLOCK TABLES;';
    db_query($sql);
    output('`6The item "`^%s`6" has been saved to the database.`n`n', $displayname);
}
output('Would you like to <a href="' . htmlentities($fromeditor . 'preview&id=' . $itemid . '&cat=') . $postcat . '">[ Review ]</a> or <a href="' . htmlentities($fromeditor . 'edit&id=' . $itemid . '&cat=') . $postcat . '">[ Edit ]</a> this item?`0', true);
addnav('', $fromeditor . 'edit&id=' . $itemid . '&cat=' . $postcat);
addnav('', $fromeditor . 'preview&id=' . $itemid . '&cat=' . $postcat);
if (getsetting('usedatacache', false)) {
    invalidatedatacache('modules-mysticalshop-editorcats');
    invalidatedatacache('modules-mysticalshop-view-' . $postcat);
    invalidatedatacache('modules-mysticalshop-enter');
    require_once './modules/mysticalshop/libcoredup.php';
    mysticalshop_massinvalidate('modules-mysticalshop-viewgoods-' . $postcat);
}
httpset('id', $itemid);
httpset('cat', $postcat);
$cat = $postcat;
function lottery_run()
{
    global $session;
    $op = httpget("op");
    $cost = get_module_setting("ticketcost");
    $numbers = get_module_setting("todaysnumbers");
    $n = $numbers;
    $prize = get_module_setting("prize");
    $prizecount = get_module_setting("howmany");
    $jackpot = (int) get_module_setting("currentjackpot");
    $bleed = (int) get_module_setting("percentbleed");
    $roundnum = (int) get_module_setting("roundnum");
    $msg = "";
    if ($op == "buy") {
        $op = "store";
        httpset("op", $op);
        if ($session['user']['gold'] >= $cost) {
            $lotto = httppost("lotto");
            if ($lotto) {
                sort($lotto);
                set_module_pref("pick", join("", $lotto));
                set_module_pref("roundnum", $roundnum);
                $session['user']['gold'] -= $cost;
                debuglog("spent {$cost} on a lottery ticket");
                $jackpot += round($cost * (100 - $bleed) / 100, 0);
                set_module_setting("currentjackpot", $jackpot);
            } else {
                $msg = translate_inline("`\$You seem to have mumbled when you requested the lottery tickets.  Please restate your numbers.`0`n`n");
            }
        } else {
            $msg = translate_inline("`\$You do not have enough to buy a lottery ticket!`0`n`n");
        }
    }
    if ($op == "store") {
        require_once "lib/villagenav.php";
        page_header("%s's Lottery", getsetting("barkeep", "`tCedrik"));
        output("Today's lottery numbers are `^%s-%s-%s-%s`7.", $n[0], $n[1], $n[2], $n[3]);
        output("The jackpot is now up to `^%s`0 gold!`n`n", $jackpot);
        if ($prize > 0) {
            if ($prizecount == 1) {
                output("The winner of the last jackpot got `^%s`0 gold!`n`n", $prize);
            } else {
                output("The %s winners of the last jackpot each got `^%s`0 gold!`n`n", $prizecount, $prize);
            }
        } else {
            output("There were no recent jackpot winners!`n`n");
        }
        $pick = get_module_pref("pick");
        if ($pick > "") {
            $n = $pick;
            output("You bought a lottery ticket for tomorrow's drawing; the numbers you chose are: `^%s-%s-%s-%s`7`n`n", $n[0], $n[1], $n[2], $n[3]);
        } else {
            output("%s", $msg);
            output("Lottery tickets cost `^%s`0 gold.", $cost);
            output("If you would like to buy one for tomorrow's drawing, please choose your numbers below and click \"Buy\".");
            rawoutput("<form action='runmodule.php?module=lottery&op=buy' method='POST'>", true);
            addnav("", "runmodule.php?module=lottery&op=buy");
            for ($i = 0; $i < 4; $i++) {
                $j = $i + 1;
                if ($j == 4) {
                    $k = "buy";
                } else {
                    $k = $j + 1;
                }
                rawoutput("<select id='lotto{$j}' name='lotto[{$i}]' onChange='document.getElementById(\"lotto{$k}\").focus()'>");
                for ($x = 0; $x < 10; $x++) {
                    rawoutput("<option value='{$x}'>{$x}</option>");
                }
                rawoutput("</select>");
            }
            $b = translate_inline("Buy");
            rawoutput("<input type='submit' class='button' value='{$b}' id='lottobuy'>");
            rawoutput("</form>");
            rawoutput("<script language='JavaScript'>document.getElementById('lotto1').focus();</script>");
        }
        output("A drawing is held at the start of each game day.");
        output("If the numbers you chose match, in any order, you win the jackpot for the day!");
        output("If no one matches the jackpot on a particular day, the sum will roll over for the following game day.");
        output("A portion of the proceeds of the lottery go to help injured forest creatures.");
        addnav("Return");
        addnav("I?Return to the Inn", "inn.php");
        villagenav();
        page_footer();
    }
}
function claneditor_run()
{
    global $session;
    tlschema("claneditor");
    $dt = httpget("dt");
    $op = httpget('op');
    if ($dt != "") {
        $sql = "SELECT * FROM " . db_prefix("clans") . " WHERE clanid='{$dt}'";
        $result = db_query($sql);
        $claninfo = db_fetch_assoc($result);
        if (db_num_rows($result) == 0) {
            $op = "";
        }
    }
    addcommentary();
    $ranks = array(CLAN_APPLICANT => "`!Applicant`0", CLAN_MEMBER => "`#Member`0", CLAN_OFFICER => "`^Officer`0", CLAN_LEADER => "`&Leader`0", CLAN_FOUNDER => "`\$Founder");
    $args = modulehook("clanranks", array("ranks" => $ranks, "clanid" => $dt));
    $ranks = translate_inline($args['ranks'], "clan");
    superusernav();
    addnav("Clans");
    addnav("List Clans", "runmodule.php?module=claneditor&op=list");
    addnav("Create a New Clan", "runmodule.php?module=claneditor&op=new");
    if ($op == "" || $op == "list") {
        page_header("Clan Listing");
        rawoutput("<table border='0' padding='0'><tr><td>");
        $sql = "SELECT MAX(" . db_prefix("clans") . ".clanid) AS clanid, MAX(clanname) AS clanname,count(" . db_prefix("accounts") . ".acctid) AS c FROM " . db_prefix("clans") . " LEFT JOIN " . db_prefix("accounts") . " ON " . db_prefix("clans") . ".clanid=" . db_prefix("accounts") . ".clanid AND clanrank>" . CLAN_APPLICANT . " GROUP BY " . db_prefix("clans") . ".clanid ORDER BY c DESC";
        $result = db_query($sql);
        if (db_num_rows($result) > 0) {
            output("`%Karissa`7 steps in as if by magic, listing the clans for you.`n");
            output("`@`bList of Clans:`b`0`n`n");
            $v = 0;
            $memb_n = translate_inline("(%s members)");
            $memb_1 = translate_inline("(%s member)");
            rawoutput('<table cellspacing="0" cellpadding="2" align="left">');
            output_notl("<tr class='trhead'><td>%s</td><td>%s</td></tr>", translate_inline("`b`&Name of Clan`b"), translate_inline("`&`iNumber of Members`i"), true);
            for ($i = 0; $i < db_num_rows($result); $i++) {
                $row = db_fetch_assoc($result);
                if ($row['c'] == 0) {
                    $sql = "DELETE FROM " . db_prefix("clans") . " WHERE clanid={$row['clanid']}";
                    db_query($sql);
                } else {
                    rawoutput('<tr class="' . ($v % 2 ? "trlight" : "trdark") . '"><td>', true);
                    if ($row['c'] == 1) {
                        $memb = sprintf($memb_1, $row['c']);
                    } else {
                        $memb = sprintf($memb_n, $row['c']);
                    }
                    output_notl("&#149; <a href='runmodule.php?module=claneditor&op=mview&dt=%s'>%s</a></td><td>%s`n", $row['clanid'], full_sanitize(htmlentities($row['clanname']), ENT_COMPAT, getsetting("charset", "ISO-8859-1")), $memb, true);
                    rawoutput('</td></tr>');
                    addnav("", "runmodule.php?module=claneditor&op=mview&dt={$row['clanid']}");
                    $v++;
                }
            }
            rawoutput("</table>", true);
        } else {
            output("`7There are no clans in the database.`n`c");
        }
        rawoutput("</td></tr><tr><td>");
        output_notl("<br>[<a href='runmodule.php?module=claneditor&op=new'>%s</a>]", translate_inline("Create a New Clan"), true);
        addnav("", "runmodule.php?module=claneditor&op=new");
        rawoutput("</td></tr></table>");
        page_footer();
    } elseif ($op == "new") {
        page_header("Clan Creation");
        $apply = httpget('apply');
        if ($apply == 1) {
            $id = httpget("id");
            $ocn = httppost('clanname');
            $ocs = httppost('clanshort');
            $clanname = stripslashes($ocn);
            $clanname = full_sanitize($clanname);
            $clanname = preg_replace("'[^[:alpha:] \\'-]'", "", $clanname);
            $clanname = addslashes($clanname);
            httppostset('clanname', $clanname);
            $clanshort = full_sanitize($ocs);
            $clanshort = preg_replace("'[^[:alpha:]]'", "", $clanshort);
            httppostset('clanshort', $clanshort);
            $sql = "SELECT * FROM " . db_prefix("clans") . " WHERE clanname='{$clanname}'";
            $result = db_query($sql);
            $e = translate_inline("`%Karissa`7 hands you a form to start a clan.");
            $e1 = translate_inline("`%Karissa`7 looks over your form but informs you that your clan name must consist only of letters, spaces, apostrophes, or dashes.  Also, your short name can consist only of letters. She hands you a blank form.");
            $e2 = translate_inline("`%Karissa`7 looks over your form but informs you that you must have at least 5 and no more than 50 characters in your clan's name (and they must consist only of letters, spaces, apostrophes, or dashes), then hands you a blank form.");
            $e3 = translate_inline("`%Karissa`7 looks over your form but informs you that you must have at least 2 and no more than 5 characters in your clan's short name (and they must all be letters), then hands you a blank form.");
            $e4 = translate_inline("`%Karissa`7 looks over your form but informs you that the clan name %s is already taken, and hands you a blank form.");
            $e5 = translate_inline("`%Karissa`7 looks over your form but informs you that the short name %s is already taken, and hands you a blank form.");
            if ($ocs == "" && $ocn == "" && !httppostisset('clanname') && !httppostisset('clanshort')) {
                output_notl($e);
                clanform();
            } elseif ($clanname != $ocn || $clanshort != $ocs) {
                output_notl($e1);
                clanform();
            } elseif (strlen($clanname) < 5 || strlen($clanname) > 50) {
                output_notl($e2);
                clanform();
            } elseif (strlen($clanshort) < 2 || strlen($clanshort) > 5) {
                output_notl($e3);
                clanform();
            } elseif (db_num_rows($result) > 0) {
                output_notl($e4, stripslashes($clanname));
                clanform();
            } else {
                $sql = "SELECT * FROM " . db_prefix("clans") . " WHERE clanshort='{$clanshort}'";
                $result = db_query($sql);
                if (db_num_rows($result) > 0) {
                    output_notl($e5, stripslashes($clanshort));
                    clanform();
                } else {
                    $sql = "INSERT INTO " . db_prefix("clans") . " (clanname,clanshort) VALUES ('{$clanname}','{$clanshort}')";
                    db_query($sql);
                    $clid = db_insert_id();
                    $sql = "UPDATE " . db_prefix("accounts") . " SET clanid='{$clid}',clanrank='" . CLAN_LEADER . "' WHERE acctid='{$id}'";
                    db_query($sql);
                    $subj = "New Clan!";
                    $msg = array("%s`0`^ has made you a new clan!", $session['user']['name']);
                    systemmail($id, $subj, $msg);
                    output("`%Karissa`7 looks over your form, and finding that everything seems to be in order, she takes your fees, stamps the form \"`\$APPROVED`7\" and files it in a drawer.`n`n");
                    output("Congratulations, you've created a new clan named %s!", stripslashes($clanname));
                }
            }
        } elseif ($apply == 0) {
            clanuserform();
        } else {
            output("`7You teleport to the Clan Hall...");
            output("`7You approach `%Karissa`7 and mention that you would like to start a new clan.");
            output("She tells you that there are three requirements to starting a clan.");
            output("First, you have to decide on a full name for your clan.");
            output("Second, you have to decide on an abbreviation for your clan.");
            output("Third you have to decide on the person that should run the clan.");
            $e = translate_inline("`n`n\"`5If you're ok with these three requirements, please fill out the following form,`7\" she says, handing you a sheet of paper.");
            output_notl($e);
            clanuserform();
        }
    } else {
        if ($op != "deleteclan") {
            page_header("The Clan of %s", full_sanitize($claninfo['clanname']));
            output("`n`c`^`bThe Clan of %s`b`c`n`n", full_sanitize($claninfo['clanname']));
        } else {
            page_header("Clan Deletion");
        }
        if ($op == "mview") {
            $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid={$claninfo['motdauthor']}";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            $motdauthname = $row['name'];
            $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid={$claninfo['descauthor']}";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            $descauthname = $row['name'];
            output("`&`bCurrent MoTD:`b `#by %s`2`n", $motdauthname);
            output_notl(nltoappon($claninfo['clanmotd']) . "`n`n");
            commentdisplay("", "clan-{$claninfo['clanid']}", "Speak into their Clan", 25, "projects");
            output_notl("`n`n");
            modulehook("collapse{", array("name" => "collapsedesc"));
            output("`&`bCurrent Description:`b `#by %s`2`n", $descauthname);
            output_notl(nltoappon($claninfo['clandesc']) . "`n");
            modulehook("}collapse");
            $sql = "SELECT count(*) AS c, clanrank FROM " . db_prefix("accounts") . " WHERE clanid={$claninfo['clanid']} GROUP BY clanrank DESC";
            $result = db_query($sql);
            // begin collapse
            modulehook("collapse{", array("name" => "clanmemberdet"));
            output("`n`bMembership Details:`b`n");
            $leaders = 0;
            while ($row = db_fetch_assoc($result)) {
                output_notl($ranks[$row['clanrank']] . ": " . $row['c'] . "`n");
                if ($row['clanrank'] >= CLAN_OFFICER) {
                    $leaders += $row['c'];
                }
            }
            output("`n");
            $noleader = translate_inline("`^There is currently no leader!  Promoting %s`^ to leader as they are the highest ranking member (or oldest member in the event of a tie).`n`n");
            if ($leaders == 0) {
                //There's no leader here, probably because the leader's account
                //expired.
                $sql = "SELECT name,acctid,clanrank FROM " . db_prefix("accounts") . " WHERE clanid={$dt} ORDER BY clanrank DESC, clanjoindate";
                $result = db_query($sql);
                $row = db_fetch_assoc($result);
                $sql = "UPDATE " . db_prefix("accounts") . " SET clanrank=" . CLAN_LEADER . " WHERE acctid='" . $row['acctid'] . "'";
                db_query($sql);
                output_notl($noleader, $row['name']);
            }
            // end collapse
            modulehook("}collapse");
        } elseif ($op == "deleteclan") {
            if (httpget("sop") == "yes") {
                //notify users of the deletion of the clan
                $sql = "SELECT acctid FROM " . db_prefix("accounts") . " WHERE clanid={$dt}";
                $result = db_query($sql);
                $subj = array("Deletion of %s", $claninfo['clanname']);
                $msg = array("The clan you were in, %s, has closed its doors.\nSorry for any inconvenience.", $claninfo['clanname']);
                while ($row = db_fetch_assoc($result)) {
                    systemmail($row['acctid'], $subj, $msg);
                }
                //change the clan if a user is in this clan
                $sql = "UPDATE " . db_prefix("accounts") . " SET clanid=0,clanrank=" . CLAN_APPLICANT . ",clanjoindate='0000-00-00 00:00:00' WHERE clanid={$dt}";
                db_query($sql);
                //change the current users clan if this user was in that clan
                if ($session['user']['clanid'] == $dt) {
                    $session['user']['clanid'] = 0;
                    $session['user']['clanrank'] = CLAN_APPLICANT;
                    $session['user']['clanjoindate'] = '0000-00-00 00:00:00';
                }
                //drop the clan.
                $sql = "DELETE FROM " . db_prefix("clans") . " WHERE clanid={$dt}";
                db_query($sql);
                module_delete_objprefs('clans', $dt);
                $op = "";
                httpset("op", "");
                unset($claninfo);
                $dt = "";
                output("That clan has been wiped.`n");
                output("`@Users within the clan have been notified.");
            } else {
                output("`%`c`bAre you SURE you want to delete this clan?`b`c`n");
                $dc = translate_inline("Delete this clan? Are you sure!");
                rawoutput("[<a href='runmodule.php?module=claneditor&op=deleteclan&sop=yes&dt={$dt}' onClick='return confirm(\"{$dc}\");'>{$dc}</a>]");
                addnav("", "runmodule.php?module=claneditor&op=deleteclan&sop=yes&dt={$dt}");
            }
        } elseif ($op == "editmodule" || $op == "editmodulesave") {
            $mdule = httpget("mdule");
            if ($op == "editmodulesave") {
                // Save module prefs
                $post = httpallpost();
                reset($post);
                while (list($key, $val) = each($post)) {
                    set_module_objpref("clans", $dt, $key, $val, $mdule);
                }
                output("`^Saved!`0`n");
            }
            rawoutput("<form action='runmodule.php?module=claneditor&op=editmodulesave&dt={$dt}&mdule={$mdule}' method='POST'>");
            module_objpref_edit("clans", $mdule, $dt);
            rawoutput("</form>");
            addnav("", "runmodule.php?module=claneditor&op=editmodulesave&dt={$dt}&mdule={$mdule}");
        } elseif ($op == "updinfo") {
            page_header("Update Clan Information");
            $clanmotd = substr(httppost('clanmotd'), 0, 4096);
            if (httppostisset('clanmotd') && $clanmotd != $claninfo['clanmotd']) {
                if ($clanmotd == "") {
                    $mauthor = 0;
                } else {
                    $mauthor = $session['user']['acctid'];
                }
                $sql = "UPDATE " . db_prefix("clans") . " SET clanmotd='{$clanmotd}',motdauthor={$mauthor} WHERE clanid={$claninfo['clanid']}";
                db_query($sql);
                invalidatedatacache("clandata-{$claninfo['clanid']}");
                $claninfo['clanmotd'] = stripslashes($clanmotd);
                output("Updating MoTD`n");
                $claninfo['motdauthor'] = $mauthor;
            }
            $clandesc = httppost('clandesc');
            if (httppostisset('clandesc') && $clandesc != $claninfo['clandesc']) {
                if ($clandesc == "") {
                    $claninfo['descauthor'] = 0;
                    $dauthor = 0;
                } else {
                    $dauthor = $session['user']['acctid'];
                }
                $sql = "UPDATE " . db_prefix("clans") . " SET clandesc='" . addslashes(substr(stripslashes($clandesc), 0, 4096)) . "',descauthor={$dauthor} WHERE clanid={$claninfo['clanid']}";
                db_query($sql);
                invalidatedatacache("clandata-{$claninfo['clanid']}");
                output("Updating description`n");
                $claninfo['clandesc'] = stripslashes($clandesc);
                $claninfo['descauthor'] = $session['user']['acctid'];
            }
            $customsay = httppost('customsay');
            if (httppostisset('customsay') && $customsay != $claninfo['customsay']) {
                $sql = "UPDATE " . db_prefix("clans") . " SET customsay='{$customsay}' WHERE clanid={$claninfo['clanid']}";
                db_query($sql);
                invalidatedatacache("clandata-{$claninfo['clanid']}");
                output("Updating custom say line`n");
                $claninfo['customsay'] = stripslashes($customsay);
            }
            $clanname = httppost('clanname');
            if ($clanname) {
                $clanname = full_sanitize($clanname);
            }
            $clanshort = httppost('clanshort');
            if ($clanshort) {
                $clanshort = full_sanitize($clanshort);
            }
            if (httppostisset('clanname') && $clanname != $claninfo['clanname']) {
                $sql = "UPDATE " . db_prefix("clans") . " SET clanname='{$clanname}' WHERE clanid={$claninfo['clanid']}";
                output("Updating the clan name`n");
                db_query($sql);
                invalidatedatacache("clandata-{$detail}");
                $claninfo['clanname'] = $clanname;
            }
            if (httppostisset('clanshort') && $clanshort != $claninfo['clanshort']) {
                $sql = "UPDATE " . db_prefix("clans") . " SET clanshort='{$clanshort}' WHERE clanid={$claninfo['clanid']}";
                output("Updating the short clan name`n");
                db_query($sql);
                invalidatedatacache("clandata-{$detail}");
                $claninfo['clanshort'] = $clanshort;
            }
            $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid={$claninfo['motdauthor']}";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            $motdauthname = $row['name'];
            $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid={$claninfo['descauthor']}";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            $descauthname = $row['name'];
            output("`&`bCurrent MoTD:`b `#by %s`2`n", $motdauthname);
            output_notl(nltoappon($claninfo['clanmotd']) . "`n");
            output("`&`bCurrent Description:`b `#by %s`2`n", $descauthname);
            output_notl(nltoappon($claninfo['clandesc']) . "`n");
            rawoutput("<form action='runmodule.php?module=claneditor&op=updinfo&dt={$dt}' method='POST'>");
            addnav("", "runmodule.php?module=claneditor&op=updinfo&dt={$dt}");
            output("`&`bMoTD:`b `7(4096 chars)`n");
            rawoutput("<textarea name='clanmotd' cols='50' rows='10'>" . htmlentities($claninfo['clanmotd'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "</textarea><br>");
            output("`bRenaming:`b`n");
            output("`iLong Name:`i ");
            rawoutput("<input name='clanname' value=\"" . htmlentities($claninfo['clanname'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "\" maxlength=50 size=50>");
            output("`n`iShort Name:`i ");
            rawoutput("<input name='clanshort' value=\"" . htmlentities($claninfo['clanshort'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "\" maxlength=5 size=5>");
            output_notl("`n");
            output("`n`&`bDescription:`b `7(4096 chars)`n");
            if (httppost('block') > "") {
                $blockdesc = translate_inline("Description blocked for inappropriate usage.");
                $sql = "UPDATE " . db_prefix("clans") . " SET descauthor=4294967295, clandesc='{$blockdesc}' where clanid='" . $claninfo['clanid'] . "'";
                output("Blocking public description`n");
                db_query($sql);
                invalidatedatacache("clandata-" . $claninfo['clanid'] . "");
                $claninfo['blockdesc'] = "";
                $claninfo['descauthor'] = 4294967295.0;
            } elseif (httppost('unblock') > "") {
                $sql = "UPDATE " . db_prefix("clans") . " SET descauthor=0, clandesc='' where clanid='" . $claninfo['clanid'] . "'";
                output("Unblocking public description`n");
                db_query($sql);
                invalidatedatacache("clandata-" . $claninfo['clanid'] . "");
                $claninfo['clandesc'] = "";
                $claninfo['descauthor'] = 0;
            }
            $blocked = translate_inline("The clan has been blocked from posting a description.`n");
            if ($claninfo['descauthor'] == 4294967295.0) {
                output_notl("`b`%" . $blocked . "`b");
            }
            rawoutput("<textarea name='clandesc' cols='50' rows='10'>" . htmlentities($claninfo['clandesc'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "</textarea><br>");
            output("`n`&`bCustom Talk Line`b `7(blank means \"says\" -- 15 chars max)`n");
            rawoutput("<input name='customsay' value=\"" . htmlentities($claninfo['customsay'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "\" maxlength=\"15\"><br/>");
            $save = translate_inline("Save");
            rawoutput("<input type='submit' class='button' value=\"{$save}\">");
            $snu = htmlentities(translate_inline("Save & Unblock public description"), ENT_COMPAT, getsetting("charset", "ISO-8859-1"));
            $snb = htmlentities(translate_inline("Save & Block public description"), ENT_COMPAT, getsetting("charset", "ISO-8859-1"));
            if ($claninfo['descauthor'] == "4294967295") {
                rawoutput("<input type='submit' name='unblock' value=\"{$snu}\" class='button'>");
            } else {
                rawoutput("<input type='submit' name='block' value=\"{$snb}\" class='button'>");
            }
            rawoutput("</form>");
        } elseif ($op == "membership") {
            output("This is the clans current membership:`n");
            $setrank = httpget('setrank');
            $who = httpget('who');
            if ($setrank > "") {
                $sql = "UPDATE " . db_prefix("accounts") . " SET clanrank={$setrank} WHERE login='******'";
                db_query($sql);
            }
            $remove = httpget('remove');
            if ($remove > "") {
                $sql = "UPDATE " . db_prefix("accounts") . " SET clanrank=" . CLAN_APPLICANT . ",clanid=0,clanjoindate='0000-00-00 00:00:00' WHERE login='******' AND clanrank<={$session['user']['clanrank']}";
                db_query($sql);
                //delete unread application emails from this user.
                //breaks if the applicant has had their name changed via
                //dragon kill, superuser edit, or lodge color change
                $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE login='******'";
                $row = db_fetch_assoc(db_query($sql));
                $subj = serialize(array($apply_short, $row['name']));
                $sql = "DELETE FROM " . db_prefix("mail") . " WHERE msgfrom=0 AND seen=0 AND subject='{$subj}'";
                db_query($sql);
            }
            $sql = "SELECT acctid,name,login,clanrank,laston,clanjoindate,dragonkills,level FROM " . db_prefix("accounts") . " WHERE clanid={$claninfo['clanid']} ORDER BY clanrank DESC,clanjoindate";
            $result = db_query($sql);
            rawoutput("<table border='0' cellpadding='2' cellspacing='0'>");
            $rank = translate_inline("Rank");
            $name = translate_inline("Name");
            $lev = translate_inline("Level");
            $dk = translate_inline("Dragon Kills");
            $jd = translate_inline("Join Date");
            $lo = translate_inline("Last On");
            $ops = translate_inline("Operations");
            $promote = translate_inline("Promote");
            $demote = translate_inline("Demote");
            $remove = translate_inline("Remove From The Clan");
            $confirm = translate_inline("Are you sure you wish to remove this member from the clan?");
            rawoutput("<tr class='trhead'><td>{$rank}</td><td>{$name}</td><td>{$lev}</td><td>{$dk}</td><td>{$jd}</td><td>{$lo}</td>" . ($session['user']['clanrank'] > CLAN_MEMBER ? "<td>{$ops}</td>" : "") . "</tr>", true);
            $i = 0;
            $tot = 0;
            while ($row = db_fetch_assoc($result)) {
                $i++;
                $tot += $row['dragonkills'];
                rawoutput("<tr class='" . ($i % 2 ? "trlight" : "trdark") . "'>");
                rawoutput("<td>");
                output_notl($ranks[$row['clanrank']]);
                rawoutput("</td><td>");
                $link = "bio.php?char=" . $row['acctid'] . "&ret=" . urlencode($_SERVER['REQUEST_URI']);
                rawoutput("<a href='{$link}'>", true);
                addnav("", $link);
                output_notl("`&%s`0", $row['name']);
                rawoutput("</a>");
                rawoutput("</td><td align='center'>");
                output_notl("`^%s`0", $row['level']);
                rawoutput("</td><td align='center'>");
                output_notl("`\$%s`0", $row['dragonkills']);
                rawoutput("</td><td>");
                output_notl("`3%s`0", $row['clanjoindate']);
                rawoutput("</td><td>");
                output_notl("`#%s`0", reltime(strtotime($row['laston'])));
                rawoutput("</td>");
                rawoutput("<td>");
                rawoutput("[ <a href='runmodule.php?module=claneditor&op=membership&dt={$dt}&setrank=" . ($row['clanrank'] + 1) . "&who=" . rawurlencode($row['login']) . "'>{$promote}</a> | ");
                addnav("", "runmodule.php?module=claneditor&op=membership&dt={$dt}&setrank=" . ($row['clanrank'] + 1) . "&who=" . rawurlencode($row['login']));
                rawoutput("<a href='runmodule.php?module=claneditor&op=membership&dt={$dt}&setrank=" . ($row['clanrank'] - 1) . "&who=" . rawurlencode($row['login']) . "'>{$demote}</a> | ");
                addnav("", "runmodule.php?module=claneditor&op=membership&dt={$dt}&setrank=" . ($row['clanrank'] - 1) . "&who=" . rawurlencode($row['login']));
                rawoutput("<a href='runmodule.php?module=claneditor&op=membership&dt={$dt}&remove=" . rawurlencode($row['login']) . "' onClick=\"return confirm('{$confirm}');\">{$remove}</a> ]");
                addnav("", "runmodule.php?module=claneditor&op=membership&dt={$dt}&remove=" . rawurlencode($row['login']));
                rawoutput("</td>");
                rawoutput("</tr>");
            }
            rawoutput("</table>");
            output("`n`n`^This clan has a total of `\$%s`^ dragon kills.", $tot);
        }
        if ($dt != "" && isset($claninfo)) {
            addnav("Clan Options");
            addnav("Main View", "runmodule.php?module=claneditor&op=mview&dt={$dt}");
            addnav("Update Clan Information", "runmodule.php?module=claneditor&op=updinfo&dt={$dt}");
            addnav("Delete this Clan", "runmodule.php?module=claneditor&op=deleteclan&dt={$dt}");
            addnav("Update Members", "runmodule.php?module=claneditor&op=membership&dt={$dt}");
            addnav("Module Prefs");
            module_editor_navs("prefs-clans", "runmodule.php?module=claneditor&op=editmodule&dt=" . $claninfo['clanid'] . "&mdule=");
        }
    }
    page_footer();
}
     }
     $sql = "SELECT login,name,superuser FROM " . db_prefix("accounts") . " WHERE name LIKE '" . addslashes($string) . "' AND locked=0 ORDER by login='******' DESC, name='{$to}' DESC, login";
     $result = db_query($sql);
     $db_num_rows = db_num_rows($result);
 }
 if ($db_num_rows == 1) {
     $row = db_fetch_assoc($result);
     output_notl("<input type='hidden' id='to' name='to' value=\"" . htmlentities($row['login'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "\">", true);
     output_notl("`^{$row['name']}`n");
     if ($row['superuser'] & SU_GIVES_YOM_WARNING && !($row['superuser'] & SU_OVERRIDE_YOM_WARNING)) {
         array_push($superusers, $row['login']);
     }
 } elseif ($db_num_rows == 0) {
     output("`\$No one was found who matches \"%s\".`n", stripslashes($to));
     output("`@Please try again.`n");
     httpset('prepop', $to, true);
     rawoutput("</form>");
     require "lib/mail/case_address.php";
     popup_footer();
 } else {
     output_notl("<select name='to' id='to' onchange='check_su_warning();'>", true);
     $superusers = array();
     while ($row = db_fetch_assoc($result)) {
         output_notl("<option value=\"" . htmlentities($row['login'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "\">", true);
         require_once "lib/sanitize.php";
         output_notl("%s", full_sanitize($row['name']));
         if ($row['superuser'] & SU_GIVES_YOM_WARNING && !($row['superuser'] & SU_OVERRIDE_YOM_WARNING)) {
             array_push($superusers, $row['login']);
         }
     }
     output_notl("</select>`n", true);
function drinks_editor()
{
    global $mostrecentmodule;
    if (!get_module_pref("canedit")) {
        check_su_access(SU_EDIT_USERS);
    }
    page_header("Drink Editor");
    require_once "lib/superusernav.php";
    superusernav();
    addnav("Drink Editor");
    addnav("Add a drink", "runmodule.php?module=drinks&act=editor&op=add&admin=true");
    $op = httpget('op');
    $drinkid = httpget('drinkid');
    $header = "";
    if ($op != "") {
        addnav("Drink Editor Main", "runmodule.php?module=drinks&act=editor&admin=true");
        if ($op == 'add') {
            $header = translate_inline("Adding a new drink");
        } else {
            if ($op == 'edit') {
                $header = translate_inline("Editing a drink");
            }
        }
    } else {
        $header = translate_inline("Current drinks");
    }
    output_notl("`&<h3>{$header}`0</h3>", true);
    $drinksarray = array("Drink,title", "drinkid" => "Drink ID,hidden", "name" => "Drink Name", "costperlevel" => "Cost per level,int", "hpchance" => "Chance of modifying HP (see below),range,0,10,1", "turnchance" => "Chance of modifying turns (see below),range,0,10,1", "alwayshp" => "Always modify hitpoints,bool", "alwaysturn" => "Always modify turns,bool", "drunkeness" => "Drunkeness,range,1,100,1", "harddrink" => "Is drink hard alchohol?,bool", "hpmin" => "Min HP to add (see below),range,-20,20,1", "hpmax" => "Max HP to add (see below),range,-20,20,1", "hppercent" => "Modify HP by some percent (see below),range,-25,25,5", "turnmin" => "Min turns to add (see below),range,-5,5,1", "turnmax" => "Max turns to add (see below),range,-5,5,1", "remarks" => "Remarks", "buffname" => "Name of the buff", "buffrounds" => "Rounds buff lasts,range,1,20,1", "buffroundmsg" => "Message each round of buff", "buffwearoff" => "Message when buff wears off", "buffatkmod" => "Attack modifier of buff", "buffdefmod" => "Defense modifier of buff", "buffdmgmod" => "Damage modifier of buff", "buffdmgshield" => "Damage shield modifier of buff", "buffeffectfailmsg" => "Effect failure message (see below)", "buffeffectnodmgmsg" => "No damage message (see below)", "buffeffectmsg" => "Effect message (see below)");
    if ($op == "del") {
        $sql = "DELETE FROM " . db_prefix("drinks") . " WHERE drinkid='{$drinkid}'";
        module_delete_objprefs('drinks', $drinkid);
        db_query($sql);
        $op = "";
        httpset('op', "");
    }
    if ($op == "save") {
        $subop = httpget("subop");
        if ($subop == "") {
            $drinkid = httppost("drinkid");
            list($sql, $keys, $vals) = postparse($drinksarray);
            if ($drinkid > 0) {
                $sql = "UPDATE " . db_prefix("drinks") . " SET {$sql} WHERE drinkid='{$drinkid}'";
            } else {
                $sql = "INSERT INTO " . db_prefix("drinks") . " ({$keys}) VALUES ({$vals})";
            }
            db_query($sql);
            if (db_affected_rows() > 0) {
                output("`^Drink saved!");
            } else {
                $str = db_error();
                if ($str == "") {
                    output("`^Drink not saved: no changes detected.");
                } else {
                    output("`^Drink not saved: `\$%s`0", $sql);
                }
            }
        } elseif ($subop == "module") {
            $drinkid = httpget("drinkid");
            // Save module settings
            $module = httpget("editmodule");
            // This should obey the same rules as the configuration editor
            // So disabling
            //$sql = "DELETE FROM " . db_prefix("module_objprefs") . " WHERE objtype='drinks' AND objid='$drinkid' AND modulename='$module'";
            //db_query($sql);
            $post = httpallpost();
            reset($post);
            while (list($key, $val) = each($post)) {
                set_module_objpref("drinks", $drinkid, $key, $val, $module);
            }
            output("`^Saved.");
        }
        if ($drinkid) {
            $op = "edit";
            httpset("drinkid", $drinkid, true);
        } else {
            $op = "";
        }
        httpset('op', $op);
    }
    if ($op == "activate") {
        $sql = "UPDATE " . db_prefix("drinks") . " SET active=1 WHERE drinkid='{$drinkid}'";
        db_query($sql);
        $op = "";
        httpset('op', "");
    }
    if ($op == "deactivate") {
        $sql = "UPDATE " . db_prefix("drinks") . " SET active=0 WHERE drinkid='{$drinkid}'";
        db_query($sql);
        $op = "";
        httpset('op', "");
    }
    if ($op == "") {
        $op = translate_inline("Ops");
        $id = translate_inline("Id");
        $nm = translate_inline("Name");
        $dkn = translate_inline("Drunkeness");
        $hard = translate_inline("Hard Alchohol?");
        $edit = translate_inline("Edit");
        $deac = translate_inline("Deactivate");
        $act = translate_inline("Activate");
        $conf = translate_inline("Are you sure you wish to delete this drink?");
        $del = translate_inline("Del");
        rawoutput("<table border=0 cellpadding=2 cellspacing=1 bgcolor='#999999'>");
        rawoutput("<tr class='trhead'>");
        rawoutput("<td>{$op}</td><td>{$id}</td><td>{$nm}</td><td>{$dkn}</td><td>{$hard}</td>");
        rawoutput("</tr>");
        $sql = "SELECT drinkid,active,name,drunkeness,harddrink FROM " . db_prefix("drinks") . " ORDER BY drinkid";
        $result = db_query($sql);
        for ($i = 0; $i < db_num_rows($result); $i++) {
            $row = db_fetch_assoc($result);
            $id = $row['drinkid'];
            rawoutput("<tr class='" . ($i % 2 ? "trlight" : "trdark") . "'>");
            rawoutput("<td nowrap>[ <a href='runmodule.php?module=drinks&act=editor&op=edit&drinkid={$id}&admin=true'>{$edit}</a>");
            addnav("", "runmodule.php?module=drinks&act=editor&op=edit&drinkid={$id}&admin=true");
            if ($row['active']) {
                rawoutput(" | <a href='runmodule.php?module=drinks&act=editor&op=deactivate&drinkid={$id}&admin=true'>{$deac}</a>");
                addnav("", "runmodule.php?module=drinks&act=editor&op=deactivate&drinkid={$id}&admin=true");
            } else {
                rawoutput(" | <a href='runmodule.php?module=drinks&act=editor&op=activate&drinkid={$id}&admin=true'>{$act}</a>");
                addnav("", "runmodule.php?module=drinks&act=editor&op=activate&drinkid={$id}&admin=true");
            }
            rawoutput(" | <a href='runmodule.php?module=drinks&act=editor&op=del&drinkid={$id}&admin=true' onClick='return confirm(\"{$conf}\");'>{$del}</a> ]</td>");
            addnav("", "runmodule.php?module=drinks&act=editor&op=del&drinkid={$id}&admin=true");
            output_notl("<td>`^%s</td>`0", $id, true);
            output_notl("<td>`&%s`0</td>", $row['name'], true);
            output_notl("<td>`^%s`0</td>", $row['drunkeness'], true);
            $hard = translate_inline("`^No");
            if ($row['harddrink']) {
                $hard = translate_inline("`\$Yes");
            }
            output_notl("<td>%s`0</td>", $hard, true);
            rawoutput("</tr>");
        }
        rawoutput("</table>");
    }
    $subop = httpget("subop");
    if ($op == "edit") {
        addnav("Drink properties", "runmodule.php?module=drinks&act=editor&op=edit&drinkid={$drinkid}&admin=true");
        module_editor_navs("prefs-drinks", "runmodule.php?module=drinks&act=editor&drinkid={$drinkid}&op=edit&subop=module&editmodule=");
        if ($subop == "module") {
            $module = httpget("editmodule");
            $oldmodule = $mostrecentmodule;
            rawoutput("<form action='runmodule.php?module=drinks&act=editor&op=save&subop=module&editmodule={$module}&drinkid={$drinkid}&admin=true' method='POST'>");
            module_objpref_edit('drinks', $module, $drinkid);
            $mostrecentmodule = $oldmodule;
            rawoutput("</form>");
            addnav("", "runmodule.php?module=drinks&act=editor&op=save&subop=module&editmodule={$module}&drinkid={$drinkid}&admin=true");
        } elseif ($subop == "") {
            $sql = "SELECT * FROM " . db_prefix("drinks") . " WHERE drinkid='" . httpget('drinkid') . "'";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
        }
    } elseif ($op == "add") {
        /* We're adding a new drink, make an empty row */
        $row = array();
        $row['drinkid'] = 0;
    }
    if (($op == "edit" || $op == "add") && $subop == "") {
        rawoutput("<form action='runmodule.php?module=drinks&act=editor&op=save&admin=true' method='POST'>");
        addnav("", "runmodule.php?module=drinks&act=editor&op=save&admin=true");
        showform($drinksarray, $row);
        rawoutput("</form>");
        output("`\$NOTE:`7 Make sure that you know what you are doing when modifying or adding drinks.`n");
        output("Just because the drinks have a lot of options, doesn't mean you have to use all of them`n`n");
        output("`2Drink ID: `7This field is used internally and should be unique.`n");
        output("`2Name: `7The name of the drink the user will see.`n");
        output("`2Cost per level: `7This value times the users level is the drink cost.`n");
        output("`2Chance of modifying HP: `7If set, this is the number of chances out of the total of this and the turn chance for HP getting modified.`n");
        output("`2Chance of modifying turns: `7If set, this is the number of chances out of the total of this and the HP chance for turns getting modified.`n");
        output("`2Always modify HP: `7If set, hitpoints will be modified.  Should not be set alongside HP chance above.`n");
        output("`2Always modify turns: `7If set, turns will be modified.  Should not be set alongside turn chance above.`n");
        output("`2Drunkeness: `7How drunk will this make the player.`n");
        output("`2Hard Drink: `7Users are only allowed a certain number of hard drinks per day regardless of drunkeness.`n");
        output("`2Min HP to add: `7If we are modifying hitpoints, and if HP percent isn't set, use this and the HP max value to pick a random amount of HP to add.  Can be negative.`n");
        output("`2Max HP to add: `7If we are modifying hitpoints and if HP percent isn't set, use this and the HP min value to pick a random amount of HP to add.  Can be negative.`n");
        output("`2HP percent: `7If we are modifying hitpoints and if this is set, the users hitpoints are modified by this percentage.  Can be negative.`n");
        output("`2Min turns to add: `7If we are modifying turns, use this and the turn max value to pick a random amount of turns to add.  Can be negative.`n");
        output("`2Max turns to add: `7If we are modifying turns, use this and the turn min value to pick a random amount of turns to add.  Can be negative.`n");
        output("`2Remarks: `7Text displayed to the user when they order the drink.`n");
        output("`2Buff name: `7What is this buff called.`n");
        output("`2Buff rounds: `7How many rounds this buff lasts.`n");
        output("`2Buff round message: `7What message should show as each round occurs.`n");
        output("`2Buff wearoff: `7What message is shown when this buff wears off.`n");
        output("`2Buff attack modifier: `7Multiplier to modify attack points by? 1.0 is no modification, 2.0 doubles their attack points.`n");
        output("`2Buff defense modifier: `7Multiplier to modify defense points by? 1.0 is no modification, 2.0 doubles their defense points.`n");
        output("`2Buff damage modifier: `7Multiplier to modify damage by? 1.0 is no modification, 2.0 doubles their damage points. This is `\$VERY POTENT`7!`n");
        output("`2Buff damage shield modifier: `7When you are hit, deals damage to your opponent based on damage done to you. 1.0 deals identical damage, 2.0 deals double damage back to the opponent.`n");
        output("`2Effect failure message: Message if this buff fails. (Only used with damage shield)`n");
        output("`2Effect no damage message: Message if no damage is done. (Only used with damage shield)`n");
        output("`2Effect message: What shows when this buff has an effect. (Only used with damage shield)`n`n");
    }
    page_footer();
}
function cities_run()
{
    global $session;
    $op = httpget("op");
    $city = urldecode(httpget("city"));
    $continue = httpget("continue");
    $danger = httpget("d");
    $su = httpget("su");
    if ($op != "faq") {
        require_once "lib/forcednavigation.php";
        do_forced_nav(false, false);
    }
    // I really don't like this being out here, but it has to be since
    // events can define their own op=.... and we might need to handle them
    // otherwise things break.
    require_once "lib/events.php";
    if ($session['user']['specialinc'] != "" || httpget("eventhandler")) {
        $in_event = handle_event("travel", "runmodule.php?module=cities&city=" . urlencode($city) . "&d={$danger}&continue=1&", "Travel");
        if ($in_event) {
            addnav("Continue", "runmodule.php?module=cities&op=travel&city=" . urlencode($city) . "&d={$danger}&continue=1");
            module_display_events("travel", "runmodule.php?module=cities&city=" . urlencode($city) . "&d={$danger}&continue=1");
            page_footer();
        }
    }
    if ($op == "travel") {
        $args = modulehook("count-travels", array('available' => 0, 'used' => 0));
        $free = max(0, $args['available'] - $args['used']);
        if ($city == "") {
            require_once "lib/villagenav.php";
            page_header("Travel");
            //modulehook("collapse{", array("name"=>"traveldesc"));
            output("`%Travelling the world can be a dangerous occupation.");
            output("Although other villages might offer things not found in your current one, getting from village to village is no easy task, and might subject you to various dangerous creatures or brigands.");
            output("Be sure you're willing to take on the adventure before you set out, as not everyone arrives at their destination intact.");
            output("Also, pay attention to the signs, some roads are safer than others.`n");
            //modulehook("}collapse");
            addnav("Forget about it");
            villagenav();
            modulehook("pre-travel");
            if (!($session['user']['superuser'] & SU_EDIT_USERS) && $session['user']['turns'] <= 0 && $free == 0) {
                // this line rewritten so as not to clash with the hitch module.
                output("`nYou don't feel as if you could face the prospect of walking to another city today, it's far too exhausting.`n");
            } else {
                addnav("Travel");
                modulehook("travel");
            }
            module_display_events("travel", "runmodule.php?module=cities&city=" . urlencode($city) . "&d={$danger}&continue=1");
            page_footer();
        } else {
            if ($continue != "1" && $su != "1" && !get_module_pref("paidcost")) {
                set_module_pref("paidcost", 1);
                if ($free > 0) {
                    // Only increment travel used if they are still within
                    // their allowance.
                    set_module_pref("traveltoday", get_module_pref("traveltoday") + 1);
                    //do nothing, they're within their travel allowance.
                } elseif ($session['user']['turns'] > 0) {
                    $session['user']['turns']--;
                } else {
                    output("Hey, looks like you managed to travel with out having any forest fights.  How'd you swing that?");
                    debuglog("Travelled with out having any forest fights, how'd they swing that?");
                }
            }
            // Let's give the lower DK people a slightly better chance.
            $dlevel = cities_dangerscale($danger);
            if (e_rand(0, 100) < $dlevel && $su != '1') {
                //they've been waylaid.
                if (module_events("travel", get_module_setting("travelspecialchance"), "runmodule.php?module=cities&city=" . urlencode($city) . "&d={$danger}&continue=1&") != 0) {
                    page_header("Something Special!");
                    if (checknavs()) {
                        page_footer();
                    } else {
                        // Reset the special for good.
                        $session['user']['specialinc'] = "";
                        $session['user']['specialmisc'] = "";
                        $skipvillagedesc = true;
                        $op = "";
                        httpset("op", "");
                        addnav("Continue", "runmodule.php?module=cities&op=travel&city=" . urlencode($city) . "&d={$danger}&continue=1");
                        module_display_events("travel", "runmodule.php?module=cities&city=" . urlencode($city) . "&d={$danger}&continue=1");
                        page_footer();
                    }
                }
                $args = array("soberval" => 0.9, "sobermsg" => "`&Facing your bloodthirsty opponent, the adrenaline rush helps to sober you up slightly.", "schema" => "module-cities");
                modulehook("soberup", $args);
                require_once "lib/forestoutcomes.php";
                $sql = "SELECT * FROM " . db_prefix("creatures") . " WHERE creaturelevel = '{$session['user']['level']}' AND forest = 1 ORDER BY rand(" . e_rand() . ") LIMIT 1";
                $result = db_query($sql);
                restore_buff_fields();
                if (db_num_rows($result) == 0) {
                    // There is nothing in the database to challenge you,
                    // let's give you a doppleganger.
                    $badguy = array();
                    $badguy['creaturename'] = "An evil doppleganger of " . $session['user']['name'];
                    $badguy['creatureweapon'] = $session['user']['weapon'];
                    $badguy['creaturelevel'] = $session['user']['level'];
                    $badguy['creaturegold'] = 0;
                    $badguy['creatureexp'] = round($session['user']['experience'] / 10, 0);
                    $badguy['creaturehealth'] = $session['user']['maxhitpoints'];
                    $badguy['creatureattack'] = $session['user']['attack'];
                    $badguy['creaturedefense'] = $session['user']['defense'];
                } else {
                    $badguy = db_fetch_assoc($result);
                    $badguy = buffbadguy($badguy);
                }
                calculate_buff_fields();
                $badguy['playerstarthp'] = $session['user']['hitpoints'];
                $badguy['diddamage'] = 0;
                $badguy['type'] = 'travel';
                $session['user']['badguy'] = createstring($badguy);
                $battle = true;
            } else {
                set_module_pref("paidcost", 0);
                //they arrive with no further scathing.
                $session['user']['location'] = $city;
                redirect("village.php", "Redirected to Village from Multiple Cities module");
            }
        }
    } elseif ($op == "fight" || $op == "run") {
        if ($op == "run" && e_rand(1, 5) < 3) {
            // They managed to get away.
            page_header("Escape");
            output("You set off running through the forest at a breakneck pace heading back the way you came.`n`n");
            $coward = get_module_setting("coward");
            if ($coward) {
                modulehook("cities-usetravel", array("foresttext" => array("In your terror, you lose your way and become lost, losing time for a forest fight.`n`n", $session['user']['location']), "traveltext" => array("In your terror, you lose your way and become lost, losing precious travel time.`n`n", $session['user']['location'])));
            }
            output("After running for what seems like hours, you finally arrive back at %s.", $session['user']['location']);
            addnav(array("Enter %s", $session['user']['location']), "village.php");
            page_footer();
        }
        $battle = true;
    } elseif ($op == "faq") {
        cities_faq();
    } elseif ($op == "") {
        page_header("Travel");
        output("A divine light ends the fight and you return to the road.");
        addnav("Continue your journey", "runmodule.php?module=cities&op=travel&city=" . urlencode($city) . "&continue=1&d={$danger}");
        module_display_events("travel", "runmodule.php?module=cities&city=" . urlencode($city) . "&d={$danger}&continue=1");
        page_footer();
    }
    if ($battle) {
        page_header("You've been waylaid!");
        require_once "battle.php";
        if ($victory) {
            require_once "lib/forestoutcomes.php";
            forestvictory($newenemies, "This fight would have yielded an extra turn except it was during travel.");
            addnav("Continue your journey", "runmodule.php?module=cities&op=travel&city=" . urlencode($city) . "&continue=1&d={$danger}");
            module_display_events("travel", "runmodule.php?module=cities&city=" . urlencode($city) . "&d={$danger}&continue=1");
        } elseif ($defeat) {
            require_once "lib/forestoutcomes.php";
            forestdefeat($newenemies, array("travelling to %s", $city));
        } else {
            require_once "lib/fightnav.php";
            fightnav(true, true, "runmodule.php?module=cities&city=" . urlencode($city) . "&d={$danger}");
        }
        page_footer();
    }
}
function jewelmonster_runevent($type, $link)
{
    global $session;
    $op = httpget('op');
    $session['user']['specialinc'] = "module:jewelmonster";
    $battle = false;
    switch ($op) {
        case "":
        case "search":
            $count = 0;
            if (is_module_active("jeweler")) {
                $count = get_module_pref("totalheld", "jeweler");
            }
            output("`3While searching for gems and gold, you feel a shadow fall upon you.");
            output("With a terrible sense of foreboding, you raise your head.");
            output("The creature before your eyes terrifies you to the bone.");
            output("`3From a scaly neck emerges the %s's head of horror, huge tusks leaning towards you in a menacing manner.`n`n", translate_inline(get_module_setting("name")));
            if ($count > 0) {
                output("Catching sight of your jeweled adornments, it rears back for a moment, before moving towards you once again and snarling.");
            }
            output("`3Snakes in its hair tell you this fight is very real, and you had best prepare!");
            addnav("Fight", $link . "op=pre");
            break;
        case "pre":
            $op = "fight";
            httpset("op", $op);
            $count = 0;
            if (is_module_active("jeweler")) {
                $count = get_module_pref("totalheld", "jeweler");
            }
            if ($session['user']['dragonkills'] <= get_module_setting("dk")) {
                $count += get_module_setting("grace");
            }
            $hpl = get_module_setting("hploss") * $count;
            if ($count == $session['user']['dragonkills'] || $count == 10) {
                $monhp = round($session['user']['maxhitpoints'] + 10) - $hpl;
                $monatk = $session['user']['attack'] * 1.1;
                $mondef = $session['user']['defense'] * 1.1;
            } else {
                $monhp = round($session['user']['maxhitpoints'] + 40) - $hpl;
                $monatk = round($session['user']['attack']) * 1.2;
                $mondef = round($session['user']['defense']) * 1.2;
            }
            # if we have a too small hp, just set it to something more reasonable.
            if ($monhp < 10) {
                $monhp = $session['user']['maxhitpoints'] + $hpl / 2;
            }
            // even out his strength a bit
            $badguylevel = $session['user']['level'] + 1;
            if ($session['user']['level'] > 9) {
                $monhp *= 1.05;
            }
            if ($session['user']['level'] < 4) {
                $badguylevel--;
            }
            $badguy = array("creaturename" => translate_inline(get_module_setting("name")), "creatureweapon" => translate_inline("Beak of Doom"), "creaturelevel" => $badguylevel, "creaturehealth" => round($monhp), "creatureattack" => $monatk, "creaturedefense" => $mondef, "noadjust" => 1, "diddamage" => 0, "type" => "jewelmonster");
            $session['user']['badguy'] = createstring($badguy);
            break;
    }
    if ($op == "fight") {
        $battle = true;
    }
    if ($battle) {
        include "battle.php";
        if ($victory) {
            output("`n`n`3You have overcome %s!", translate_inline(get_module_setting("name")));
            if (get_module_pref("totalheld", "jeweler") > 0) {
                output("Your jewelry burns your skin, as if to remind you of your narrow escape.`n`n");
            }
            output("You aren't waiting around to see if it is dead or just resting!`n`n");
            if ($session['user']['hitpoints'] <= 0) {
                output("`n`n`^With the last of your energy, you press a piece of cloth to your wounds, stopping your bloodloss before you are completely dead.`n");
                $session['user']['hitpoints'] = 1;
            }
            $exp = round($session['user']['experience'] * get_module_setting("expgain"));
            // even out the gain a bit... it was too huge at the top and pathetic at the bottom
            if ($session['user']['level'] > 9) {
                $exp *= 0.8;
            }
            if ($session['user']['level'] < 6) {
                $exp *= 1.2;
            }
            if ($session['user']['level'] == 1) {
                $exp += 20;
            }
            // to stop people sometimes gaining 2 xp
            $exp = round($exp);
            output("`3The fight earns you `^%s `3experience.`0", $exp);
            $session['user']['experience'] += round($exp);
            $badguy = array();
            $session['user']['badguy'] = "";
            $session['user']['specialinc'] = "";
        } elseif ($defeat) {
            $badguy = array();
            $session['user']['badguy'] = "";
            $session['user']['specialinc'] = "";
            output("`n`n`3With one final crushing blow, %s pins you to the ground.", translate_inline(get_module_setting("name")));
            if ($session['user']['gold'] > 10) {
                output("While you lie there, helpless, its snake hair extricates some of your gold.");
                $lost = round($session['user']['gold'] * 0.2, 0);
                $session['user']['gold'] -= $lost;
                debuglog("lost {$lost} gold to the jewelmonster");
            }
            if (e_rand(0, 2) == 2 && $session['user']['gems'] > 4) {
                output("In several snakes' mouths you see 4 of your precious gems.`0", $cl);
                $session['user']['gems'] -= 4;
                debuglog("lost 4 gems to the jewelmonster");
            }
            output("An evil smile comes across the %s's grotesque face, before it leaves you lying on the ground rather than kill you.", translate_inline(get_module_setting("name")));
            $exp = round($session['user']['experience'] * get_module_setting("expgain"));
            output("With this humiliation, you lose `^%s `3experience.`0", $exp);
            output("You are able to cling to life... barely.`0");
            $session['user']['experience'] -= $exp;
            $session['user']['hitpoints'] = 1;
        } else {
            require_once "lib/fightnav.php";
            if ($type == "forest") {
                fightnav(true, false);
            } else {
                fightnav(true, false, $link);
            }
        }
    }
}
function tatmonster_runevent($type, $link)
{
    global $session;
    // Handle the case where Petra gets deactivated.
    if (!is_module_active("petra")) {
        output("You hear a rustling in the underbrush, which dies away after a few moments.`n`n");
        output("When nothing at all happens after a couple of minutes, you continue on your way.");
        return;
    }
    $op = httpget('op');
    require_once "lib/partner.php";
    $partner = get_partner();
    $session['user']['specialinc'] = "module:tatmonster";
    $battle = false;
    switch ($op) {
        case "":
        case "search":
            output("`3Walking down a deserted trail, you hear a rustling sound coming from the bushes.");
            output("You can smell something burning, and hear something churning.");
            output("You have no idea if you should check it out, but your curiosity is getting the upper hand.");
            output("`3As you step closer and closer to the bush, the burning scent gets more pronounced and the churning grows louder and louder.`n`n");
            if (get_module_pref("tatnumber", "petra") > 0) {
                output("You feel a brief burning sensation from the tattoos on your arm, as if they are reacting to something!`n`n");
            }
            output("`3There is a feeling of dread, deep in your bones.");
            output("Do you want to wait and see what is making the noise, or flee?");
            addnav("W?Wait", $link . "op=wait");
            addnav("R?Run", $link . "op=flee");
            break;
        case "flee":
            $charmloss = e_rand(get_module_setting("mincharmloss") * 2, get_module_setting("maxcharmloss") * 2);
            output("`3Turning around, you hasten back the way you came.");
            output("With a glance backwards, you see a stray cat come out of the trees.`n`n");
            output("Face red with shame, you don't know if you'll ever be able to let %s`3 know that you got scared by a cat!`n`n", $partner);
            output("You lose %s charm from the shame of your cowardice.", $charmloss);
            debuglog("lost {$charmloss} charm from cowardice to the tatmonster");
            $session['user']['charm'] -= $charmloss;
            if ($session['user']['charm'] < 0) {
                $session['user']['charm'] = 0;
            }
            $session['user']['specialinc'] = "";
            break;
        case "wait":
            output("`3You wait for a moment to see what transpires.`n`n");
            output("`3Out from the bushes springs the Mighty `#%s`3.", get_module_setting("name"));
            output("It lashes out with its three slobbering maws, each of them snarling and growling.");
            output("As you rear back in fear, one of the powerful heads narrowly misses you with its teeth.`n");
            output("Circling around you, the beast blocks your escape!`n");
            addnav("Fight", $link . "op=pre");
            break;
        case "pre":
            $op = "fight";
            httpset("op", $op);
            // accommodate for data left from older versions of petra
            require_once "modules/petra.php";
            petra_calculate();
            // Lets build the Tat Monster NOW!
            $numtats = get_module_pref("tatpower", "petra");
            if ($session['user']['dragonkills'] <= get_module_setting("dk")) {
                $numtats += get_module_setting("grace");
            }
            $hpl = get_module_setting("hploss") * $numtats;
            // the test needs to be changed so that it no longer
            // either assumes that one can only obtain ten tattoos,
            // or that $numtats is an integer
            // JT: changed to 8.4 so existing behaviour was preserved.
            if (floor($numtats) == $session['user']['dragonkills'] || $numtats >= 8.4) {
                $monhp = round($session['user']['maxhitpoints'] * 1.1) - $hpl;
                $monatk = round($session['user']['attack'] * 1.05);
                $mondef = round($session['user']['defense'] * 1.05);
            } else {
                $monhp = round($session['user']['maxhitpoints'] * 1.5) - $hpl;
                $monatk = round($session['user']['attack'] * 1.15);
                $mondef = round($session['user']['defense'] * 1.15);
            }
            // If we have too small hp, then just set the monster = to
            // the players hitpoints + 20 %.
            if ($monhp <= 10) {
                $monhp = round($session['user']['maxhitpoints'] * 1.2);
            }
            // even out his strength a bit
            $badguylevel = $session['user']['level'] + 1;
            if ($session['user']['level'] > 9) {
                $monhp *= 1.05;
            }
            if ($session['user']['level'] > 3) {
                $badguylevel--;
            }
            $badguy = array("creaturename" => translate_inline(get_module_setting("name")), "creatureweapon" => translate_inline("Slobbering Maws"), "creaturelevel" => $session['user']['level'] + 1, "creaturehealth" => round($monhp), "creatureattack" => $monatk, "creaturedefense" => $mondef, "noadjust" => 1, "diddamage" => 0);
            $attackstack = array("enemies" => array($badguy), "options" => array("type" => "tattoomonster"));
            $session['user']['badguy'] = createstring($attackstack);
            break;
    }
    if ($op == "fight") {
        $battle = true;
    }
    if ($battle) {
        include "battle.php";
        if ($victory) {
            output("`n`n`3You have overcome the beast!");
            output("The sensation in your arms slowly fades, and you return to normal.`n`n");
            output("You approach this three-headed monstrosity, to ensure that it truly is dead.");
            output("As you near it, one of its heads slowly opens an eye!");
            if (get_module_pref("tatnumber", "petra") > 0) {
                output("It catches sight of the tattoos on your arms and recoils in horror!");
            }
            output("It twitches some more, and you realize that you have done well even to subdue it, and you had best not remain to give it another chance when it recovers.`n`n");
            if ($session['user']['hitpoints'] <= 0) {
                output("`^With the last of your energy, you press a piece of cloth to your wounds, stopping your bloodloss before you are completely dead.`n");
                $session['user']['hitpoints'] = 1;
            }
            $exp = round($session['user']['experience'] * get_module_setting("expgain"));
            // even out the gain a bit... it was too huge at the top and pathetic at the bottom
            if ($session['user']['level'] > 9) {
                $exp *= 0.8;
            }
            if ($session['user']['level'] < 6) {
                $exp *= 1.2;
            }
            if ($session['user']['level'] == 1) {
                $exp += 20;
            }
            // to stop people sometimes gaining 2 xp
            $exp = round($exp);
            output("`3Achieving this grand feat, you receive `^%s `3experience.`0", $exp);
            $session['user']['experience'] += round($exp);
            $badguy = array();
            $session['user']['badguy'] = "";
            $session['user']['specialinc'] = "";
        } elseif ($defeat) {
            $badguy = array();
            $session['user']['badguy'] = "";
            $session['user']['specialinc'] = "";
            output("`n`n`3With one final crushing blow, the beast levels you.");
            if ($session['user']['gold'] > 10) {
                output("As the blood escapes your body, your purse splits and yields some of your gold.");
                $lost = round($session['user']['gold'] * 0.2, 0);
                $session['user']['gold'] -= $lost;
                debuglog("lost {$lost} gold to the tatmonster");
            }
            $exp = round($session['user']['experience'] * get_module_setting("expgain"));
            output("Feeling the pain of loss, you lose `^%s `3experience.`0", $exp);
            $session['user']['experience'] -= $exp;
            if (e_rand(0, 2) == 2) {
                $charmloss = e_rand(get_module_setting("mincharmloss"), get_module_setting("maxcharmloss"));
                output("The beast leaves a long, jagged scar on your skin, causing you to lose `5%s `3charm.`0", $charmloss);
                $session['user']['charm'] -= $charmloss;
                debuglog("lost {$charmloss} charm to the tatmonster");
                if ($session['user']['charm'] < 0) {
                    $session['user']['charm'] = 0;
                }
            }
            output("You are able to cling to life... but just barely.`0");
            $session['user']['hitpoints'] = 1;
        } else {
            require_once "lib/fightnav.php";
            if ($type == "forest") {
                fightnav(true, false);
            } else {
                fightnav(true, false, $link);
            }
        }
    }
}
<?php

if (httppost("newday") != "") {
    #	$offset = "-".(24 / (int)getsetting("daysperday",4))." hours";
    #	$newdate = date("Y-m-d H:i:s",strtotime($offset));
    #	$sql = "UPDATE " . db_prefix("accounts") . " SET lasthit='$newdate' WHERE acctid='$userid'";
    $sql = "UPDATE " . db_prefix("accounts") . " SET lasthit='0000-00-00 00:00:00' WHERE acctid='{$userid}'";
    db_query($sql);
} elseif (httppost("fixnavs") != "") {
    $sql = "UPDATE " . db_prefix("accounts") . " SET allowednavs='', restorepage='', specialinc='' WHERE acctid='{$userid}'";
    db_query($sql);
    $sql = "DELETE FROM " . db_prefix("accounts_output") . " WHERE acctid='{$userid}';";
    db_query($sql);
} elseif (httppost("clearvalidation") != "") {
    $sql = "UPDATE " . db_prefix("accounts") . " SET emailvalidation='' WHERE acctid='{$userid}'";
    db_query($sql);
}
$op = "edit";
httpset("op", "edit");
function ferryman_fight()
{
    $op = httpget("op");
    global $session;
    $from = "forest.php?";
    if ($op == "fightferryman") {
        $badguy = array("creaturename" => translate_inline("`7The Ferryman`0"), "creaturelevel" => $session['user']['level'] + 2, "creatureweapon" => translate_inline("Ferry Pole"), "creatureattack" => $session['user']['attack'], "creaturedefense" => $session['user']['defense'], "creaturehealth" => round($session['user']['maxhitpoints'], 0), "diddamage" => 0, "didsurprise" => 1, "type" => "ferryman");
        $session['user']['badguy'] = createstring($badguy);
        $op = "fight";
        httpset('op', "fight");
    }
    if ($op == "run") {
        output("`2With nothing but murky water all around, you have nowhere to run!`n`n");
        $op = "fight";
        httpset('op', "fight");
    }
    if ($op == "fight") {
        $battle = true;
    }
    if ($battle) {
        require_once "battle.php";
        if ($victory) {
            output("`n`@You have managed to defeat the Ferryman!");
            output("You cautiously approach the body, and suddenly, it shimmers and disappears before your eyes!`n`n");
            if ($session['user']['hitpoints'] <= 0) {
                output("`n`n`^Using a bit of river weed, you are able to staunch your own wounds, stopping your bloodloss before you are completely dead.`n");
                $session['user']['hitpoints'] = 1;
            }
            output("`2Without the ferryman, you are left to drift with the river currents.");
            output("It takes a long time, but you eventually get to the other shore.`n`n");
            if ($session['user']['hitpoints'] <= 0) {
                output("`n`n`^Your staunch your own wounds with a bit of moss growing nearby, stopping your bloodloss before you are completely dead.`n");
                $session['user']['hitpoints'] = 1;
            }
            $maxfflost = get_module_setting("maxfflost");
            if ($session['user']['turns'] < $maxfflost) {
                $lostff = $session['user']['turns'];
            } else {
                $lostff = $maxfflost;
            }
            $session['user']['turns'] -= $lostff;
            output("`&You have lost some Stamina!");
            $session['user']['specialinc'] = "";
            $session['user']['specialmisc'] = "";
        } elseif ($defeat) {
            require_once "lib/taunt.php";
            $taunt = select_taunt_array();
            $lostgold = $session['user']['gold'];
            output("`n`@You have been killed by the Ferryman!");
            output("As your last breath escapes you, all you hear is haunting laughter.");
            addnav("Daily News", "news.php");
            addnews("`%%s `7was last seen aboard a small boat.`0", $session['user']['name']);
            debuglog("killed by Ferryman, losing {$lostgold}");
            $session['user']['gold'] = 0;
            $session['user']['specialinc'] = "";
            $session['user']['specialmisc'] = "";
        } else {
            fightnav(true, true);
        }
    }
}
        output("`n`n`&Because you have slain the dragon %s time, you start with some extras.  You also keep additional permanent hitpoints you've earned.`n", $session['user']['dragonkills']);
    } else {
        addnews(sprintf_translate("`#%s`# has earned the title `&%s`# for having slain the `@Green Dragon`& `^%s`# times!", $regname, $session['user']['title'], $session['user']['dragonkills']));
        output("`n`n`&Because you have slain the dragon %s times, you start with some extras.  You also keep additional permanent hitpoints you've earned.`n", $session['user']['dragonkills']);
    }
    $session['user']['charm'] += 5;
    output("`^You gain FIVE charm points for having defeated the dragon!`n");
    debuglog("slew the dragon and starts with {$session['user']['gold']} gold and {$session['user']['gems']} gems");
    // Moved this hear to make some things easier.
    modulehook("dragonkill", array());
    invalidatedatacache("list.php-warsonline");
}
if ($op == "run") {
    output("The creature's tail blocks the only exit to its lair!");
    $op = "fight";
    httpset('op', 'fight');
}
if ($op == "fight" || $op == "run") {
    $battle = true;
}
if ($battle) {
    require_once "battle.php";
    if ($victory) {
        $flawless = 0;
        if ($badguy['diddamage'] != 1) {
            $flawless = 1;
        }
        $session['user']['dragonkills']++;
        output("`&With a mighty final blow, `@The Green Dragon`& lets out a tremendous bellow and falls at your feet, dead at last.");
        addnews(sprintf_translate("`&%s has slain the hideous creature known as `@The Green Dragon`&.  All across the land, people rejoice!", $session['user']['name']));
        tlschema("nav");
function proveyourself_run()
{
    global $session, $badguy, $battle;
    $op = httpget('op');
    page_header("Nightmare Court");
    switch ($op) {
        case "start":
            output("You head inside a large warehouse-type building.  A black-robed Mutant in a small reception area notices you and steps forward.  \"`4Welcome,`0\" he says, spreading his three misshapen arms dramatically.  \"`4This is a place where all of my kind will one day come to face their deepest fears.`0\"`n`nAh, the Obligatory Drama.  You nod and smile patiently as he explains.`n`n\"`4In this place, we teach how to accept one's limitations, and how to face and fight one's nightmares regardless.  It's a deeply intense and spiritual experience`0\"`n`n\"`#How much?`0\" you ask.`n`n\"`4Ah, the unfortunate topic of coin, how sadly necessary in a world obsessed with material wealth...`0\"`n`n\"`#`iHow much.`i`0\"`n`n\"`4It'll cost you a cigarette.`0\"`n`n\"`#Right, then.`0\"`n`n");
            if (!get_module_pref("playedtoday") && $session['user']['gems'] && $session['user']['hitpoints'] >= $session['user']['maxhitpoints']) {
                addnav("What will you do?");
                addnav("Fight", "runmodule.php?module=proveyourself&op=enter");
                addnav("Flee", "village.php");
            } else {
                if (get_module_pref("playedtoday")) {
                    addnav("You've already played today");
                    addnav("Back to the Outpost", "village.php");
                } else {
                    if (!$session['user']['gems']) {
                        addnav("You don't have a Cigarette handy");
                        addnav("Back to the Outpost", "village.php");
                    } else {
                        if ($session['user']['hitpoints'] < $session['user']['maxhitpoints']) {
                            addnav("You need to heal up first");
                            addnav("Back to the Outpost", "village.php");
                        }
                    }
                }
            }
            break;
        case "enter":
            output("You drop your cigarette into an unnecessarily ornate box, and the Mutant ushers you through a wooden door and into the mouth of a long, dark, red-carpeted corridor.`n`n\"`4Drink this,`0\" he says, passing you a simple wooden goblet filled with a sticky-looking fluid.  You sniff cautiously, then drink.  It tastes of dust and steel.`n`n\"`4Now remember; nothing in here can hurt you unless you allow it to.`0\"  His voice drops to a whisper as he presses a battery-operated torch into your hand.  \"`4Good luck.`0\"`n`nThe door closes gently behind him, and a faint `iclick`i is heard.`n`nYou flick on the torch and take a few steps away from the single overhead lamp.`n`nYou begin the long walk down the corridor.  Before long the red carpet runs out, leaving you walking on a bare concrete floor.`n`nAs you proceed further away from the light, the corridor becomes narrower, and cracks appear every few feet in the plaster.  Another half a minute of putting one foot in front of the other, and you look down to find that you're now walking on steel treadplate.`n`nYou mark off the cracks in the walls as you proceed, noting their increasing frequency.  Within another minute, the walls are crumbling away to reveal a cold chain-link fence, behind which, nothing but darkness.`n`nYou feel the steel give way to rust which bends worryingly beneath your feet, little pieces of dead metal sticking to your boots and falling back with a quiet tinny rustling.`n`nYou still cannot see the end of the corridor.`n`nThe sour metallic scent of oily, corroded metal lingers around oxidized chain-link fences.  You tread warily around the holes in the floor; even with your torch, you can't see what's underneath the thinning treadplate.  You see something shining in the distance, and quicken your pace.  A heavy steel door.`n`nYou look back over your shoulder.  You cannot see the entrance.  Through the steel door, then.  You grip the handle to the right, and pull.`n`nYou hadn't realized how silent this place was until you opened the door; a throaty rushing noise issued from its tracks as corroded bearings spun in dust-blackened oil.  You step through.`n`nIs the battery in your torch dying?`n`nYou pull out your lighter, and ignite.`n`nThe flame is a dull, dirty orange, plumes of soot-darkened smoke billowing from your mundane, butane-driven lighter.`n`nYou tell yourself that the torch is not dying; its cone of light is not dimming to a deep orange, not turning redder and dimmer by the second.  None of that is happening.`n`nThe torch is just as bright as ever.  The problem is that the darkness is getting thicker.`n`nWithin seconds you are blind, and aware of how far away you are from other people, and medical attention.`n`nAware that if you get knocked out here, you won't be going to the FailBoat.`n`nYou feel the hot, damp breath on your face before you hear the growl.`n`n");
            addnav("Continue");
            addnav("Continue", "runmodule.php?module=proveyourself&op=beginfighting");
            break;
        case "beginfighting":
            $session['user']['gems']--;
            restore_buff_fields();
            $badguy = array();
            $badguy['creaturename'] = "Nightmare";
            $badguy['creatureweapon'] = "Serrated Blades";
            $badguy['creaturelevel'] = 1;
            $badguy['creaturegold'] = 0;
            $badguy['creatureexp'] = 0;
            $badguy['creaturehealth'] = 1000000000000.0;
            $badguy['creatureattack'] = 1;
            $badguy['creaturedefense'] = 1;
            $badguy['hidehitpoints'] = 1;
            calculate_buff_fields();
            $badguy['playerstarthp'] = $session['user']['hitpoints'];
            $badguy['diddamage'] = 0;
            $badguy['type'] = 'nightmare';
            $badguy['creatureaiscript'] = "require(\"ai/nightmare.php\");";
            $session['user']['badguy'] = createstring($badguy);
            $battle = true;
            break;
        case "run":
            output("You can't run from your nightmare.`n`n");
            $op = "fight";
            httpset('op', $op);
            $battle = true;
            break;
        case "fight":
            $battle = true;
            break;
        case "end":
            $points = httpget("points");
            $highscore = get_module_pref("highscore");
            output("You regain your senses while rolling around on the floor, waving your weapon at the empty air.  You're at the end of the corridor.  You look back to see the entryway not thirty feet away, and your Mutant friend striding along the corridor.`n`n\"`4Feeling better now?`0\"`n`n\"`#What the `ihell`i was in that drink?`0\"`n`n\"`4Died, did you?  Ah, well.  It's an experience, anyway.`0\"  He looks around at the chunks you've taken out of the walls.  \"`4Well, I reckon you knocked about %s hitpoints out of your imagination.  Naturally it'll all go on the Hall O' Fame.`0\"`n`nYou take a deep breath and begin to point a recriminating finger.  After a moment you shrug, get to your feet and leave, smacking the Mutant around the back of the head as you go.`n`n", $points);
            if ($points > $highscore) {
                output("`4You beat your personal record!`0`n`n");
                set_module_pref("highscore", $points);
            }
            addnav("Exit");
            addnav("Back to the Outpost", "village.php");
            break;
        case "hof":
            page_header("Nightmare Enthusiasts");
            $acc = db_prefix("accounts");
            $mp = db_prefix("module_userprefs");
            $sql = "SELECT {$acc}.name AS name,\r\n\t\t\t\t{$acc}.acctid AS acctid,\r\n\t\t\t\t{$mp}.value AS highscore,\r\n\t\t\t\t{$mp}.userid FROM {$mp} INNER JOIN {$acc}\r\n\t\t\t\tON {$acc}.acctid = {$mp}.userid \r\n\t\t\t\tWHERE {$mp}.modulename = 'proveyourself' \r\n\t\t\t\tAND {$mp}.setting = 'highscore' \r\n\t\t\t\tAND {$mp}.value > 0 ORDER BY ({$mp}.value+0)\t\r\n\t\t\t\tDESC limit 200";
            $result = db_query($sql);
            $rank = translate_inline("Damage Points");
            $name = translate_inline("Name");
            output("`n`b`c`4Nightmare Enthusiasts`0`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", number_format($row['highscore']));
                rawoutput("</td></tr>");
            }
            rawoutput("</table>");
            addnav("Back to HoF", "hof.php");
            villagenav();
            break;
    }
    if ($battle) {
        include_once "battle.php";
        if ($defeat) {
            addnav("You have been killed.");
            $session['user']['hitpoints'] = $session['user']['maxhitpoints'];
            $points = 1000000000000.0 - $badguy['creaturehealth'];
            addnav("What happens next?", "runmodule.php?module=proveyourself&op=end&points=" . $points);
        } else {
            if ($victory) {
                addnav("Now what?");
                addnav("What happens next?", "runmodule.php?module=proveyourself&op=end&points=" . $points);
            } else {
                require_once "lib/fightnav.php";
                fightnav(true, true, "runmodule.php?module=proveyourself", true);
            }
        }
    }
    page_footer();
}
                     debug("Moving companions");
                     $sql = "UPDATE " . db_prefix("companions") . " SET companionlocation = '" . addslashes($val) . "' WHERE companionlocation = '" . addslashes($old[$key]) . "'";
                     db_query($sql);
                 }
                 $oldval = "";
                 if (isset($old[$key])) {
                     $oldval = $old[$key];
                 }
                 gamelog("`@changed module setting `^{$module}.{$key}`@ from `3{$oldval}`@ to `#{$val}`0", "settings");
                 modulehook("changesetting", array("module" => $module, "setting" => $key, "old" => $oldval, "new" => $val), true);
             }
         }
         output("`^Module %s settings saved.`0`n", $module);
     }
     $save = "";
     httpset('save', "");
 }
 if ($save == "") {
     $info = get_module_info($module);
     if (count($info['settings']) > 0) {
         load_module_settings($mostrecentmodule);
         $msettings = array();
         while (list($key, $val) = each($info['settings'])) {
             if (is_array($val)) {
                 $v = $val[0];
                 $x = explode("|", $v);
                 $val[0] = $x[0];
                 $x[0] = $val;
             } else {
                 $x = explode("|", $val);
             }
$refresh = httpget("refresh");
$commenting = httpget("commenting");
$comment = httppost('insertcommentary');
// Don't give people a chance at a special event if they are just browsing
// the commentary (or talking) or dealing with any of the hooks in the village.
if (!$op && $com == "" && !$comment && !$refresh && !$commenting) {
    if (module_events("gardens", getsetting("gardenchance", 0)) != 0) {
        if (checknavs()) {
            page_footer();
        } else {
            // Reset the special for good.
            $session['user']['specialinc'] = "";
            $session['user']['specialmisc'] = "";
            $skipgardendesc = true;
            $op = "";
            httpset("op", "");
        }
    }
}
if (!$skipgardendesc) {
    checkday();
    $gardentext = array("text" => "`n`nYou walk through a gate and on to one of the many winding paths that makes its way through the well-tended gardens.`n`nFrom the flowerbeds that bloom even in darkest winter, to the hedges whose shadows promise forbidden secrets, these gardens provide a refuge for those seeking out the Green Dragon; a place where they can forget their troubles for a while and just relax.`n`nOne of the fairies buzzing about the garden flies up to remind you that the garden is a place for roleplaying and peaceful conversation, and to confine out-of-character comments to the other areas of the game.`n`n");
    $gardentext = modulehook("gardentext", $gardentext);
    output_notl("%s", $gardentext['text']);
}
addnav("Places");
modulehook("gardens", array());
commentdisplay("", "gardens", "Chat with other players", 30, "says");
module_display_events("gardens", "gardens.php");
addnav("Leave");
villagenav();
Ejemplo n.º 23
0
if ($battle) {
    require_once "battle.php";
    if ($victory) {
        $killedin = $badguy['location'];
        $handled = pvpvictory($badguy, $killedin, $options);
        // Handled will be true if a module has already done the addnews or
        // whatever was needed.
        if (!$handled) {
            if ($killedin == $iname) {
                addnews(sprintf_translate("`4%s`3 defeated `4%s`3 by sneaking into their room in the inn!", $session['user']['name'], $badguy['creaturename']));
            } else {
                addnews(sprintf_translate("`4%s`3 defeated `4%s`3 in fair combat in the fields of %s.", $session['user']['name'], $badguy['creaturename'], $killedin));
            }
        }
        $op = "";
        httpset('op', $op);
        if ($killedin == $iname) {
            addnav("Return to the inn", "inn.php");
        } else {
            villagenav();
        }
        if ($session['user']['hitpoints'] <= 0) {
            output("`n`n`&Using a bit of cloth nearby, you manage to staunch your wounds so that you do not die as well.");
            $session['user']['hitpoints'] = 1;
        }
    } elseif ($defeat) {
        $killedin = $badguy['location'];
        $taunt = select_taunt_array();
        // This is okay because system mail which is all it's used for is
        // not translated
        $handled = pvpdefeat($badguy, $killedin, $taunt, $options);
function module_events($eventtype, $basechance, $baseLink = false)
{
    if ($baseLink === false) {
        global $PHP_SELF;
        $baseLink = substr($PHP_SELF, strrpos($PHP_SELF, "/") + 1) . "?";
    } else {
        //debug("Base link was specified as $baseLink");
        //debug(debug_backtrace());
    }
    if (e_rand(1, 100) <= $basechance) {
        global $PHP_SELF;
        $events = module_collect_events($eventtype);
        $chance = r_rand(1, 100);
        reset($events);
        $sum = 0;
        foreach ($events as $event) {
            if ($event['rawchance'] == 0) {
                continue;
            }
            if ($chance > $sum && $chance <= $sum + $event['normchance']) {
                $_POST['i_am_a_hack'] = 'true';
                tlschema("events");
                output("`^`c`bSomething Special!`c`b`0");
                tlschema();
                $op = httpget('op');
                httpset('op', "");
                module_do_event($eventtype, $event['modulename'], false, $baseLink);
                httpset('op', $op);
                return 1;
            }
            $sum += $event['normchance'];
        }
    }
    return 0;
}
function onslaught_run()
{
    global $session, $battle, $enemies;
    global $companions, $companion, $newcompanions;
    debug($session['user']['location']);
    switch (httpget('op')) {
        case "lookaround":
            page_header("What's the situation?");
            $rawnum = onslaught_nummonsters();
            require_once "lib/dialogue.php";
            $vague = vagueify($rawnum);
            output("Taking a moment during a lull in the fighting to look around, you'd say as a rough estimate that there are between %s and %s monsters rampaging through the Outpost.`n`n", $vague['low'], $vague['high']);
            $playercount = 0;
            output("Looking around you, you can see the following players engaged in battle alongside you:`n");
            $sql = "SELECT name,acctid,level FROM " . db_prefix("accounts") . " WHERE locked=0 AND loggedin=1 AND alive=1 AND location='" . $session['user']['location'] . "' AND laston>'" . date("Y-m-d H:i:s", strtotime("-" . getsetting("LOGINTIMEOUT", 900) . " seconds")) . "' ORDER BY level DESC";
            $result = db_query($sql);
            while ($row = db_fetch_assoc($result)) {
                $playercount++;
                output("`0%s`0`n", $row['name']);
            }
            if (!$playercount) {
                output("`bNobody!`b  You're fighting all on your lonesome!`n`n");
            } else {
                output_notl("`n");
            }
            $def = onslaught_checkwalls();
            output("You take a quick glance at the walls, and see they've got %s hitpoints, whatever the hell a \"hitpoint\" is.`n`n", $def);
            $breakchance = e_rand(0, 100);
            if ($breakchance > 50) {
                addnav("What will you do?");
                addnav("Reinforce the defences", "runmodule.php?module=onslaught&op=reinforce");
                addnav("Get back into the fight", "runmodule.php?module=onslaught&op=start&nodesc=1");
                addnav("Run outside and let the Outpost fend for itself", "runmodule.php?module=onslaught&op=runmap");
            } else {
                addnav("And here comes another monster!");
                addnav("Fight!", "runmodule.php?module=onslaught&op=continue&nodesc=1");
            }
            break;
        case "reinforce":
            page_header("Outpost Walls");
            $lv = onslaught_checkmonsters();
            $num = onslaught_nummonsters();
            $def = onslaught_checkwalls();
            output("`0You take a look at the Outpost walls.  Fortunately there are some lengths of timber, a hammer, and some nails sat conveniently next to a portion that's looking a little worse for wear.`n`nThis Outpost's hitpoints: `b%s`b`n`n", number_format($def));
            $stopchance = e_rand(0, 100);
            if ($lv > 100 && $def < $num && $stopchance > 80) {
                output("Before you have a chance to pick up the hammer, you hear the sound of approaching thunderous footsteps from behind you!  You whirl around, dropping the hammer and drawing your weapon, to see a slavering beast bearing down upon you!`n`n");
                addnav("Oh dear...");
                addnav("Fight!", "runmodule.php?module=onslaught&op=start&nodesc=1");
            } else {
                addnav("What will you do?");
                require_once "modules/staminasystem/lib/lib.php";
                $cost = stamina_getdisplaycost("Reinforcement");
                addnav(array("Reinforce the defences (`Q%s%%`0)", $cost), "runmodule.php?module=onslaught&op=reinforceconfirm");
                addnav("Return to the Outpost", "village.php");
            }
            break;
        case "reinforceconfirm":
            $iterations = httpget('iterations');
            if (!$iterations) {
                $iterations = 1;
            }
            page_header("Outpost Walls");
            $lv = onslaught_checkmonsters();
            $num = onslaught_nummonsters();
            output("`0You pick up the hammer and nails, and set about reinforcing the walls with new wood.`n`n");
            require_once "modules/staminasystem/lib/lib.php";
            for ($i = 0; $i < $iterations; $i++) {
                $def = onslaught_checkwalls();
                $stopchance = e_rand(0, 100);
                if ($lv > 100 && $def < $num && $stopchance > 80) {
                    output("Before you have a chance to pound a single nail, you hear the sound of approaching thunderous footsteps from behind you!  You whirl around, dropping the hammer and drawing your weapon, to see a slavering beast bearing down upon you!`n`n");
                    addnav("Oh dear...");
                    addnav("Fight!", "runmodule.php?module=onslaught&op=start&nodesc=1");
                    $nomore = 1;
                    break;
                } else {
                    $act = process_action("Reinforcement");
                    $actinfo = get_player_action("Reinforcement");
                    $actlvl = $actinfo['lvl'];
                    if ($act['lvlinfo']['levelledup'] == true) {
                        output("`n`c`b`0You gained a level in Reinforcement!  You are now level %s!  This action will cost fewer Stamina points now, so reinforcing Outposts will tire you out a little less.`b`c`n", $act['lvlinfo']['newlvl']);
                    }
                    $stamina = get_stamina();
                    $failchance = e_rand(1, 100);
                    if ($failchance > $stamina) {
                        output("`4`c`bDisaster!`b`c`0`n");
                        $red = get_stamina(0);
                        $death = e_rand(0, 100);
                        if ($death > $red) {
                            output("`\$Your exhaustion makes itself known - the hammer rebounds rather spectacularly and hits you square in the forehead, knocking you out cold.  The head injury causes you to lose 10% of your experience, and all your Requisition is stolen by opportunistic Midgets.`n`n`0");
                            $session['user']['hitpoints'] = 0;
                            $session['user']['experience'] = round($session['user']['experience'] * 0.9);
                            $session['user']['gold'] = 0;
                            addnav("It's FailBoat time!");
                            addnav("Well, damn.", "shades.php");
                            $nomore = 1;
                            break;
                        } else {
                            output("You're so exhausted that you make a right pig's ear of the job!`n`nThe fresh plank hangs for a second on one lonely nail before falling off.  What a waste of time!`n`n");
                        }
                    } else {
                        $definc = e_rand($actlvl * 0.8, $actlvl * 1.2);
                        if ($definc < 2) {
                            $definc = 2;
                        }
                        $newdef = $def + $definc;
                        output("You hammer the board to the walls, reinforcing them quite nicely and adding %s hitpoints to this Outpost's defences.`n`nThis Outpost's hitpoints: `b%s`b`n`n", $definc, number_format($newdef));
                        require_once "modules/cityprefs/lib.php";
                        $cid = get_cityprefs_cityid("location", $session['user']['location']);
                        if ($cid) {
                            set_module_objpref("city", $cid, "defences", $newdef);
                        }
                    }
                }
            }
            if (!$nomore) {
                $cost = stamina_getdisplaycost("Reinforcement");
                addnav(array("Wall reinforcement: (`Q%s%%`0)", $cost));
                addnav("Reinforce once", "runmodule.php?module=onslaught&op=reinforceconfirm");
                addnav("5?Reinforce x 5", "runmodule.php?module=onslaught&op=reinforceconfirm&iterations=5");
                addnav("1?Reinforce x 10", "runmodule.php?module=onslaught&op=reinforceconfirm&iterations=10");
                addnav("O?Return to the Outpost", "village.php");
            }
            break;
        case "runsuccess":
            page_header("Run Like Hell!");
            output("You manage to flee your opponent.  You stand close to the Outpost gates, watching the carnage inside.  For the moment, everybody and everything is leaving you alone.  That will not last for long.`n`nNearby, someone has abandoned their timber, hammer and nails.  Abandoned or been dragged from, anyway.`n`n");
            addnav("What will you do?");
            addnav("Reinforce the defences", "runmodule.php?module=onslaught&op=reinforce");
            addnav("Get back into the fight", "runmodule.php?module=onslaught&op=start&nodesc=1");
            addnav("Run outside and let the Outpost fend for itself", "runmodule.php?module=onslaught&op=runmap");
            addnav("Take stock of the situation", "runmodule.php?module=onslaught&op=lookaround");
            break;
        case "runmap":
            redirect("runmodule.php?module=worldmapen&op=beginjourney", "Onslaught - Running Away");
            break;
        case "start":
            page_header("Breach!");
            output("`b`i`4THE WALLS OF %s ARE BREACHED!`0`i`b`nMonsters are pouring into the Outpost through jagged, splintered holes in the Outpost defences!  You picked one `ihell`i of a time to go about your business here!`n`n", strtoupper($session['user']['location']));
            onslaught_getenemy();
            break;
        case "run":
            page_header("Breach!");
            if (e_rand(1, 5) < 3) {
                // They managed to get away.
                $battle = false;
                redirect("runmodule.php?module=onslaught&op=runsuccess", "Onslaught: successful running");
            } else {
                output("You try to run, but your enemy gives chase!`n");
                $op = "fight";
                httpset('op', $op);
                $battle = true;
            }
            break;
        case "fight":
            page_header("Breach!");
            $battle = true;
            break;
        case "continue":
            page_header("Breach!");
            $out1 = onslaught_getcompanion();
            $out2 = onslaught_companion_escape();
            if ($out1) {
                output("`0%s`n", $out1);
            } else {
                if ($out2) {
                    output("`0%s`n", $out2);
                }
            }
            onslaught_getenemy();
            if (!$battle) {
                $left = onslaught_checkmonsters();
                if ($left > 100) {
                    $breakchance = e_rand(0, 100);
                    if ($breakchance > 70) {
                        addnav("Phew!");
                        addnav("Looks like everything else is busy...", "");
                        addnav("Reinforce the defences", "runmodule.php?module=onslaught&op=reinforce");
                        addnav("Get back into the fight", "runmodule.php?module=onslaught&op=start&nodesc=1");
                        addnav("Run outside and let the Outpost fend for itself", "runmodule.php?module=onslaught&op=runmap");
                        addnav("Take stock of the situation", "runmodule.php?module=onslaught&op=lookaround");
                    } else {
                        addnav("They just keep coming!");
                        addnav("Here comes another one!", "runmodule.php?module=onslaught&op=continue&nodesc=1");
                    }
                } else {
                    output("There are no more monsters to fight...`n`n");
                    //Display cleanup text, tart this up a bit
                    addnav("Village", "village.php");
                }
            }
            break;
    }
    if ($battle) {
        include_once "battle.php";
        // if( isset( $enemies ) && !$pvp )
        // $badguy = &$enemies;
        if ($victory) {
            $experience = e_rand($badguy['creatureexp'] * 1.25, $badguy['creatureexp'] * 2);
            $experience = round($experience);
            output("`#You receive `6%s `#experience!`n", $experience);
            $session['user']['experience'] += $experience;
            $left = onslaught_checkmonsters();
            if ($left > 100) {
                $breakchance = e_rand(0, 100);
                if ($breakchance > 70) {
                    addnav("Phew!");
                    addnav("Looks like everything else is busy...", "");
                    addnav("Reinforce the defences", "runmodule.php?module=onslaught&op=reinforce");
                    addnav("Get back into the fight", "runmodule.php?module=onslaught&op=start&nodesc=1");
                    addnav("Run outside and let the Outpost fend for itself", "runmodule.php?module=onslaught&op=runmap");
                    addnav("Take stock of the situation", "runmodule.php?module=onslaught&op=lookaround");
                } else {
                    addnav("They just keep coming!");
                    addnav("Here comes another one!", "runmodule.php?module=onslaught&op=continue&nodesc=1");
                }
            } else {
                output("You lower your weapon, blood splattered over your clothing.  It looks like you're winning - there are no more monsters to fight just now.`n`n");
                //Display cleanup text, tart this up a bit
                addnav("Village", "village.php");
            }
        } elseif ($defeat) {
            require_once "lib/forestoutcomes.php";
            forestdefeat(array($badguy), "in an Outpost");
        } else {
            require_once "lib/fightnav.php";
            fightnav(true, true, "runmodule.php?module=onslaught&nodesc=1");
        }
    }
    page_footer();
}