function mapchat_run()
{
    global $session;
    $xyz = httpget('xyz');
    page_header("Tent!");
    output("There's a tent here!");
    require_once "lib/commentary.php";
    addcommentary();
    viewcommentary("worldmap" . $xyz, "Map Chat!", 25);
    addnav("Go Back", "runmodule.php?module=worldmapen&op=continue");
    page_footer();
}
function fourthwall_run()
{
    global $session;
    page_header("The Place Behind the Fourth Wall");
    output("Much like the pleasant gardens of Common Ground, The Place Behind the Fourth Wall has an entry point from every Outpost on the Island.  Contestants may enter The Place Behind the Fourth Wall, or Location Four as it is officially known, from any Outpost - but may only return to the Outpost from which they came in.`n`nIt is a bright, blurry place, where it's rather difficult to focus on anything other than the other contestants - and even then, some find it easier to shut their eyes and simply talk and listen.`n`nIn contrast to Common Ground, The Place Behind the Fourth Wall is an area for out-of-character conversations, real-life chat, giving and receiving help with the game, and so on.  As always, official bug reports may be posted in the Enquirer - this isn't the place for them, as conversations can go too quickly for staff to find bug reports.`n`nPlease, no roleplaying in Location Four - the whole rest of the Island is a better place for that.`n`nHave fun!");
    require_once "lib/commentary.php";
    addcommentary();
    viewcommentary("fourthwall", "Chatty Chat Chat");
    addnav("Return");
    addnav("Back to the Outpost", "village.php");
    page_footer();
}
function forestchat_run()
{
    global $session;
    page_header("Who is here?");
    output("You look around yourself to see if there are any warriors nearby who you can chinwag with.`n`n");
    require_once "lib/commentary.php";
    addcommentary();
    $loc = substr($session['user']['location'], 0, 10);
    viewcommentary("forest-" . $loc, "Chat with others who walk this path...", 25);
    addnav("Continue");
    addnav("Back to the Jungle", "forest.php");
    page_footer();
}
function worldmapchat_run()
{
    global $session;
    page_header("Who is here?");
    output("Because the more out-of-the-way areas of Improbable Island can provide a shred more privacy than the town squares, you can sometimes find people hanging around and just chatting.  If, that is, they've not hidden themselves too well.`n`nYou look around yourself to see if there are any travellers nearby who you can chinwag with.`n`n");
    require_once "lib/commentary.php";
    addcommentary();
    $loc = get_module_pref("worldXYZ", "worldmapen");
    viewcommentary("worldmap-" . $loc, "Chat with others who walk this path...", 25);
    addnav("Continue your Journey");
    addnav("Back to the World Map", "runmodule.php?module=worldmapen&op=continue");
    page_footer();
}
function biochat_dohook($hookname, $args)
{
    global $session;
    switch ($hookname) {
        case "bioend":
            require_once "lib/commentary.php";
            output("`n`n`0%s`0's Natter feed:`n", $args['name']);
            addcommentary();
            $section = "bio-" . $args['acctid'];
            viewcommentary($section, "Natter!", 25);
            if (!strpos(httpget('ret'), "bio.php")) {
                set_module_pref("lastplace", httpget('ret'));
            }
            $sql = "SELECT COUNT(commentid) AS totalcomments FROM " . db_prefix("commentary") . " WHERE section='{$section}'";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            $all = $row['totalcomments'];
            set_module_pref("total", $all, "biochat", $args['acctid']);
            if ($args['acctid'] == $session['user']['acctid']) {
                //this is the player looking at his or her own bio
                set_module_pref("seen", $all);
            }
            $return = get_module_pref("lastplace");
            if ($return) {
                $return = substr($return, strrpos($return, "/") + 1);
                addnav("Been clicking around Bios and Nattering for a while?");
                addnav("Go `iright`i back to where you came from", $return);
            }
            debug($return);
            break;
        case "commentaryoptions":
            if (!strpos($_SERVER['REQUEST_URI'], "char=" . $session['user']['acctid'] . "&")) {
                $link = "bio.php?char=" . $session['user']['acctid'] . "&ret=" . URLEncode($_SERVER['REQUEST_URI']);
                $total = get_module_pref("total");
                $seen = get_module_pref("seen");
                output("<a href=\"{$link}\">View my Bio</a> ", true);
                if ($seen != $total) {
                    $new = $total - $seen;
                    if ($new == 1) {
                        output("(1 unread Natter) ");
                    } else {
                        output("(%s unread Natters) ", $new);
                    }
                }
                addnav("", $link);
            }
            break;
    }
    return $args;
}
function scry_run()
{
    global $session;
    addcommentary();
    $area = httpget("area");
    $village = httpget("village");
    $op = httpget("op");
    $cost = $session['user']['level'] * get_module_setting("cost");
    if ($op == "pay") {
        if ($session['user']['gold'] >= $cost) {
            $session['user']['gold'] -= $cost;
            set_module_pref("talks", 0);
            set_module_pref("speaking", 1);
            debuglog("spent {$cost} gold to scry a remote village");
            redirect("runmodule.php?module=scry&op=talk&area=" . htmlentities($area, ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "&village=" . htmlentities($village, ENT_COMPAT, getsetting("charset", "ISO-8859-1")));
            page_footer();
        } else {
            page_header("Gypsy Seer's tent");
            villagenav();
            addnav("Continue looking around", "gypsy.php");
            output("`5You offer the old gypsy woman your `^%s`5 gold for her scrying services, but she informs you that such a pittance is far too little.", $session['user']['gold']);
            page_footer();
        }
    } elseif ($op == "talk") {
        $times = get_module_setting("uses");
        if ($times && get_module_pref("talks") >= $times) {
            page_header("Gypsy Seer's tent");
            output("`5Looking around dazedly, it takes you a moment to realize that you are no longer viewing the village of %s and that the gypsy woman is staring at you with her hand out.", $village);
            output("`5\"`!I'll need more gold if you want to keep taking up space for my other paying customers!`5\", she demands.`n`n");
            output("You start to demand, \"`&What other customers?`5\" but decide that it's best not to annoy someone who has such power.");
            addnav(array("Scrying (%s gold)", $cost));
            addnav(array("Scry %s", $village), "runmodule.php?module=scry&op=pay&area=" . htmlentities($area, ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "&village=" . htmlentities($village, ENT_COMPAT, getsetting("charset", "ISO-8859-1")));
            addnav("Other");
            addnav("Return to the tent", "gypsy.php");
            villagenav();
            page_footer();
        } else {
            page_header("Peering in the bowl, you view %s", $village);
            output("`5While staring into the inky water, you are able to make out the people of %s:`n", $village);
            commentdisplay("", $area, "Project", 25, "projects");
            addnav("Look up from the bowl", "gypsy.php");
            page_footer();
        }
    }
}
<?php

// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the
// Free Software Foundation; either version 2 of the License, or (at your
// option) any later version.
//
// File: superuser.php
require_once "common.php";
isnewday(2);
addcommentary();
addnav("M?Return to the Mundane", "village.php");
if (!isset($_GET['op'])) {
    $_GET['op'] = '';
}
if ($_GET['op'] == "newsdelete") {
    $sql = "DELETE FROM news WHERE newsid='{$_GET['newsid']}'";
    db_query($sql);
    $return = $_GET['return'];
    $return = preg_replace("'[?&]c=[[:digit:]-]*'", "", $return);
    $return = substr($return, strrpos($return, "/") + 1);
    redirect($return);
}
if ($_GET['op'] == "commentdelete") {
    $sql = "DELETE FROM commentary WHERE commentid='{$_GET['commentid']}'";
    db_query($sql);
    $return = $_GET['return'];
    $return = preg_replace("'[?&]c=[[:digit:]-]*'", "", $return);
    $return = substr($return, strrpos($return, "/") + 1);
    if (strpos($return, "?") === false && strpos($return, "&") !== false) {
        $x = strpos($return, "&");
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();
}
function drpap_run()
{
    global $session;
    $c = get_module_pref("count");
    // if ($c){
    // if (is_module_active("medals")){
    // require_once "modules/medals.php";
    // medals_award_medal("sexchange","Gender Reassignment","This player switched their gender at Doc Paprika's office!","medal_museumquest.png");
    // }
    // }
    $t = get_module_setting("times");
    $gold = get_module_setting("gold");
    $gems = get_module_setting("gems");
    $op = httpget('op');
    $dec = httpget('dec');
    $gen = translate_inline($session['user']['sex'] == 0 ? "sir" : "madam");
    $ngen = translate_inline($session['user']['sex'] == 1 ? "sir" : "madam");
    $g = translate_inline($gems == 1 ? "Gem" : "Gems");
    page_header("Dr Paprika's Office");
    switch ($op) {
        case "enter":
            if ($c < $t) {
                output("`3Subtle tunes play in the background; classic rock.");
                output("In the Center of the waiting room, is a large table - covered with out-of-date magazines.");
                output("A beautiful receptionist looks at you, across a pane of glass.");
                output("She glances at you, and waves, \"`%Hello there %s.", $gen);
                output("Are you here to see `QDr Paprika`%?");
                output("He is the only doctor in %s, excelling in the field of `\$Gender Changes`%.`3\"", get_module_setting("paploc"));
                addnav("Where to?");
                addnav("Dr Paprika's Room", "runmodule.php?module=drpap&op=office");
                addnav("Waiting Room", "runmodule.php?module=drpap&op=waitroom");
            } else {
                output("`3\"`%I am sorry %s, but you have already had %s `\$Gender Changes`%.", $gen, $c);
                output("Since the limit is %s, we are able to deny you service now.", $t);
                output("Please take care.`3\"");
                if (get_module_setting("reset") == 1) {
                    output("`3The receptionist adds, \"`%If you come back with some `@dragon's blood`%, we might be able to work something out.`3\"");
                }
            }
            break;
        case "office":
            if ($dec != "yes") {
                if ($session['user']['gold'] >= $gold && $session['user']['gems'] >= $gems) {
                    output("`3You walk in a white room, very white.");
                    output("A long operating table, is accompanied by a small swivel chair.");
                    output("Strutting out from the shadows, `QDr Paprika `3appears, and shakes your hand.");
                    output("\"`\$So, you wish to have a `%Gender Change `\$operation?`3\"");
                    addnav("Choices");
                    addnav("Yes", "runmodule.php?module=drpap&op=office&dec=yes");
                    addnav("Return to the Waiting Room", "runmodule.php?module=drpap&op=waitroom");
                } else {
                    output("`QDr Paprika `3stares at your blankly.");
                    output("\"`\$I am sorry %s, but you do not have the proper funds for this operation.`3\"", $gen);
                    output("`QDr Paprika `3points to a sign, stating \"`%Gender Operations cost `^%s `%Gold and `5%s `%%s.`3\"", $gold, $gems, $g);
                }
            } else {
                output("`QDr Paprika `3nods and begins to prep himself.");
                output("\"`\$Please lay down on the operating table... I will be with your shortly...`3\"");
                output("`QDr Paprika `3hovers over you and then pulls out a tiny bottle of ether.");
                output("He presses it to your nose and instructs, \"`\$Please count to One Hundred...`3\"");
                output("You begin to count...`n`n");
                for ($i = 1; $i <= $session['user']['level']; $i++) {
                    output("%s...`n", $i);
                }
                if ($session['user']['sex'] == 0) {
                    $session['user']['sex'] = 1;
                } else {
                    $session['user']['sex'] = 0;
                }
                $c++;
                set_module_pref("count", $c);
                $session['user']['gold'] -= $gold;
                $session['user']['gems'] -= $gems;
                require_once "lib/titles.php";
                $newtitle = get_dk_title($session['user']['dragonkills'], $session['user']['sex']);
                require_once "lib/names.php";
                $newname = change_player_title($newtitle);
                $session['user']['title'] = $newtitle;
                $session['user']['name'] = $newname;
                output("`nYou awaken hours later, your muscles shuddering.");
                output("You grasp the mirror to your side, and then look at yourself.");
                output("Surprisingly, you are now a healthy looking %s.", $ngen);
                output("You stand quickly, and shake `QDr Paprika's `3hand, thanking him profusely.");
                output("Taking up your clothes, you strut out from the office, smiling happily.");
            }
            break;
        case "waitroom":
            output("`3All around you, people are sitting.");
            output("Some are thumbing through magazines, whilst others are tapping their feet in anticipation.`n`n");
            require_once "lib/commentary.php";
            addcommentary();
            viewcommentary("drpap", "Nervous People are Around", 15, "says");
            addnav("Return to Lobby", "runmodule.php?module=drpap&op=enter");
            break;
    }
    addnav("Leave");
    villagenav();
    page_footer();
}
function darkhorse_runevent($type, $link)
{
    global $session;
    $from = $link;
    $gameret = substr($link, 0, -1);
    $session['user']['specialinc'] = "module:darkhorse";
    require_once "lib/sanitize.php";
    $iname = get_module_setting("tavernname");
    rawoutput("<span style='color: #787878'>");
    output_notl("`c`b%s`b`c", $iname);
    $op = httpget('op');
    switch ($op) {
        case "":
        case "search":
            darkhorse_checkday();
            output("A cluster of trees nearby looks familiar...");
            output("You're sure you've seen this place before.");
            output("As you approach the grove, a strange mist creeps in around you; your mind begins to buzz, and you're no longer sure exactly how you got here.");
            if (darkhorse_tavernmount()) {
                require_once "lib/mountname.php";
                list($name, $lcname) = getmountname();
                output("%s`0 seems to have known the way, however.", $name);
            }
            output("`n`nThe mist clears, and before you is a log building with smoke trailing from its chimney.");
            output("A sign over the door says `7\"%s.\"`0", $iname);
            addnav("Enter the tavern", $from . "op=tavern");
            addnav("Leave this place", $from . "op=leaveleave");
            break;
        case "tavern":
            darkhorse_checkday();
            output("You stand near the entrance of the tavern and survey the scene before you.");
            output("Whereas most taverns are noisy and raucous, this one is quiet and nearly empty.");
            output("In the corner, an old man plays with some dice.");
            output("You notice that the tables have been etched on by previous adventurers who have found this place before, and behind the bar, a stick of an old man hobbles around, polishing glasses, as though there were anyone here to use them.");
            addnav("Talk to the old man", $from . "op=oldman");
            addnav("Talk to the bartender", $from . "op=bartender");
            // Special case here.  go and see if the comment area is blocked and
            // if so, don't put the link in.
            $args = modulehook("blockcommentarea", array("section" => "darkhorse"));
            if (!isset($args['block']) || $args['block'] != 'yes') {
                addnav("Examine the tables", $from . "op=tables");
            }
            addnav("Exit the tavern", $from . "op=leave");
            break;
        case "tables":
            require_once "lib/commentary.php";
            addcommentary();
            commentdisplay("You examine the etchings in the table:`n`n", "darkhorse", "Add your own etching:");
            addnav("Return to the Main Room", $from . "op=tavern");
            break;
        case "bartender":
            darkhorse_bartender($from);
            break;
        case "oldman":
            darkhorse_checkday();
            addnav("Old Man");
            modulehook("darkhorsegame", array("return" => $gameret));
            output("The old man looks up at you, his eyes sunken and hollow.");
            output("His red eyes make it seem that he may have been crying recently so you ask him what is bothering him.");
            if ($session['user']['sex'] == SEX_MALE) {
                output("\"`7Aah, I met an adventurer in the woods, and figured I'd play a little game with her, but she won and took almost all of my money.`0\"`n`n");
            } else {
                output("\"`7Aah, I met an adventurer in the woods, and figured I'd play a little game with him, but he won and took almost all of my money.`0\"`n`n");
            }
            $c = navcount();
            if ($c != 0) {
                output("`0\"`7Say... why not do an old man a favor and let me try to win some of it back from you?");
                if ($c > 1) {
                    output(" I can play several games!`0\"");
                } else {
                    output(" Shall we play a game?`0\"");
                }
            }
            $session['user']['specialmisc'] = "";
            addnav("Return to the Main Room", $from . "op=tavern");
            break;
        case "leave":
            output("You duck out of the tavern, and wander into the thick foliage around you.");
            output("That strange mist revisits you, making your mind buzz.");
            output("The mist clears, and you find yourself again where you were before the mist first covered you.");
            if (!darkhorse_tavernmount()) {
                output(" How exactly you got to the tavern is not exactly clear.");
            }
            $session['user']['specialinc'] = "";
            break;
        case "leaveleave":
            output("You decide that the tavern holds no appeal for you today.");
            $session['user']['specialinc'] = "";
            break;
    }
    rawoutput("</span>");
}
function pub_newpittsburgh_run()
{
    global $session;
    $td = gametimedetails();
    $gt = $td['secssofartoday'];
    //8400 seconds in a day
    //3600 seconds in an hour
    //midnight: 0
    //1am: 3600
    //2am: 7200
    //3am: 10800
    //4am: 14400
    //5am: 18000
    //6am: 21600
    //7am: 25200
    //8am: 28800
    //9am: 32400
    //10am: 36000
    //11am: 39600
    //12pm midday: 43200
    //1pm: 46800
    //2pm: 50400
    //3pm: 54000
    //4pm: 57600
    //5pm: 61200
    //6pm: 64800
    //7pm: 68400
    //8pm: 72000
    //9pm: 75600
    //10pm: 79200
    //11pm: 82800
    //11:59:59: 86399
    //midnight: 0
    page_header("Vigour Mortis");
    $op = httpget("op");
    switch ($op) {
        case "start":
            rawoutput("<table cellpadding=0 cellspacing=0><tr><td><img src='images/pubsigns/newpittsburgh.png' align='left'>");
            $phrases = array(1 => "From the corner, the pub quiz appears to have recently finished, and the quizmaster is reading out the answers - Question 1: Brains. Question 2: BRAINS!, Question 3: BRAAAAINS.", 2 => "George stares at the television, static reflected in his cold, dead eyes.", 3 => "George turns to the bar and takes stock of his inventory of pickled brainstuffs.");
            $chosenphrase = array_rand($phrases);
            output("You walk through a broken door and pick your way over shattered glass to a battered sideboard.  Around you, a number of congenial zombies shuffle in various directions, groaning and mumbling to one another.  The air is thick with the smell of rotting flesh and dust, and congealing blood stains many a tabletop.  A number of zombies cluster around a ridiculously small CRT television, which is displaying static.  The bartender, George, seems to be discussing the relative merits of brains with a local.`n`n");
            output_notl("%s`n`n", $phrases[$chosenphrase]);
            rawoutput("</td></tr></table>");
            require_once "lib/commentary.php";
            addcommentary();
            viewcommentary("pub_newpittsburgh");
            addnav("Talk to people");
            addnav("George", "runmodule.php?module=pub_newpittsburgh&op=bartender");
            modulehook("pub_newpittsburgh");
            break;
        case "continue":
            rawoutput("<table cellpadding=0 cellspacing=0><tr><td><img src='images/pubsigns/newpittsburgh.png' align='left'>");
            output("You rejoin your fellows at the cluttered tables.`n`n");
            rawoutput("</td></tr></table>");
            require_once "lib/commentary.php";
            addcommentary();
            viewcommentary("pub_newpittsburgh");
            addnav("Talk to people");
            addnav("George", "runmodule.php?module=pub_newpittsburgh&op=bartender");
            modulehook("pub_newpittsburgh");
            break;
        case "bartender":
            //add a text parser here at some point, I think...
            //maybe make this opening text time-dependent?
            $text = array();
            $text['hello'] = "George shambles over with a grimace.  \"`2Yes, mate.  What'll it be?`0\"`n`n";
            $drinks = array();
            $hook = array();
            $hook['drinks'] = $drinks;
            $hook['text'] = $text;
            $hook = modulehook("pub_newpittsburgh_bartender", $hook);
            $text = $hook['text'];
            //debug($hook);
            $drinks = $hook['drinks'];
            output_notl($text['hello']);
            foreach ($drinks as $key => $vals) {
                addnav("What'll it be?");
                if (!$vals['blockdrink']) {
                    if ($session['user']['gold'] >= $vals['price']) {
                        addnav(array("%s (%s Req)", $vals['verbosename'], $vals['price']), "runmodule.php?module=pub_newpittsburgh&op=drink&drink=" . $key);
                    } else {
                        addnav(array("%s (%s Req)", $vals['verbosename'], $vals['price']), "");
                    }
                }
            }
            if (!$hook['blockreturnnav']) {
                addnav("Never mind");
                addnav("Return to the lounge", "runmodule.php?module=pub_newpittsburgh&op=continue");
            }
            break;
        case "drink":
            $hook = array("drink" => httpget("drink"));
            $hook = modulehook("pub_newpittsburgh_drink", $hook);
            if (!$hook['blockbarnav']) {
                addnav("More!");
                addnav("Get George's attention again", "runmodule.php?module=pub_newpittsburgh&op=bartender");
            }
            if (!$hook['blockreturnnav']) {
                addnav("That's enough");
                addnav("Return to the lounge", "runmodule.php?module=pub_newpittsburgh&op=continue");
            }
            break;
    }
    addnav("Leave");
    addnav("Back to New Pittsburgh", "village.php");
    page_footer();
}
function wcgpoints_run()
{
    global $session;
    page_header("Cobblestone Cottage");
    $submit = translate_inline("Carry On");
    switch (httpget('op')) {
        case "enter":
            $uid_ok = get_module_pref("uidok");
            output("`4`bWARNING: Cobblestone Cottage is currently in BETA, and a little shaky.`b  Please don't send Petitions about this feature - use the chat area below, or the Enquirer.`0`n`n");
            if (get_module_pref("wcgid") && $uid_ok) {
                if (!get_module_pref("fail")) {
                    $points = wcgpoints_getpoints();
                    output("`0Jake greets you with a broad smile.  \"`@Welcome back, man.  You've got %s cobblestones waiting to spend.  Have fun!`0\"`n`n", number_format($points));
                    modulehook("wcg-features");
                } else {
                    //WCG ID present but not verified
                    debug("WCG ID not verified");
                    output("Jake greets you with a concerned look.  \"`@Man, I've been wondering where you've been.  I asked the Cosmos how many Cobblestones to give you, and it wouldn't answer.  Something about a messed-up Verification Code, whatever that means.`0\"`n`nIt looks like your Verification Code needs to be re-checked - you can find it via your Profile page on the World Community Grid website, and change our record of it via your Preferences in any Outpost.`n`n");
                    addnav("Let's do that, then", "runmodule.php?module=wcgpoints&op=verify");
                }
            } else {
                debug("No WCG ID entered");
                output("`0You head into a beautiful stone cottage.  A long-haired young man sits behind a desk at the entrance, idly smoking a cigarette.  As you catch his eye, he grins and rests his cigarette in an ashtray.  It smells kinda funny.`n`n\"`@Hey, man.  Welcome to Cobblestone Cottage!`0\"  He shakes your hand.  \"`@The name's Jake.  It doesn't look like you're hooked up yet.  Here, let me fix that for you, and you'll be rolling in cobblestones in no time.`0\"`n`n\"`#Cobblestones?`0\" you ask.`n`n\"`@Cobblestones, man, cobblestones!`0\" exclaims the hippy.  \"`@Whole new local currency - you saw the mess the banks made of the last one!  This stuff is as indie as it `igets`i, man.  You can only spend them in this very cottage.  Let's get you hooked up.`0\"`n`nHe sits down and pulls out a worn leather notebook and a purple-feathered quill pen.  \"`@What's your ID, my friend?`0\"`n`n");
                output("`J`bPinned to the slightly run-down fourth wall of the cottage is this message:`b`n`n`0The ID that the dirty hippy is asking for is your World Community Grid username.`n`n`bWhat's the story, daddy-o?`b`n`nYour computer can cure AIDS and cancer.`n`nNo, seriously.  It can also help provide us with cheap, environmentally-friendly electricity, sort out world hunger, and kick Dengue Fever in the nuts.  It can do a lot, really.  Most people hardly ever use the full capacity of their computer's CPU's.  You'll certainly have unused CPU cycles lying around while you're surfing the Internet or playing this game.  It'd be a terrible shame to waste those cycles.  Why not donate them to a worthy cause?`n`nScientists and humanitarian researchers need all the computing power they can get their hands on in order to analyse protein structures, chemical properties and other computationally-intensive stuff.  You can download a program that'll perform this life-saving research on your very own computer - and it'll run at a very low priority, so that when you do want to use your PC for something computationally intensive like playing a 3D game, your computer will be just as responsive.`n`nThe more CPU cycles you donate to humanitarian research, the more cobblestones Jake will give you.  These cobblestones can be used to play games or obtain other resources inside the Cottage.  See the list at the end of this page to see what you can do with your cobblestones, and check back as we come up with new features.`n`n`bThe nitty-gritty`b`n`nIn a nutshell, World Community Grid is a distributed computing network that performs humanitarian research using your computer's unused CPU cycles.  The project uses the BOINC networked computing client, which runs on Windows, Mac, Linux, FreeBSD and many other platforms, and doesn't affect the normal day-to-day performance of your computer.  When your computer's screensaver is active, the World Community Grid client will request instructions, process them, and send them back.  When your computer is in use, the client goes into Snooze mode and doesn't use any CPU cycles, so you'll likely not notice that the client is running.`n`nHumanitarian work performed by your computer for World Community Grid includes, but is not limited to:`nDeveloping drugs to combat cancer in children and adults;`nDeveloping antiviral medication for new influenza strains;`nCalculating the electronic properties of materials in order to find an organic compound that we can use to make dirt-cheap solar panels;`nDetermining the best options to create a new strain of rice that will provide maximum nutrition and thrive in a harsh environment;`nUncovering new drugs to combat dengue hemorrhagic fever, hepatitis C, West Nile encephalitis, and Yellow fever;`nIdentifying candidate drugs that have the right shape and chemical characteristics to block HIV protease;`nHuman proteome folding.`n`nFor more information or to join, search for World Community Grid in Wikipedia or your favourite search engine.`n`n`bHow World Community Grid interacts with Improbable Island`b`n`nAt each new game day, Jake will reward you with his entirely-made-up currency based on how many World Community Grid points you've accumulated since the previous game day.  More information on how WCG Points are calculated and rewarded can be found via a web search, or on the World Community Grid website.  You may install and run the BOINC client on more than one machine if you wish, under the same WCG username - this will result in more points and thus more cobblestones.`n`nWCG only updates their stats every 24 hours, and the work done by your computer must be verified first - so the XML file that Improbable Island reads to determine your cobblestone awards may be several days behind the actual work done by your computer.  To save undue stress on World Community Grid's servers, cobblestones are only awarded at each new Game Day.  If you joined World Community Grid today, it may be a day or two (or three!) before Jake gives you `iany`i cobblestones at all - however, if you allow your computer to run the BOINC client reasonably often, you should get more cobblestones every day after the first batch arrive.`n`nIf you've been a member of World Community Grid for some time, Jake will give you an initial bag of cobblestones corresponding to the total work done by your computer over the course of your entire WCG membership.  You'll be stinking rich!`n`n`bDISCLAIMER`b`nImprobable Island is not affiliated with or endorsed by IBM or World Community Grid.  In fact, I'd be surprised if they even knew about this.`n`n`bGETTING STARTED`b`nThere are three steps to the process - signing up at World Community Grid, installing the BOINC client, and associating your World Community Grid account with your Improbable Island username.`n`n`bSteps One and Two`b`nIf you're already signed up with World Community Grid, you can skip this bit.`n");
                rawoutput("Head over to <a href=\"http://www.worldcommunitygrid.org/reg/viewRegister.do?teamID=" . get_module_setting("teamid") . "\" target='new'>World Community Grid</a>, and follow the onscreen instructions to sign up, download and install the WCG BOINC client.");
                output("`n`n`bStep Three`b`nEnter your World Community Grid username and Verification Code into the boxes below.`n");
                rawoutput("<form action='runmodule.php?module=wcgpoints&op=verify' method='POST'>World Community Grid username: <input name='wcgid' value=\"\"><br />World Community Grid Verification Code: <input name='vcode' value=\"\"><br />Your verification code can be found on <a href=\"https://secure.worldcommunitygrid.org/ms/viewMyProfile.do\">this page</a>.  Copy-paste it into the box above, making sure you don't leave any tabs or spaces in there.<br /><input type='submit' class='button' value='{$submit}'></form>");
                addnav("", "runmodule.php?module=wcgpoints&op=verify");
                output("`bFeatures available in Cobblestone Cottage:`b`n`n");
                modulehook("wcg-features-desc");
            }
            require_once "lib/commentary.php";
            addcommentary();
            viewcommentary("wcgpoints", "Interject your own opinions about trying to get the damned thing working!", 25);
            addnav("Exit to Common Ground", "gardens.php");
            break;
        case "verify":
            //Player has entered a WCG ID
            //Check that it exists
            $id = httppost('wcgid');
            $vcode = httppost('vcode');
            $id = str_replace(" ", "+", $id);
            $source = "http://www.worldcommunitygrid.org/verifyMember.do?name=" . $id . "&code=" . $vcode;
            if ($xmlObj = simplexml_load_file($source)) {
                if (!$xmlObj->MemberStat && !$xmlObj->MemberStats->MemberStat) {
                    debug($xmlObj);
                    output("Jake scans his notebook and frowns.  \"`@You sure that's right, man?`0\"`n`n");
                    output("Something went wrong.  Please double-check the information you provided - remember that both usernames and verification codes are case-sensitive.`n`nHere's the error that World Community Grid passed back - it may or may not be useful:`n`4`b%s`b`0`nIf there is no error message above, then it's likely that World Community Grid is running its nightly stats update - in which case, try again in an hour or so.`n`n", $xmlObj);
                    rawoutput("<form action='runmodule.php?module=wcgpoints&op=verify' method='POST'>World Community Grid username: <input name='wcgid' value=\"\"><br />World Community Grid Verification Code: <input name='vcode' value=\"\"><br />Your verification code can be found on <a href=\"https://secure.worldcommunitygrid.org/ms/viewMyProfile.do\">this page</a>.  Copy-paste it into the box above, making sure you don't leave any tabs or spaces in there.<br /><input type='submit' class='button' value='{$submit}'></form>");
                    addnav("", "runmodule.php?module=wcgpoints&op=verify");
                } else {
                    //Check that the username isn't already taken
                    $sql = "SELECT acctid FROM " . db_prefix("accounts") . "";
                    $result = db_query($sql);
                    $idlo = strtolower($id);
                    for ($i = 0; $i < db_num_rows($result); $i++) {
                        $row = db_fetch_assoc($result);
                        $check = strtolower(get_module_pref("wcgid", "wcgpoints", $row['acctid']));
                        if ($check == $idlo) {
                            debug("Match found");
                            if (get_module_pref("wcgid-verified", "wcgpoints", $row['acctid'])) {
                                output("`bThat World Community Grid username has already been taken!`b`n`n");
                                $alreadyexists = 1;
                                rawoutput("<form action='runmodule.php?module=wcgpoints&op=verify1' method='POST'>World Community Grid username: <input name='wcgid' value=\"\"><br />World Community Grid Verification Code: <input name='vcode' value=\"\"><br />Your verification code can be found on <a href=\"https://secure.worldcommunitygrid.org/ms/viewMyProfile.do\">this page</a>.  Copy-paste it into the box above, making sure you don't leave any tabs or spaces in there.<br /><input type='submit' class='button' value='{$submit}'></form>");
                                addnav("", "runmodule.php?module=wcgpoints&op=verify");
                                break;
                            }
                        }
                    }
                    if (!$alreadyexists) {
                        set_module_pref("uidok", true);
                        set_module_pref("wcgid", $id);
                        set_module_pref("user_vcode", $vcode);
                        $points = $xmlObj->MemberStat->StatisticsTotals->Points;
                        if (!$points) {
                            $points = $xmlObj->MemberStats->MemberStat->StatisticsTotals->Points;
                        }
                        if (!$points) {
                            $points = $xmlObj->MemberStatsWithTeamHistory->MemberStats->MemberStat->StatisticsTotals->Points;
                        }
                        if (!$points) {
                            output("The hippy smiles.  \"`@Okay, you're all set.  Come back tomorrow and we'll sort you out with some cobblestones.`0\"`n`nYour account was verified successfully, but no points have been processed yet.  Points sometimes process a day or two late - check back and you'll get some cobblestones soon.`n`n");
                        } else {
                            set_module_pref("points", $points);
                            output("The hippy smiles.  \"`@Okay, you're all set.  Let's sort you out with some cobblestones...`0\"  He reaches underneath his desk and brings out a large bag.  \"`@Here you go, man.  %s cobblestones.  Have fun!`0\"`n`nThose should last you a while...`n`n", number_format($points));
                        }
                    }
                }
            } else {
                output("Whoops!  The XML file from World Community Grid couldn't be loaded.  This could be because World Community Grid is updating its point totals, in which case try again in an hour.  If it's still not working in a couple of hours, please Petition the admins to find out what went wrong.  Thanks!`n`n");
            }
            addnav("Exit to Common Ground", "gardens.php");
            break;
    }
    page_footer();
    return true;
}
function pub_kittania_run()
{
    global $session;
    $td = gametimedetails();
    $gt = $td['secssofartoday'];
    //8400 seconds in a day
    //3600 seconds in an hour
    //midnight: 0
    //1am: 3600
    //2am: 7200
    //3am: 10800
    //4am: 14400
    //5am: 18000
    //6am: 21600
    //7am: 25200
    //8am: 28800
    //9am: 32400
    //10am: 36000
    //11am: 39600
    //12pm midday: 43200
    //1pm: 46800
    //2pm: 50400
    //3pm: 54000
    //4pm: 57600
    //5pm: 61200
    //6pm: 64800
    //7pm: 68400
    //8pm: 72000
    //9pm: 75600
    //10pm: 79200
    //11pm: 82800
    //11:59:59: 86399
    //midnight: 0
    page_header("The Sunny Spot");
    $op = httpget("op");
    switch ($op) {
        case "start":
            rawoutput("<table cellpadding=0 cellspacing=0><tr><td><img src='images/pubsigns/kittania.png' align='left'>");
            $phrases = array(1 => "flirting cheerfully with one of her patrons as she draws a pint", 2 => "wearily giving directions to a confused Rookie", 3 => "gossiping idly about the latest chef in town");
            $chosenphrase = array_rand($phrases);
            output("You climb up a short ladder and emerge into the largest treehouse you've ever seen.  Large branches are visible through the transluscent net drape of the ceiling.  A few kittymorphs chat and consume drinks while lounging in some of the many inviting hammocks, while others share a meal on reclining couches.  Large soft pillows are scattered about the floor around trays full of drink and smokeables.   The landlady Miu-Miu is a tawny, middle-aged kittymorph.  Right now she's %s.`n`nThe soft murmur of conversation is punctuated by laughter, and the smell of strange incense hangs in the air, mingling with the fresh green scent of the tree itself.`n`n", $phrases[$chosenphrase]);
            rawoutput("</td></tr></table>");
            require_once "lib/commentary.php";
            addcommentary();
            viewcommentary("pub_kittania");
            addnav("Talk to people");
            addnav("Miu-Miu", "runmodule.php?module=pub_kittania&op=bartender");
            modulehook("pub_kittania");
            break;
        case "continue":
            rawoutput("<table cellpadding=0 cellspacing=0><tr><td><img src='images/pubsigns/kittania.png' align='left'>");
            output("You rejoin your fellows in the open space.`n`n");
            rawoutput("</td></tr></table>");
            require_once "lib/commentary.php";
            addcommentary();
            viewcommentary("pub_kittania");
            addnav("Talk to people");
            addnav("Miu-Miu", "runmodule.php?module=pub_kittania&op=bartender");
            modulehook("pub_kittania");
            break;
        case "bartender":
            //add a text parser here at some point, I think...
            //maybe make this opening text time-dependent?
            $text = array();
            $text['hello'] = "Miu-Miu shows you a slightly tired smile.  \"`2Yes love, what'll you have?`0\"`n`n";
            $drinks = array();
            $hook = array();
            $hook['drinks'] = $drinks;
            $hook['text'] = $text;
            $hook = modulehook("pub_kittania_bartender", $hook);
            $text = $hook['text'];
            //debug($hook);
            $drinks = $hook['drinks'];
            output_notl($text['hello']);
            foreach ($drinks as $key => $vals) {
                addnav("What'll it be?");
                if (!$vals['blockdrink']) {
                    if ($session['user']['gold'] >= $vals['price']) {
                        addnav(array("%s (%s Req)", $vals['verbosename'], $vals['price']), "runmodule.php?module=pub_kittania&op=drink&drink=" . $key);
                    } else {
                        addnav(array("%s (%s Req)", $vals['verbosename'], $vals['price']), "");
                    }
                }
            }
            if (!$hook['blockreturnnav']) {
                addnav("Never mind");
                addnav("Return to the lounge", "runmodule.php?module=pub_kittania&op=continue");
            }
            break;
        case "drink":
            $hook = array("drink" => httpget("drink"));
            $hook = modulehook("pub_kittania_drink", $hook);
            if (!$hook['blockbarnav']) {
                addnav("More!");
                addnav("Get Miu-Miu's attention again", "runmodule.php?module=pub_kittania&op=bartender");
            }
            if (!$hook['blockreturnnav']) {
                addnav("That's enough");
                addnav("Return to the lounge", "runmodule.php?module=pub_kittania&op=continue");
            }
            break;
    }
    addnav("Leave");
    addnav("Back to Kittania", "village.php");
    page_footer();
}
function rail_ironhorse_run()
{
    global $session;
    $op = httpget("op");
    $fromhid = httpget("hid");
    $fromrid = httpget("rid");
    $locs = rail_ironhorse_getlocs();
    switch ($op) {
        case "board":
            page_header("On the Train!");
            // Conductor walks through the train here
            if (rail_hascard("railpass_active") || rail_hascard("railpassfirst_active")) {
                // they already have a punched ticket - they're fine
                if (e_rand(1, 20) == 1) {
                    output("`2The `@Conductor `2lurches through the train again, examining passes, taking bribes, exchanging familiar nods with the regular riders.`0`n`n");
                }
            } else {
                if (rail_hascard("railpass") && rail_hascard("railpassfirst")) {
                    // they have both - we have to ask them which they want to use
                    output("`0The `@Conductor `0examines your passes. \"`2Why, you seem to have both regular and first class passes here. Which would you prefer to use today?`0\"`n`n");
                    addnav("Which pass will you use?");
                    addnav("Just the regular today, thanks", "runmodule.php?module=rail_ironhorse&op=choose&hid={$fromhid}&rid={$fromrid}&pass=reg");
                    addnav("It's first class for me, baby", "runmodule.php?module=rail_ironhorse&op=choose&hid={$fromhid}&rid={$fromrid}&pass=first");
                    page_footer();
                    break;
                } else {
                    // they have one or the other but not both - we can punch automatically
                    if (rail_hascard("railpass")) {
                        // they have a regular pass
                        output("`2The `@Conductor `2peers myopically at your Rail Pass and fumbles with a ticket punch. Ka-`btchik`b! Now you're free to ride the train as much as you want for the rest of the day!`0`n`n");
                        rail_ironhorse_activatepass("railpass");
                    } else {
                        // they have a first class pass
                        output("`2The `@Conductor `2inspects your First Class Rail Pass and deferentially produces a ticket punch. Ka-`btchik`b! Now you can ride `ifirst class`i for the rest of the day! Awesome!`0`n`n");
                        rail_ironhorse_activatepass("railpassfirst");
                    }
                }
            }
            $hookargs = array("hid" => $fromhid, "rid" => $fromrid);
            modulehook("ironhorse-onboard", $hookargs);
            set_module_pref("hasridden", 1);
            output("`2The wheels clatter, the car shakes with the astounding speed. Why, you must be going a good twenty-five miles an hour!`0`n`n");
            addnav("Get off!");
            foreach ($locs as $loc => $locarray) {
                if ($loc == "WA" || $loc == "DB") {
                } else {
                    if ($locarray[0] == $fromhid) {
                        addnav(array("`2Back to %s: `0%s", $loc, $locarray[2]), "runmodule.php?module=rail_ironhorse&op=leave&hid={$fromhid}&rid={$fromrid}&loc={$loc}");
                    } else {
                        addnav(array("`2%s: `0%s", $loc, $locarray[2]), "runmodule.php?module=rail_ironhorse&op=leave&hid={$fromhid}&rid={$fromrid}&loc={$loc}");
                    }
                }
            }
            if (rail_hascard("railpassfirst_active")) {
                addnav("First Class");
                addnav("Request Stop", "runmodule.php?module=rail_ironhorse&op=request&hid={$fromhid}&rid=fromrid");
            }
            addcommentary();
            viewcommentary("Riding the Train", "Shout over the engine's thunder:");
            page_footer();
            break;
        case "leave":
            page_header("You have reached your destination!");
            rail_ironhorse_cleanup($fromhid);
            switch (e_rand(1, 200)) {
                // where are we leaving to?
                case 1:
                    $loc = "WA";
                    break;
                case 2:
                    $loc = "DB";
                    break;
                default:
                    $loc = httpget("loc");
                    break;
            }
            $tohid = $locs[$loc][0];
            $torid = $locs[$loc][1];
            $house = improbablehousing_gethousedata($locs[$loc][0]);
            $tohousename = $house['data']['name'];
            set_module_pref("worldXYZ", $house['location'], "worldmapen");
            set_module_pref("lastCity", $locs[$loc][3], "worldmapen");
            $session['user']['location'] = "House: " . $tohousename . ", Room " . $torid . "";
            output("`0The `@Conductor `0smiles toothily as you prepare to disembark. \"`2Thank-you for travelling with the `bImprobable Island Railway Company`b. Please don't forget to take all your luggage with you, and have an improbable day!`0\"`n`n");
            output("`2%s`0`n`n", $locs[$loc][4]);
            addnav("Get off the train");
            addnav(array("`2%s`0 Platform", $locs[$loc][2]), "runmodule.php?module=improbablehousing&op=interior&hid={$tohid}&rid={$torid}");
            if (!($loc == "WA") && !($loc == "DB")) {
                addnav("Wait, I've changed my mind");
                addnav("`2Stay `0 on board", "runmodule.php?module=rail_ironhorse&op=board&hid={$tohid}&rid={$torid}");
            } else {
                output("`2You feel stronger after your pleasant train ride, and rather refreshed!`n`n`0");
                if ($session['user']['hitpoints'] < $session['user']['maxhitpoints']) {
                    $session['user']['hitpoints'] = $session['user']['maxhitpoints'];
                } else {
                    $session['user']['hitpoints'] = $session['user']['hitpoints'] * 1.1;
                    require_once "modules/staminasystem/lib/lib.php";
                    addstamina(25000);
                }
            }
            page_footer();
            break;
        case "request":
            page_header("First Class has its privileges!");
            output("`2As holder of an Improbable Island Railway Company `bFirst Class`b Rail Pass, you have the privilege of asking the train to let you off anywhere on the map. Yes, even in the deepest ocean, should that be your whim! This is, after all, an `iImprobable`i railway system; it can accomplish the seemingly impossible.`n`nSimply tell the `@Conductor `2where on the Island you would like to be dropped off.`0`n`n");
            rawoutput("<form action='runmodule.php?module=rail_ironhorse&op=requestfinish&hid=" . $fromhid . "&rid=" . $fromrid . "' method='POST'>");
            // Note: Width 2 means a 2-digit number. Set the default location to 13,11 Improbable Central.
            rawoutput("X = <input name='stopX' width='2' value='13'> , Y = <input name='stopY' width='2' value='11'><br/><br/>");
            rawoutput("<input type='submit' class='button' value='" . translate_inline("Stop here!") . "'>");
            rawoutput("</form>");
            addnav("", "runmodule.php?module=rail_ironhorse&op=requestfinish&hid={$fromhid}&rid={$fromrid}");
            addnav("Wait, I've changed my mind");
            addnav("`2Stay `0 on board", "runmodule.php?module=rail_ironhorse&op=board&hid={$fromhid}&rid={$fromrid}");
            page_footer();
            break;
        case "requestfinish":
            page_header("First Class has its privileges!");
            $x = httppost("stopX");
            $y = httppost("stopY");
            // strip out any non-numeric characters that got entered by mistake
            $x = ereg_replace("[^0-9]", "", $x);
            $y = ereg_replace("[^0-9]", "", $y);
            // make sure they entered values that are in range for the size of the map.
            $sizeX = get_module_setting("worldmapsizeX", "worldmapen");
            $sizeY = get_module_setting("worldmapsizeY", "worldmapen");
            if ($x <= 0 || $x > $sizeX || $y <= 0 || $y > $sizeY) {
                output("`2Sorry mate, stay on the map. Train service doesn't run outside the Improbability bubble. Nice try though.`0");
                addnav("Oops!");
                addnav("Let's try that again", "runmodule.php?module=rail_ironhorse&op=request&hid={$fromhid}&rid={$fromrid}");
            } else {
                output("`0The `@Conductor `0smiles, all sleek and fangsome, as you prepare to disembark. \"`2Thank-you for travelling with the `bImprobable Island Railway Company`b. Please don't forget to take all your luggage with you, and have an improbable day!`0\"`n`n");
                rail_ironhorse_cleanup($fromhid);
                $maploc = $x . "," . $y . ",1";
                set_module_pref("worldXYZ", $maploc, "worldmapen");
                addnav("Thanks!");
                addnav("`2Leave `0 the train", "runmodule.php?module=worldmapen&op=continue");
            }
            page_footer();
            break;
        case "choose":
            $pass = httpget("pass");
            if ($pass == "first") {
                rail_ironhorse_activatepass("railpassfirst");
            } else {
                rail_ironhorse_activatepass("railpass");
            }
            addnav("", "runmodule.php?module=rail_ironhorse&op=board&hid={$fromhid}&rid={$fromrid}");
            redirect("runmodule.php?module=rail_ironhorse&op=board&hid={$fromhid}&rid={$fromrid}");
            break;
        case "stationmaster":
            page_header("The Stationmaster");
            $val = rail_collector_valuehand();
            // note, we only get here if there's a joker in the hand, so only first class passes
            if ($val['value'] > 2) {
                $phrase = "that's quite a hand you have there. Quite a hand! I think in this case we could even stretch to `b" . $val['value'] . "`b First Class Rail Passes.";
            } else {
                if ($val['value'] > 1) {
                    $phrase = "excellent. For that hand, we could easily give you `btwo`b First Class Rail Passes.";
                } else {
                    $phrase = "no question about it, definitely a `bFirst Class Rail Pass`b.";
                }
            }
            output("`2Having heard that this eccentric railroad company will sometimes give out a rail pass in exchange for used playing cards, you show the Stationmaster your grubby little collection. \"`#Interested?`2\" you ask.`n`n\"`^Why yes. Those would be worth... let me see. Oh, %s`2\"`0`n`n", $phrase);
            addnav("What do you say?");
            addnav("It's a deal!", "runmodule.php?module=rail_ironhorse&op=stationmasterdeal&hid={$fromhid}&rid={$fromrid}");
            addnav("No thanks, I'll wait", "runmodule.php?module=improbablehousing&op=interior&hid={$fromhid}&rid={$fromrid}");
            page_footer();
            break;
        case "stationmasterdeal":
            page_header("The Stationmaster");
            $val = rail_collector_valuehand();
            for ($i = 0; $i < $val['value']; $i++) {
                give_item("railpassfirst");
            }
            $qty = rail_collector_emptyhand();
            output("`2The Stationmaster thanks you, and the two of you make the exchange to your mutual satisfaction. What on earth the Company `iwants`i with all those old playing cards... well. You've naturally wondered about that from time to time, but they're not saying.`0`n`n");
            addnav("Leave");
            addnav("Return to the platform", "runmodule.php?module=improbablehousing&op=interior&hid={$fromhid}&rid={$fromrid}");
            page_footer();
            break;
    }
}
function pub_squathole_run()
{
    global $session;
    $td = gametimedetails();
    $gt = $td['secssofartoday'];
    //8400 seconds in a day
    //3600 seconds in an hour
    //midnight: 0
    //1am: 3600
    //2am: 7200
    //3am: 10800
    //4am: 14400
    //5am: 18000
    //6am: 21600
    //7am: 25200
    //8am: 28800
    //9am: 32400
    //10am: 36000
    //11am: 39600
    //12pm midday: 43200
    //1pm: 46800
    //2pm: 50400
    //3pm: 54000
    //4pm: 57600
    //5pm: 61200
    //6pm: 64800
    //7pm: 68400
    //8pm: 72000
    //9pm: 75600
    //10pm: 79200
    //11pm: 82800
    //11:59:59: 86399
    //midnight: 0
    page_header("Booz");
    $op = httpget("op");
    switch ($op) {
        case "start":
            rawoutput("<table cellpadding=0 cellspacing=0><tr><td><img src='images/pubsigns/squathole_1.png' align='left'>");
            $phrases = array(1 => "A number of Midgets stand around drinking pints of Wanker, and holding what sounds like a dirty limerick contest.  None of them are quite clever enough to know what a limerick is, but they're giving it their best shot.", 2 => "A small knot of Midgets are brawling on the top of a table, spilling beer and foul secretions everywhere. It looks like they've been at it for awhile, and the pub is starting to show the damage.  The ratty blue tarp above the grouping is letting in the elements, which doesn't deter any of the fighting throng.  Bottles, mugs and fists are brandished, and one particularly angry Midget has torn off bits of a table and looks disappointed that there's no chandelier for him to swing from.", 3 => "You think the sign once read 'Mourners of Life Poetry Club,' but that surely can't be right.");
            $chosenphrase = array_rand($phrases);
            output("`0Booz, the Squat Hole pub, is basically a series of drooping tarpaulins, unsteadily propped up with branches and a few stakes.  Its mostly knee-high patrons sit on empty beer kegs, resting their drinks or their feet on other kegs.  The stench of armpit and stale beer hangs in the air.  Someone has propped a few rotting boards on top of more kegs - this is the bar.  A tiny woman scampers back and forth across it, doling out alcohol to patrons who are temporarily still upright.  Her name is Chlamydia.  You know, like the flower.`n`n%s`n`n", $phrases[$chosenphrase]);
            rawoutput("</td></tr></table>");
            require_once "lib/commentary.php";
            addcommentary();
            viewcommentary("pub_squathole");
            addnav("Talk to people");
            addnav("Chlamydia", "runmodule.php?module=pub_squathole&op=bartender");
            modulehook("pub_squathole");
            break;
        case "continue":
            rawoutput("<table cellpadding=0 cellspacing=0><tr><td><img src='images/pubsigns/squathole_1.png' align='left'>");
            output("You head back into the main section of the pub, ducking under flappy bits of tarpaulin.`n`n");
            rawoutput("</td></tr></table>");
            require_once "lib/commentary.php";
            addcommentary();
            viewcommentary("pub_squathole");
            addnav("Talk to people");
            addnav("Chlamydia", "runmodule.php?module=pub_squathole&op=bartender");
            modulehook("pub_squathole");
            break;
        case "bartender":
            //add a text parser here at some point, I think...
            //maybe make this opening text time-dependent?
            $text = array();
            $text['hello'] = "Chlamydia shows you a smile and squeaks at you.  \"`2Yes luv, wha' c'n I gitcha?`0\"`n`n";
            $drinks = array();
            $hook = array();
            $hook['drinks'] = $drinks;
            $hook['text'] = $text;
            $hook = modulehook("pub_squathole_bartender", $hook);
            $text = $hook['text'];
            //debug($hook);
            $drinks = $hook['drinks'];
            output_notl($text['hello']);
            foreach ($drinks as $key => $vals) {
                addnav("Wha' indeed?");
                if (!$vals['blockdrink']) {
                    if ($session['user']['gold'] >= $vals['price']) {
                        addnav(array("%s (%s Req)", $vals['verbosename'], $vals['price']), "runmodule.php?module=pub_squathole&op=drink&drink=" . $key);
                    } else {
                        addnav(array("%s (%s Req)", $vals['verbosename'], $vals['price']), "");
                    }
                }
            }
            if (!$hook['blockreturnnav']) {
                addnav("Never mind");
                addnav("Return to the lounge", "runmodule.php?module=pub_squathole&op=continue");
            }
            break;
        case "drink":
            $hook = array("drink" => httpget("drink"));
            $hook = modulehook("pub_squathole_drink", $hook);
            if (!$hook['blockbarnav']) {
                addnav("More!");
                addnav("Get Chlamydia's attention again", "runmodule.php?module=pub_squathole&op=bartender");
            }
            if (!$hook['blockreturnnav']) {
                addnav("That's enough");
                addnav("Return to the lounge", "runmodule.php?module=pub_squathole&op=continue");
            }
            break;
    }
    addnav("Leave");
    addnav("Back to Squat Hole", "village.php");
    page_footer();
}
function claneditor_run()
{
    global $session;
    tlschema("claneditor");
    $dt = httpget("dt");
    $op = httpget('op');
    if ($dt != "") {
        $sql = "SELECT * FROM " . db_prefix("clans") . " WHERE clanid='{$dt}'";
        $result = db_query($sql);
        $claninfo = db_fetch_assoc($result);
        if (db_num_rows($result) == 0) {
            $op = "";
        }
    }
    addcommentary();
    $ranks = array(CLAN_APPLICANT => "`!Applicant`0", CLAN_MEMBER => "`#Member`0", CLAN_OFFICER => "`^Officer`0", CLAN_LEADER => "`&Leader`0", CLAN_FOUNDER => "`\$Founder");
    $args = modulehook("clanranks", array("ranks" => $ranks, "clanid" => $dt));
    $ranks = translate_inline($args['ranks'], "clan");
    superusernav();
    addnav("Clans");
    addnav("List Clans", "runmodule.php?module=claneditor&op=list");
    addnav("Create a New Clan", "runmodule.php?module=claneditor&op=new");
    if ($op == "" || $op == "list") {
        page_header("Clan Listing");
        rawoutput("<table border='0' padding='0'><tr><td>");
        $sql = "SELECT MAX(" . db_prefix("clans") . ".clanid) AS clanid, MAX(clanname) AS clanname,count(" . db_prefix("accounts") . ".acctid) AS c FROM " . db_prefix("clans") . " LEFT JOIN " . db_prefix("accounts") . " ON " . db_prefix("clans") . ".clanid=" . db_prefix("accounts") . ".clanid AND clanrank>" . CLAN_APPLICANT . " GROUP BY " . db_prefix("clans") . ".clanid ORDER BY c DESC";
        $result = db_query($sql);
        if (db_num_rows($result) > 0) {
            output("`%Karissa`7 steps in as if by magic, listing the clans for you.`n");
            output("`@`bList of Clans:`b`0`n`n");
            $v = 0;
            $memb_n = translate_inline("(%s members)");
            $memb_1 = translate_inline("(%s member)");
            rawoutput('<table cellspacing="0" cellpadding="2" align="left">');
            output_notl("<tr class='trhead'><td>%s</td><td>%s</td></tr>", translate_inline("`b`&Name of Clan`b"), translate_inline("`&`iNumber of Members`i"), true);
            for ($i = 0; $i < db_num_rows($result); $i++) {
                $row = db_fetch_assoc($result);
                if ($row['c'] == 0) {
                    $sql = "DELETE FROM " . db_prefix("clans") . " WHERE clanid={$row['clanid']}";
                    db_query($sql);
                } else {
                    rawoutput('<tr class="' . ($v % 2 ? "trlight" : "trdark") . '"><td>', true);
                    if ($row['c'] == 1) {
                        $memb = sprintf($memb_1, $row['c']);
                    } else {
                        $memb = sprintf($memb_n, $row['c']);
                    }
                    output_notl("&#149; <a href='runmodule.php?module=claneditor&op=mview&dt=%s'>%s</a></td><td>%s`n", $row['clanid'], full_sanitize(htmlentities($row['clanname']), ENT_COMPAT, getsetting("charset", "ISO-8859-1")), $memb, true);
                    rawoutput('</td></tr>');
                    addnav("", "runmodule.php?module=claneditor&op=mview&dt={$row['clanid']}");
                    $v++;
                }
            }
            rawoutput("</table>", true);
        } else {
            output("`7There are no clans in the database.`n`c");
        }
        rawoutput("</td></tr><tr><td>");
        output_notl("<br>[<a href='runmodule.php?module=claneditor&op=new'>%s</a>]", translate_inline("Create a New Clan"), true);
        addnav("", "runmodule.php?module=claneditor&op=new");
        rawoutput("</td></tr></table>");
        page_footer();
    } elseif ($op == "new") {
        page_header("Clan Creation");
        $apply = httpget('apply');
        if ($apply == 1) {
            $id = httpget("id");
            $ocn = httppost('clanname');
            $ocs = httppost('clanshort');
            $clanname = stripslashes($ocn);
            $clanname = full_sanitize($clanname);
            $clanname = preg_replace("'[^[:alpha:] \\'-]'", "", $clanname);
            $clanname = addslashes($clanname);
            httppostset('clanname', $clanname);
            $clanshort = full_sanitize($ocs);
            $clanshort = preg_replace("'[^[:alpha:]]'", "", $clanshort);
            httppostset('clanshort', $clanshort);
            $sql = "SELECT * FROM " . db_prefix("clans") . " WHERE clanname='{$clanname}'";
            $result = db_query($sql);
            $e = translate_inline("`%Karissa`7 hands you a form to start a clan.");
            $e1 = translate_inline("`%Karissa`7 looks over your form but informs you that your clan name must consist only of letters, spaces, apostrophes, or dashes.  Also, your short name can consist only of letters. She hands you a blank form.");
            $e2 = translate_inline("`%Karissa`7 looks over your form but informs you that you must have at least 5 and no more than 50 characters in your clan's name (and they must consist only of letters, spaces, apostrophes, or dashes), then hands you a blank form.");
            $e3 = translate_inline("`%Karissa`7 looks over your form but informs you that you must have at least 2 and no more than 5 characters in your clan's short name (and they must all be letters), then hands you a blank form.");
            $e4 = translate_inline("`%Karissa`7 looks over your form but informs you that the clan name %s is already taken, and hands you a blank form.");
            $e5 = translate_inline("`%Karissa`7 looks over your form but informs you that the short name %s is already taken, and hands you a blank form.");
            if ($ocs == "" && $ocn == "" && !httppostisset('clanname') && !httppostisset('clanshort')) {
                output_notl($e);
                clanform();
            } elseif ($clanname != $ocn || $clanshort != $ocs) {
                output_notl($e1);
                clanform();
            } elseif (strlen($clanname) < 5 || strlen($clanname) > 50) {
                output_notl($e2);
                clanform();
            } elseif (strlen($clanshort) < 2 || strlen($clanshort) > 5) {
                output_notl($e3);
                clanform();
            } elseif (db_num_rows($result) > 0) {
                output_notl($e4, stripslashes($clanname));
                clanform();
            } else {
                $sql = "SELECT * FROM " . db_prefix("clans") . " WHERE clanshort='{$clanshort}'";
                $result = db_query($sql);
                if (db_num_rows($result) > 0) {
                    output_notl($e5, stripslashes($clanshort));
                    clanform();
                } else {
                    $sql = "INSERT INTO " . db_prefix("clans") . " (clanname,clanshort) VALUES ('{$clanname}','{$clanshort}')";
                    db_query($sql);
                    $clid = db_insert_id();
                    $sql = "UPDATE " . db_prefix("accounts") . " SET clanid='{$clid}',clanrank='" . CLAN_LEADER . "' WHERE acctid='{$id}'";
                    db_query($sql);
                    $subj = "New Clan!";
                    $msg = array("%s`0`^ has made you a new clan!", $session['user']['name']);
                    systemmail($id, $subj, $msg);
                    output("`%Karissa`7 looks over your form, and finding that everything seems to be in order, she takes your fees, stamps the form \"`\$APPROVED`7\" and files it in a drawer.`n`n");
                    output("Congratulations, you've created a new clan named %s!", stripslashes($clanname));
                }
            }
        } elseif ($apply == 0) {
            clanuserform();
        } else {
            output("`7You teleport to the Clan Hall...");
            output("`7You approach `%Karissa`7 and mention that you would like to start a new clan.");
            output("She tells you that there are three requirements to starting a clan.");
            output("First, you have to decide on a full name for your clan.");
            output("Second, you have to decide on an abbreviation for your clan.");
            output("Third you have to decide on the person that should run the clan.");
            $e = translate_inline("`n`n\"`5If you're ok with these three requirements, please fill out the following form,`7\" she says, handing you a sheet of paper.");
            output_notl($e);
            clanuserform();
        }
    } else {
        if ($op != "deleteclan") {
            page_header("The Clan of %s", full_sanitize($claninfo['clanname']));
            output("`n`c`^`bThe Clan of %s`b`c`n`n", full_sanitize($claninfo['clanname']));
        } else {
            page_header("Clan Deletion");
        }
        if ($op == "mview") {
            $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid={$claninfo['motdauthor']}";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            $motdauthname = $row['name'];
            $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid={$claninfo['descauthor']}";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            $descauthname = $row['name'];
            output("`&`bCurrent MoTD:`b `#by %s`2`n", $motdauthname);
            output_notl(nltoappon($claninfo['clanmotd']) . "`n`n");
            commentdisplay("", "clan-{$claninfo['clanid']}", "Speak into their Clan", 25, "projects");
            output_notl("`n`n");
            modulehook("collapse{", array("name" => "collapsedesc"));
            output("`&`bCurrent Description:`b `#by %s`2`n", $descauthname);
            output_notl(nltoappon($claninfo['clandesc']) . "`n");
            modulehook("}collapse");
            $sql = "SELECT count(*) AS c, clanrank FROM " . db_prefix("accounts") . " WHERE clanid={$claninfo['clanid']} GROUP BY clanrank DESC";
            $result = db_query($sql);
            // begin collapse
            modulehook("collapse{", array("name" => "clanmemberdet"));
            output("`n`bMembership Details:`b`n");
            $leaders = 0;
            while ($row = db_fetch_assoc($result)) {
                output_notl($ranks[$row['clanrank']] . ": " . $row['c'] . "`n");
                if ($row['clanrank'] >= CLAN_OFFICER) {
                    $leaders += $row['c'];
                }
            }
            output("`n");
            $noleader = translate_inline("`^There is currently no leader!  Promoting %s`^ to leader as they are the highest ranking member (or oldest member in the event of a tie).`n`n");
            if ($leaders == 0) {
                //There's no leader here, probably because the leader's account
                //expired.
                $sql = "SELECT name,acctid,clanrank FROM " . db_prefix("accounts") . " WHERE clanid={$dt} ORDER BY clanrank DESC, clanjoindate";
                $result = db_query($sql);
                $row = db_fetch_assoc($result);
                $sql = "UPDATE " . db_prefix("accounts") . " SET clanrank=" . CLAN_LEADER . " WHERE acctid='" . $row['acctid'] . "'";
                db_query($sql);
                output_notl($noleader, $row['name']);
            }
            // end collapse
            modulehook("}collapse");
        } elseif ($op == "deleteclan") {
            if (httpget("sop") == "yes") {
                //notify users of the deletion of the clan
                $sql = "SELECT acctid FROM " . db_prefix("accounts") . " WHERE clanid={$dt}";
                $result = db_query($sql);
                $subj = array("Deletion of %s", $claninfo['clanname']);
                $msg = array("The clan you were in, %s, has closed its doors.\nSorry for any inconvenience.", $claninfo['clanname']);
                while ($row = db_fetch_assoc($result)) {
                    systemmail($row['acctid'], $subj, $msg);
                }
                //change the clan if a user is in this clan
                $sql = "UPDATE " . db_prefix("accounts") . " SET clanid=0,clanrank=" . CLAN_APPLICANT . ",clanjoindate='0000-00-00 00:00:00' WHERE clanid={$dt}";
                db_query($sql);
                //change the current users clan if this user was in that clan
                if ($session['user']['clanid'] == $dt) {
                    $session['user']['clanid'] = 0;
                    $session['user']['clanrank'] = CLAN_APPLICANT;
                    $session['user']['clanjoindate'] = '0000-00-00 00:00:00';
                }
                //drop the clan.
                $sql = "DELETE FROM " . db_prefix("clans") . " WHERE clanid={$dt}";
                db_query($sql);
                module_delete_objprefs('clans', $dt);
                $op = "";
                httpset("op", "");
                unset($claninfo);
                $dt = "";
                output("That clan has been wiped.`n");
                output("`@Users within the clan have been notified.");
            } else {
                output("`%`c`bAre you SURE you want to delete this clan?`b`c`n");
                $dc = translate_inline("Delete this clan? Are you sure!");
                rawoutput("[<a href='runmodule.php?module=claneditor&op=deleteclan&sop=yes&dt={$dt}' onClick='return confirm(\"{$dc}\");'>{$dc}</a>]");
                addnav("", "runmodule.php?module=claneditor&op=deleteclan&sop=yes&dt={$dt}");
            }
        } elseif ($op == "editmodule" || $op == "editmodulesave") {
            $mdule = httpget("mdule");
            if ($op == "editmodulesave") {
                // Save module prefs
                $post = httpallpost();
                reset($post);
                while (list($key, $val) = each($post)) {
                    set_module_objpref("clans", $dt, $key, $val, $mdule);
                }
                output("`^Saved!`0`n");
            }
            rawoutput("<form action='runmodule.php?module=claneditor&op=editmodulesave&dt={$dt}&mdule={$mdule}' method='POST'>");
            module_objpref_edit("clans", $mdule, $dt);
            rawoutput("</form>");
            addnav("", "runmodule.php?module=claneditor&op=editmodulesave&dt={$dt}&mdule={$mdule}");
        } elseif ($op == "updinfo") {
            page_header("Update Clan Information");
            $clanmotd = substr(httppost('clanmotd'), 0, 4096);
            if (httppostisset('clanmotd') && $clanmotd != $claninfo['clanmotd']) {
                if ($clanmotd == "") {
                    $mauthor = 0;
                } else {
                    $mauthor = $session['user']['acctid'];
                }
                $sql = "UPDATE " . db_prefix("clans") . " SET clanmotd='{$clanmotd}',motdauthor={$mauthor} WHERE clanid={$claninfo['clanid']}";
                db_query($sql);
                invalidatedatacache("clandata-{$claninfo['clanid']}");
                $claninfo['clanmotd'] = stripslashes($clanmotd);
                output("Updating MoTD`n");
                $claninfo['motdauthor'] = $mauthor;
            }
            $clandesc = httppost('clandesc');
            if (httppostisset('clandesc') && $clandesc != $claninfo['clandesc']) {
                if ($clandesc == "") {
                    $claninfo['descauthor'] = 0;
                    $dauthor = 0;
                } else {
                    $dauthor = $session['user']['acctid'];
                }
                $sql = "UPDATE " . db_prefix("clans") . " SET clandesc='" . addslashes(substr(stripslashes($clandesc), 0, 4096)) . "',descauthor={$dauthor} WHERE clanid={$claninfo['clanid']}";
                db_query($sql);
                invalidatedatacache("clandata-{$claninfo['clanid']}");
                output("Updating description`n");
                $claninfo['clandesc'] = stripslashes($clandesc);
                $claninfo['descauthor'] = $session['user']['acctid'];
            }
            $customsay = httppost('customsay');
            if (httppostisset('customsay') && $customsay != $claninfo['customsay']) {
                $sql = "UPDATE " . db_prefix("clans") . " SET customsay='{$customsay}' WHERE clanid={$claninfo['clanid']}";
                db_query($sql);
                invalidatedatacache("clandata-{$claninfo['clanid']}");
                output("Updating custom say line`n");
                $claninfo['customsay'] = stripslashes($customsay);
            }
            $clanname = httppost('clanname');
            if ($clanname) {
                $clanname = full_sanitize($clanname);
            }
            $clanshort = httppost('clanshort');
            if ($clanshort) {
                $clanshort = full_sanitize($clanshort);
            }
            if (httppostisset('clanname') && $clanname != $claninfo['clanname']) {
                $sql = "UPDATE " . db_prefix("clans") . " SET clanname='{$clanname}' WHERE clanid={$claninfo['clanid']}";
                output("Updating the clan name`n");
                db_query($sql);
                invalidatedatacache("clandata-{$detail}");
                $claninfo['clanname'] = $clanname;
            }
            if (httppostisset('clanshort') && $clanshort != $claninfo['clanshort']) {
                $sql = "UPDATE " . db_prefix("clans") . " SET clanshort='{$clanshort}' WHERE clanid={$claninfo['clanid']}";
                output("Updating the short clan name`n");
                db_query($sql);
                invalidatedatacache("clandata-{$detail}");
                $claninfo['clanshort'] = $clanshort;
            }
            $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid={$claninfo['motdauthor']}";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            $motdauthname = $row['name'];
            $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid={$claninfo['descauthor']}";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            $descauthname = $row['name'];
            output("`&`bCurrent MoTD:`b `#by %s`2`n", $motdauthname);
            output_notl(nltoappon($claninfo['clanmotd']) . "`n");
            output("`&`bCurrent Description:`b `#by %s`2`n", $descauthname);
            output_notl(nltoappon($claninfo['clandesc']) . "`n");
            rawoutput("<form action='runmodule.php?module=claneditor&op=updinfo&dt={$dt}' method='POST'>");
            addnav("", "runmodule.php?module=claneditor&op=updinfo&dt={$dt}");
            output("`&`bMoTD:`b `7(4096 chars)`n");
            rawoutput("<textarea name='clanmotd' cols='50' rows='10'>" . htmlentities($claninfo['clanmotd'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "</textarea><br>");
            output("`bRenaming:`b`n");
            output("`iLong Name:`i ");
            rawoutput("<input name='clanname' value=\"" . htmlentities($claninfo['clanname'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "\" maxlength=50 size=50>");
            output("`n`iShort Name:`i ");
            rawoutput("<input name='clanshort' value=\"" . htmlentities($claninfo['clanshort'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "\" maxlength=5 size=5>");
            output_notl("`n");
            output("`n`&`bDescription:`b `7(4096 chars)`n");
            if (httppost('block') > "") {
                $blockdesc = translate_inline("Description blocked for inappropriate usage.");
                $sql = "UPDATE " . db_prefix("clans") . " SET descauthor=4294967295, clandesc='{$blockdesc}' where clanid='" . $claninfo['clanid'] . "'";
                output("Blocking public description`n");
                db_query($sql);
                invalidatedatacache("clandata-" . $claninfo['clanid'] . "");
                $claninfo['blockdesc'] = "";
                $claninfo['descauthor'] = 4294967295.0;
            } elseif (httppost('unblock') > "") {
                $sql = "UPDATE " . db_prefix("clans") . " SET descauthor=0, clandesc='' where clanid='" . $claninfo['clanid'] . "'";
                output("Unblocking public description`n");
                db_query($sql);
                invalidatedatacache("clandata-" . $claninfo['clanid'] . "");
                $claninfo['clandesc'] = "";
                $claninfo['descauthor'] = 0;
            }
            $blocked = translate_inline("The clan has been blocked from posting a description.`n");
            if ($claninfo['descauthor'] == 4294967295.0) {
                output_notl("`b`%" . $blocked . "`b");
            }
            rawoutput("<textarea name='clandesc' cols='50' rows='10'>" . htmlentities($claninfo['clandesc'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "</textarea><br>");
            output("`n`&`bCustom Talk Line`b `7(blank means \"says\" -- 15 chars max)`n");
            rawoutput("<input name='customsay' value=\"" . htmlentities($claninfo['customsay'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "\" maxlength=\"15\"><br/>");
            $save = translate_inline("Save");
            rawoutput("<input type='submit' class='button' value=\"{$save}\">");
            $snu = htmlentities(translate_inline("Save & Unblock public description"), ENT_COMPAT, getsetting("charset", "ISO-8859-1"));
            $snb = htmlentities(translate_inline("Save & Block public description"), ENT_COMPAT, getsetting("charset", "ISO-8859-1"));
            if ($claninfo['descauthor'] == "4294967295") {
                rawoutput("<input type='submit' name='unblock' value=\"{$snu}\" class='button'>");
            } else {
                rawoutput("<input type='submit' name='block' value=\"{$snb}\" class='button'>");
            }
            rawoutput("</form>");
        } elseif ($op == "membership") {
            output("This is the clans current membership:`n");
            $setrank = httpget('setrank');
            $who = httpget('who');
            if ($setrank > "") {
                $sql = "UPDATE " . db_prefix("accounts") . " SET clanrank={$setrank} WHERE login='******'";
                db_query($sql);
            }
            $remove = httpget('remove');
            if ($remove > "") {
                $sql = "UPDATE " . db_prefix("accounts") . " SET clanrank=" . CLAN_APPLICANT . ",clanid=0,clanjoindate='0000-00-00 00:00:00' WHERE login='******' AND clanrank<={$session['user']['clanrank']}";
                db_query($sql);
                //delete unread application emails from this user.
                //breaks if the applicant has had their name changed via
                //dragon kill, superuser edit, or lodge color change
                $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE login='******'";
                $row = db_fetch_assoc(db_query($sql));
                $subj = serialize(array($apply_short, $row['name']));
                $sql = "DELETE FROM " . db_prefix("mail") . " WHERE msgfrom=0 AND seen=0 AND subject='{$subj}'";
                db_query($sql);
            }
            $sql = "SELECT acctid,name,login,clanrank,laston,clanjoindate,dragonkills,level FROM " . db_prefix("accounts") . " WHERE clanid={$claninfo['clanid']} ORDER BY clanrank DESC,clanjoindate";
            $result = db_query($sql);
            rawoutput("<table border='0' cellpadding='2' cellspacing='0'>");
            $rank = translate_inline("Rank");
            $name = translate_inline("Name");
            $lev = translate_inline("Level");
            $dk = translate_inline("Dragon Kills");
            $jd = translate_inline("Join Date");
            $lo = translate_inline("Last On");
            $ops = translate_inline("Operations");
            $promote = translate_inline("Promote");
            $demote = translate_inline("Demote");
            $remove = translate_inline("Remove From The Clan");
            $confirm = translate_inline("Are you sure you wish to remove this member from the clan?");
            rawoutput("<tr class='trhead'><td>{$rank}</td><td>{$name}</td><td>{$lev}</td><td>{$dk}</td><td>{$jd}</td><td>{$lo}</td>" . ($session['user']['clanrank'] > CLAN_MEMBER ? "<td>{$ops}</td>" : "") . "</tr>", true);
            $i = 0;
            $tot = 0;
            while ($row = db_fetch_assoc($result)) {
                $i++;
                $tot += $row['dragonkills'];
                rawoutput("<tr class='" . ($i % 2 ? "trlight" : "trdark") . "'>");
                rawoutput("<td>");
                output_notl($ranks[$row['clanrank']]);
                rawoutput("</td><td>");
                $link = "bio.php?char=" . $row['acctid'] . "&ret=" . urlencode($_SERVER['REQUEST_URI']);
                rawoutput("<a href='{$link}'>", true);
                addnav("", $link);
                output_notl("`&%s`0", $row['name']);
                rawoutput("</a>");
                rawoutput("</td><td align='center'>");
                output_notl("`^%s`0", $row['level']);
                rawoutput("</td><td align='center'>");
                output_notl("`\$%s`0", $row['dragonkills']);
                rawoutput("</td><td>");
                output_notl("`3%s`0", $row['clanjoindate']);
                rawoutput("</td><td>");
                output_notl("`#%s`0", reltime(strtotime($row['laston'])));
                rawoutput("</td>");
                rawoutput("<td>");
                rawoutput("[ <a href='runmodule.php?module=claneditor&op=membership&dt={$dt}&setrank=" . ($row['clanrank'] + 1) . "&who=" . rawurlencode($row['login']) . "'>{$promote}</a> | ");
                addnav("", "runmodule.php?module=claneditor&op=membership&dt={$dt}&setrank=" . ($row['clanrank'] + 1) . "&who=" . rawurlencode($row['login']));
                rawoutput("<a href='runmodule.php?module=claneditor&op=membership&dt={$dt}&setrank=" . ($row['clanrank'] - 1) . "&who=" . rawurlencode($row['login']) . "'>{$demote}</a> | ");
                addnav("", "runmodule.php?module=claneditor&op=membership&dt={$dt}&setrank=" . ($row['clanrank'] - 1) . "&who=" . rawurlencode($row['login']));
                rawoutput("<a href='runmodule.php?module=claneditor&op=membership&dt={$dt}&remove=" . rawurlencode($row['login']) . "' onClick=\"return confirm('{$confirm}');\">{$remove}</a> ]");
                addnav("", "runmodule.php?module=claneditor&op=membership&dt={$dt}&remove=" . rawurlencode($row['login']));
                rawoutput("</td>");
                rawoutput("</tr>");
            }
            rawoutput("</table>");
            output("`n`n`^This clan has a total of `\$%s`^ dragon kills.", $tot);
        }
        if ($dt != "" && isset($claninfo)) {
            addnav("Clan Options");
            addnav("Main View", "runmodule.php?module=claneditor&op=mview&dt={$dt}");
            addnav("Update Clan Information", "runmodule.php?module=claneditor&op=updinfo&dt={$dt}");
            addnav("Delete this Clan", "runmodule.php?module=claneditor&op=deleteclan&dt={$dt}");
            addnav("Update Members", "runmodule.php?module=claneditor&op=membership&dt={$dt}");
            addnav("Module Prefs");
            module_editor_navs("prefs-clans", "runmodule.php?module=claneditor&op=editmodule&dt=" . $claninfo['clanid'] . "&mdule=");
        }
    }
    page_footer();
}
function grassyfield_runevent($type)
{
    require_once "lib/buffs.php";
    require_once "lib/commentary.php";
    addcommentary();
    global $session, $playermount;
    // We assume this event only shows up in the forest currently.
    $from = "forest.php?";
    $session['user']['specialinc'] = "module:grassyfield";
    $op = httpget('op');
    if ($op == "return") {
        $session['user']['specialmisc'] = "";
        $session['user']['specialinc'] = "";
        redirect($from, "Redirected to " . $from . " from Grassy Field module");
    }
    checkday();
    output("`n`c`#You Stumble Upon a Grassy Field`c`n`n");
    addnav("Return to the forest", $from . "op=return");
    require_once "lib/mountname.php";
    list($name, $lcname) = getmountname();
    if ($session['user']['specialmisc'] != "Nothing to see here, move along.") {
        if ($session['user']['hashorse'] > 0) {
            list($max, $cur) = grassyfield_getrounds();
            if ($cur > $max * 0.5) {
                // XXX: this message really should be a module objpref
                if ($playermount['partrecharge']) {
                    tlschema("mounts");
                    output($playermount['partrecharge']);
                    tlschema();
                } else {
                    output("`&You allow %s`& to frolic and gambol in the field.", $lcname);
                }
            } else {
                // XXX: this message really should be a module objpref
                if ($playermount['recharge']) {
                    tlschema("mounts");
                    output($playermount['recharge']);
                    tlschema();
                } else {
                    output("`&You allow %s`& to hunt and rest in the field.", $lcname);
                }
            }
            $buff = unserialize($playermount['mountbuff']);
            if (!isset($buff['schema']) || $buff['schema'] == "") {
                $buff['schema'] = "mounts";
            }
            apply_buff('mount', $buff);
            if ($session['user']['hitpoints'] < $session['user']['maxhitpoints']) {
                output("`n`^Your nap leaves you completely healed!");
                $session['user']['hitpoints'] = $session['user']['maxhitpoints'];
            }
            $args = array('soberval' => 0.8, 'sobermsg' => "`n`&Naps are quite a sobering experience!`n", 'schema' => "module-grassyfield");
            modulehook("soberup", $args);
            $session['user']['turns']--;
            output("`n`n`^You spend some time - and Stamina - lying around.");
        } else {
            output("`&Deciding to take a moment and a load off your poor weary feet you take a quick break from your ventures to take in the beautiful surroundings.");
            output("`n`n`^Your break leaves you completely healed!");
            if ($session['user']['hitpoints'] < $session['user']['maxhitpoints']) {
                $session['user']['hitpoints'] = $session['user']['maxhitpoints'];
            }
        }
        $session['user']['specialmisc'] = "Nothing to see here, move along.";
    } else {
        output("`&You relax a while in the fields enjoying the sun and the shade.");
    }
    commentdisplay("`n`n`@Talk with the others lounging here.`n", "grassyfield", "Speak lazily", 10);
}
function commentaryinfo_run()
{
    global $session;
    switch (httpget("op")) {
        case "closetalk":
            page_header("Close Talk");
            $player = httpget("player");
            $ret = httpget("ret");
            if ($session['user']['acctid'] > $player) {
                $join = "closetalk-" . $player . "-" . $session['user']['acctid'];
            } else {
                $join = "closetalk-" . $session['user']['acctid'] . "-" . $player;
            }
            $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid={$player}";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            $playername = $row['name'];
            output("`0You gently call out to chat with %s`0.`n`n", $playername);
            require_once "lib/commentary.php";
            addcommentary();
            viewcommentary($join, "Whisper", 25);
            addnav("Leave");
            if (strpos($ret, "&refresh=1")) {
                $retparts = explode("&refresh=1", $ret);
            } else {
                if (strpos($ret, "?refresh=1")) {
                    $retparts = explode("?refresh=1", $ret);
                } else {
                    if (strpos($ret, "&c=")) {
                        $retparts = explode("&c=", $ret);
                    } else {
                        if (strpos($ret, "?c=")) {
                            $retparts = explode("?c=", $ret);
                        } else {
                            if (strpos($ret, "?&")) {
                                $retparts = explode("?&", $ret);
                            }
                        }
                    }
                }
            }
            debug($retparts);
            $back = rtrim($retparts[0], "?");
            $back = ltrim($back, "/");
            debug($back);
            if ($back == "" || !$back) {
                $back = "village.php";
            }
            addnav("Back to where you came from", $back);
            //addnav("Village","village.php");
            debug(unserialize($session['user']['allowednavs']));
            break;
    }
    page_footer();
}