function mutemod_domute($id)
{
    global $session;
    $op = httpget('op');
    if (is_module_active("biocomment") && httpget('refresh')) {
        return false;
    }
    if ($op == "mute") {
        set_module_pref("muted", 1, false, $id);
        modulehook("mute", array("userid" => $id, "staffid" => $session['user']['acctid'], "when" => date("Y-m-d H:i:s")));
        output("`n`\$This player has now been muted!");
        output("`nThis will last until it is lifted, by you or another member of staff!`0`n");
    } elseif ($op == "unmute") {
        set_module_pref("muted", 0, false, $id);
        output("`n`\$This player has now been unmuted!");
        output("`nThey can talk again!`0`n");
    } elseif ($op == "tempmute") {
        set_module_pref("tempmute", 1, false, $id);
        modulehook("tempmute", array("userid" => $id, "staffid" => $session['user']['acctid'], "length" => 1, "when" => date("Y-m-d H:i:s")));
        output("`n`\$This player has now been muted temporarily!");
        output("`nThey cannot talk until the next new day!`0`n");
    } elseif ($op == "untempmute") {
        set_module_pref("tempmute", 0, false, $id);
        output("`n`\$This player has now been unmuted (from a temporary mute)!");
        output("`nThey can talk again!`0`n");
    } elseif ($op == "exttempmute") {
        $tmuted = get_module_pref("tempmute", false, $id) + 1;
        set_module_pref("tempmute", $tmuted, false, $id);
        modulehook("tempmute", array("userid" => $id, "staffid" => $session['user']['acctid'], "length" => $tmuted, "when" => date("Y-m-d H:i:s")));
        output("`n`\$This player´s tempory mute has been extended!");
        output("`nThey cannot talk until %s days have passed!`0`n", $tmuted);
    }
}
function cakeordeath_run()
{
    global $session;
    page_header("Cake Or Death");
    switch (httpget("op")) {
        case "examine":
            // Tell the player what the deal with Cake Or Death is
            $counter = number_format(get_module_setting("counter"));
            output("`0A shiny wooden table sits back from the main street.  Behind it, a man sits idly reading the Improbable Island Enquirer.  Before him, sat on the table, is a large sponge cake.  Above him is a banner, displaying the name of his game:`b'`5Cake`0 or `4Death!`0'`b`n`nHe sees you pondering the sign, and calls over to you.  `b'`5Cake`0 or `4Death!`0  `b`5Cake`0 or `4Death!`0' he cries.  'Ninety-nine per cent chance of `b`5Cake`0`b!'`n`nIt's not often that an immaculately-dressed gentleman with glowing green eyes offers you a 99% chance of cake.  What would you like to do?");
            //add navs
            addnav("CAKE!", "runmodule.php?module=cakeordeath&op=play");
            addnav("Back away slowly", "village.php");
            break;
        case "play":
            $counter = get_module_setting("counter");
            addnav("Back to the Outpost", "village.php");
            if ($counter > 0) {
                output("The green-eyed gentleman hands you a slice of cake, on a paper plate.  You thank him, and walk away merrily wolfing down your prize.`n`nYou feel `5Full Of Cake!`0");
                set_module_setting("counter", get_module_setting("counter") - 1);
                apply_buff('tastycake', array("name" => "`5Full Of Cake`0", "rounds" => 10, "atkmod" => 1.1, "defmod" => 1.1, "roundmsg" => "`5The cake you ate earlier has boosted your energy!`n", "schema" => "module-cakeordeath"));
            }
            if ($counter <= 0) {
                output("The green-eyed gentleman hands you a slice of cake, on a paper plate.  You thank him, and walk away merrily wolfing down your prize.`n`nYou feel `5Full Of Cake!`0`n`nMoments later, the slow-acting poison starts to take effect.  The world begins to melt in front of you.  Grey spots dance on the edges of your vision.  Behind you, a green-eyed monster offers you another slice of cake, laughing and pointing.`n`nYou curse your luck as the hallucinations begin to kick in.");
                set_module_setting("counter", 100);
                apply_buff('failcake', array("name" => "`5Full Of FailCake`0", "rounds" => -1, "regen" => -10, "startmsg" => "`5You are walking on pink icing.  The sky is made of jam.  Your eyes are two cherries.  That cake was awesome.`0`n", "roundmsg" => "`5The poisoned cake saps your strength, and you lose ten hitpoints!`0`n", "schema" => "module-cakeordeath"));
                if (is_module_active("medals")) {
                    require_once "modules/medals.php";
                    medals_award_medal("failcake", "Failcake Fancier", "This player was unfortunate at the Cake or Death stand...", "medal_failcake.png");
                }
            }
            break;
    }
    page_footer();
}
function marriage_lovedrinks()
{
    $z = 2;
    $s = get_module_setting('loveDrinksAdd');
    if (is_module_installed('drinks') && $s < $z) {
        $sql = array();
        $ladd = array();
        if ($s < 1) {
            // We use 'lessthan' so more drinks can be packaged with this
            $sql[] = "INSERT INTO " . db_prefix("drinks") . " VALUES (0, 'Love Brew', 1, 25, 5, 0, 0, 0, 20, 0, 5, 15, 0.0, 0, 0, 'Cedrik reaches under the bar, pulling out a purple cupid shaped bottle... as he pours it into a crystalline glass, the glass shines and he puts a pineapple within the liquid... \"Here, have a Love Brew..\" says Cedrik.. and as you try it, you feel uplifted!', '`%Love Brew', 12, 'You remember love..', 'Despair sets in.', '1.1', '.9', '1.5', '0', '', '', '')";
            $ladd[] = "Love Brew";
        }
        if ($s < 2) {
            // We use 'lessthan' so more drinks can be packaged with this
            $sql[] = "INSERT INTO " . db_prefix("drinks") . " VALUES (0, 'Heart Mist', 1, 25, 5, 0, 0, 0, 20, 0, 5, 15, 0.0, 0, 0, 'Cedrik grabs for a rather garish looking bottle on the shelf behind him... as he pours it into a large yellow mug, the porcelain seems to dissolve.. ooh er.. he puts a tomato within the sweet smelling gunk... \"Here, have a Heart Mist..\" says Cedrik.. and as you try it, you see symbols of love!', '`\$Heart Mist', 18, '`%Misty hearts fly around you..', '`#The sky falls...', '1.1', '.9', '1.5', '0', '', '', '')";
            $ladd[] = "Heart Misy";
        }
        foreach ($sql as $val) {
            db_query($val);
        }
        foreach ($ladd as $val) {
            $sql = "SELECT * FROM " . db_prefix("drinks") . " WHERE name='{$val}' ORDER BY costperlevel";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            set_module_objpref('drinks', $row['drinkid'], 'loveOnly', 1, 'marriage');
        }
        set_module_setting('loveDrinksAdd', $z);
        output("`n`c`b`^Marriage Module - Drinks have been added to the Loveshack`0`b`c");
    } elseif (!is_module_active('drinks')) {
        set_module_setting('loveDrinksAdd', 0);
    }
}
function marriage_install()
{
    if (!is_module_active('marriage')) {
        output_notl("`n`c`b`QMarriage Module - Installed`0`b`c");
    } else {
        output_notl("`n`c`b`QMarriage Module - Updated`0`b`c");
    }
    module_addhook("drinks-text");
    module_addhook("drinks-check");
    module_addhook("moderate");
    module_addhook("newday");
    module_addhook("changesetting");
    module_addhook_priority("footer-inn", 1);
    module_addhook("village");
    module_addhook("footer-hof");
    module_addhook("superuser");
    module_addhook("footer-oldchurch");
    module_addhook("footer-gardens");
    module_addhook("delete_character");
    //module_addhook("charstats");
    module_addhook("faq-toc");
    module_addhook("biostat");
    module_addhook("allprefs");
    module_addhook("allprefnavs");
    if ($SCRIPT_NAME == "modules.php") {
        $module = httpget("module");
        if ($module == "marriage") {
            require_once "modules/marriage/lovedrinks.php";
            marriage_lovedrinks();
        }
    }
    return true;
}
function ecs_load_module_dependencies()
{
    if (is_module_active('econsult')) {
        require_once get_stylesheet_directory() . '/modules/econsult/acf_export/econsult-acf-fields.php';
    }
    if (is_module_active('testimonials')) {
        require_once get_stylesheet_directory() . '/modules/testimonials/acf-field.php';
    }
}
function letteropener_install()
{
    if (!is_module_active('letteropener')) {
        output("`2Installing Letter opener Module.`n");
        output("`b`4Be sure to set access for Admin and Moderators from User Settings!`b`n");
    }
    set_module_pref("letteraccess", 1, "letteropener");
    module_addhook("footer-popup");
    module_addhook("superuser");
    return true;
}
function serialisededitor_install()
{
    if (is_module_active('serialisededitor')) {
        output("`c`b`QUpdating 'serialisededitor' Module.`0`b`c`n");
    } else {
        output("`c`b`QInstalling 'serialisededitor' Module.`0`b`c`n");
        $sarray = array('weapon' => 'sword', 'armour' => 'shield', 'horse' => array('saddle' => 'yes', 'saddlebags' => array('clothes' => array('shirt' => 'yes', 'trousers' => 'yes', 'money' => array('gold' => 36363, 'gems' => 32), 'shoes' => 'yes')), 'feed' => 'straw'), 'rucksack' => array('food' => 'sandwiches and biscuits.', 'drink' => '5 cans of lager.'), 'pockets' => array('lint' => 'fluff', 'button' => 'why is there a button in my pocket?'));
        set_module_setting('array', serialize($sarray));
    }
    module_addhook('superuser');
    return TRUE;
}
function translationwizard_install()
{
    module_addhook("superuser");
    module_addhook("header-modules");
    if (is_module_active("translationwizard")) {
        output_notl("`c`b`\$ Module Translationwizard updated`b`c`n`n");
    }
    $wizard = array('tid' => array('name' => 'tid', 'type' => 'int(11) unsigned', 'extra' => 'auto_increment'), 'language' => array('name' => 'language', 'type' => 'varchar(10)'), 'uri' => array('name' => 'uri', 'type' => 'varchar(255)'), 'intext' => array('name' => 'intext', 'type' => 'text'), 'outtext' => array('name' => 'outtext', 'type' => 'text'), 'author' => array('name' => 'author', 'type' => 'varchar(50)'), 'version' => array('name' => 'version', 'type' => 'varchar(50)'), 'key-PRIMARY' => array('name' => 'PRIMARY', 'type' => 'primary key', 'unique' => '1', 'columns' => 'tid'), 'key-one' => array('name' => 'language', 'type' => 'key', 'unique' => '0', 'columns' => 'language,uri'), 'key-two' => array('name' => 'uri', 'type' => 'key', 'unique' => '0', 'columns' => 'uri'));
    require_once "lib/tabledescriptor.php";
    synctable(db_prefix("temp_translations"), $wizard, true);
    return true;
}
function friendlist_install()
{
    if (!is_module_active('friendlist')) {
        output("`n`c`b`QFriend List Module - Installed`0`b`c");
    } else {
        output("`n`c`b`QFriend List Module - Updated`0`b`c");
    }
    module_addhook("checkuserpref");
    module_addhook("faq-toc");
    module_addhook("mailfunctions");
    module_addhook("charstats");
    return true;
}
function worldmapen_dohook($hookname, $args)
{
    global $session;
    // If the cities module is deactivated, we do nothing.
    if (!is_module_active("cities")) {
        return $args;
    }
    if (file_exists("modules/worldmapen/dohook/{$hookname}.php")) {
        require "modules/worldmapen/dohook/{$hookname}.php";
    } else {
        debug("Sorry, I don't have the hook '{$hookname}' programmed.");
    }
    return $args;
}
/**
 * Settings
 * 
 * Provides a more organized preference system. Allows admins to restructure
 * their settings layout easily.
 * 
 * @author Stephen Kise
 * @todo Fix the template preference and cookie manipulation.
 */
