function proveyourself_run()
{
    global $session, $badguy, $battle;
    $op = httpget('op');
    page_header("Nightmare Court");
    switch ($op) {
        case "start":
            output("You head inside a large warehouse-type building.  A black-robed Mutant in a small reception area notices you and steps forward.  \"`4Welcome,`0\" he says, spreading his three misshapen arms dramatically.  \"`4This is a place where all of my kind will one day come to face their deepest fears.`0\"`n`nAh, the Obligatory Drama.  You nod and smile patiently as he explains.`n`n\"`4In this place, we teach how to accept one's limitations, and how to face and fight one's nightmares regardless.  It's a deeply intense and spiritual experience`0\"`n`n\"`#How much?`0\" you ask.`n`n\"`4Ah, the unfortunate topic of coin, how sadly necessary in a world obsessed with material wealth...`0\"`n`n\"`#`iHow much.`i`0\"`n`n\"`4It'll cost you a cigarette.`0\"`n`n\"`#Right, then.`0\"`n`n");
            if (!get_module_pref("playedtoday") && $session['user']['gems'] && $session['user']['hitpoints'] >= $session['user']['maxhitpoints']) {
                addnav("What will you do?");
                addnav("Fight", "runmodule.php?module=proveyourself&op=enter");
                addnav("Flee", "village.php");
            } else {
                if (get_module_pref("playedtoday")) {
                    addnav("You've already played today");
                    addnav("Back to the Outpost", "village.php");
                } else {
                    if (!$session['user']['gems']) {
                        addnav("You don't have a Cigarette handy");
                        addnav("Back to the Outpost", "village.php");
                    } else {
                        if ($session['user']['hitpoints'] < $session['user']['maxhitpoints']) {
                            addnav("You need to heal up first");
                            addnav("Back to the Outpost", "village.php");
                        }
                    }
                }
            }
            break;
        case "enter":
            output("You drop your cigarette into an unnecessarily ornate box, and the Mutant ushers you through a wooden door and into the mouth of a long, dark, red-carpeted corridor.`n`n\"`4Drink this,`0\" he says, passing you a simple wooden goblet filled with a sticky-looking fluid.  You sniff cautiously, then drink.  It tastes of dust and steel.`n`n\"`4Now remember; nothing in here can hurt you unless you allow it to.`0\"  His voice drops to a whisper as he presses a battery-operated torch into your hand.  \"`4Good luck.`0\"`n`nThe door closes gently behind him, and a faint `iclick`i is heard.`n`nYou flick on the torch and take a few steps away from the single overhead lamp.`n`nYou begin the long walk down the corridor.  Before long the red carpet runs out, leaving you walking on a bare concrete floor.`n`nAs you proceed further away from the light, the corridor becomes narrower, and cracks appear every few feet in the plaster.  Another half a minute of putting one foot in front of the other, and you look down to find that you're now walking on steel treadplate.`n`nYou mark off the cracks in the walls as you proceed, noting their increasing frequency.  Within another minute, the walls are crumbling away to reveal a cold chain-link fence, behind which, nothing but darkness.`n`nYou feel the steel give way to rust which bends worryingly beneath your feet, little pieces of dead metal sticking to your boots and falling back with a quiet tinny rustling.`n`nYou still cannot see the end of the corridor.`n`nThe sour metallic scent of oily, corroded metal lingers around oxidized chain-link fences.  You tread warily around the holes in the floor; even with your torch, you can't see what's underneath the thinning treadplate.  You see something shining in the distance, and quicken your pace.  A heavy steel door.`n`nYou look back over your shoulder.  You cannot see the entrance.  Through the steel door, then.  You grip the handle to the right, and pull.`n`nYou hadn't realized how silent this place was until you opened the door; a throaty rushing noise issued from its tracks as corroded bearings spun in dust-blackened oil.  You step through.`n`nIs the battery in your torch dying?`n`nYou pull out your lighter, and ignite.`n`nThe flame is a dull, dirty orange, plumes of soot-darkened smoke billowing from your mundane, butane-driven lighter.`n`nYou tell yourself that the torch is not dying; its cone of light is not dimming to a deep orange, not turning redder and dimmer by the second.  None of that is happening.`n`nThe torch is just as bright as ever.  The problem is that the darkness is getting thicker.`n`nWithin seconds you are blind, and aware of how far away you are from other people, and medical attention.`n`nAware that if you get knocked out here, you won't be going to the FailBoat.`n`nYou feel the hot, damp breath on your face before you hear the growl.`n`n");
            addnav("Continue");
            addnav("Continue", "runmodule.php?module=proveyourself&op=beginfighting");
            break;
        case "beginfighting":
            $session['user']['gems']--;
            restore_buff_fields();
            $badguy = array();
            $badguy['creaturename'] = "Nightmare";
            $badguy['creatureweapon'] = "Serrated Blades";
            $badguy['creaturelevel'] = 1;
            $badguy['creaturegold'] = 0;
            $badguy['creatureexp'] = 0;
            $badguy['creaturehealth'] = 1000000000000.0;
            $badguy['creatureattack'] = 1;
            $badguy['creaturedefense'] = 1;
            $badguy['hidehitpoints'] = 1;
            calculate_buff_fields();
            $badguy['playerstarthp'] = $session['user']['hitpoints'];
            $badguy['diddamage'] = 0;
            $badguy['type'] = 'nightmare';
            $badguy['creatureaiscript'] = "require(\"ai/nightmare.php\");";
            $session['user']['badguy'] = createstring($badguy);
            $battle = true;
            break;
        case "run":
            output("You can't run from your nightmare.`n`n");
            $op = "fight";
            httpset('op', $op);
            $battle = true;
            break;
        case "fight":
            $battle = true;
            break;
        case "end":
            $points = httpget("points");
            $highscore = get_module_pref("highscore");
            output("You regain your senses while rolling around on the floor, waving your weapon at the empty air.  You're at the end of the corridor.  You look back to see the entryway not thirty feet away, and your Mutant friend striding along the corridor.`n`n\"`4Feeling better now?`0\"`n`n\"`#What the `ihell`i was in that drink?`0\"`n`n\"`4Died, did you?  Ah, well.  It's an experience, anyway.`0\"  He looks around at the chunks you've taken out of the walls.  \"`4Well, I reckon you knocked about %s hitpoints out of your imagination.  Naturally it'll all go on the Hall O' Fame.`0\"`n`nYou take a deep breath and begin to point a recriminating finger.  After a moment you shrug, get to your feet and leave, smacking the Mutant around the back of the head as you go.`n`n", $points);
            if ($points > $highscore) {
                output("`4You beat your personal record!`0`n`n");
                set_module_pref("highscore", $points);
            }
            addnav("Exit");
            addnav("Back to the Outpost", "village.php");
            break;
        case "hof":
            page_header("Nightmare Enthusiasts");
            $acc = db_prefix("accounts");
            $mp = db_prefix("module_userprefs");
            $sql = "SELECT {$acc}.name AS name,\r\n\t\t\t\t{$acc}.acctid AS acctid,\r\n\t\t\t\t{$mp}.value AS highscore,\r\n\t\t\t\t{$mp}.userid FROM {$mp} INNER JOIN {$acc}\r\n\t\t\t\tON {$acc}.acctid = {$mp}.userid \r\n\t\t\t\tWHERE {$mp}.modulename = 'proveyourself' \r\n\t\t\t\tAND {$mp}.setting = 'highscore' \r\n\t\t\t\tAND {$mp}.value > 0 ORDER BY ({$mp}.value+0)\t\r\n\t\t\t\tDESC limit 200";
            $result = db_query($sql);
            $rank = translate_inline("Damage Points");
            $name = translate_inline("Name");
            output("`n`b`c`4Nightmare Enthusiasts`0`n`n`c`b");
            rawoutput("<table border='0' cellpadding='2' cellspacing='1' align='center'>");
            rawoutput("<tr class='trhead'><td align=center>{$name}</td><td align=center>{$rank}</td></tr>");
            for ($i = 0; $i < db_num_rows($result); $i++) {
                $row = db_fetch_assoc($result);
                if ($row['name'] == $session['user']['name']) {
                    rawoutput("<tr class='trhilight'><td>");
                } else {
                    rawoutput("<tr class='" . ($i % 2 ? "trdark" : "trlight") . "'><td align=left>");
                }
                output_notl("%s", $row['name']);
                rawoutput("</td><td align=right>");
                output_notl("%s", number_format($row['highscore']));
                rawoutput("</td></tr>");
            }
            rawoutput("</table>");
            addnav("Back to HoF", "hof.php");
            villagenav();
            break;
    }
    if ($battle) {
        include_once "battle.php";
        if ($defeat) {
            addnav("You have been killed.");
            $session['user']['hitpoints'] = $session['user']['maxhitpoints'];
            $points = 1000000000000.0 - $badguy['creaturehealth'];
            addnav("What happens next?", "runmodule.php?module=proveyourself&op=end&points=" . $points);
        } else {
            if ($victory) {
                addnav("Now what?");
                addnav("What happens next?", "runmodule.php?module=proveyourself&op=end&points=" . $points);
            } else {
                require_once "lib/fightnav.php";
                fightnav(true, true, "runmodule.php?module=proveyourself", true);
            }
        }
    }
    page_footer();
}
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 titans_load_battle($id)
{
    global $session, $badguy, $battle;
    $titan = titans_get_titan($id);
    if ($titan && !$titan['battlelog']['killed']) {
        restore_buff_fields();
        $creature = $titan['creature'];
        $creature['titaninfo']['badguy']['hpstart'] = $creature['creaturehealth'];
        $creature['titaninfo']['player']['hpstart'] = $session['user']['hitpoints'];
        $badguy = $creature;
        calculate_buff_fields();
        $session['user']['badguy'] = createstring($badguy);
        $battle = true;
        return $titan;
    } else {
        redirect("runmodule.php?module=titans&titanop=battleover");
        return false;
    }
}
         if ($val == "at" || $val == "de") {
             $dk++;
         }
     }
     $dk += (int) (($session['user']['maxhitpoints'] - $session['user']['level'] * 10) / 5);
     $dk = round($dk * 0.33, 0);
     $atkflux = e_rand(0, $dk);
     $atkflux = min($atkflux, round($dk * 0.25));
     $defflux = e_rand(0, $dk - $atkflux);
     $defflux = min($defflux, round($dk * 0.25));
     $hpflux = ($dk - ($atkflux + $defflux)) * 5;
     debug("DEBUG: {$dk} modification points total.`n");
     debug("DEBUG: +{$atkflux} allocated to attack.`n");
     debug("DEBUG: +{$defflux} allocated to defense.`n");
     debug("DEBUG: +" . $hpflux / 5 . "*5 to hitpoints`n");
     calculate_buff_fields();
     $master['creatureattack'] += $atkflux;
     $master['creaturedefense'] += $defflux;
     $master['creaturehealth'] += $hpflux;
     $attackstack['enemies'][0] = $master;
     $attackstack['options']['type'] = 'train';
     $session['user']['badguy'] = createstring($attackstack);
     $battle = true;
     if ($victory) {
         $badguy = unserialize($session['user']['badguy']);
         $badguy = $badguy['enemies'][0];
         output("With a flurry of blows you dispatch your master.`n");
     }
 } else {
     output("You ready your %s and %s and approach `^%s`0.`n`n", $session['user']['weapon'], $session['user']['armor'], $master['creaturename']);
     output("A small crowd of onlookers has gathered, and you briefly notice the smiles on their faces, but you feel confident. ");
function heidi_run()
{
    global $session;
    $op = httpget("op");
    $addgold = get_module_pref("addgold");
    $addgold *= round(min(1, $session['user']['dragonkills']) * max(1, $session['user']['dragonkills'] * 0.5 / $session['user']['maxhitpoints']));
    $addgold -= max(1000, $session['user']['maxhitpoints']);
    if ($addgold <= 0) {
        $addgold = 10 * $session['user']['level'];
    }
    $pvpchange = get_module_pref("pvpchange");
    $changeallowed = get_module_setting("changeallowed");
    $allowgift = get_module_setting("allowgift");
    $allowdp = get_module_setting("allowdp");
    $turnadd = get_module_setting("turnadd");
    $turnmult = get_module_setting("turnmult");
    $newdayturns = get_module_pref("newdayturns");
    $turngain = ceil($newdayturns * $turnmult / 100) + $turnadd;
    $gemspaid = get_module_pref("gemspaid");
    $dk = $session['user']['dragonkills'];
    page_header("Heidi's Place");
    villagenav();
    output("`&`c`bHeidi, the Well-wisher`b`c`n");
    if ($changeallowed) {
        addnav("Burn Blue Candle - lose 1 PvP", "runmodule.php?module=heidi&op=blue");
    }
    if ($allowdp && $session['user']['dragonkills'] > 10) {
        addnav("O?Ask about the Orange candles", "runmodule.php?module=heidi&op=orange");
    }
    if ($allowgift) {
        addnav(array("Make a Donation - %s gold", $addgold), "runmodule.php?module=heidi&op=give");
    }
    modulehook("heidi-start", array("changeallowed" => $changeallowed, "allowdp" => $allowdp && $session['user']['dragonkills'] > 10, "allowgift" => $allowgift, "giftgold" => $addgold));
    if ($op == "") {
        output("`7You step into Heidi's small hut, gazing around at the multitude of colored candles that flicker from the shelves on every wall.`n`n");
        output("`7After a moment you are greeted by a pleasant-looking felyne with a smile on her face.`n`n");
        output("\"`&It is so lovely to see you, %s!", $session['user']['name']);
        output("`&Welcome, then, and reflect on the beauty of the well.`7\"`n`n");
        output("`7A small fountain trickles into what looks more like a pool than a well.");
        output("`7As Heidi whistles softly, crystals in the bottom of the pool begin to glow, eventually forming the numbers: %s.`n`n", $addgold);
        output("`7\"`&Perhaps ye have come to give! Or to burn a candle for a spell?`7\"");
    } elseif ($op == "give" && $session['user']['gold'] < $addgold && $allowgift) {
        // you don't have enough money.
        output("`7Heidi eyes you with concern.`n`n");
        output("\"`&Child, ye be trying to give, when ye have not the affluence to give.`7`n`n");
        output("`&Take comfort, for the mother sees inside thy heart today.`7\"`n`n");
        output("You're not so sure you understand who this mother is, but you realize that you haven't enough gold to donate what the well requests, and so you leave quietly.`n`n");
    } elseif ($op == "give" && $allowgift) {
        output("`7You lean forward, and place %s gold into the well.`n`n", $addgold);
        output("Heidi concentrates on a small candle for several moments, whispering words you cannot understand.`n`n");
        output("\"`&Somewhere, come the morning fair, someone less fortunate shall wake up with a gift of gold.`7`n`n");
        output("`&The pleasure in giving, be within you today!`7\" she exclaims.`n`n");
        debuglog("gave {$addgold} gold as an anonymous gift to someone less fortunate.");
        $session['user']['gold'] -= $addgold;
        apply_buff('heidi', array("name" => "`QUnselfishness`0", "rounds" => 15, "defmod" => 1.05, "survivenewday" => 1, "roundmsg" => "`QGiving to others makes you feel empowered.`0", "schema" => "module-heidi"));
    } elseif ($op == "orange") {
        output("`7Heidi smiles and motions to the small box of orange candles on a shelf nearby.`n`n");
        output("\"`&Orange is the color of change!");
        output("What's done in life is done, but we can mend bridges if we wish to make the change in ourselves.`7\"`n`n");
        if (!get_module_pref("pendingdp")) {
            output("`7For a cost of %s gems, you will be able to rechoose your dragon point allocation after new day.`n`n", $dk);
        }
        $gemsremain = $dk - $gemspaid;
        if (get_module_pref("pendingdp")) {
            output("`7Heidi looks at you deeply for a moment and then smiles tenderly, \"`&Child, child, you must give time for the past changes to take effect before trying again.`7\"`n`n");
        } elseif ($session['user']['gems']) {
            addnav("Payment");
            // User has enough to pay in full
            if ($session['user']['gems'] >= $gemsremain) {
                // You can always pay what you still owe if you have it.
                addnav(array("Pay in full (%s %s)", $gemsremain, translate_inline($gemsremain == 1 ? "gem" : "gems")), "runmodule.php?module=heidi&op=orangepay&amt={$gemsremain}");
            }
            // Don't make user pay in full if he doesn't want to
            if ($session['user']['gems'] < $gemsremain) {
                addnav(array("Pay an installment (%s %s)", $session['user']['gems'], translate_inline($session['user']['gems'] == 1 ? "gem" : "gems")), "runmodule.php?module=heidi&op=orangepay&amt=" . $session['user']['gems']);
            }
            if ($gemsremain > 25 && $session['user']['gems'] >= 25) {
                addnav(array("Pay an installment (%s %s)", 25, translate_inline("gems")), "runmodule.php?module=heidi&op=orangepay&amt=25");
            }
            // Give some text about the installment
            if ($gemspaid == 0 && ($dk > 25 || $session['user']['gems'] < $gemsremain)) {
                output("`7As your total price is %s gems you might not wish to pay in full immediately, and instead pay in installments.`n`n", $dk);
                output("`\$You will not be able to rechoose your dragon point allocation until the whole amount has been paid, and you cannot regain any gems you have already given once you start to make the installments.`n`n");
                output("`\$Once you pay the full cost, you will lose any hitpoints, attack or defense that you have purchased with dragonpoints until the next new day when you will be able to once again choose their allocation.`n`n");
            } elseif ($gemspaid) {
                output("`^You have paid %s gems so far and have %s remaining in order to rechoose your dragon points at new day.`n`n", $gemspaid, $gemsremain);
                output("`\$You will not be able to rechoose your dragon point allocation until the whole amount has been paid, and you cannot regain any gems you have already given once you start to make the installments.`n`n");
                output("`\$Once you pay the full cost, you will lose any hitpoints, attack or defense that you have purchased with dragonpoints until the next new day when you will be able to once again choose their allocation.`n`n");
                output("`\$Additionally, any buffs you have from visiting Tynan will be immediately reset.  Such is the cost of change.`n`n");
            }
        } else {
            // User doesn't have any gems on him.
            output("`7You don't have enough gems to pay right now.`n`n");
        }
    } elseif ($op == "orangepay") {
        $amt = httpget("amt");
        $gemspaid += $amt;
        $gemsremain = $dk - $gemspaid;
        set_module_pref("gemspaid", $gemspaid);
        if ($gemsremain) {
            debuglog("Spent {$amt} gems on dp reallocation installment with Heidi. {$gemspaid} spent in total.  {$gemsremain} left to pay.");
        } else {
            debuglog("Spent {$amt} gems to pay remaining amount on dp reallocation with Heidi.  {$dk} spent total.");
        }
        $session['user']['gems'] -= $amt;
        if ($gemsremain) {
            output("`7Heidi thanks you for the gems and reminds you that you have now paid %s of the %s total gems you owe.`n`n", $gemspaid, $dk);
        } else {
            output("`7Heidi thanks you for the payment and smiles.");
            output("She takes a small, orange candle, lights it and places it in a small silver holder, before whispering words that seem foreign to your ears.");
            output("She finally opens her eyes and reminds you that you will be able to rechoose your dragon point allocation at new day.`n`n");
            set_module_pref("gemspaid", 0);
            $hpcount = 0;
            $atcount = 0;
            $defcount = 0;
            reset($session['user']['dragonpoints']);
            while (list($key, $val) = each($session['user']['dragonpoints'])) {
                if ($val == "hp") {
                    $hpcount += 5;
                }
                if ($val == "at") {
                    $atcount++;
                }
                if ($val == "de") {
                    $defcount++;
                }
            }
            restore_buff_fields();
            $session['user']['maxhitpoints'] -= $hpcount;
            $session['user']['hitpoints'] -= $hpcount;
            $session['user']['attack'] -= $atcount;
            $session['user']['defense'] -= $defcount;
            set_module_pref("attack", 0, "tynan");
            set_module_pref("defense", 0, "tynan");
            set_module_pref("hitpoints", 0, "tynan");
            strip_buff("tynanSTAT");
            if ($session['user']['hitpoints'] <= 1) {
                $session['user']['hitpoints'] = 1;
            }
            // call the reset hook before we wipe the array just in case
            // something cares!
            modulehook("dkpointspentreset");
            $session['user']['dragonpoints'] = array();
            set_module_pref("pendingdp", 1);
            calculate_buff_fields();
        }
    } elseif ($session['user']['playerfights'] == 0 || $pvpchange >= $changeallowed) {
        // you have no PvP left today or have already burned the blue
        // enough today
        output("`7Heidi eyes you with a smile.`n`n");
        if ($session['user']['playerfights'] == 0) {
            output("\"`&'Tis all very well to want peace, when one has none extra to give!`7\"`n`n");
        } else {
            // No more burning allowed today.
            output("\"`&Your desire for peace is noble, but is misplaced at this time.`7\"`n`n");
        }
        output("\"`&Perhaps tomorrow ye will come to see me, before ye slay your enemies in fury?`7\"`n`n");
    } else {
        output("`7Heidi takes a small, sky-blue candle, lights it and places it in a small silver holder.");
        output("She regards you with a smile.`n`n");
        output("\"`&Your gesture of kindness to your fellow beings shall reward you.");
        output("Go in peace, warrior.`7\"`n`n");
        output("`6You `@gain`6 %s turns!`n`n", $turngain);
        $session['user']['turns'] += $turngain;
        $session['user']['playerfights']--;
        $pvpchange++;
        set_module_pref("pvpchange", $pvpchange);
        debuglog("exchanged one PvP fight for {$turngain} forest fights.");
        $newdayturns *= 0.75;
        // second and subsequent burns have lower benefit
        set_module_pref("newdayturns", $newdayturns);
    }
    modulehook("heidi-end", array("changeallowed" => $changeallowed, "allowdp" => $allowdp && $session['user']['dragonkills'] > 10, "allowgift" => $allowgift, "giftgold" => $addgold));
    page_footer();
}
function strip_buff($name)
{
    global $session, $buffreplacements;
    restore_buff_fields();
    if (isset($session['bufflist'][$name])) {
        unset($session['bufflist'][$name]);
    }
    if (isset($buffreplacements[$name])) {
        unset($buffreplacements[$name]);
    }
    calculate_buff_fields();
}
/**
 * Brings all the output elements together and terminates the rendering of the page.  Saves the current user info and updates the rendering statistics
 * Hooks provided:
 *	footer-{$script name}
 *	everyfooter
 *
 */
function page_footer($saveuser = true)
{
    global $output, $nestedtags, $header, $nav, $session, $REMOTE_ADDR, $REQUEST_URI, $pagestarttime, $quickkeys, $template, $y2, $z2, $logd_version, $copyright, $SCRIPT_NAME, $nopopups, $footer, $dbinfo;
    $z = $y2 ^ $z2;
    $footer = $template['footer'];
    //page footer module hooks
    $script = substr($SCRIPT_NAME, 0, strpos($SCRIPT_NAME, "."));
    $replacementbits = array();
    $replacementbits = modulehook("footer-{$script}", $replacementbits);
    if ($script == "runmodule" && ($module = httpget('module')) > "") {
        // This modulehook allows you to hook directly into any module without
        // the need to hook into footer-runmodule and then checking for the
        // required module.
        modulehook("footer-{$module}", $replacementbits);
    }
    // Pass the script file down into the footer so we can do something if
    // we need to on certain pages (much like we do on the header.
    // Problem is 'script' is a valid replacement token, so.. use an
    // invalid one which we can then blow away.
    $replacementbits['__scriptfile__'] = $script;
    $replacementbits = modulehook("everyfooter", $replacementbits);
    if ($session['user']['loggedin']) {
        $replacementbits = modulehook("everyfooter-loggedin", $replacementbits);
    }
    unset($replacementbits['__scriptfile__']);
    //output any template part replacements that above hooks need (eg,
    //advertising)
    reset($replacementbits);
    while (list($key, $val) = each($replacementbits)) {
        $header = str_replace("{" . $key . "}", "{" . $key . "}" . join($val, ""), $header);
        $footer = str_replace("{" . $key . "}", "{" . $key . "}" . join($val, ""), $footer);
    }
    $builtnavs = buildnavs();
    restore_buff_fields();
    calculate_buff_fields();
    tlschema("common");
    $charstats = charstats();
    restore_buff_fields();
    $sql = "SELECT motddate FROM " . db_prefix("motd") . " ORDER BY motditem DESC LIMIT 1";
    $result = db_query_cached($sql, "motd-dates");
    $row = db_fetch_assoc($result);
    db_free_result($result);
    $headscript = "";
    if (isset($session['user']['lastmotd']) && $row['motddate'] > $session['user']['lastmotd'] && (!isset($nopopup[$SCRIPT_NAME]) || $nopopups[$SCRIPT_NAME] != 1) && $session['user']['loggedin']) {
        // $headscript.=popup("motd.php");
        $session['needtoviewmotd'] = true;
    } else {
        $session['needtoviewmotd'] = false;
    }
    $pre_headscript = "<LINK REL=\"shortcut icon\" HREF=\"favicon.ico\" TYPE=\"image/x-icon\"/>";
    if ($headscript > "") {
        $header = str_replace("{headscript}", $pre_headscript . "<script language='JavaScript'>" . $headscript . "</script>", $header);
    } else {
        $header = str_replace("{headscript}", $pre_headscript, $header);
    }
    $script = "";
    if (!isset($session['user']['name'])) {
        $session['user']['name'] = "";
    }
    if (!isset($session['user']['login'])) {
        $session['user']['login'] = "";
    }
    //clean up unclosed output tags.
    while (list($key, $val) = each($nestedtags)) {
        if ($nestedtags[$key] === true) {
            $output .= "</{$key}>";
        }
        unset($nestedtags[$key]);
    }
    //output keypress script
    $script .= "<script language='JavaScript'>\r\n\t<!--\r\n\tdocument.onkeypress=keyevent;\r\n\tfunction keyevent(e){\r\n\t\tvar c;\r\n\t\tvar target;\r\n\t\tvar altKey;\r\n\t\tvar ctrlKey;\r\n\t\tif (window.event != null) {\r\n\t\t\tc=String.fromCharCode(window.event.keyCode).toUpperCase();\r\n\t\t\taltKey=window.event.altKey;\r\n\t\t\tctrlKey=window.event.ctrlKey;\r\n\t\t}else{\r\n\t\t\tc=String.fromCharCode(e.charCode).toUpperCase();\r\n\t\t\taltKey=e.altKey;\r\n\t\t\tctrlKey=e.ctrlKey;\r\n\t\t}\r\n\t\tif (window.event != null)\r\n\t\t\ttarget=window.event.srcElement;\r\n\t\telse\r\n\t\t\ttarget=e.originalTarget;\r\n\t\tif (target.nodeName.toUpperCase()=='INPUT' || target.nodeName.toUpperCase()=='TEXTAREA' || altKey || ctrlKey){\r\n\t\t}else{";
    reset($quickkeys);
    while (list($key, $val) = each($quickkeys)) {
        $script .= "\n\t\t\tif (c == '" . strtoupper($key) . "') { {$val}; return false; }";
    }
    $script .= "\r\n\t\t}\r\n\t}\r\n\t//-->\r\n\t</script>";
    //handle paypal
    if (strpos($footer, "{paypal}") || strpos($header, "{paypal}")) {
        $palreplace = "{paypal}";
    } else {
        $palreplace = "{stats}";
    }
    //NOTICE |
    //NOTICE | Although under the license, you're not required to keep this
    //NOTICE | paypal link, I do request, as the author of this software
    //NOTICE | which I have made freely available to you, that you leave it in.
    //NOTICE |
    $paypalstr = '<table align="center"><tr><td>';
    $currency = getsetting("paypalcurrency", "USD");
    if (!isset($_SESSION['logdnet']) || !isset($_SESSION['logdnet']['']) || $_SESSION['logdnet'][''] == "" || !isset($session['user']['laston']) || date("Y-m-d H:i:s", strtotime("-1 hour")) > $session['user']['laston']) {
        $already_registered_logdnet = false;
    } else {
        $already_registered_logdnet = true;
    }
    if (getsetting("logdnet", 0) && $session['user']['loggedin'] && !$already_registered_logdnet) {
        //account counting, just for my own records, I don't use this in the calculation for server order.
        $sql = "SELECT count(*) AS c FROM " . db_prefix("accounts");
        $result = db_query_cached($sql, "acctcount", 600);
        $row = db_fetch_assoc($result);
        $c = $row['c'];
        $a = getsetting("serverurl", "http://" . $_SERVER['SERVER_NAME'] . ($_SERVER['SERVER_PORT'] == 80 ? "" : ":" . $_SERVER['SERVER_PORT']) . dirname($_SERVER['REQUEST_URI']));
        if (!preg_match("/\\/\$/", $a)) {
            $a = $a . "/";
            savesetting("serverurl", $a);
        }
        $l = getsetting("defaultlanguage", "en");
        $d = getsetting("serverdesc", "Another LoGD Server");
        $e = getsetting("gameadminemail", "*****@*****.**");
        $u = getsetting("logdnetserver", "http://logdnet.logd.com/");
        if (!preg_match("/\\/\$/", $u)) {
            $u = $u . "/";
            savesetting("logdnetserver", $u);
        }
        global $logd_version;
        $v = $logd_version;
        $c = rawurlencode($c);
        $a = rawurlencode($a);
        $l = rawurlencode($l);
        $d = rawurlencode($d);
        $e = rawurlencode($e);
        $v = rawurlencode($v);
        $u = rawurlencode($u);
        $paypalstr .= "<script language='JavaScript' src='images/logdnet.php?op=register&c={$c}&l={$l}&v={$v}&a={$a}&d={$d}&e={$e}&u={$u}'></script>";
    } else {
        $paypalstr .= '<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_blank">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="business" value="*****@*****.**">
<input type="hidden" name="item_name" value="Legend of the Green Dragon Author Donation from ' . full_sanitize($session['user']['name']) . '">
<input type="hidden" name="item_number" value="' . htmlentities($session['user']['login'] . ":" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . '">
<input type="hidden" name="no_shipping" value="1">
<input type="hidden" name="notify_url" value="http://lotgd.net/payment.php">
<input type="hidden" name="cn" value="Your Character Name">
<input type="hidden" name="cs" value="1">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="tax" value="0">
<input type="image" src="images/paypal1.gif" border="0" name="submit" alt="Donate!">
</form>';
    }
    $paysite = getsetting("paypalemail", "");
    if ($paysite != "") {
        $paypalstr .= '</td></tr><tr><td colspan=\'2\' align=\'center\'>';
        $paypalstr .= '<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_blank">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="business" value="' . $paysite . '">
<input type="hidden" name="item_name" value="' . getsetting("paypaltext", "Legend of the Green Dragon Site Donation from") . ' ' . full_sanitize($session['user']['name']) . '">
<input type="hidden" name="item_number" value="' . htmlentities($session['user']['login'] . ":" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . '">
<input type="hidden" name="no_shipping" value="1">';
        if (file_exists("payment.php")) {
            $paypalstr .= '<input type="hidden" name="notify_url" value="http://' . $_SERVER["HTTP_HOST"] . dirname($_SERVER['REQUEST_URI']) . '/payment.php">';
        }
        $paypalstr .= '<input type="hidden" name="cn" value="Your Character Name">
<input type="hidden" name="cs" value="1">
<input type="hidden" name="currency_code" value="' . $currency . '">
<input type="hidden" name="lc" value="' . getsetting("paypalcountry-code", "US") . '">
<input type="hidden" name="bn" value="PP-DonationsBF">
<input type="hidden" name="tax" value="0">
<input type="image" src="images/paypal2.gif" border="0" name="submit" alt="Donate!">
</form>';
    }
    $paypalstr .= '</td></tr></table>';
    $footer = str_replace($palreplace, (strpos($palreplace, "paypal") ? "" : "{stats}") . $paypalstr, $footer);
    $header = str_replace($palreplace, (strpos($palreplace, "paypal") ? "" : "{stats}") . $paypalstr, $header);
    //NOTICE |
    //NOTICE | Although I will not deny you the ability to remove the above
    //NOTICE | paypal link, I do request, as the author of this software
    //NOTICE | which I made available for free to you that you leave it in.
    //NOTICE |
    //output the nav
    $footer = str_replace("{" . $z . "}", ${$z}, $footer);
    $header = str_replace("{nav}", $builtnavs, $header);
    $footer = str_replace("{nav}", $builtnavs, $footer);
    //output the motd
    $header = str_replace("{motd}", motdlink(), $header);
    $footer = str_replace("{motd}", motdlink(), $footer);
    //output the mail link
    if (isset($session['user']['acctid']) && $session['user']['acctid'] > 0 && $session['user']['loggedin']) {
        $header = str_replace("{mail}", maillink(), $header);
        $footer = str_replace("{mail}", maillink(), $footer);
    } else {
        $header = str_replace("{mail}", "", $header);
        $footer = str_replace("{mail}", "", $footer);
    }
    //output petition count
    $header = str_replace("{petition}", "<a href='petition.php' onClick=\"" . popup("petition.php") . ";return false;\" target='_blank' align='right' class='motd'>" . translate_inline("Petition for Help") . "</a>", $header);
    $footer = str_replace("{petition}", "<a href='petition.php' onClick=\"" . popup("petition.php") . ";return false;\" target='_blank' align='right' class='motd'>" . translate_inline("Petition for Help") . "</a>", $footer);
    if ($session['user']['superuser'] & SU_EDIT_PETITIONS) {
        $sql = "SELECT count(petitionid) AS c,status FROM " . db_prefix("petitions") . " GROUP BY status";
        $result = db_query_cached($sql, "petition_counts");
        $petitions = array(0 => 0, 1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0, 7 => 0);
        while ($row = db_fetch_assoc($result)) {
            $petitions[(int) $row['status']] = $row['c'];
        }
        $pet = translate_inline("`0`bPetitions:`b");
        $ued = translate_inline("`0`bUser Editor`b");
        db_free_result($result);
        if ($session['user']['superuser'] & SU_EDIT_USERS) {
            $p = "<a href='user.php'>{$ued}</a>|<a href='viewpetition.php'>{$pet}</a>";
            addnav("", "user.php");
            addnav("", "viewpetition.php");
        } else {
            $p = "<a href='viewpetition.php'>{$pet}</a>";
            addnav("", "viewpetition.php");
        }
        $p .= " `\${$petitions[5]}`0|`^{$petitions[4]}`0|`b{$petitions[0]}`b|{$petitions[1]}|`!{$petitions[3]}`0|`#{$petitions[7]}`0|`%{$petitions[6]}`0|`i{$petitions[2]}`i";
        $pcount = templatereplace("petitioncount", array("petitioncount" => appoencode($p, true)));
        $footer = str_replace("{petitiondisplay}", $pcount, $footer);
        $header = str_replace("{petitiondisplay}", $pcount, $header);
    } else {
        $footer = str_replace("{petitiondisplay}", "", $footer);
        $header = str_replace("{petitiondisplay}", "", $header);
    }
    //output character stats
    $footer = str_replace("{stats}", $charstats, $footer);
    $header = str_replace("{stats}", $charstats, $header);
    //do something -- I don't know what
    $header = str_replace("{script}", $script, $header);
    //output view PHP source link
    $sourcelink = "source.php?url=" . preg_replace("/[?].*/", "", $_SERVER['REQUEST_URI']);
    $footer = str_replace("{source}", "<a href='{$sourcelink}' onclick=\"" . popup($sourcelink) . ";return false;\" target='_blank'>" . translate_inline("View PHP Source") . "</a>", $footer);
    $header = str_replace("{source}", "<a href='{$sourcelink}' onclick=\"" . popup($sourcelink) . ";return false;\" target='_blank'>" . translate_inline("View PHP Source") . "</a>", $header);
    //output version
    $footer = str_replace("{version}", "Version: {$logd_version}", $footer);
    //output page generation time
    $gentime = getmicrotime() - $pagestarttime;
    $session['user']['gentime'] += $gentime;
    $session['user']['gentimecount']++;
    $load = exec("uptime");
    $load = split("load average:", $load);
    $load = split(", ", $load[1]);
    $perfhook = array("gentime" => $gentime, "dbinfo" => $dbinfo, "cpu" => $load, "script" => $SCRIPT_NAME, "request" => $REQUEST_URI);
    $perfhook = modulehook("footer-performance", $perfhook);
    $l1 = $load[0];
    $l5 = $load[1];
    $l15 = $load[2];
    $mem = memory_get_usage(true);
    if ($mem < 1024) {
        $memdisp = $mem . " bytes";
    } else {
        if ($mem < 1048576) {
            $memdisp = round($mem / 1024, 6) . " kilobytes";
        } else {
            $memdisp = round($mem / 1048576, 6) . " megabytes";
        }
    }
    if (!isset($dbinfo['cache_fail'])) {
        $dbinfo['cache_fail'] = 0;
    }
    global $output_time;
    $footer = str_replace("{pagegen}", "Page gen: " . round($gentime, 3) . "s / " . $dbinfo['queriesthishit'] . " queries (" . round($dbinfo['querytime'], 3) . "s), cache " . $dbinfo['cache_success'] . " successful (" . round($dbinfo['cachetime'], 3) . "s) / " . $dbinfo['cache_fail'] . " failed.  Average for this account: " . round($session['user']['gentime'] / $session['user']['gentimecount'], 3) . "s - " . round($session['user']['gentime'], 3) . "/" . round($session['user']['gentimecount'], 3) . "<br />Current CPU Load: {$l1} | {$l5} | {$l15}<br />Memory usage for this page: {$memdisp}", $footer);
    tlschema();
    // global $allqueries;
    // debug($allqueries);
    // global $cachedqueries;
    // debug($cachedqueries);
    // global $module_prefs;
    // debug($module_prefs);
    // global $moduleperformance;
    // debug($moduleperformance);
    // global $allqueriesbyfile;
    // debug($allqueriesbyfile);
    //clean up spare {fields}s from header and footer (in case they're not used)
    $footer = preg_replace("/{[^} \t\n\r]*}/i", "", $footer);
    $header = preg_replace("/{[^} \t\n\r]*}/i", "", $header);
    //finalize output
    $output = $header . $output . $footer;
    $session['user']['gensize'] += strlen($output);
    $session['output'] = $output;
    if ($saveuser === true) {
        saveuser();
    }
    unset($session['output']);
    //this somehow allows some frames to load before the user's navs say it can
    //session_write_close();
    echo $output;
    $session['badnav'] = 0;
    exit;
}
function cities_run()
{
    global $session;
    $op = httpget("op");
    $city = urldecode(httpget("city"));
    $continue = httpget("continue");
    $danger = httpget("d");
    $su = httpget("su");
    if ($op != "faq") {
        require_once "lib/forcednavigation.php";
        do_forced_nav(false, false);
    }
    // I really don't like this being out here, but it has to be since
    // events can define their own op=.... and we might need to handle them
    // otherwise things break.
    require_once "lib/events.php";
    if ($session['user']['specialinc'] != "" || httpget("eventhandler")) {
        $in_event = handle_event("travel", "runmodule.php?module=cities&city=" . urlencode($city) . "&d={$danger}&continue=1&", "Travel");
        if ($in_event) {
            addnav("Continue", "runmodule.php?module=cities&op=travel&city=" . urlencode($city) . "&d={$danger}&continue=1");
            module_display_events("travel", "runmodule.php?module=cities&city=" . urlencode($city) . "&d={$danger}&continue=1");
            page_footer();
        }
    }
    if ($op == "travel") {
        $args = modulehook("count-travels", array('available' => 0, 'used' => 0));
        $free = max(0, $args['available'] - $args['used']);
        if ($city == "") {
            require_once "lib/villagenav.php";
            page_header("Travel");
            //modulehook("collapse{", array("name"=>"traveldesc"));
            output("`%Travelling the world can be a dangerous occupation.");
            output("Although other villages might offer things not found in your current one, getting from village to village is no easy task, and might subject you to various dangerous creatures or brigands.");
            output("Be sure you're willing to take on the adventure before you set out, as not everyone arrives at their destination intact.");
            output("Also, pay attention to the signs, some roads are safer than others.`n");
            //modulehook("}collapse");
            addnav("Forget about it");
            villagenav();
            modulehook("pre-travel");
            if (!($session['user']['superuser'] & SU_EDIT_USERS) && $session['user']['turns'] <= 0 && $free == 0) {
                // this line rewritten so as not to clash with the hitch module.
                output("`nYou don't feel as if you could face the prospect of walking to another city today, it's far too exhausting.`n");
            } else {
                addnav("Travel");
                modulehook("travel");
            }
            module_display_events("travel", "runmodule.php?module=cities&city=" . urlencode($city) . "&d={$danger}&continue=1");
            page_footer();
        } else {
            if ($continue != "1" && $su != "1" && !get_module_pref("paidcost")) {
                set_module_pref("paidcost", 1);
                if ($free > 0) {
                    // Only increment travel used if they are still within
                    // their allowance.
                    set_module_pref("traveltoday", get_module_pref("traveltoday") + 1);
                    //do nothing, they're within their travel allowance.
                } elseif ($session['user']['turns'] > 0) {
                    $session['user']['turns']--;
                } else {
                    output("Hey, looks like you managed to travel with out having any forest fights.  How'd you swing that?");
                    debuglog("Travelled with out having any forest fights, how'd they swing that?");
                }
            }
            // Let's give the lower DK people a slightly better chance.
            $dlevel = cities_dangerscale($danger);
            if (e_rand(0, 100) < $dlevel && $su != '1') {
                //they've been waylaid.
                if (module_events("travel", get_module_setting("travelspecialchance"), "runmodule.php?module=cities&city=" . urlencode($city) . "&d={$danger}&continue=1&") != 0) {
                    page_header("Something Special!");
                    if (checknavs()) {
                        page_footer();
                    } else {
                        // Reset the special for good.
                        $session['user']['specialinc'] = "";
                        $session['user']['specialmisc'] = "";
                        $skipvillagedesc = true;
                        $op = "";
                        httpset("op", "");
                        addnav("Continue", "runmodule.php?module=cities&op=travel&city=" . urlencode($city) . "&d={$danger}&continue=1");
                        module_display_events("travel", "runmodule.php?module=cities&city=" . urlencode($city) . "&d={$danger}&continue=1");
                        page_footer();
                    }
                }
                $args = array("soberval" => 0.9, "sobermsg" => "`&Facing your bloodthirsty opponent, the adrenaline rush helps to sober you up slightly.", "schema" => "module-cities");
                modulehook("soberup", $args);
                require_once "lib/forestoutcomes.php";
                $sql = "SELECT * FROM " . db_prefix("creatures") . " WHERE creaturelevel = '{$session['user']['level']}' AND forest = 1 ORDER BY rand(" . e_rand() . ") LIMIT 1";
                $result = db_query($sql);
                restore_buff_fields();
                if (db_num_rows($result) == 0) {
                    // There is nothing in the database to challenge you,
                    // let's give you a doppleganger.
                    $badguy = array();
                    $badguy['creaturename'] = "An evil doppleganger of " . $session['user']['name'];
                    $badguy['creatureweapon'] = $session['user']['weapon'];
                    $badguy['creaturelevel'] = $session['user']['level'];
                    $badguy['creaturegold'] = 0;
                    $badguy['creatureexp'] = round($session['user']['experience'] / 10, 0);
                    $badguy['creaturehealth'] = $session['user']['maxhitpoints'];
                    $badguy['creatureattack'] = $session['user']['attack'];
                    $badguy['creaturedefense'] = $session['user']['defense'];
                } else {
                    $badguy = db_fetch_assoc($result);
                    $badguy = buffbadguy($badguy);
                }
                calculate_buff_fields();
                $badguy['playerstarthp'] = $session['user']['hitpoints'];
                $badguy['diddamage'] = 0;
                $badguy['type'] = 'travel';
                $session['user']['badguy'] = createstring($badguy);
                $battle = true;
            } else {
                set_module_pref("paidcost", 0);
                //they arrive with no further scathing.
                $session['user']['location'] = $city;
                redirect("village.php", "Redirected to Village from Multiple Cities module");
            }
        }
    } elseif ($op == "fight" || $op == "run") {
        if ($op == "run" && e_rand(1, 5) < 3) {
            // They managed to get away.
            page_header("Escape");
            output("You set off running through the forest at a breakneck pace heading back the way you came.`n`n");
            $coward = get_module_setting("coward");
            if ($coward) {
                modulehook("cities-usetravel", array("foresttext" => array("In your terror, you lose your way and become lost, losing time for a forest fight.`n`n", $session['user']['location']), "traveltext" => array("In your terror, you lose your way and become lost, losing precious travel time.`n`n", $session['user']['location'])));
            }
            output("After running for what seems like hours, you finally arrive back at %s.", $session['user']['location']);
            addnav(array("Enter %s", $session['user']['location']), "village.php");
            page_footer();
        }
        $battle = true;
    } elseif ($op == "faq") {
        cities_faq();
    } elseif ($op == "") {
        page_header("Travel");
        output("A divine light ends the fight and you return to the road.");
        addnav("Continue your journey", "runmodule.php?module=cities&op=travel&city=" . urlencode($city) . "&continue=1&d={$danger}");
        module_display_events("travel", "runmodule.php?module=cities&city=" . urlencode($city) . "&d={$danger}&continue=1");
        page_footer();
    }
    if ($battle) {
        page_header("You've been waylaid!");
        require_once "battle.php";
        if ($victory) {
            require_once "lib/forestoutcomes.php";
            forestvictory($newenemies, "This fight would have yielded an extra turn except it was during travel.");
            addnav("Continue your journey", "runmodule.php?module=cities&op=travel&city=" . urlencode($city) . "&continue=1&d={$danger}");
            module_display_events("travel", "runmodule.php?module=cities&city=" . urlencode($city) . "&d={$danger}&continue=1");
        } elseif ($defeat) {
            require_once "lib/forestoutcomes.php";
            forestdefeat($newenemies, array("travelling to %s", $city));
        } else {
            require_once "lib/fightnav.php";
            fightnav(true, true, "runmodule.php?module=cities&city=" . urlencode($city) . "&d={$danger}");
        }
        page_footer();
    }
}
function onslaught_getenemy()
{
    global $session, $badguy, $battle;
    $sql = "SELECT * FROM " . db_prefix("creatures") . " WHERE 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'] = 'onslaught';
    $session['user']['badguy'] = createstring($badguy);
    $battle = true;
    output("Before you have time to even `iblink,`i let alone call for backup or medical assistance, something rushes up from behind...`n`nYou have encountered %s!`n`n", $badguy['creaturename']);
}