function settings_getmoduleinfo()
{
    $info = ['name' => 'Settings', 'author' => '`&`bStephen Kise`b', 'version' => '0.1', 'category' => 'Miscellaneous', 'description' => 'A more organized preference system.', 'download' => 'nope'];
    // is_module_active() apparently only returns true after the module has been
    // encoutered... Just click 'reinstall' to quickly see the settings.
    if (is_module_active('settings') && $info['settings']['rewrite'] == '') {
        $userprefs = db_prefix('module_userprefs');
        $modules = db_prefix('modules');
        $sql = db_query("SELECT DISTINCT mu.modulename, mu.setting, m.formalname\n            FROM {$userprefs} AS mu\n            LEFT JOIN {$modules} AS m ON m.modulename = mu.modulename\n            WHERE setting LIKE 'user_%'");
        $fill = [];
        while ($row = db_fetch_assoc($sql)) {
            $fill["{$row['modulename']}__{$row['setting']}"] = $row['formalname'];
        }
        $info['settings']['rewrite'] = 'Rewrite condition for module settings, textarea| ' . json_encode($fill);
    }
    return $info;
}
function farmhouses_install()
{
    module_addhook("dwellings");
    module_addhook("dwellings-list-type");
    if (!is_module_active('farmhouses')) {
        $sql = "SELECT module FROM " . db_prefix("dwellingtypes") . " WHERE module='farmhouses'";
        $res = db_query($sql);
        if (db_num_rows($res) == 0) {
            $sql = "INSERT INTO " . db_prefix("dwellingtypes") . " (module) VALUES ('farmhouses')";
            db_query($sql);
        }
    }
    $sql = "SELECT typeid FROM " . db_prefix("dwellingtypes") . " WHERE module='farmhouses'";
    $result = db_query($sql);
    $row = db_fetch_assoc($result);
    set_module_setting("typeid", $row['typeid'], "farmhouses");
    return true;
}
function peerpressure_runevent($type)
{
    global $session;
    $session['user']['specialinc'] = "module:peerpressure";
    // For translation reasons, you cannot really substitute in his/her
    // since the gender can change other things
    if ($session['user']['sex']) {
        addnews("`&%s`7 heroically decided to seek out `@The Green Dragon`7 with cheers of encouragement from her peers ringing in her ears.", $session['user']['name']);
    } else {
        addnews("`&%s`7 heroically decided to seek out `@The Green Dragon`7 with cheers of encouragement from his peers ringing in his ears.", $session['user']['name']);
    }
    output("`2Wandering the village, going about your business, you are suddenly surrounded by a group of villagers.");
    output("They wonder why such an experienced adventurer as yourself hasn't slain a dragon yet.");
    output("You mutter some embarrassed excuses but they aren't listening.");
    output("They crowd around you closer, and lift you up on their shoulders.");
    $isforest = 0;
    $vloc = modulehook('validforestloc', array());
    foreach ($vloc as $i => $l) {
        if ($session['user']['location'] == $l) {
            $isforest = 1;
            break;
        }
    }
    if ($isforest || count($vloc) == 0) {
        output("`n`nCheering your name the whole way, they carry you into the forest, and right to the mouth of a cave outside the town!`n`n");
    } else {
        $key = array_rand($vloc);
        output("`n`nCheering your name the whole way, they carry you far into the forest, and right to the mouth of a cave outside the town of %s!`n`n", $key);
        $session['user']['location'] = $key;
    }
    output("Still cheering your name, they put you down and eagerly wait for you to enter and slay that dragon.`n`n");
    output("You know that you'd never live it down if you tried to back out now.");
    output("Swallowing your fear as best you can, you enter the cave.");
    if (is_module_active("dragonplace")) {
        addnav("Enter the cave", "runmodule.php?module=dragonplace&op=cave");
    } else {
        addnav("Enter the cave", "dragon.php?nointro=1");
    }
    $session['user']['specialinc'] = "";
    checkday();
    //increment buffs, newday buffs, and heal... and probably throw people off in general
    $session['user']['specialinc'] = "module:peerpressure";
    apply_buff('peerpressure', array("name" => "`2Heroic Valor", "rounds" => 20, "atkmod" => 1 + get_module_pref("dayspast") / 100, "defmod" => 1 + get_module_pref("dayspast") / 100, "startmsg" => "`2You fight bravely, considering the pressure you're under.", "wearoff" => "`@The Green Dragon`2 has beaten and burnt the bravery out of you.", "schema" => "module-peerpressure"));
}
function strategyhut_run()
{
    global $session;
    $cost = get_module_setting("cost");
    $op = httpget("op");
    page_header("The Strategy Hut");
    output("`5`c`bThe Strategy Hut`b`c");
    if ($op == "") {
        addnav(array("Ask for Advice (`^%s gold`0)", $cost), "runmodule.php?module=strategyhut&op=ask");
        output("`&You enter the hut, to find `6Atrus `&busy at his desk.");
        output("\"`^Well, a young warrior in search of help!");
        output("For a small fee, I will offer advice to you.`3\"`n`n");
        output("`&Hesitantly, you approach the burly warrior.`n`n");
        output("`&You blink a few times before you realize he was actually talking to you.");
        output("`6Atrus `&doesn't seem very patient, so you'd better decide quickly if you want to hear his advice!`n");
    } elseif ($session['user']['gold'] < $cost) {
        output("`&You go through your pockets, searching for money, but you don't have enough.");
        output("After a moment of intense searching, `6Atrus `&starts to scowl, and you decide to leave before he gets annoyed.`n`n");
    } else {
        $session['user']['gold'] -= $cost;
        debuglog("spent {$cost} gold at the strategy hut");
        output("`&You give `6Atrus `^%s gold`7.", $cost);
        output("`&He nods, and thinks for a moment.`n`n");
        $phrases = array("\"`^Heal often, bank often.`3\"", "\"`^Think balance: weapons and armor must be close in level, not enough defense and your first attack will be your last.`3\"", "\"`^Don't be afraid to slum, in the lower DK levels, speed is NOT a priority. Later is different.`3\"", "\"`^That stat bar is your life, when it gets into the yellow zone, heal. When it goes red, pray.`3\"", "\"`^In PvP, pick your targets with care. If not sure, DON'T... or you'll be explaining to {deathoverlord}`^ what happened.`3\"", "\"`^You don't always need to resurrect. There will be times to save favor for emergencies.`3\"", "\"`^If it's a game bug, petition it. If it's a gameplay issue, petition it.`3\"", "\"`^A good offense is not always a good defense, even the strongest players die in the forest.`3\"", "\"`^Confidence is one thing: attacking a God is suicide. Check the bio first.`3\"", "\"`^Keep an open mind and think it through. Only a fool fights blindly.`3\"", "\"`^There is a dragon, and when you are ready, it will be too. Patience.`3\"", "\"`^Travelling between towns can be dangerous. Heal first.`3\"", "\"`^Talk to everyone in all the villages, visit the shops and stalls. Explore. Learn.`3\"", "\"`^Lower DK players die often in the beginning. It happens to all of us.`3\"", "\"`^When you face the dragon, be ready and fully healed... or it will eat you for lunch.`3\"", "\"`^Your mount or familiar is an asset... learn what it can do, and know its limits. *And* yours, as well.`3\"", "\"`^There is no shame in knowing when to run. Better a bruised ego than a visit to {deathoverlord}`^.`3\"", "\"`^Log in ONCE per game day only, or you will be killed repeatedly... and lose experience as a result. There is no safe place.`3\"", "\"`^If you can't resurrect, log off and wait for New Day. You are already dead.`3\"", "\"`^A good player treats his fellows with courtesy and respect. A wise player knows that new friends can help him succeed.`3\"", "\"`^Don't forget to feed your mount or familiar.`3\"");
        $question = e_rand(0, count($phrases) - 1);
        $phrases = translate_inline($phrases);
        $myphrase = $phrases[$question];
        $myphrase = str_replace('{deathoverlord}', getsetting('deathoverlord', '`$Ramius'), $myphrase);
        output_notl("%s`n`n", $myphrase);
        output("`&You ponder his advice for a moment, before thanking him and making your exit.`n`n");
        if (is_module_active("medals")) {
            require_once "modules/medals.php";
            medals_award_medal("strategyhut", "Strategy Seeker", "This player asked for help in the Strategy Hut.", "medal_strategy.png");
        }
    }
    villagenav();
    page_footer();
}
function timedcombat_teach_dohook($hookname, $args)
{
    global $session, $last_timestamp;
    switch ($hookname) {
        case "newday":
            set_module_pref("taughttoday", 0);
            break;
        case "biostat":
            if (httpget('op') == "teachtimedcombat") {
                set_module_pref("able", true, "timedcombat", $args['acctid']);
                debug(get_module_pref("able", "timedcombat", $args['acctid']));
                set_module_pref("taughttoday", 1);
                increment_module_pref("taught");
                output("`bYou have successfully taught this character how to do Timed Combat!`b`n");
                if (is_module_active("medals")) {
                    require_once "modules/medals.php";
                    medals_award_medal("timedcombat_teach", "Time Tutor", "This player taught another player how to do Timed Combat!", "medal_timeteacher.png");
                }
                require_once "lib/systemmail.php";
                $subj = $session['user']['name'] . " taught you a new skill!";
                $body = "You can now perform Timed Combat in fights!  If you time your fight commands correctly, you'll get a double-attack and double-defence bonus!  The bonus applies to everything you do in combat.  Try timing your five-round auto-fights - one correct hit wins you five rounds of extra power, and the same goes for ten-round auto-fighting too!  If you don't want to muck about with counting under your breath, you can ignore the new skill and carry on fighting as you've always done.  Get four perfect hits in a row and you can teach other players!  Have fun!";
                systemmail($args['acctid'], $subj, $body);
            }
            $ret = httpget('ret');
            if ($args['acctid'] != $session['user']['acctid'] && !get_module_pref("taughttoday") && get_module_pref("maxchain", "timedcombat") >= 4) {
                //get the players' chat locations from commentaryinfo.php - it's handy!
                $tloc = get_module_pref("loc", "commentaryinfo");
                $sloc = get_module_pref("loc", "commentaryinfo", $args['acctid']);
                if ($tloc == $sloc && !get_module_pref("able", "timedcombat", $args['acctid'])) {
                    output("This player doesn't know how to do Timed Combat.  You can teach one student per game day.`n`n");
                    addnav("Teach this player the Timed Combat skill", "bio.php?op=teachtimedcombat&char=" . $args['acctid'] . "&ret=" . urlencode($ret));
                }
            }
            break;
    }
    return $args;
}
function supplycrate_use($args)
{
    increment_module_pref("cratesopened", 1, "supplycrates");
    $found = get_module_pref("cratesopened", "supplycrates");
    if (is_module_active("medals")) {
        if ($found > 250) {
            require_once "modules/medals.php";
            medals_award_medal("crate1000", "Supreme Crate Finder", "This player has opened more than 250 Supply Crates!", "medal_crategold.png");
        }
        if ($found > 50) {
            require_once "modules/medals.php";
            medals_award_medal("crate500", "Expert Crate Finder", "This player has opened more than 50 Supply Crates!", "medal_cratesilver.png");
        }
        if ($found > 10) {
            require_once "modules/medals.php";
            medals_award_medal("crate100", "Supreme Crate Finder", "This player has opened more than 10 Supply Crates!", "medal_cratebronze.png");
        }
    }
    $crateables = get_items_with_settings("cratefind");
    $randompool = array();
    foreach ($crateables as $item => $prefs) {
        for ($i = 0; $i < $prefs['cratefind']; $i++) {
            $randompool[] = $item;
        }
    }
    output("You spend a few minutes prying open your Supply Crate.`n");
    $giveitems = array();
    $numitems = e_rand(get_module_setting("minitems", "supplycrates"), get_module_setting("maxitems", "supplycrates"));
    $chosenitems = array_rand($randompool, $numitems);
    foreach ($chosenitems as $key => $poolkey) {
        $item = $randompool[$poolkey];
        $name = $crateables[$item]['verbosename'];
        output("You find a %s!`n", $name);
        give_item($item);
    }
    return $args;
}
function druid_runevent($type, $link)
{
    global $session;
    $session['user']['specialinc'] = "module:druid";
    $op = httpget('op');
    if ($op == "" || $op == "search") {
        output("`n`2You enter a meadow, dominated by the largest `@Oak Tree `2you have ever seen.`n`n");
        output("`6Beneath the tree is a small cottage, an ancient figure standing before it.`n");
        output("`6Despite his elfin features, you instinctively know him to be a `%Druid Priest.`n`n");
        output("`@He offers you a bowl of `^Hearty Broth.");
        output("`@Unsure of his benevolence, what do you do?");
        addnav("Accept the Broth", "forest.php?op=take");
        addnav("Refuse the Broth", "forest.php?op=dont");
    } elseif ($op == "take") {
        $session['user']['specialinc'] = "";
        output("`n`@You take the `^Bowl of Broth`@ and raise it to your lips.");
        output("After a brief hesitation, you drink deeply.");
        output("`@ You feel the `^Broth `@burning within you.`n`n ");
        switch (e_rand(1, 10)) {
            case 1:
                output("`6The broth fills you with ENERGY.`n`n");
                output("You gain some Stamina!`n");
                $session['user']['turns'] += 2;
                break;
            case 2:
                output("`6The broth enhances your vision.`n`n");
                output("You find `^2 Gems `6on the ground!`n");
                debuglog("gained 2 Gems from Druid");
                $session['user']['gems'] += 2;
                break;
            case 3:
                output("`6The broth must have had some oysters in it!`n`n");
                output("`^You gain `^5 charm!");
                $session['user']['charm'] += 5;
                break;
            case 4:
                output("`6The broth fills you with strength!`n`n");
                $hptype = "permanently";
                if (!get_module_setting("carrydk") || is_module_active("globalhp") && !get_module_setting("carrydk", "globalhp")) {
                    $hptype = "temporarily";
                }
                $hptype = translate_inline($hptype);
                output("`6Your maximum hitpoints are `b%s`b `&increased`6 by 1!", $hptype);
                $session['user']['maxhitpoints'] += 1;
                $session['user']['hitpoints'] += 1;
                set_module_pref("extrahps", get_module_pref("extrahps") + 1);
                break;
            case 5:
            case 6:
                output("`6You gag on the foul tasting liquid!`n`n");
                $dkhp = 0;
                while (list($key, $val) = each($session['user']['dragonpoints'])) {
                    if ($val == "hp") {
                        $dkhp++;
                    }
                }
                $maxhitpoints = 10 * $session['user']['level'] + $dkhp * 5;
                suspend_temp_stats();
                if ($session['user']['maxhitpoints'] > $maxhitpoints) {
                    $hptype = "permanently";
                    if (!get_module_setting("carrydk") || is_module_active("globalhp") && !get_module_setting("carrydk", "globalhp")) {
                        $hptype = "temporarily";
                    }
                    $hptype = translate_inline($hptype);
                    $session['user']['maxhitpoints'] -= 1;
                    set_module_pref("extrahps", get_module_pref("extrahps") - 1);
                    output("`6Your maximum hitpoints are `b%s`b `\$decreased`6 by 1!`n", $hptype);
                }
                if ($session['user']['hitpoints'] > 3) {
                    $session['user']['hitpoints'] -= 2;
                    output("`6You `\$lose 2 `6hitpoints and gain some rather bad breath!");
                }
                restore_temp_stats();
                break;
            case 7:
                $expgain = round($session['user']['experience'] * 0.1, 0);
                if ($expgain < 10) {
                    $expgain = 10;
                }
                $session['user']['experience'] += $expgain;
                output("`6 Your faith was well placed, pilgrim!`n`n");
                output("`6You gain `^%s experience`6!`n", $expgain);
                break;
            case 8:
                if ($session['user']['charm'] > 3) {
                    output("`6The broth spills down your new tunic, detracting from your charm!`n`n");
                    output("`6You `\$lose 2 `6charm!");
                    $session['user']['charm'] -= 2;
                } else {
                    output("`6The Elvish broth warms your body and gives your skin a healthy glow.");
                    output("You `^gain 2 `6charm!");
                    $session['user']['charm'] += 2;
                }
                break;
            case 9:
                $loss = round($session['user']['hitpoints'] * 0.7, 0);
                if ($loss > 0 && $session['user']['hitpoints'] > $loss) {
                    output("`6The broth leaves you feeling weakened.`n`n");
                    output("You `\$lose `^%s `6hitpoints!", $loss);
                    $session['user']['hitpoints'] -= $loss;
                    break;
                }
            case 10:
                if ($session['user']['turns'] >= 1) {
                    output("`6The broth drains your ENERGY.`n`n");
                    output("You `\$lose`6 some Stamina!`n");
                    $session['user']['turns'] -= 1;
                } else {
                    output("`6Strangely, the broth has no effect on your tired body.`n`n");
                }
                break;
        }
    } else {
        $session['user']['specialinc'] = "";
        output("`n`@You simply don't trust the old druid and you decline his offer.");
        switch (e_rand(1, 4)) {
            case 1:
                $expgain = round($session['user']['experience'] * 0.05, 0);
                if ($expgain < 3) {
                    $expgain = 3;
                }
                $session['user']['experience'] += $expgain;
                output("As you turn to walk away, the old man begins to take a great offense.");
                output("Before he can fume about your refusal, you act quickly to ease the tension.");
                output("You humbly bow to the Druid, offering soft words of praise and peace as you back away from his sacred place.");
                output("You certainly don't want to upset him and you make your exit as polite as possible!`n`n");
                output("`6You gain `^%s`6 experience from avoiding danger!`n", $expgain);
                break;
            case 2:
                if ($session['user']['charm'] > 3) {
                    output("As you turn to walk away, the Druid is insulted by your refusal and throws the bowl of scalding soup after you.");
                    output("You can almost hear the trees laughing as your clothing is stained with the foul broth.`n`n");
                    output("`6You `\$lose 2 `6charm!");
                    $session['user']['charm'] -= 2;
                } else {
                    output("As you turn to walk away, the Druid goes back to enjoying his broth and simply ignores your passing.");
                }
                break;
            case 3:
                $loss = round($session['user']['hitpoints'] * 0.1, 0);
                output("As you turn to walk away, a loud voice booms in the air around you.");
                output("You dash into the forest, not waiting to see what powers you've offended.");
                if ($loss > 0 && $loss < $session['user']['hitpoints']) {
                    $session['user']['hitpoints'] -= $loss;
                    output("Recklessly trying to escape, you trip on some roots and injure yourself in a graceless fall.");
                    output("`n`6You `\$lose `^%s`6 hitpoints!`n", $loss);
                }
                break;
            case 4:
                output("`n`n`6Fearful for your safety, you run for hours.");
                if ($session['user']['turns'] > 0) {
                    output("`n`nYou `\$lose`6 some Stamina!`n");
                    $session['user']['turns'] -= 1;
                }
                break;
        }
    }
}
function stocks_dohook($hookname, $args)
{
    global $REQUEST_URI;
    global $session;
    $stocks = get_module_setting("victim");
    $capital = getsetting("villagename", LOCATION_FIELDS);
    switch ($hookname) {
        case "village-desc":
            if ($session['user']['location'] != $capital) {
                break;
            }
            $op = httpget("op");
            if ($op == "stocks") {
                // Get rid of the op=stocks bit from the URI
                $REQUEST_URI = preg_replace("/[&?]?op=stocks/", "", $REQUEST_URI);
                $_SERVER['REQUEST_URI'] = preg_replace("/[&?]?op=stocks/", "", $_SERVER['REQUEST_URI']);
                if ($stocks == 0) {
                    output("`n`0You head over to examine the stocks, and wondering how they work, you place your head and hands in the notches for them when SNAP, they clap shut, trapping you inside!`0`n");
                    modulehook("stocksenter");
                } elseif ($stocks != $session['user']['acctid']) {
                    $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid='{$stocks}'";
                    $result = db_query_cached($sql, "stocks");
                    $row = db_fetch_assoc($result);
                    output("`n`0You head over to examine the stocks, and out of compassion, you help %s`0 out of the stocks.  ", $row['name']);
                    output("Wondering how they got in there in the first place, you place your own head and hands in them when SNAP, they clap shut, trapping you inside! `0`n");
                    modulehook("stocksenter");
                }
                set_module_setting("victim", $session['user']['acctid']);
                invalidatedatacache("stocks");
            } else {
                $examine = translate_inline("Examine Stocks");
                if ($stocks == 0) {
                    output("`n`0Next to the stables is an empty set of stocks.");
                    rawoutput(" [<a href='village.php?op=stocks'>{$examine}</a>]");
                    output_notl("`0`n");
                    addnav("", "village.php?op=stocks");
                } elseif ($stocks == $session['user']['acctid']) {
                    output("`n`@You are now stuck in the stocks!  All around you, people gape and stare. Small children climb on your back, waving wooden swords, and declaring you to be the slain dragon, with them the victor.  This really grates you because you know you could totally take any one of these kids!  Nearby, artists are drawing caricatures of paying patrons pretending to throw various vegetables at you.`0`n");
                    if (is_module_active("medals")) {
                        require_once "modules/medals.php";
                        medals_award_medal("stocks", "Stock Hog", "This player got stuck in the stocks!", "medal_stockades.png");
                    }
                } else {
                    $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid='{$stocks}'";
                    $result = db_query_cached($sql, "stocks");
                    $row = db_fetch_assoc($result);
                    output("`n`0Next to the statue is a set of stocks in which `&%s`0 seems to have become stuck!", $row['name']);
                    output_notl(" [");
                    rawoutput("<a href='village.php?op=stocks'>{$examine}</a>");
                    output_notl("]`0`n");
                    addnav("", "village.php?op=stocks");
                }
            }
            break;
        case "dragonkill":
        case "namechange":
            if ($stocks == $session['user']['acctid']) {
                invalidatedatacache("stocks");
            }
            break;
    }
    return $args;
}
function racekittymorph_checkcity()
{
    global $session;
    $race = "Kittymorph";
    $city = "Kittania";
    if ($session['user']['race'] == $race && is_module_active("cities")) {
        //if they're this race and their home city isn't right, set it up.
        if (get_module_pref("homecity", "cities") != $city) {
            //home city is wrong
            set_module_pref("homecity", $city, "cities");
        }
    }
    return true;
}
function pointstransfer_run()
{
    global $session;
    require_once "lib/systemmail.php";
    page_header("Hunter's Lodge");
    $op = httpget("op");
    $mint = get_module_setting("mint");
    addnav("L?Return to the Lodge", "lodge.php");
    if ($op == "") {
        $allowed = pointstransfer_pointscheck();
        if ($allowed < $mint) {
            output("`7.J. C. Petersen smiles at your generosity, but leaves the forms where they are.");
            $sallowed = ($allowed > 0 ? "`@" : "`\$") . $allowed;
            if (is_module_active("titlechange")) {
                output("`n`n\"`&I'm sorry, but counting any points used towards title changes, you have %s`& points available, which isn't enough for a transfer.", $sallowed);
            } else {
                output("`n`n\"`&I'm sorry, but you have %s`& points available, which isn't enough for a transfer.", $sallowed);
            }
            if ($mint) {
                output("You need at least `@%s`& points available.`7\"", $mint);
            } else {
                output_notl("`7\"");
            }
        } else {
            output("`7J. C. Petersen smiles at your generosity, and pulls out a form.");
            if (is_module_active("titlechange")) {
                output("`n`n\"`&Including any points used towards title changes, you have `@%s`& points available.", $allowed);
            } else {
                output("`n`n\"`&You have `@%s`& points available.", $allowed);
            }
            if ($mint) {
                output("You have the `@%s`& points needed for a minimum transfer.", $mint);
            }
            output("How many points would you like to transfer, and to whom?`7\"");
            $amount = get_module_pref("amount");
            $target = get_module_pref("target");
            $anon = get_module_pref("anon");
            $note = get_module_pref("note");
            $target = color_sanitize($target);
            rawoutput("<form action='runmodule.php?module=pointstransfer&op=confirm' method='POST'>");
            addnav("", "runmodule.php?module=pointstransfer&op=confirm");
            output("`n`nPoints: ");
            rawoutput("<input name='amount' width='8' value={$amount}>");
            output("`n`nRecipient: ");
            rawoutput("<input name='target' value={$target}>");
            output("`n`nAnonymous Transfer: ");
            rawoutput("<select name='anon'>");
            $no = translate_inline("No");
            $yes = translate_inline("Yes");
            rawoutput("<option value='0'" . ($anon == 0 ? " selected" : "") . ">{$no}</option>");
            rawoutput("<option value='1'" . ($anon == 1 ? " selected" : "") . ">{$yes}</option>");
            rawoutput("</select>");
            output("`n`nOptional Note:");
            rawoutput("<input size='75' name='note' value={$note}>");
            output_notl("`n`n");
            $click = translate_inline("Confirm");
            rawoutput("<input type='submit' class='button' value='{$click}'>");
            rawoutput("</form>");
        }
    } elseif ($op == "confirm") {
        $amount = abs((int) httppost("amount"));
        $target = httppost("target");
        $anon = httppost("anon");
        $note = preg_replace("/[`][bic]/", "", stripslashes(httppost("note")));
        set_module_pref("amount", $amount);
        set_module_pref("target", $target);
        set_module_pref("anon", $anon);
        set_module_pref("note", $note);
        if (!$amount) {
            output("`7J. C. Petersen gives you an odd look.");
            output("`n`n\"`&Why would you give someone zero points?");
            output("Perhaps you should try again when you're thinking more clearly?`7\"");
            addnav("Try Again", "runmodule.php?module=pointstransfer");
        } elseif ($amount < $mint) {
            output("`7J. C. Petersen gives you an odd look.");
            output("`n`n\"`&I'm sorry, but you need to donate at least `@%s`& points.", $mint);
            output("Perhaps you should try again, giving more?`7\"");
            addnav("Try Again", "runmodule.php?module=pointstransfer");
        } elseif ($amount > pointstransfer_pointscheck()) {
            output("`7J. C. Petersen gives you an odd look.");
            output("`n`n\"`&I'm sorry, but you don't have `@%s`& points to give.", $amount);
            output("Perhaps you should try again with less, or donate more?`7\"");
            addnav("Try Again", "runmodule.php?module=pointstransfer");
        } else {
            $newtarget = "";
            for ($x = 0; $x < strlen($target); $x++) {
                $newtarget .= substr($target, $x, 1) . "%";
                //Eric rocks.
            }
            $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE name LIKE '%" . addslashes($newtarget) . "' AND locked=0";
            $result = db_query($sql);
            if (!db_num_rows($result)) {
                output("`7J. C. Petersen gives you an odd lock.");
                output("`n`n\"`&I'm sorry, but I don't know anyone by that name.");
                output("Perhaps you should try again?`7\"");
                addnav("Try Again", "runmodule.php?module=pointstransfer");
            } elseif (db_num_rows($result) > 50) {
                output("`7J. C. Petersen gives you an odd lock.");
                output("`n`n\"`&I'm sorry, but there's way too many people who might go by that name.");
                output("Perhaps you should narrow it down, next time?`7\"");
                addnav("Try Again", "runmodule.php?module=pointstransfer");
            } elseif (db_num_rows($result) > 1) {
                rawoutput("<form action='runmodule.php?module=pointstransfer&op=send' method='POST'>");
                addnav("", "runmodule.php?module=pointstransfer&op=send");
                addnav("Start Over", "runmodule.php?module=pointstransfer");
                output("`7J. C. Petersen looks at you.");
                output("`n`n\"`&There's a few people I know by that name.");
                output("Tell me which one you mean, and I'll send those points right off.`7\"");
                output("`n`nPoints: `@%s`7", $amount);
                output("`n`nRecipient: ");
                rawoutput("<select name='target'>");
                for ($i = 0; $i < db_num_rows($result); $i++) {
                    $row = db_fetch_assoc($result);
                    $name = $row['name'];
                    rawoutput("<option value='{$name}'>" . full_sanitize($name) . "</option>");
                }
                rawoutput("</select>");
                output("`n`nAnonymous Transfer: `&%s`7", $anon ? "Yes" : "No");
                output("`n`nOptional Note: `&%s`7", $note);
                output_notl("`n`n");
                $send = translate_inline("Send");
                rawoutput("<input type='submit' class='button' value='{$send}'>");
                rawoutput("</form>");
            } else {
                addnav("Start Over", "runmodule.php?module=pointstransfer");
                $row = db_fetch_assoc($result);
                $name = $row['name'];
                output("`7J. C. Petersen smiles at you.");
                output("`n`n\"`&This all looks to be in order to me.");
                output("This is what you meant, right?`7\"");
                output("`n`nPoints: `@%s`7", $amount);
                output("`n`nRecipient: `&%s`7", $name);
                output("`n`nAnonymous Transfer: `&%s`7", $anon ? "Yes" : "No");
                output("`n`nOptional Note: `&%s`7", $note ? $note : "`inone`i");
                output_notl("`n`n");
                rawoutput("<form action='runmodule.php?module=pointstransfer&op=send' method='POST'>");
                addnav("", "runmodule.php?module=pointstransfer&op=send");
                rawoutput("<input type='hidden' value='{$name}' name='target'>");
                $send = translate_inline("Send");
                rawoutput("<input type='submit' class='button' value='{$send}'>");
                rawoutput("</form>");
            }
        }
    } elseif ($op == "send") {
        addnav("Send To Someone Else", "runmodule.php?module=pointstransfer");
        $amount = get_module_pref("amount");
        $target = httppost("target");
        if ($target == $session['user']['name']) {
            output("`7J. C. Petersen gives you a weird look and puts down his pen.");
            output("`n`n\"`&Why would you ever want to transfer points to yourself?");
            output("Perhaps you should try again when you're thinking more clearly?`7\"");
        } else {
            $anon = get_module_pref("anon");
            $note = get_module_pref("note");
            $note = $note ? "`n`nThey also added this note:`n" . $note : "";
            $sql = "SELECT acctid FROM " . db_prefix("accounts") . " WHERE name='{$target}'";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            $targetid = $row['acctid'];
            $sql = "UPDATE " . db_prefix("accounts") . " SET donation=donation+{$amount} WHERE acctid={$targetid}";
            db_query($sql);
            $session['user']['donation'] -= $amount;
            if ($anon) {
                systemmail($targetid, array("`@Donator Points Transfer`0"), array("`2Someone has gifted you with `@%s`2 donator points. %s", $amount, $note));
            } else {
                systemmail($targetid, array("`@Donator Points Transfer`0"), array("`&%s`2 has gifted you with `@%s`2 donator points. %s", $session['user']['name'], $amount, $note));
            }
            debuglog($session['user']['name'] . " sent {$amount} donator points to {$target}" . ($anon ? " anonymously." : "."));
            debuglog($session['user']['name'] . " sent {$amount} donator points to {$target}" . ($anon ? " anonymously." : "."), false, $targetid);
            output("`7J. C. Petersen finishes recording the transfer.");
            output("`n`n\"`&Okay, the points have been sent.");
            output("Have a nice day.`7\"");
        }
    }
    page_footer();
}
function mountprereq_run()
{
    global $session;
    $op = httpget('op');
    $id = httpget("id");
    if ($op == "bestiary") {
        page_header("Bestiary");
        if (get_module_setting('viewactiveonly') == 1) {
            $sql = "SELECT mountname,mountid,mountdkcost FROM " . db_prefix("mounts") . " WHERE mountactive=1 ORDER BY mountdkcost,mountcostgems,mountcostgold";
        } else {
            $sql = "SELECT mountname,mountid,mountdkcost FROM " . db_prefix("mounts") . " ORDER BY mountdkcost,mountcostgems,mountcostgold";
        }
        $result = db_query($sql);
        $end = "";
        if (get_module_pref('viewed') == 0) {
            $wonder = "You briefly wonder why you never noticed this here before.";
            set_module_pref('viewed', 1);
            set_module_pref('vieweddk', 1);
        } elseif (get_module_pref('vieweddk') == 0) {
            $wonder = "It seems to have changed somewhat since you last saw it.";
            $end = "Feeling a little more confident since the last time you were here, you also decide to look up on some of the entries that you previously ignored.";
            set_module_pref('vieweddk', 1);
        } else {
            $wonder = "It does not seem to have changed since you last saw it.";
            $end = "`nAs the list descends down the page, more and more fantasic creatures make their appearance. Feeling a little overwhelmed, you decide to ignore the entries of the beasts that seem out of your league.";
        }
        output("You discover a dusty tome left on a stool. %s `nGingerly, you prise open the heavy cover, and discover a Table of Contents page. How helpful!`n%s", $wonder, $end);
        addnav("View the entry on...");
        for ($i = 0; $i < db_num_rows($result); $i++) {
            $row = db_fetch_assoc($result);
            if ($row['mountdkcost'] <= $session['user']['dragonkills'] && get_module_objpref("mounts", $row['mountid'], "boolshow") != 0) {
                addnav(array("View %s`0", $row['mountname']), "runmodule.php?module=mountprereq&op=browse&id={$row['mountid']}");
            }
        }
        addnav("Close the book");
        addnav("Return from whence you came", "stables.php");
    }
    if ($op == "browse") {
        page_header("Bestiary");
        $sql = "SELECT * FROM " . db_prefix("mounts") . " WHERE mountid='{$id}'";
        $result = db_query_cached($sql, "mountdata-{$id}", 3600);
        if (db_num_rows($result) <= 0) {
            output("You find that the book is actually full of empty pages!");
        } else {
            $mount = db_fetch_assoc($result);
            $buff = unserialize($mount['mountbuff']);
            if (get_module_setting('boolshowcost') == 1) {
                output("`c`&-=%s`&=-`7`c`n`n", $mount['mountname']);
                output("`b`c`#Costs`b`c`7");
                $goldcost = "";
                $gemcost = "";
                $donationcost = "";
                $favorcost = "";
                $upgrade = "";
                if (get_module_objpref("mounts", $id, "favorcost") != 0) {
                    $favorcost = '`n' . get_module_objpref("mounts", $id, "favorcost") . ' `$Favor`7';
                }
                if (get_module_objpref("mounts", $id, "donationcost") != 0) {
                    $donationcost = '`n' . get_module_objpref("mounts", $id, "donationcost") . ' Donation Point(s)';
                }
                if ($mount['mountcostgold'] != "" && $mount['mountcostgold'] != 0) {
                    $goldcost = '`n' . $mount['mountcostgold'] . ' `^Gold`7';
                }
                if ($mount['mountcostgems'] != "" && $mount['mountcostgems'] != 0) {
                    $gemcost = '`n' . $mount['mountcostgems'] . ' `%Gem(s)`7';
                }
                if ($mount['mountfeedcost'] != "" && $mount['mountfeedcost'] != 0 && $buff['rounds'] > 0) {
                    $cost = $mount['mountfeedcost'] * $session['user']['level'];
                    $feedcost = '`nFeeding costs ' . $cost . ' `6Gold`7';
                }
                output("`c{$goldcost} {$gemcost} {$favorcost} {$donationcost} {$feedcost}`c`n");
            }
            if (get_module_objpref("mounts", $id, "buffatkmod") == "") {
                if ($buff['atkmod'] != "" && get_module_setting('toggleatkmod') == 1) {
                    $var = mountprereq_calc($buff['atkmod']);
                    $atkmod = round($var * 100 - 100, 2);
                    if ($atkmod != 0) {
                        if ($atkmod > 0) {
                            $sign1 = '+';
                        }
                        $atk = '`n' . $sign1 . $atkmod . '% attack';
                    }
                }
            } else {
                $atk = "`nAttack Modifier: " . get_module_objpref("mounts", $id, "buffatkmod");
            }
            if (get_module_objpref("mounts", $id, "buffdefmod") == "") {
                if ($buff['defmod'] != "" && get_module_setting('toggledefmod') == 1) {
                    $var0 = mountprereq_calc($buff['defmod']);
                    $defmod = round($var0 * 100 - 100, 2);
                    if ($defmod != 0) {
                        if ($defmod > 0) {
                            $sign2 = '+';
                        }
                        $def = '`n' . $sign2 . $defmod . '% defense';
                    }
                }
            } else {
                $def = "`nDefense Modifier: " . get_module_objpref("mounts", $id, "buffdefmod");
            }
            if (get_module_objpref("mounts", $id, "buffregen") == "") {
                if ($buff['regen'] != "" && get_module_setting('toggleregen') == 1) {
                    $var1 = round(mountprereq_calc($buff['regen']), 0);
                    if ($var1 != 0) {
                        if ($var1 > 0) {
                            $sign3 = '+';
                        }
                        $regen = '`n' . $sign3 . $var1 . 'HP regeneration per round';
                    }
                }
            } else {
                $regen = "`nRegen: " . get_module_objpref("mounts", $id, "buffregen");
            }
            if (get_module_objpref("mounts", $id, "buffdamageshield") == "") {
                if ($buff['damageshield'] != "" && get_module_setting('toggledamageshield') == 1) {
                    $var2 = mountprereq_calc($buff['damageshield']);
                    $damageshieldmod = round($var2 * 100, 2);
                    if ($damageshieldmod != 0) {
                        if ($damageshieldmod >= 0) {
                            $sign4 = '+';
                        }
                        $damageshield = '`n' . $sign4 . $damageshieldmod . '% damage shield';
                    }
                }
            } else {
                $damageshield = "`nDamageshield: " . get_module_objpref("mounts", $id, "buffdamageshield");
            }
            if (get_module_objpref("mounts", $id, "bufflifetap") == "") {
                if ($buff['lifetap'] != "" && get_module_setting('togglelifetap') == 1) {
                    $var3 = mountprereq_calc($buff['lifetap']);
                    $lifetapmod = round($var3 * 100, 2);
                    if ($lifetapmod != 0) {
                        if ($lifetapmod >= 0) {
                            $sign5 = '+';
                        }
                        $lifetap = '`n' . $sign5 . $lifetapmod . '% HP leech';
                    }
                }
            } else {
                $lifetap = "`nLifetap: " . get_module_objpref("mounts", $id, "bufflifetap");
            }
            if (get_module_objpref("mounts", $id, "buffminioncount") == "") {
                if ($buff['minioncount'] != "" && get_module_setting('toggleminioncount') == 1) {
                    $var4 = round(mountprereq_calc($buff['minioncount']), 0);
                    if ($var4 != 0) {
                        $minioncount = '`n' . $var4 . ' attack(s) maximum per round';
                    }
                }
            } else {
                $minioncount = "`nMaximum number of Attacks per round: " . get_module_objpref("mounts", $id, "buffminioncount");
            }
            if (get_module_objpref("mounts", $id, "buffmaxbadguydamage") == "") {
                if ($buff['maxbadguydamage'] != "" && get_module_setting('togglemaxbadguydamage') == 1) {
                    $var5 = round(mountprereq_calc($buff['maxbadguydamage']), 0);
                    if ($var5 != 0) {
                        $maxbadguydamage = '`n' . $var5 . ' maximum damage per attack';
                    }
                }
            } else {
                $maxbadguydamage = "`nMaximum damage per Attack per round: " . get_module_objpref("mounts", $id, "buffmaxbadguydamage");
            }
            if (get_module_objpref("mounts", $id, "buffbadguyatkmod") == "") {
                if ($buff['badguyatkmod'] != "" && get_module_setting('togglebadguyatkmod') == 1) {
                    $var6 = mountprereq_calc($buff['badguyatkmod']);
                    $badguyatk = round($var6 * 100 - 100, 2);
                    if ($badguyatk != 0) {
                        if ($badguyatk >= 0) {
                            $sign6 = '+';
                        }
                        $badguyatkmod = '`n' . $sign6 . $badguyatk . '% enemy attack';
                    }
                }
            } else {
                $badguyatkmod = "`nEnemy Attack Modifier: " . get_module_objpref("mounts", $id, "buffbadguyatkmod");
            }
            if (get_module_objpref("mounts", $id, "buffbadguydefmod") == "") {
                if ($buff['badguydefmod'] != "" && get_module_setting('togglebadguydefmod') == 1) {
                    $var7 = mountprereq_calc($buff['badguydefmod']);
                    $badguydef = round($var7 * 100 - 100, 2);
                    if ($badguydef != 0) {
                        if ($badguydef >= 0) {
                            $sign7 = '+';
                        }
                        $badguydefmod = '`n' . $sign7 . $badguydef . '% enemy defense';
                    }
                }
            } else {
                $badguydefmod = "`nEnemy Defense Modifier: " . get_module_objpref("mounts", $id, "buffbadguydefmod");
            }
            if (get_module_objpref("mounts", $id, "buffbadguydmgmod") == "") {
                if ($buff['badguydmgmod'] != "" && get_module_setting('togglebadguydmgmod') == 1) {
                    $var8 = mountprereq_calc($buff['badguydmgmod']);
                    $badguydmg = round($var8 * 100 - 100, 2);
                    if ($badguydmg != 0) {
                        if ($badguydmg >= 0) {
                            $sign8 = '+';
                        }
                        $badguydmgmod = '`n' . $sign8 . $badguydmg . '% enemy damage modifier';
                    }
                }
            } else {
                $badguydmgmod = "`nEnemy Damage Modifier: " . get_module_objpref("mounts", $id, "badguydmgmod");
            }
            if (get_module_objpref("mounts", $id, "buffinv") == "") {
                if ($buff['invulnerable'] != "" && get_module_setting('toggleinv') == 1) {
                    $var9 = round(mountprereq_calc($buff['invulnerable']), 0);
                    if ($var9 == 1) {
                        $var9 = "INVULNERABLE!!";
                        $inv = '`n' . $var9;
                    }
                }
            } else {
                $inv = "`nInvulnerability: " . get_module_objpref("mounts", $id, "buffinv");
            }
            if (get_module_objpref("mounts", $id, "ffs") == "") {
                if ($mount['mountforestfights'] != "" && $mount['mountforestfights'] != 0 && get_module_setting('toggleffs') == 1) {
                    $ffs = '`n' . $mount[mountforestfights] . ' extra turn(s) per day';
                }
            } else {
                $ffs = "`nExtra Forest Fights each day: " . get_module_objpref("mounts", $id, "ffs");
            }
            if (get_module_objpref("mounts", $id, "mountspd", "speed") < 0) {
                $spd = '`n' . abs(get_module_objpref("mounts", $id, "mountspd", "speed")) . ' Agility penalty';
            } elseif (get_module_objpref("mounts", $id, "mountspd", "speed") > 0) {
                $spd = '`n' . get_module_objpref("mounts", $id, "mountspd", "speed") . ' Agility bonus';
            } else {
                $spd = '';
            }
            if (get_module_objpref("mounts", $id, "buffrounds") == "") {
                if ($buff['rounds'] != "" && $buff['rounds'] != 0 && get_module_setting('toggleround') == 1) {
                    $round = $buff['rounds'];
                    if ($round < 0) {
                        $round = 'Permanent';
                    }
                    $rounds = '`n' . $round . ' Rounds';
                }
            } else {
                $rounds = "`nRounds: " . get_module_objpref("mounts", $id, "buffrounds");
            }
            if (get_module_objpref("mounts", $id, "buffname") == "") {
                if ($buff['name'] != "" && get_module_setting('togglename') == 1) {
                    $name = $buff['name'];
                }
            } else {
                $name = get_module_objpref("mounts", $id, "buffname");
            }
            if (is_module_active('mountupgrade') && get_module_setting('boolmountupgrade') == 1 && get_module_objpref("mounts", $id, "upgradeto", "mountupgrade") > 0) {
                $upgradeto = get_module_objpref("mounts", $id, "upgradeto", "mountupgrade");
                $sql = "SELECT mountname FROM " . db_prefix("mounts") . " WHERE mountid='{$upgradeto}'";
                $result = db_query($sql);
                $upgrademount = db_fetch_assoc($result);
                $upgrade = '`n`nupgrades to ' . $upgrademount['mountname'] . '`7';
                if (get_module_objpref("mounts", $id, "upgradedks") == "") {
                    if (get_module_objpref("mounts", $id, "reqdks", "mountupgrade") != "" && get_module_objpref("mounts", $id, "reqdks", "mountupgrade") != 0 && get_module_setting('toggleupgradedks') == 1) {
                        $upgradedks = '`n' . get_module_objpref("mounts", $id, "reqdks", "mountupgrade") . ' DKs required to upgrade';
                    }
                } else {
                    $upgradedks = "`nDKs required for upgrade: " . get_module_objpref("mounts", $id, "upgradedks");
                }
                if (get_module_objpref("mounts", $id, "upgradelevels") == "") {
                    if (get_module_objpref("mounts", $id, "reqlevels", "mountupgrade") != "" && get_module_objpref("mounts", $id, "reqlevels", "mountupgrade") != 0 && get_module_setting('toggleupgradelevels') == 1) {
                        $upgradelevels = '`n' . get_module_objpref("mounts", $id, "reqdks", "mountupgrade") . ' levelss required to upgrade';
                    }
                } else {
                    $upgradelevels = "`nLevels required for upgrade: " . get_module_objpref("mounts", $id, "upgradelevels");
                }
                if (get_module_objpref("mounts", $id, "upgradedays") == "") {
                    if (get_module_objpref("mounts", $id, "reqdays", "mountupgrade") != "" && get_module_objpref("mounts", $id, "reqdays", "mountupgrade") != 0 && get_module_setting('toggleupgradedays') == 1) {
                        $upgradedays = '`n' . get_module_objpref("mounts", $id, "reqdays", "mountupgrade") . ' Days required to upgrade';
                    }
                } else {
                    $upgradedays = "`nDays required for upgrade: " . get_module_objpref("mounts", $id, "upgradedays");
                }
                if (get_module_objpref("mounts", $id, "upgradeffs") == "") {
                    if (get_module_objpref("mounts", $id, "reqffs", "mountupgrade") != "" && get_module_objpref("mounts", $id, "reqffs", "mountupgrade") != 0 && get_module_setting('toggleupgradeffs') == 1) {
                        $upgradeffs = '`n' . get_module_objpref("mounts", $id, "reqffs", "mountupgrade") . ' forest fights required to upgrade';
                    }
                } else {
                    $upgradeffs = "`nForest fights required for upgrade: " . get_module_objpref("mounts", $id, "upgradeffs");
                }
                if (getmodulesetting('toggleupgradeview') && get_module_objpref("mounts", $id, "boolshowupgrade") == 1) {
                    addnav("View Upgrade");
                    addnav(array("View %s`0", $upgrademount['mountname']), "runmodule.php?module=mountprereq&op=browse&id={$upgradeto}");
                }
            }
            output("`n`b`c`@Special Abilities`7`b`c");
            output("`c`7{$name}`7 {$rounds} {$atk} {$def} {$regen} {$damageshield} {$lifetap} {$minioncount} {$maxbadguydamage} {$badguyatkmod} {$badguydefmod} {$badguydmgmod} {$ffs} {$spd} {$upgrade} {$upgradedks} {$upgradelevels} {$upgradedays} {$upgradeffs}`c`n");
            output("`n`c`b`^Ownership Requirements`7`b`c");
            $dkreq = "";
            $charmreq = "";
            $recareq = "";
            $sexreq = "";
            $donationreq = "";
            $favorreq = "";
            $alignreq = "";
            if ($mount['mountdkcost'] != 0 && $mount['mountdkcost'] != "") {
                $dkreq = "`nDragonkills: " . $mount['mountdkcost'];
            }
            if (get_module_objpref("mounts", $id, "charmreq") != 0) {
                $charmreq = "`nCharm: " . get_module_objpref("mounts", $id, "charmreq");
            }
            if (get_module_objpref("mounts", $id, "racereq") != "") {
                $racereq = "`n" . get_module_objpref("mounts", $id, "racereq") . " `0Race";
            }
            if (get_module_objpref("mounts", $id, "sexreq") != 2) {
                if (get_module_objpref("mounts", $id, "sexreq") == 0) {
                    $sex = "`!Male`7";
                } else {
                    $sex = "`rFemale`7";
                }
                $sexreq = "`n{$sex} owners";
            }
            if (get_module_objpref("mounts", $id, "favorreq") != 0) {
                $favorreq = "`nFavor: " . get_module_objpref("mounts", $id, "favorreq");
            }
            if (get_module_objpref("mounts", $id, "donationreq") != 0) {
                $donationreq = "`nDonation Points: " . get_module_objpref("mounts", $id, "donationreq");
            }
            if (is_module_active('alignment') && get_module_objpref("mounts", $id, "boolalign") != 0) {
                if (get_module_objpref("mounts", $id, "boolalign") == 1) {
                    $align = "`nBelow `4" . get_module_objpref("mounts", $id, "alignlo") . "`7 alignment.`n";
                } elseif (get_module_objpref("mounts", $id, "boolalign") == 3) {
                    $align = "`nAbove `@" . get_module_objpref("mounts", $id, "alignhi") . "`7 alignment.`n";
                } else {
                    $align = "`nBetween `4" . get_module_objpref("mounts", $id, "alignlo") . "`7 and `@" . get_module_objpref("mounts", $id, "alignhi") . "`7 alignment.";
                }
            }
            output("`c{$dkreq} {$charmreq} {$favorreq} {$alignreq} {$donationreq} {$racereq} {$sexreq}`7 {$align}`0`c`n");
            if (is_module_active('mountrarity') && get_module_setting('boolmountrarity') == 1 && get_module_objpref("mounts", $id, "rarity", "mountrarity") != 100) {
                $rare = get_module_objpref("mounts", $id, "rarity", "mountrarity");
                if ($rare <= 20) {
                    $raretext = '`b`$extremely rare`b`7!!';
                } elseif ($rare <= 40) {
                    $raretext = '`@rare`7!';
                } elseif ($rare <= 60) {
                    $raretext = 'uncommon.';
                } elseif ($rare <= 80) {
                    $raretext = 'common.';
                } else {
                    $raretext = 'very common.';
                }
                output("`n`c`b`&Miscellaneous Infomation`c`b");
                output("`c`7The`& %s`7 is %s`c`n", $mount['mountname'], $raretext);
            }
            if (get_module_objpref("mounts", $id, "outputtext") != "") {
                output("`n`c`Q`i%s`7`i`c`n", stripslashes(get_module_objpref("mounts", $id, "outputtext")));
            }
            addnav("Go Back");
            addnav("Flip back to the Contents page", "runmodule.php?module=mountprereq&op=bestiary");
        }
    }
    page_footer();
}
function get_module_pref($name, $module = false, $user = false)
{
    global $module_prefs, $mostrecentmodule, $session;
    if ($module === false) {
        $module = $mostrecentmodule;
    }
    if ($user === false) {
        if (isset($session['user']['loggedin']) && $session['user']['loggedin']) {
            $user = $session['user']['acctid'];
        } else {
            $user = 0;
        }
    }
    if (isset($module_prefs[$user][$module][$name])) {
        return $module_prefs[$user][$module][$name];
    }
    //load here, not before
    load_module_prefs($module, $user);
    //check if *now* it's loaded
    if (isset($module_prefs[$user][$module][$name])) {
        return $module_prefs[$user][$module][$name];
    }
    if (!is_module_active($module)) {
        return NULL;
    }
    //we couldn't find this elsewhere, load the default value if it exists.
    $info = get_module_info($module);
    if (isset($info['prefs'][$name])) {
        if (is_array($info['prefs'][$name])) {
            $v = $info['prefs'][$name][0];
            $x = explode("|", $v);
        } else {
            $x = explode("|", $info['prefs'][$name]);
        }
        if (isset($x[1])) {
            set_module_pref($name, $x[1], $module, $user);
            return $x[1];
        }
    }
    return NULL;
}
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 jewelmonster_runevent($type, $link)
{
    global $session;
    $op = httpget('op');
    $session['user']['specialinc'] = "module:jewelmonster";
    $battle = false;
    switch ($op) {
        case "":
        case "search":
            $count = 0;
            if (is_module_active("jeweler")) {
                $count = get_module_pref("totalheld", "jeweler");
            }
            output("`3While searching for gems and gold, you feel a shadow fall upon you.");
            output("With a terrible sense of foreboding, you raise your head.");
            output("The creature before your eyes terrifies you to the bone.");
            output("`3From a scaly neck emerges the %s's head of horror, huge tusks leaning towards you in a menacing manner.`n`n", translate_inline(get_module_setting("name")));
            if ($count > 0) {
                output("Catching sight of your jeweled adornments, it rears back for a moment, before moving towards you once again and snarling.");
            }
            output("`3Snakes in its hair tell you this fight is very real, and you had best prepare!");
            addnav("Fight", $link . "op=pre");
            break;
        case "pre":
            $op = "fight";
            httpset("op", $op);
            $count = 0;
            if (is_module_active("jeweler")) {
                $count = get_module_pref("totalheld", "jeweler");
            }
            if ($session['user']['dragonkills'] <= get_module_setting("dk")) {
                $count += get_module_setting("grace");
            }
            $hpl = get_module_setting("hploss") * $count;
            if ($count == $session['user']['dragonkills'] || $count == 10) {
                $monhp = round($session['user']['maxhitpoints'] + 10) - $hpl;
                $monatk = $session['user']['attack'] * 1.1;
                $mondef = $session['user']['defense'] * 1.1;
            } else {
                $monhp = round($session['user']['maxhitpoints'] + 40) - $hpl;
                $monatk = round($session['user']['attack']) * 1.2;
                $mondef = round($session['user']['defense']) * 1.2;
            }
            # if we have a too small hp, just set it to something more reasonable.
            if ($monhp < 10) {
                $monhp = $session['user']['maxhitpoints'] + $hpl / 2;
            }
            // even out his strength a bit
            $badguylevel = $session['user']['level'] + 1;
            if ($session['user']['level'] > 9) {
                $monhp *= 1.05;
            }
            if ($session['user']['level'] < 4) {
                $badguylevel--;
            }
            $badguy = array("creaturename" => translate_inline(get_module_setting("name")), "creatureweapon" => translate_inline("Beak of Doom"), "creaturelevel" => $badguylevel, "creaturehealth" => round($monhp), "creatureattack" => $monatk, "creaturedefense" => $mondef, "noadjust" => 1, "diddamage" => 0, "type" => "jewelmonster");
            $session['user']['badguy'] = createstring($badguy);
            break;
    }
    if ($op == "fight") {
        $battle = true;
    }
    if ($battle) {
        include "battle.php";
        if ($victory) {
            output("`n`n`3You have overcome %s!", translate_inline(get_module_setting("name")));
            if (get_module_pref("totalheld", "jeweler") > 0) {
                output("Your jewelry burns your skin, as if to remind you of your narrow escape.`n`n");
            }
            output("You aren't waiting around to see if it is dead or just resting!`n`n");
            if ($session['user']['hitpoints'] <= 0) {
                output("`n`n`^With the last of your energy, you press a piece of cloth to your wounds, stopping your bloodloss before you are completely dead.`n");
                $session['user']['hitpoints'] = 1;
            }
            $exp = round($session['user']['experience'] * get_module_setting("expgain"));
            // even out the gain a bit... it was too huge at the top and pathetic at the bottom
            if ($session['user']['level'] > 9) {
                $exp *= 0.8;
            }
            if ($session['user']['level'] < 6) {
                $exp *= 1.2;
            }
            if ($session['user']['level'] == 1) {
                $exp += 20;
            }
            // to stop people sometimes gaining 2 xp
            $exp = round($exp);
            output("`3The fight earns you `^%s `3experience.`0", $exp);
            $session['user']['experience'] += round($exp);
            $badguy = array();
            $session['user']['badguy'] = "";
            $session['user']['specialinc'] = "";
        } elseif ($defeat) {
            $badguy = array();
            $session['user']['badguy'] = "";
            $session['user']['specialinc'] = "";
            output("`n`n`3With one final crushing blow, %s pins you to the ground.", translate_inline(get_module_setting("name")));
            if ($session['user']['gold'] > 10) {
                output("While you lie there, helpless, its snake hair extricates some of your gold.");
                $lost = round($session['user']['gold'] * 0.2, 0);
                $session['user']['gold'] -= $lost;
                debuglog("lost {$lost} gold to the jewelmonster");
            }
            if (e_rand(0, 2) == 2 && $session['user']['gems'] > 4) {
                output("In several snakes' mouths you see 4 of your precious gems.`0", $cl);
                $session['user']['gems'] -= 4;
                debuglog("lost 4 gems to the jewelmonster");
            }
            output("An evil smile comes across the %s's grotesque face, before it leaves you lying on the ground rather than kill you.", translate_inline(get_module_setting("name")));
            $exp = round($session['user']['experience'] * get_module_setting("expgain"));
            output("With this humiliation, you lose `^%s `3experience.`0", $exp);
            output("You are able to cling to life... barely.`0");
            $session['user']['experience'] -= $exp;
            $session['user']['hitpoints'] = 1;
        } else {
            require_once "lib/fightnav.php";
            if ($type == "forest") {
                fightnav(true, false);
            } else {
                fightnav(true, false, $link);
            }
        }
    }
}
function crying_runevent($type)
{
    global $session;
    $innname = getsetting("innname", LOCATION_INN);
    $op = httpget('op');
    $session['user']['specialinc'] = "module:crying";
    $from = "inn.php?";
    require_once "lib/partner.php";
    $partner = get_partner();
    if ($op == "") {
        output("`7As you are standing in %s, minding your own business, a woman begins to sob loudly.", $innname);
        output("You watch as she walks away from %s`7 and over to where her husband is sitting, crying, \"I lost it, and now HE has lost it too! We shall never afford another ring as beautiful as that one!\"`n`n", getsetting("barkeep", "`tCedrik"));
        output("You watch her as she wrings her hands and cries inconsolably.`n`n");
        output("Your hand strays to the piece of jewelry in your pocket, and you wonder whether you should return the ring to her.");
        output("After all, it might be very valuable, and perhaps you could sell it for gems.");
        output("You struggle with your conscience, wondering what to do.");
        set_module_pref("seentoday", 1);
        addnav("Return the Ring", $from . "op=give");
        addnav("Ignore the Lady", $from . "op=ignore");
        page_footer();
    } elseif ($op == "give") {
        set_module_pref("ring", 0, "breakin");
        $whathappens = e_rand(1, 5);
        output("You approach the lady and gently touch her shoulder.");
        output("As she turns around and faces you with teary eyes, you extend your hand and offer the ring.`n`n");
        output("Her eyes become saucers, and she grabs the ring in gratitude, before throwing her arms about you in ecstatic gratitude.`n`n");
        output("`&\"You are indeed a warrior of true noble heart! Please, accept this gift of my gratitude, and wear it with pride!\"");
        output("`7She grabs your wrist, and around it ties a leather band that carries a tiger's tooth.");
        output("You're a little hesitant to accept such a strange gift, but you don't want to offend her, so you thank her and walk away from her table.");
        set_module_pref("hasbracelet", 1);
        $upmatt = get_module_pref("upmatt");
        // need to check if matthias module exists on this server, and only award astute once
        if (is_module_active("matthias") && $upmatt == 0) {
            $astute = get_module_pref("astuteness", "matthias");
            $astute += 2;
            set_module_pref("astuteness", $astute, "matthias");
            set_module_pref("upmatt", 1);
        }
        if ($whathappens <= 2) {
            // Seth/Violet sees and approves
            output("`n`nFrom the other side of the room, %s`7 is watching.`n`n", $partner);
            if ($session['user']['sex'] == SEX_MALE) {
                output("She beams at you for your kindheartedness.`n`n");
            } else {
                output("He beams at you for your kindheartedness.`n`n");
            }
            output("`&You gain a charm point!");
            $session['user']['charm']++;
        } elseif ($whathappens == 3) {
            // Seth/Violet sees and disapproves
            output("`n`nFrom the other side of the room, %s`7 is watching.`n`n", $partner);
            if ($session['user']['sex'] == SEX_MALE) {
                output("She glares at you in jealous anger.`n`n");
            } else {
                output("He glares at you in jealous anger.`n`n");
            }
            output("You `4lose`7 a charm point!");
            if ($session['user']['charm'] > 0) {
                $session['user']['charm']--;
            }
        } elseif ($whathappens >= 4) {
            output("You are so tremendously happy at her reaction, that you feel fantastic!");
            // gain feelgood vibes (buff)
            apply_buff('feelgood', array("name" => "`%Feelgood Vibes", "rounds" => 15, "wearoff" => "You feel normal again.", "atkmod" => 1.05, "roundmsg" => "Your positivity helps you hit harder!", "schema" => "module-crying"));
        }
        $session['user']['specialinc'] = "";
    } elseif ($op == "ignore") {
        output("`n`7The lady is still sobbing, but hey, you're a heartless warrior, and you don't care. Right?`n");
        $session['user']['specialinc'] = "";
    }
}
function oldman_runevent($type)
{
    global $session;
    // We assume this event only shows up in the forest currently.
    $from = "forest.php?";
    $session['user']['specialinc'] = "module:oldman";
    require_once "lib/partner.php";
    $partner = get_partner();
    $op = httpget('op');
    if ($op == "" || $op == "search") {
        output("`@You encounter a strange old man!`n`n");
        output("He beckons you over to talk with you.");
        output("He looks harmless enough, but you have heard tales of the evil creatures which lurk in this forest disguised as normal people.`n`n");
        addnav("Old Man");
        addnav("Talk with him", $from . "op=talk");
        addnav("Back away", $from . "op=chicken");
    } elseif ($op == "chicken") {
        $session['user']['specialinc'] = "";
        output("`@You back away slowly, and then when you are out of sight, turn and move quickly to another part of the forest.`n`n");
        if (e_rand(1, 2) == 2) {
            output("`@You are quite sure that your paranoia saved your life today.");
        } else {
            output("`@You are quite sure that %s`@ would think you are a wuss for being scared of an old man.", $partner);
            if ($session['user']['sex'] == SEX_MALE) {
                output("Fortunately, she isn't here to see your cowardice.");
            } else {
                output("Fortunately, he isn't here to see your cowardice.");
            }
        }
    } elseif ($op == "talk") {
        // Okay.. now we get to have fun.  Which old man do they get?
        switch (e_rand(1, 5)) {
            case 1:
                // This is the pretty stick.
                $session['user']['specialinc'] = "";
                output("`@As you approach, he pulls out his Pretty Stick, whacks you on the temple, giggles, and runs away!`n`n");
                output("`^You `%gain one`^ charm point!");
                $session['user']['charm']++;
                break;
            case 2:
                // The ugly stick
                $session['user']['specialinc'] = "";
                if ($session['user']['charm'] > 0) {
                    output("`@As you approach, he pulls out his Ugly Stick, whacks you on the nose, giggles, and runs away!`n`n");
                    output("`^You `%lose one`^ charm point!");
                    $session['user']['charm']--;
                } else {
                    output("`@As you approach, he pulls out his Ugly Stick, whacks you on the nose, then gasps as his stick `%loses one`@ charm point.`n`n");
                    output("`@He quickly recovers his composure and runs away!`n`n");
                    output("Dang! You're even uglier than his Ugly Stick!");
                }
                break;
            case 3:
                // The lost man.
                output("`@\"`#I am lost,`@\" he says, \"`#can you lead me back to town?`@\"`n`n");
                output("You know that if you do, you will lose time for a forest fight for today.`n`n");
                output("Will you help out this poor old man?");
                addnav("Old Man");
                addnav("Walk him to town", $from . "op=walk");
                addnav("Leave him here", $from . "op=leavehim");
                break;
            case 4:
                // The betting game
                output("`@\"`#Would you like to play a little guessing game?`@\", he asks.");
                output("Knowing his sort, you know he will probably insist on a small wager if you do.`n`n");
                output("`@Do you wish to play his game?`n`n");
                addnav("Old Man");
                addnav("Play game", $from . "op=game");
                addnav("Leave", $from . "op=nogame");
                break;
            case 5:
                // The necromancer
                output("`@As you approach the old man, his face twists into a maniacal, evil grin.");
                switch (e_rand(1, 15)) {
                    case 1:
                        $session['user']['specialinc'] = "";
                        output("`@When you reach him, he mutters, \"`#Didn't y' own mother teach you never t' talk t' strangers?`@\"");
                        output("The old necromancer cackles and pulls out a black wand, waving it quickly over your head.`n`n");
                        output("`@You feel a searing pain as your soul is forcibly ripped from your body and cast into the underworld to fuel his evil spells!`n`n");
                        output("`^Your spirit has been ripped from your body!`n");
                        output("`^That treacherous old man searches your body and takes all of your gold.`n");
                        output("You lose 5% of your experience!`n");
                        output("You may continue playing again tomorrow.");
                        $session['user']['alive'] = false;
                        $session['user']['hitpoints'] = 0;
                        $session['user']['experience'] *= 0.95;
                        $session['user']['gold'] = 0;
                        addnav("Daily News", "news.php");
                        addnews("The body of %s was found in the woods, stripped of all gold and with dark symbols drawn upon it.", $session['user']['name']);
                        break;
                    case 2:
                    case 3:
                        $session['user']['specialinc'] = "";
                        output("`@When you reach him, he mutters, \"`#Aye, me %s, come a wee bit closer.  That's it, just a bit CLOSER!`@\"`n`n", translate_inline($session['user']['sex'] ? "lass" : "lad"));
                        output("As the old necromancer screams that last word, he pulls out a black wand and your body twists in agony as if molten fire has replaced your blood.`n`n");
                        output("Your vision goes dark and you feel the hand of %s`@ closing around your heart.", getsetting("deathoverlord", '`$Ramius'));
                        output("Just as you are sure you will die, the pain stops as quickly as it began.`n`n");
                        output("You climb to your feet, shaking and weak.");
                        output("The old necromancer is nowhere to be seen.`n`n");
                        output("`@You feel you will never be quite the %s you were before.`n`n", translate_inline($session['user']['sex'] ? "woman" : "man"));
                        if ($session['user']['maxhitpoints'] > $session['user']['level'] * 10) {
                            $session['user']['maxhitpoints']--;
                            set_module_pref("extrahps", get_module_pref("extrahps") - 1);
                            $hptype = "permanently";
                            if (!get_module_setting("carrydk") || is_module_active("globalhp") && !get_module_setting("carrydk", "globalhp")) {
                                $hptype = "temporarily";
                            }
                            $hptype = translate_inline($hptype);
                            output("`^You `b%s`b `\$lose`^ one hitpoint!`n", $hptype);
                        }
                        $loss = round($session['user']['maxhitpoints'] * 0.25, 0);
                        if ($loss > $session['user']['hitpoints']) {
                            $loss = $session['user']['hitpoints'] - 1;
                        }
                        output("`^You have taken `\$%s`^ damage from wounds.", $loss);
                        $session['user']['hitpoints'] -= $loss;
                        if ($session['user']['sex']) {
                            $msg = "%s came home from the forest, a bit less the woman than she was before.";
                        } else {
                            $msg = "%s came home from the forest, a bit less the man than he was before.";
                        }
                        addnews($msg, $session['user']['name']);
                        break;
                    case 4:
                    case 5:
                    case 6:
                    case 7:
                    case 8:
                    case 9:
                    case 10:
                        output("`@When you reach him, he mutters, \"`#A gem for me own self, yes?`@\"`n`n");
                        output("Do you give him a gem?");
                        addnav("Old Man");
                        addnav("Give him a gem", $from . "op=givegem");
                        addnav("Keep your gems", $from . "op=keepgem");
                        break;
                    case 11:
                    case 12:
                    case 13:
                    case 14:
                    case 15:
                        $session['user']['specialinc'] = "";
                        output("`@You are almost in front of him, when you hear a crashing sound coming from your right.`n`n");
                        output("You turn to look and see one of the bodyguards from the Inn walking through the woods heading your direction.");
                        output("You turn back to the old man, but he seems to have vanished.`n`n");
                        output("Oh well, you'll never know what he wanted now.");
                        break;
                }
                break;
        }
    } elseif ($op == "walk") {
        // Walking the oldman (#3) to town
        $session['user']['turns']--;
        output("`@You take the time to lead the old man back to town.`n`n");
        if (e_rand(0, 1) == 0) {
            output("`@In exchange, he whacks you with his Pretty Stick and you `%gain one`@ charm point.");
            $session['user']['charm']++;
        } else {
            output("`@In exchange, he gives you `%a gem`@!");
            $session['user']['gems']++;
            debuglog("gained 1 gem for walking old man to village");
        }
    } elseif ($op == "leavehim") {
        $session['user']['specialinc'] = "";
        // Being a cruel insensitive clod who hates old men.
        output("`@You tell the old man that you are far too busy to aid him.`n`n");
        output("`@Not a big deal, he should be able to find his way back to town on his own, he made his way out here, didn't he?");
        output("A wolf howls in the distance to your left, and a few seconds later one howls somewhere closer to your right.");
        output("Yep, he should be fine.");
    } elseif ($op == "nogame") {
        // Penny-pincher :)
        $session['user']['specialinc'] = "";
        output("`@Afraid to part with your precious precious money, you decline the old man his game.`n`n");
        output("There wasn't much point to it anyhow, as you certainly would have won.`n`n");
        output("Yep, definitely not afraid of the old man, nope.");
    } elseif ($op == "game") {
        if ($session['user']['gold'] <= 0) {
            $session['user']['specialinc'] = "";
            output("`@The old man reaches out with his stick and pokes your coin purse.  \"`#Empty?!?!  How can you bet with no money??`@\" he shouts.");
            output("With that, he turns with a HARUMPH, and disappears into the underbrush.");
        } else {
            oldman_bettinggame($from);
        }
    } elseif ($op == "givegem") {
        if ($session['user']['gems'] <= 0) {
            $session['user']['specialinc'] = "";
            output("`@You reach into your pack to find that you have no gems.");
            output("The old man looks at you expectantly.`n`n");
            output("When he sees you have no gems, he starts to frown.");
            output("Sensing trouble, you turn to flee toward the forest.`n`n");
            output("From behind you, you hear an evil laugh and feel a sharp pain in your back!`n`n");
            $loss = round($session['user']['maxhitpoints'] * 0.2, 0);
            if ($loss > $session['user']['hitpoints']) {
                $loss = $session['user']['hitpoints'] - 1;
            }
            output("`^You have taken `\$%s`^ damage from wounds.", $loss);
            $session['user']['hitpoints'] -= $loss;
        } else {
            $session['user']['specialinc'] = "";
            output("`@Feeling sorry for the old man, you reach into your pack and extract a gem which he snatches eagerly from your hand.`n");
            $session['user']['gems']--;
            switch (e_rand(1, 6)) {
                case 1:
                case 2:
                case 3:
                    output("`@He cackles with glee.");
                    output("He turns to you and says, \"`#Since y' made such a fine bargain w' me, me %s, I'll be puttin' in a good word for y' with m' ol' friend %s`#.`@\"`n`n", translate_inline($session['user']['sex'] ? "deary" : "lad"), getsetting("deathoverlord", '`$Ramius'));
                    output("`@The necromancer pulls out a black wand, raps you thrice on the head, and runs off into the forest.`n`n");
                    $favor = e_rand(5, 20);
                    output("`^You gain `&%s`^ favor with `\$Ramius`^.", $favor);
                    $session['user']['deathpower'] += $favor;
                    break;
                case 4:
                case 5:
                    if (is_module_active("specialtydarkarts")) {
                        output("`@He cackles with glee.");
                        output("He turns to you and says, \"`#Since y' made such a fine bargain w' me, me %s, I'll be teachin' y' a bit of m' art!`@\"`n`n", translate_inline($session['user']['sex'] ? "deary" : "lad"));
                        output("`@The necromancer pulls out a black wand, raps you thrice on the head, and runs off into the forest.`n`n");
                        output("`^You feel knowledge of the `\$Dark Arts`^ settle into your brain like a stain of blood into straw.`n");
                        require_once "lib/increment_specialty.php";
                        increment_specialty('`$', 'DA');
                        break;
                    }
                    // Fall through if we don't have dark arts enabled.
                // Fall through if we don't have dark arts enabled.
                case 6:
                    output("`@He runs off into the forest.`n`n");
                    output("That greedy old man stole your gem!");
            }
        }
    } elseif ($op == "keepgem") {
        $session['user']['specialinc'] = "";
        output("`@Not wanting to part with one of your precious gems, you turn around and march back toward the forest.`n`n");
        output("From behind you, you hear an evil laugh and feel a sharp pain in your back!`n`n");
        $loss = round($session['user']['maxhitpoints'] * 0.1, 0);
        if ($loss > $session['user']['hitpoints']) {
            $loss = $session['user']['hitpoints'] - 1;
        }
        output("`^You have taken `\$%s`^ damage from wounds.", $loss);
        $session['user']['hitpoints'] -= $loss;
    }
    output("`0");
}
function quester_cities()
{
    if (is_module_active("cities")) {
        $locarray = array();
        $locarray = modulehook("validlocation", $locarray);
        //unset the blocked cities
        $blocked = explode(";", get_module_setting("excludecities"));
        foreach ($locarray as $lockey => $locval) {
            foreach ($blocked as $block) {
                if ($lockey == $block) {
                    unset($locarray[$lockey]);
                }
            }
        }
        //unset the capital
        unset($locarray[getsetting("villagename", LOCATION_FIELDS)]);
        //if for some reason somthing went wrong, set the default city as the city
        if (count($locarray) == 0) {
            set_module_pref("levelloc", getsetting("villagename", LOCATION_FIELDS));
        } else {
            set_module_pref("levelloc", array_rand($locarray));
        }
    }
}
function tatmonster_runevent($type, $link)
{
    global $session;
    // Handle the case where Petra gets deactivated.
    if (!is_module_active("petra")) {
        output("You hear a rustling in the underbrush, which dies away after a few moments.`n`n");
        output("When nothing at all happens after a couple of minutes, you continue on your way.");
        return;
    }
    $op = httpget('op');
    require_once "lib/partner.php";
    $partner = get_partner();
    $session['user']['specialinc'] = "module:tatmonster";
    $battle = false;
    switch ($op) {
        case "":
        case "search":
            output("`3Walking down a deserted trail, you hear a rustling sound coming from the bushes.");
            output("You can smell something burning, and hear something churning.");
            output("You have no idea if you should check it out, but your curiosity is getting the upper hand.");
            output("`3As you step closer and closer to the bush, the burning scent gets more pronounced and the churning grows louder and louder.`n`n");
            if (get_module_pref("tatnumber", "petra") > 0) {
                output("You feel a brief burning sensation from the tattoos on your arm, as if they are reacting to something!`n`n");
            }
            output("`3There is a feeling of dread, deep in your bones.");
            output("Do you want to wait and see what is making the noise, or flee?");
            addnav("W?Wait", $link . "op=wait");
            addnav("R?Run", $link . "op=flee");
            break;
        case "flee":
            $charmloss = e_rand(get_module_setting("mincharmloss") * 2, get_module_setting("maxcharmloss") * 2);
            output("`3Turning around, you hasten back the way you came.");
            output("With a glance backwards, you see a stray cat come out of the trees.`n`n");
            output("Face red with shame, you don't know if you'll ever be able to let %s`3 know that you got scared by a cat!`n`n", $partner);
            output("You lose %s charm from the shame of your cowardice.", $charmloss);
            debuglog("lost {$charmloss} charm from cowardice to the tatmonster");
            $session['user']['charm'] -= $charmloss;
            if ($session['user']['charm'] < 0) {
                $session['user']['charm'] = 0;
            }
            $session['user']['specialinc'] = "";
            break;
        case "wait":
            output("`3You wait for a moment to see what transpires.`n`n");
            output("`3Out from the bushes springs the Mighty `#%s`3.", get_module_setting("name"));
            output("It lashes out with its three slobbering maws, each of them snarling and growling.");
            output("As you rear back in fear, one of the powerful heads narrowly misses you with its teeth.`n");
            output("Circling around you, the beast blocks your escape!`n");
            addnav("Fight", $link . "op=pre");
            break;
        case "pre":
            $op = "fight";
            httpset("op", $op);
            // accommodate for data left from older versions of petra
            require_once "modules/petra.php";
            petra_calculate();
            // Lets build the Tat Monster NOW!
            $numtats = get_module_pref("tatpower", "petra");
            if ($session['user']['dragonkills'] <= get_module_setting("dk")) {
                $numtats += get_module_setting("grace");
            }
            $hpl = get_module_setting("hploss") * $numtats;
            // the test needs to be changed so that it no longer
            // either assumes that one can only obtain ten tattoos,
            // or that $numtats is an integer
            // JT: changed to 8.4 so existing behaviour was preserved.
            if (floor($numtats) == $session['user']['dragonkills'] || $numtats >= 8.4) {
                $monhp = round($session['user']['maxhitpoints'] * 1.1) - $hpl;
                $monatk = round($session['user']['attack'] * 1.05);
                $mondef = round($session['user']['defense'] * 1.05);
            } else {
                $monhp = round($session['user']['maxhitpoints'] * 1.5) - $hpl;
                $monatk = round($session['user']['attack'] * 1.15);
                $mondef = round($session['user']['defense'] * 1.15);
            }
            // If we have too small hp, then just set the monster = to
            // the players hitpoints + 20 %.
            if ($monhp <= 10) {
                $monhp = round($session['user']['maxhitpoints'] * 1.2);
            }
            // even out his strength a bit
            $badguylevel = $session['user']['level'] + 1;
            if ($session['user']['level'] > 9) {
                $monhp *= 1.05;
            }
            if ($session['user']['level'] > 3) {
                $badguylevel--;
            }
            $badguy = array("creaturename" => translate_inline(get_module_setting("name")), "creatureweapon" => translate_inline("Slobbering Maws"), "creaturelevel" => $session['user']['level'] + 1, "creaturehealth" => round($monhp), "creatureattack" => $monatk, "creaturedefense" => $mondef, "noadjust" => 1, "diddamage" => 0);
            $attackstack = array("enemies" => array($badguy), "options" => array("type" => "tattoomonster"));
            $session['user']['badguy'] = createstring($attackstack);
            break;
    }
    if ($op == "fight") {
        $battle = true;
    }
    if ($battle) {
        include "battle.php";
        if ($victory) {
            output("`n`n`3You have overcome the beast!");
            output("The sensation in your arms slowly fades, and you return to normal.`n`n");
            output("You approach this three-headed monstrosity, to ensure that it truly is dead.");
            output("As you near it, one of its heads slowly opens an eye!");
            if (get_module_pref("tatnumber", "petra") > 0) {
                output("It catches sight of the tattoos on your arms and recoils in horror!");
            }
            output("It twitches some more, and you realize that you have done well even to subdue it, and you had best not remain to give it another chance when it recovers.`n`n");
            if ($session['user']['hitpoints'] <= 0) {
                output("`^With the last of your energy, you press a piece of cloth to your wounds, stopping your bloodloss before you are completely dead.`n");
                $session['user']['hitpoints'] = 1;
            }
            $exp = round($session['user']['experience'] * get_module_setting("expgain"));
            // even out the gain a bit... it was too huge at the top and pathetic at the bottom
            if ($session['user']['level'] > 9) {
                $exp *= 0.8;
            }
            if ($session['user']['level'] < 6) {
                $exp *= 1.2;
            }
            if ($session['user']['level'] == 1) {
                $exp += 20;
            }
            // to stop people sometimes gaining 2 xp
            $exp = round($exp);
            output("`3Achieving this grand feat, you receive `^%s `3experience.`0", $exp);
            $session['user']['experience'] += round($exp);
            $badguy = array();
            $session['user']['badguy'] = "";
            $session['user']['specialinc'] = "";
        } elseif ($defeat) {
            $badguy = array();
            $session['user']['badguy'] = "";
            $session['user']['specialinc'] = "";
            output("`n`n`3With one final crushing blow, the beast levels you.");
            if ($session['user']['gold'] > 10) {
                output("As the blood escapes your body, your purse splits and yields some of your gold.");
                $lost = round($session['user']['gold'] * 0.2, 0);
                $session['user']['gold'] -= $lost;
                debuglog("lost {$lost} gold to the tatmonster");
            }
            $exp = round($session['user']['experience'] * get_module_setting("expgain"));
            output("Feeling the pain of loss, you lose `^%s `3experience.`0", $exp);
            $session['user']['experience'] -= $exp;
            if (e_rand(0, 2) == 2) {
                $charmloss = e_rand(get_module_setting("mincharmloss"), get_module_setting("maxcharmloss"));
                output("The beast leaves a long, jagged scar on your skin, causing you to lose `5%s `3charm.`0", $charmloss);
                $session['user']['charm'] -= $charmloss;
                debuglog("lost {$charmloss} charm to the tatmonster");
                if ($session['user']['charm'] < 0) {
                    $session['user']['charm'] = 0;
                }
            }
            output("You are able to cling to life... but just barely.`0");
            $session['user']['hitpoints'] = 1;
        } else {
            require_once "lib/fightnav.php";
            if ($type == "forest") {
                fightnav(true, false);
            } else {
                fightnav(true, false, $link);
            }
        }
    }
}
function waterfall_runevent($type)
{
    global $session;
    // We assume this event only shows up in the forest currently.
    $from = "forest.php?";
    $session['user']['specialinc'] = "module:waterfall";
    $op = httpget('op');
    switch ($op) {
        case "search":
        case "":
            output("`n`2You see a small path that leads away from the main trail. The path is overgrown and you almost didn't see it as you crept by.`n`n");
            output("As you crouch down to study the trail, you notice footprints leading down the path but, oddly, none coming out. While studying the path you hear what sounds like running water.`n");
            addnav("T?Follow the Trail", $from . "op=trail");
            addnav("Continue in the forest", $from . "op=leave");
            break;
        case "trail":
            output("`2You take the path and begin exploring...`n`n");
            $rand = e_rand(1, 12);
            switch ($rand) {
                case 1:
                case 2:
                case 3:
                case 4:
                case 5:
                    output("`2After a few hours of exploring you become lost.`n`n");
                    output("`&You `\$lose `&some Stamina finding your way back.`n`n");
                    if ($session['user']['turns'] > 0) {
                        $session['user']['turns']--;
                    }
                    $session['user']['specialinc'] = "";
                    break;
                case 6:
                case 7:
                case 8:
                    output("`^After a few minutes of exploring you find a waterfall!`n`n");
                    output("`2You also notice a small ledge along the rock face of the waterfall.`n");
                    output("Should you walk the ledge?");
                    addnav("Walk the ledge", $from . "op=ledge");
                    addnav("Return to the forest", $from . "op=leaveleave");
                    break;
                case 9:
                case 10:
                case 11:
                case 12:
                    output("`^After a few minutes exploring the area you find a waterfall!`n");
                    output("`2Thirsty from the walk to the falls you are trying to decide whether or not to take a drink.`n");
                    addnav("Take a drink", $from . "op=drink");
                    addnav("Return to the forest", $from . "op=leaveleave");
                    break;
            }
            break;
        case "ledge":
            $session['user']['specialinc'] = "";
            $fall = e_rand(1, 9);
            switch ($fall) {
                case 1:
                case 2:
                case 3:
                case 4:
                    $gems = e_rand(1, 2);
                    output("`&You carefully walk the ledge behind the waterfall and find... `%%s %s`n", $gems, translate_inline($gems == 1 ? "gem" : "gems"));
                    $session['user']['gems'] += $gems;
                    debuglog("found {$gems} gem(s) behind the waterfall.");
                    break;
                case 5:
                case 6:
                case 7:
                case 8:
                    $lhps = round($session['user']['hitpoints'] * 0.25);
                    $session['user']['hitpoints'] -= $lhps;
                    output("`&You carefully walk the ledge behind the waterfall but not carefully enough!`n");
                    output("You slip and fall, hurting yourself.`n`n");
                    output("`4You have lost `\$%s `4hitpoints during your fall.", $lhps);
                    if ($session['user']['gold'] > 0) {
                        $gold = round($session['user']['gold'] * 0.15);
                        output("`4You also notice that you lost `^%s gold `4during the ordeal.`n`n", $gold);
                        $session['user']['gold'] -= $gold;
                        debuglog("lost {$gold} gold when he fell in the water by the waterfall.");
                    }
                    break;
                case 9:
                    output("`7As you are walking the ledge you slip and fall,`n");
                    output("hitting the rocks and the water below!`n`n");
                    output("`4`nYou have died and lost all your gold!");
                    output("`nYou may continue playing tomorrow.`n");
                    $session['user']['turns'] = 0;
                    $session['user']['hitpoints'] = 0;
                    debuglog("lost {$session['user']['gold']} gold when he fell from the top of the waterfall.");
                    $session['user']['gold'] = 0;
                    $session['user']['alive'] = false;
                    addnews("`%The broken body of %s`% was found partially submerged by the rocks under a waterfall.", $session['user']['name']);
                    addnav("Daily News", "news.php");
                    break;
            }
            break;
        case "drink":
            $session['user']['specialinc'] = "";
            $cnt = e_rand(1, 6);
            switch ($cnt) {
                case 1:
                case 2:
                case 3:
                    output("`2You drink from the falls and feel refreshed!`n`n");
                    output("`^You have been restored to full health!");
                    if ($session['user']['hitpoints'] < $session['user']['maxhitpoints']) {
                        $session['user']['hitpoints'] = $session['user']['maxhitpoints'];
                    }
                    break;
                case 4:
                    output("`2You walk to the base of the waterfall and drink deeply of the pure water.`n");
                    output("As you drink, you feel a tingling sensation spread all over your body...`n");
                    output("You feel refreshed and healthier than ever!`n`n");
                    $hptype = "permanently";
                    if (!get_module_setting("carrydk") || is_module_active("globalhp") && !get_module_setting("carrydk", "globalhp")) {
                        $hptype = "temporarily";
                    }
                    $hptype = translate_inline($hptype);
                    output("`^Your hitpoints have been restored and your maximum hitpoints have been %s increased by 1.", $hptype);
                    $session['user']['maxhitpoints']++;
                    if ($session['user']['hitpoints'] < $session['user']['maxhitpoints']) {
                        $session['user']['hitpoints'] = $session['user']['maxhitpoints'];
                    }
                    set_module_pref("extrahps", get_module_pref("extrahps") + 1);
                    break;
                case 5:
                case 6:
                    output("`2You drink from the falls and you start feeling weird.  You sit down and become ill.`n");
                    output("`4You lose some Stamina while recovering!");
                    if ($session['user']['turns'] > 0) {
                        $session['user']['turns']--;
                    }
                    break;
            }
            break;
        case "leave":
            output("`^You stare at the path for a few more moments trying to get the courage to explore it. A piercing chill runs up your spine that makes you start trembling.  At this point you have decided to stay on the main trail.  You quickly move away from the mysterious trail.");
            $session['user']['specialinc'] = "";
            break;
        case "leaveleave":
            output("`^You decide that discretion is the better part of valor, or at least survival, and return to the forest.");
            $session['user']['specialinc'] = "";
            break;
    }
    output_notl("`0");
}
function racegobot_checkcity()
{
    global $session;
    $race = "Gobot";
    if (is_module_active("racerobot")) {
        $city = get_module_setting("villagename", "racerobot");
    } else {
        $city = getsetting("villagename", LOCATION_FIELDS);
    }
    if ($session['user']['race'] == $race && is_module_active("cities")) {
        //if they're this race and their home city isn't right, set it up.
        if (get_module_pref("homecity", "cities") != $city) {
            //home city is wrong
            set_module_pref("homecity", $city, "cities");
        }
    }
    return true;
}