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 oldhouse_dohook($hookname, $args)
{
    global $session;
    switch ($hookname) {
        case "newday":
            set_module_pref("scaretoday", 0);
            break;
        case "changesetting":
            if ($args['setting'] == "villagename") {
                if ($args['old'] == get_module_setting("oldhouseloc")) {
                    set_module_setting("oldhouseloc", $args['new']);
                }
            }
            break;
        case "village":
            if ($session['user']['location'] == get_module_setting("oldhouseloc")) {
                tlschema($args['schemas']['tavernnav']);
                addnav($args['tavernnav']);
                tlschema();
                addnav("O?The Old House", "runmodule.php?module=oldhouse");
            }
            break;
    }
    return $args;
}
function drpap_dohook($hookname, $args)
{
    global $session;
    switch ($hookname) {
        case "village":
            if ($session['user']['location'] == get_module_setting("paploc") && $session['user']['dragonkills'] >= get_module_setting("dk")) {
                tlschema($args['schemas']['marketnav']);
                addnav($args['marketnav']);
                tlschema();
                addnav("Dr Paprika's Office", "runmodule.php?module=drpap&op=enter");
            }
            break;
        case "changesetting":
            if ($args['setting'] == "villagename") {
                if ($args['old'] == get_module_setting("paploc")) {
                    set_module_setting("paploc", $args['new']);
                }
            }
            break;
        case "dragonkilltext":
            if (get_module_setting("reset") == 1) {
                set_module_pref("count", 0);
            }
            break;
        case "moderate":
            $args['drpap'] = "Dr Paprika's Waiting Room";
            break;
    }
    return $args;
}
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 specificmaplocation_dohook($hookname, $args)
{
    global $session;
    switch ($hookname) {
        case "worldnav":
            if (get_module_setting("finder1") == "Nobody" && get_module_pref("worldXYZ", "worldmapen") == "14,37,1") {
                output("You found one of the ten boxes of cigarettes!  You open it up to find a hundred of the damned things!  Woohoo!");
                $session['user']['gems'] += 100;
                set_module_setting("finder1", $session['user']['name']);
            }
            if (get_module_setting("finder2") == "Nobody" && get_module_pref("worldXYZ", "worldmapen") == "6,33,1") {
                output("You found one of the ten boxes of cigarettes!  You open it up to find a hundred of the damned things!  Woohoo!");
                $session['user']['gems'] += 100;
                set_module_setting("finder2", $session['user']['name']);
            }
            if (get_module_setting("finder3") == "Nobody" && get_module_pref("worldXYZ", "worldmapen") == "17,31,1") {
                output("You found one of the ten boxes of cigarettes!  You open it up to find a hundred of the damned things!  Woohoo!");
                $session['user']['gems'] += 100;
                set_module_setting("finder3", $session['user']['name']);
            }
            if (get_module_setting("finder4") == "Nobody" && get_module_pref("worldXYZ", "worldmapen") == "25,26,1") {
                output("You found one of the ten boxes of cigarettes!  You open it up to find a hundred of the damned things!  Woohoo!");
                $session['user']['gems'] += 100;
                set_module_setting("finder4", $session['user']['name']);
            }
            if (get_module_setting("finder5") == "Nobody" && get_module_pref("worldXYZ", "worldmapen") == "7,21,1") {
                output("You found one of the ten boxes of cigarettes!  You open it up to find a hundred of the damned things!  Woohoo!");
                $session['user']['gems'] += 100;
                set_module_setting("finder5", $session['user']['name']);
            }
            if (get_module_setting("finder6") == "Nobody" && get_module_pref("worldXYZ", "worldmapen") == "22,20,1") {
                output("You found one of the ten boxes of cigarettes!  You open it up to find a hundred of the damned things!  Woohoo!");
                $session['user']['gems'] += 100;
                set_module_setting("finder6", $session['user']['name']);
            }
            if (get_module_setting("finder7") == "Nobody" && get_module_pref("worldXYZ", "worldmapen") == "14,17,1") {
                output("You found one of the ten boxes of cigarettes!  You open it up to find a hundred of the damned things!  Woohoo!");
                $session['user']['gems'] += 100;
                set_module_setting("finder7", $session['user']['name']);
            }
            if (get_module_setting("finder8") == "Nobody" && get_module_pref("worldXYZ", "worldmapen") == "3,9,1") {
                output("You found one of the ten boxes of cigarettes!  You open it up to find a hundred of the damned things!  Woohoo!");
                $session['user']['gems'] += 100;
                set_module_setting("finder8", $session['user']['name']);
            }
            if (get_module_setting("finder9") == "Nobody" && get_module_pref("worldXYZ", "worldmapen") == "22,6,1") {
                output("You found one of the ten boxes of cigarettes!  You open it up to find a hundred of the damned things!  Woohoo!");
                $session['user']['gems'] += 100;
                set_module_setting("finder9", $session['user']['name']);
            }
            if (get_module_setting("finder10") == "Nobody" && get_module_pref("worldXYZ", "worldmapen") == "4,3,1") {
                output("You found one of the ten boxes of cigarettes!  You open it up to find a hundred of the damned things!  Woohoo!");
                $session['user']['gems'] += 100;
                set_module_setting("finder10", $session['user']['name']);
            }
            break;
    }
    return $args;
}
function get_default_accs_list()
{
    $accs = unserialize(get_module_setting("accessories", "mountaccessories"));
    if (!is_array($accs)) {
        $accs = array();
        set_module_setting("accessories", serialize($accs), "mountaccessories");
    }
    $accs = unserialize(get_module_setting("accessories", "mountaccessories"));
    return $accs;
}
function dpresurrect_run()
{
    global $session;
    page_header("Returning to Improbable Island");
    $op = httpget('op');
    if ($op == "resurrect") {
        $session['user']['donationspent'] += get_module_setting("pointsrequired");
        output("`\$The Watcher`0 nods.  \"`7I'm not above taking the occasional bribe.  That's what makes the world go round, right?`0\"  You nod sadly.  \"`7Prepare a rowboat, we have a restoration coming through!`0\"`n`nWelcome back to Improbable Island...");
        addnav("Return to Improbable Island", "newday.php?resurrection=true");
        set_module_setting("timestaken", get_module_setting("timestaken") + 1);
    }
    page_footer();
}
function hepzibah_dohook($hookname, $args)
{
    global $session;
    switch ($hookname) {
        case "changesetting":
            if ($args['setting'] == "villagename") {
                if ($args['old'] == get_module_setting("hepzibahloc")) {
                    set_module_setting("hepzibahloc", $args['new']);
                }
            }
            break;
    }
    return $args;
}
function statue_dohook($hookname, $args)
{
    global $REQUEST_URI;
    global $session;
    $capital = getsetting("villagename", LOCATION_FIELDS);
    $hero = get_module_setting("hero");
    switch ($hookname) {
        case "village-desc":
            if ($session['user']['location'] != $capital) {
                break;
            }
            if ($hero == 0) {
                output("`n`@The people wandering past periodically stop to admire a statue of the ancient hero, `&MightyE`@.`0`n");
            } else {
                $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid='{$hero}'";
                $result = db_query_cached($sql, "lasthero");
                $row = db_fetch_assoc($result);
                output("`0The inhabitants of %s are busy erecting a statue for their newest hero, `&%s`0, on the only statue pedestal around.  The remains of the statue that had stood there before lie in such ruins around the pedestal that it is no longer recognizable.`0`n`n", $session['user']['location'], $row['name']);
            }
            break;
        case "index":
            if (!get_module_setting("showonindex")) {
                break;
            }
            $heroname = "MightyE";
            if ($hero != 0) {
                $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid='{$hero}'";
                $result = db_query_cached($sql, "lasthero");
                $row = db_fetch_assoc($result);
                $heroname = $row['name'];
            }
            output("`@The most recent hero of the realm is: `&%s`0`n`n", $heroname);
            break;
        case "dragonkill":
            set_module_setting("hero", $session['user']['acctid']);
            invalidatedatacache("lasthero");
            break;
        case "namechange":
            if ($hero == $session['user']['acctid']) {
                invalidatedatacache("lasthero");
            }
            break;
    }
    return $args;
}
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 worldmapen_editor_manual($op, $subop, $act)
{
    $vloc = array();
    $vname = getsetting("villagename", LOCATION_FIELDS);
    $vloc[$vname] = "village";
    $vloc = modulehook("validlocation", $vloc);
    ksort($vloc);
    if ($act == "save") {
        foreach ($vloc as $loc => $val) {
            $space_valx = preg_replace('/\\s/', '_', $loc . 'X');
            $space_valy = preg_replace('/\\s/', '_', $loc . 'Y');
            set_module_setting($loc . 'X', httppost($space_valx));
            set_module_setting($loc . 'Y', httppost($space_valy));
            set_module_setting($loc . 'Z', 1);
            // Eventually we'll do the Z coord too
            // set_module_setting($loc.'Z',
            //        httppost($loc."Z"));
        }
        output("`^`bSettings saved successfully.`b`n");
        reset($vloc);
    }
    output("`^Maximum X value is `b%s`b`n", get_module_setting("worldmapsizeX"));
    output("`^Maximum Y value is `b%s`b`n", get_module_setting("worldmapsizeY"));
    $worldarray = array("World Locations,title");
    foreach ($vloc as $loc => $val) {
        $mapx = get_module_setting("worldmapsizeX");
        $mapy = get_module_setting("worldmapsizeY");
        //Added to allow setting cities outside of the map. - Making cities inaccessible via normal travel.
        $myx = $mapx + 1;
        $worldarray[] = array("Locations for %s,title", $loc);
        $worldarray[$loc . 'X'] = array("X Coordinate,range,1,{$myx},1");
        $worldarray[$loc . 'Y'] = array("Y coordinate,range,1,{$mapy},1");
    }
    rawoutput("<form method='post' action='runmodule.php?module=worldmapen&op=edit&subop=manual&act=save&admin=true'>");
    require_once "lib/showform.php";
    global $module_settings;
    showform($worldarray, $module_settings['worldmapen']);
    rawoutput("</form>");
    addnav("", "runmodule.php?module=worldmapen&op=edit&subop=manual&act=save&admin=true");
    addnav("E?Return to World Map Editor", "runmodule.php?module=worldmapen&op=edit&admin=true");
}
function ella_dohook($hookname, $args)
{
    global $session;
    switch ($hookname) {
        case "changesetting":
            if ($args['setting'] == "villagename") {
                if ($args['old'] == get_module_setting("ellaloc")) {
                    set_module_setting("ellaloc", $args['new']);
                }
            }
            break;
        case "newday":
            $dayswait = get_module_pref("dayswait");
            // let's just correct if something goes wrong somehow.
            if ($dayswait < 0) {
                $dayswait = 0;
            }
            if ($dayswait > 0) {
                $dayswait--;
            }
            set_module_pref("dayswait", $dayswait);
            if ($dayswait == 0) {
                set_module_pref("candance", 1);
            }
            break;
        case "village":
            // Moved the check for candance down into the run.  Buildings
            // shouldn't just vanish!
            if ($session['user']['location'] == get_module_setting("ellaloc")) {
                tlschema($args['schemas']['marketnav']);
                addnav($args['marketnav']);
                tlschema();
                addnav("Ella's Dance Studio", "runmodule.php?module=ella");
            }
            break;
    }
    return $args;
}
function crazyaudrey_run()
{
    global $session;
    $op = httpget('op');
    if ($op == "pet") {
        page_header("Crazy Audrey's Zoo");
        $cost = get_module_setting("cost");
        $animal = get_module_setting("animal");
        $lcanimal = get_module_setting("lanimal");
        $plural = get_module_setting("animals");
        $lcplural = get_module_setting("lanimals");
        $profit = get_module_setting("profit");
        output("`5You cautiously approach Crazy Audrey.");
        output("Next to her is a sign that reads, \"`#%s gold to pet %s`#,`5\" and a basket filled with `^%s`5 gold!", $cost, $lcplural, $profit);
        if ($session['user']['gold'] >= $cost) {
            output("You place your `^%s`5 gold in the basket, and spend a few minutes petting one of the %s`5.", $cost, $lcplural);
            output("Soon though, Crazy Audrey chases you off, and you stand at a distance admiring the %s`5.", $lcplural);
            $session['user']['gold'] -= $cost;
            debuglog("spent {$cost} gold to pet audrey's pets");
            $profit += $cost;
            set_module_setting("profit", $profit);
            $buffname = get_module_setting("buffname");
            apply_buff('crazyaudrey', array("name" => $buffname, "rounds" => 5, "activate" => "defense", "defmod" => 1.05, "schema" => "module-crazyaudrey"));
            output("`5After a few minutes, you once again try to approach in order to look into her baskets.");
            if (get_module_pref("played") == 0) {
                addnav("Look at Crazy Audrey's baskets", "runmodule.php?module=crazyaudrey&op=baskets");
            } else {
                output("`5As you approach closer, Crazy Audrey looks up and screams at you. \"`%Hey!!  I recognize you!  You've already played with my %s`% today!  Get away from here, you pervy %s`% fancier!`5\"", $lcplural, $lcanimal);
                output("You quickly step back and admire the %s`5 from a safe distance.", $lcplural);
            }
        } else {
            output("Not having `^%s`5 gold, you wander sadly away.", $cost);
        }
    } elseif ($op == "baskets" || $op == "play" || $op == "run") {
        page_header("Crazy Audrey");
        crazyaudrey_baskets("module-internal", "runmodule.php?module=crazyaudrey");
    }
    if ($op != "baskets") {
        require_once "lib/villagenav.php";
        villagenav();
    }
    page_footer();
}
function settings_run()
{
    global $session;
    $op = httpget('op');
    $category = stripslashes(rawurldecode(httpget('cat'))) ?: 'Account';
    page_header("Settings - {$category}");
    switch ($op) {
        case 'save':
            $accounts = db_prefix('accounts');
            $post = httpallpost();
            unset($post['showFormTabIndex']);
            foreach ($post as $key => $val) {
                $post[$key] = stripcslashes($val);
            }
            $post['oldvalues'] = json_decode($post['oldvalues'], true);
            foreach ($post['oldvalues'] as $key => $val) {
                $post['oldvalues'][$key] = stripslashes($val);
            }
            $post = modulehook('prefs-change', $post);
            if ($post['return'] != '') {
                $return = $post['return'];
                unset($post['return']);
            }
            //Fix template changes.
            if (md5(md5($post['oldpass'])) == $session['user']['password'] && $post['newpass'] != '') {
                require_once 'lib/systemmail.php';
                $newPass = md5(md5($post['newpass']));
                db_query("UPDATE {$accounts}\n                    SET password = '******'\n                    WHERE acctid = '{$session['user']['acctid']}'");
                systemmail($session['user']['acctid'], 'Account Settings', "`@Your password was changed successfully!");
            }
            unset($post['newpass']);
            unset($post['oldpass']);
            foreach ($post as $key => $val) {
                if ($key == 'bio' && $val != $post['oldvalues']['bio']) {
                    $session['user']['bio'] = $val;
                } else {
                    if (!is_array($val) && $val != $post['oldvalues'][$key]) {
                        if (strpos($key, '__user') || strpos($key, '__check')) {
                            $moduleKey = explode('__', $key);
                            set_module_pref($moduleKey[1], $val, $moduleKey[0]);
                            unset($moduleKey);
                        } else {
                            $session['user']['prefs'][$key] = $val;
                        }
                    }
                }
            }
            $prefs = @serialize($session['user']['prefs']);
            db_query("UPDATE {$accounts} SET prefs = '{$prefs}'\n                WHERE acctid = '{$session['user']['acctid']}'");
            redirect("runmodule.php?module=settings&cat={$return}&save=true");
            addnav('Go back', 'runmodule.php?module=settings');
            break;
        default:
            $modules = db_prefix('modules');
            $userprefs = db_prefix('module_userprefs');
            $rewrite = trim(get_module_setting('rewrite'));
            $rewrite = json_decode($rewrite, true);
            $languages = getsetting('serverlanguages', 'en, English');
            $prefs = $session['user']['prefs'];
            $prefs['bio'] = $session['user']['bio'];
            $prefs['template'] = $_COOKIE['template'] ?: getsetting('defaultskin', 'jade.htm');
            $prefs['email'] = $session['user']['emailaddress'];
            $prefsFormat = ['Account' => ['bio' => 'Short biography, textarea', 'newpass' => 'New password, password', 'oldpass' => 'If you are changing your password&comma; type your old one, password', 'email' => 'Email, text'], 'Display' => ['template' => 'Skin, theme', 'language' => 'Which language do you prefer?, enum, ' . $languages, 'timestamp' => 'Show timestamps in commentary?, enum, 0, None, 1, Real Time, 2, Relative Time'], 'Game Behavior' => ['emailonmail' => 'Receive emails when you receive a mail?, bool', 'systemmail' => 'Receive emails for system messages?, bool', 'Be sure to check your email\'s spam folder and add our email as a trusted sender!, note', 'dirtyemail' => 'Allow profanity in mail?, bool', 'timeoffset' => sprintf_translate('Hours to offset time (currently %s)?, int', date($prefs['timeformat'], strtotime('now') + $prefs['timeoffset'] * 3600)), 'ihavenocheer' => 'Disable holiday text?, bool', 'nojump' => 'Disable jumping to the commentary when posting or refreshing?, bool']];
            if (count(explode(',', $languages)) < 3) {
                unset($prefs['Display']['language']);
            }
            $prefsFormat = modulehook('prefs-format', $prefsFormat);
            $prefsTemp = [];
            $modulesFound = [];
            $sql = db_query("SELECT modulename, formalname FROM {$modules}\n                WHERE infokeys LIKE '%|prefs|%'\n                AND active = 1\n                ORDER BY modulename");
            while ($row = db_fetch_assoc($sql)) {
                $formal = $row['formalname'];
                $modulesFound[$row['modulename']] = true;
                if (module_status($row['modulename']) == MODULE_FILE_NOT_PRESENT) {
                    foreach ($rewrite as $key => $moduleName) {
                        if ($moduleName == $formal || strpos($key, $row['modulename']) !== false) {
                            unset($rewrite[$key]);
                        }
                    }
                    set_module_setting('rewrite', json_encode($rewrite));
                } else {
                    $prefsTemp[$formal] = get_module_info($row['modulename'])['prefs'];
                }
                unset($prefsTemp[$formal][0]);
                foreach ($prefsTemp[$formal] as $setting => $description) {
                    $description = explode('|', $description)[0];
                    if (strpos($setting, 'user_') === false) {
                        unset($prefsTemp[$formal][$setting]);
                    } else {
                        $structuredKey = "{$row['modulename']}__{$setting}";
                        if ($rewrite[$structuredKey] != $formal) {
                            $prefsTemp[$rewrite[$structuredKey]][$structuredKey] = $description;
                        } else {
                            $prefsTemp[$formal][$structuredKey] = $description;
                        }
                        unset($prefsTemp[$formal][$setting]);
                    }
                }
                if (count($prefsTemp[$formal]) == 0) {
                    unset($prefsTemp[$formal]);
                    unset($modulesFound[$row['modulename']]);
                }
            }
            foreach ($modulesFound as $name => $true) {
                $sql = db_query("SELECT modulename, setting, value FROM {$userprefs}\n                    WHERE modulename = '{$name}'\n                    AND (setting LIKE 'user_%' OR setting LIKE 'check_%')\n                    AND userid = '{$session['user']['acctid']}'\n                    ");
                while ($row = db_fetch_assoc($sql)) {
                    $prefs["{$row['modulename']}__{$row['setting']}"] = $row['value'];
                }
            }
            $prefsFormat = array_merge_recursive($prefsFormat, $prefsTemp);
            $prefsFormat = modulehook('prefs-format', $prefsFormat);
            require_once 'lib/villagenav.php';
            villagenav();
            addnav('Refresh', 'runmodule.php?module=settings');
            addnav('Categories');
            foreach (array_keys($prefsFormat) as $int => $name) {
                addnav($name, "runmodule.php?module=settings&cat=" . rawurlencode($name));
            }
            output("`c`b`i`Q{$category} Settings`b`i`c");
            if (httpget('save')) {
                output("`@`iYour Settings have been saved!`i`n");
            }
            rawoutput("<form action='runmodule.php?module=settings&op=save' method = 'POST'>");
            require_once 'lib/showform.php';
            showform($prefsFormat[$category], $prefs);
            rawoutput(sprintf("<input type='hidden' name='oldvalues' value='%s' />", json_encode($prefs)));
            rawoutput("<input type='hidden' name='return' value='{$category}' />");
            rawoutput("</form>");
            rawoutput("<script type='text/javascript'>\n                document.getElementsByName('template')[0].onchange = function () {\n                    var index = this.selectedIndex;\n                    var selection = this.children[index].value;\n                    document.cookie = 'template=' + selection + ';expires=86400';\n                }\n\n                </script>");
            addnav('', 'runmodule.php?module=settings&op=save');
            break;
    }
    page_footer();
}
function iitems_worldmapdrop_dohook($hookname, $args)
{
    global $session;
    switch ($hookname) {
        case "iitems-show-inventory":
            //debug("Hook?");
            $drop = httpget('dropworldmap');
            if ($drop) {
                $squares = unserialize(get_module_setting("iitemsquares"));
                $ploc = get_module_pref("worldXYZ", "worldmapen");
                if (httpget('dropmapall')) {
                    $qty = iitems_discard_all_items(httpget('discard'));
                    output("`0You drop the items to your feet.  Maybe someone else will find a use for them.`n");
                } else {
                    iitems_discard_item(httpget('discard'));
                    $qty = 1;
                    output("`0You drop the item to your feet.  Maybe someone else will find a use for it.`n");
                }
                $squares[$ploc][$drop] += $qty;
                set_module_setting("iitemsquares", serialize($squares));
            }
            break;
        case "iitems-inventory":
            //debug($args);
            if ($args['master']['dropworldmap'] && httpget('from') == "worldnav") {
                rawoutput("<a href=\"runmodule.php?module=iitems&op=inventory&from=" . httpget('from') . "&dropworldmap=" . $args['player']['itemid'] . "&discard=" . $args['inventorykey'] . "\">Drop this item on the Map for someone else to pick up</a><br />");
                addnav("", "runmodule.php?module=iitems&op=inventory&from=" . httpget('from') . "&dropworldmap=" . $args['player']['itemid'] . "&discard=" . $args['inventorykey']);
                if ($args['player']['quantity'] > 1) {
                    rawoutput("<a href=\"runmodule.php?module=iitems&op=inventory&from=" . httpget('from') . "&dropworldmap=" . $args['player']['itemid'] . "&discard=" . $args['inventorykey'] . "&dropmapall=true\">Drop all of these items on the Map for someone else to pick up</a><br />");
                    addnav("", "runmodule.php?module=iitems&op=inventory&from=" . httpget('from') . "&dropworldmap=" . $args['player']['itemid'] . "&discard=" . $args['inventorykey'] . "&dropmapall=true");
                }
            }
            break;
        case "worldnav":
            $ploc = implode(",", $args);
            $squares = unserialize(get_module_setting("iitemsquares"));
            $itemid = httpget('iitem-pickup');
            if ($itemid) {
                require_once "modules/iitems/lib/lib.php";
                $itemdetails = iitems_get_item_details($itemid);
                //Pick up iitems
                if (httpget('alliitems')) {
                    //Pick up all iitems
                    output("`0You pick up the %s %s and put them in your backpack.`n", ${$squares}[$ploc][$itemid], $itemdetails['plural']);
                    for ($i = 0; $i < $squares[$ploc][$itemid]; $i++) {
                        iitems_give_item($itemid);
                    }
                    unset($squares[$ploc][$itemid]);
                } else {
                    //Pick up single iitem
                    if ($squares[$ploc][$itemid]) {
                        output("`0You pick up the %s and put it in your backpack.`n", $itemdetails['verbosename']);
                        iitems_give_item($itemid);
                        $squares[$ploc][$itemid]--;
                        if ($squares[$ploc][$itemid] === 0) {
                            unset($squares[$ploc][$itemid]);
                        }
                    } else {
                        output("`0You bend over to pick up the %s, but it's suddenly not there anymore!  Some crafty bastard has pinched it from right under your nose!`n", $itemdetails['verbosename']);
                    }
                }
                set_module_setting("iitemsquares", serialize($squares));
            }
            //Show iitems that can be picked up
            if (!is_array($squares)) {
                $squares = array();
                set_module_setting("iitemsquares", serialize($squares));
            }
            if (is_array($squares[$ploc])) {
                if (count($squares[$ploc])) {
                    //this square has something in it!
                    $iitems = $squares[$ploc];
                    addnav("Pick up items");
                    require_once "modules/iitems/lib/lib.php";
                    foreach ($iitems as $id => $qty) {
                        $item = iitems_get_item_details($id);
                        if ($qty < 1) {
                            unset($squares[$ploc][$id]);
                        }
                        $showwarn = 1;
                        addnav(array("Pick up %s", $item['verbosename']), "runmodule.php?module=worldmapen&op=continue&iitem-pickup=" . $id);
                        if ($qty > 1) {
                            output("`0There are %s %s here.`n`n", $qty, $item['plural']);
                            addnav(array("Pick up all %s", $item['plural']), "runmodule.php?module=worldmapen&op=continue&iitem-pickup=" . $id . "&alliitems=1");
                        } else {
                            if ($qty == 1) {
                                output("`0There is a %s here.`n`n", $item['verbosename']);
                            }
                        }
                    }
                    if ($showwarn && $session['user']['dragonkills'] < 1 && $session['user']['level'] < 10) {
                        output("`JLogs and stone are only really useful if you're building a Dwelling.  To build a Dwelling, you'll need a Land Claim stake from Improbable Central, which will set you back 100 Cigarettes.  If you're not building a Dwelling, then there's not much reason to pick them up (logs and stone are really heavy!).  This message will disappear once you've got a few more levels under your belt.`0`n");
                    }
                } else {
                    //this square is empty, unset it
                    unset($squares[$ploc]);
                    set_module_setting("iitemsquares", serialize($squares));
                }
            }
            break;
    }
    return $args;
}
function serialisededitor_run()
{
    page_header('Editing Serialised Array');
    $op = httpget('op');
    if ($op == 'source') {
        if (httpget('subop') == 'save') {
            $code = httppost('code');
            // Don't serialise the array as it already is.
            set_module_setting('array', $code, 'serialisededitor');
            output('`#Array has been serialised and saved.`0`n`n');
        } else {
            // Don't unserialise, leave as is.
            $code = get_module_setting('array', 'serialisededitor');
        }
        $size = translate_inline(array('Width', 'Height'));
        $submit = translate_inline('Submit');
        rawoutput('<script language="JavaScript" type="text/javascript">function increase_row(target, value){target.rows = target.rows + value;}function increase_col(target, value){target.cols = target.cols + value;}</script>');
        rawoutput('<form action="runmodule.php?module=serialisededitor&op=source&subop=save" method="POST">');
        addnav('', 'runmodule.php?module=serialisededitor&op=source&subop=save');
        rawoutput('<table border="0" cellpadding="0" cellspacing="0">');
        rawoutput('<tr><td><textarea name="code" cols="40" rows="10" id="textarea">' . stripslashes($code) . '</textarea></td><td rowspan="2" valign="top"><input type="submit" onClick="increase_row(textarea,1);" value="+" />&nbsp;<input type="submit" onClick="increase_row(textarea,-1);" value="-" /><br /><span class="colLtWhite">' . $size[1] . '</span></td></tr>');
        rawoutput('<tr><td colspan="2"><input type="submit" onClick="increase_col(textarea,1);" value="+" />&nbsp;<input type="submit" onClick="increase_col(textarea,-1);" value="-" /><br /><span class="colLtWhite">' . $size[0] . '</span></td></tr>');
        rawoutput('<tr><td colspan="2"><input type="submit" class="button" value="' . $submit . '" /></td></tr>');
        rawoutput('</table></form>');
    } elseif ($op == 'find') {
        $subop = httpget('subop');
        $name = httppost('name') ? httppost('name') : '';
        $search = translate_inline('Search by name: ');
        $search2 = translate_inline('Search');
        rawoutput('<form action="runmodule.php?module=serialisededitor&op=find&subop=search" method="POST">' . $search . '<input type="text" size="30" name="name" value="' . $name . '" />&nbsp;<input type="submit" value="' . $search2 . '" class="button" /></form><br /><br />');
        addnav('', 'runmodule.php?module=serialisededitor&op=find&subop=search');
        if ($subop == 'search') {
            $search = "%";
            for ($i = 0; $i < strlen($name); $i++) {
                $search .= substr($name, $i, 1) . "%";
            }
            $sql = "SELECT acctid, name, level, login\r\n\t\t\t\t\tFROM " . db_prefix('accounts') . "\r\n\t\t\t\t\tWHERE (locked = 0 AND name LIKE '{$search}')\r\n\t\t\t\t\tORDER BY level DESC";
            $result = db_query($sql);
            if (($max = db_num_rows($result)) > 0) {
                if ($max > 100) {
                    output('`#Listing first 100:`n`n');
                    $max = 100;
                }
                $ops = translate_inline('Op');
                $pname = translate_inline('Name');
                $login = translate_inline('Login');
                $acctid = translate_inline('AcctID');
                $level = translate_inline('Level');
                $submit = translate_inline('Submit');
                $i = 0;
                rawoutput('<form action="runmodule.php?module=serialisededitor&op=find&subop=list" method="POST">');
                addnav('', 'runmodule.php?module=serialisededitor&op=find&subop=list');
                rawoutput('<table border="0" celpadding="0" cellspacing="1" align="center">');
                rawoutput('<tr class="trhead"><td>' . $ops . '</td><td>' . $pname . '</td><td>' . $login . '</td><td>' . $acctid . '</td><td>' . $level . '</td></tr>');
                while ($row = db_fetch_assoc($result)) {
                    rawoutput('<tr class="' . ($i % 2 ? 'trdark' : 'trlight') . '"><td align="center"><input type="radio" name="userid" value="' . $row['acctid'] . '" /></td><td>');
                    output_notl('`&%s', $row['name']);
                    rawoutput('</td><td>');
                    output_notl('%s', $row['login']);
                    rawoutput('</td><td align="center">');
                    output_notl('%s', $row['acctid']);
                    rawoutput('</td><td align="center">');
                    output_notl('`^%s', $row['level']);
                    rawoutput('</td></tr>');
                    $i++;
                    if ($i >= $max) {
                        break;
                    }
                }
                $sql = "SELECT modulename\r\n\t\t\t\t\t\tFROM " . db_prefix('modules') . "\r\n\t\t\t\t\t\r\n\t\t\t\t\t\tORDER BY modulename ASC";
                $result = db_query($sql);
                $select = '';
                while ($row = db_fetch_assoc($result)) {
                    $select .= '<option>' . $row['modulename'] . '</option>';
                }
                rawoutput('<tr class="trlight"><td colspan="5">');
                output('`#Please select a module: ');
                rawoutput('<select name="modulename">' . $select . '</select></td></tr>');
                rawoutput('<tr class="trdark"><td align="center" colspan="5"><input type="hidden" name="name" value="' . $name . '" /><input type="submit" class="button" value="' . $submit . '" /></td></tr></table></form><br /><br />');
            } else {
                output('`#Sorry, but there were no matches. Please try again.`0`n');
            }
        } elseif ($subop == 'list') {
            $userid = httppost('userid');
            $module = httppost('modulename');
            $sql = "SELECT a.name, b.setting, b.value\r\n\t\t\t\t\tFROM " . db_prefix('accounts') . " a, " . db_prefix('module_userprefs') . " b\r\n\t\t\t\t\tWHERE b.modulename = '" . $module . "'\r\n\t\t\t\t\t\tAND a.acctid = b.userid\r\n\t\t\t\t\t\tAND a.acctid = '" . $userid . "'";
            $result = db_query($sql);
            if (db_num_rows($result) > 0) {
                output('`#The data in the boxes should still be serialised, if it is not, then it isn\'t a serialised array.`0`n`n');
                $edit = translate_inline('Edit This Array');
                $i = 0;
                while ($row = db_fetch_assoc($result)) {
                    $array = unserialize($row['value']);
                    if (is_array($array)) {
                        rawoutput('<form action="runmodule.php?module=serialisededitor&op=find&subop=push" method="POST">');
                        addnav('', 'runmodule.php?module=serialisededitor&op=find&subop=push');
                        rawoutput('<textarea name="array" cols="40" rows="6">' . $row['value'] . '</textarea><br />');
                        rawoutput('<input type="hidden" name="data" value="' . $module . '|' . $row['setting'] . '|' . $userid . '" /><input type="submit" class="button" value="' . $edit . '" /></form><br /><br />');
                        $i++;
                    }
                }
                if ($i == 0) {
                    output('`#This module has no serialised arrays. Please try another.`0`n');
                }
            } else {
                output('`#This user does not have any prefs with this module. Please try another.`0`n');
            }
        } elseif ($subop == 'push') {
            $data = httppost('data');
            $array = httppost('array');
            if (!empty($data) && !empty($array)) {
                set_module_setting('data', $data, 'serialisededitor');
                set_module_setting('array', stripslashes($array), 'serialisededitor');
                output('`#The array data has been saved and is ready for editing. Click the Editor link to the side to begin.`0`n');
            } else {
                output('`$Error: `4No array data could be found. Please try again.`0`n');
            }
        } elseif ($subop == 'pop') {
            if (httpget('subop2') == 'return') {
                $array = get_module_setting('array', 'serialisededitor');
                $data = get_module_setting('data', 'serialisededitor');
                if (!empty($data)) {
                    list($modulename, $setting, $userid) = explode('|', $data);
                    db_query("UPDATE " . db_prefix('module_userprefs') . " SET value = '" . $array . "' WHERE modulename = '" . $modulename . "' AND setting = '" . $setting . "' AND userid = '" . $userid . "'");
                    output("`#The array data has been saved back to its original location.`0`n`n");
                    set_module_setting('data', '', 'serialisededitor');
                    set_module_setting('array', '', 'serialisededitor');
                } else {
                    output('`$Error: `4The data was missing, could not put the array back.`0`n');
                }
            } else {
                output('`#If you have finished editing the array then you can return the data back to its original location.`n`n');
                output('Click the link to the side to put it back.');
                addnav('Put Back');
                addnav('Continue', 'runmodule.php?module=serialisededitor&op=find&subop=push&subop2=return');
            }
        }
    } else {
        $sarray = unserialize(get_module_setting('array', 'serialisededitor'));
        // The unserialised array gets added to a new array with the key '0'.
        $names[] = !is_array($sarray) ? array('population' => 'you') : $sarray;
        $keyid = httpget('key') ? httpget('key') : httppost('key');
        if (!empty($keyid)) {
            $urls = '';
            $parts = '';
            $i = 1;
            $keyids = explode('|', $keyid);
            foreach ($keyids as $key => $value) {
                // Take a specific array from the multi-dimensional array and add it back with its own key.
                // Only with a specific branch of the tree.
                $names[] = $names[$i - 1][$value];
                // This makes the links for under the form.
                $parts .= $i == 1 ? $value : '|' . $value;
                $urls .= '[<a href="runmodule.php?module=serialisededitor&key=' . $parts . '">' . $value . '</a>]';
                addnav('', 'runmodule.php?module=serialisededitor&key=' . $parts);
                $i++;
            }
            // Reverse the array because we want the last to be first and have the key '0'.
            $names = array_reverse($names);
        }
        if (httpget('subop') == 'save') {
            // These are arrays!
            $keyname = httppost('keyname');
            $keyvalue = httppost('keyvalue');
            $keynameorig = httppost('keynameorig');
            $keyvalueorig = httppost('keyvalueorig');
            // Chars to strip out.
            $find = array('"', "'");
            $messages = '`#';
            foreach ($keyname as $key => $value) {
                if (!empty($value)) {
                    // Strip out quotes from key name.
                    $value = str_replace($find, '', $value);
                    if (isset($keynameorig[$key]) && $value != $keynameorig[$key]) {
                        // Key name changed, do this first.
                        if (!isset($names[0][$value])) {
                            // Easiest way to rename is to create a new key with the same value and delete the old key.
                            // This is the reason why renamed keys get put last, they're new. :)
                            $names[0][$value] = $names[0][$keynameorig[$key]];
                            unset($names[0][$keynameorig[$key]]);
                            $messages .= 'The key name `b' . $keynameorig[$key] . '`b has been renamed to `b' . $value . '`b.`n';
                        } else {
                            $messages .= '`$The key name `b' . $value . '`b already exists in this array branch. Please use another.`#`n';
                        }
                    }
                    if (!empty($keyvalue[$key])) {
                        if ($keyvalue[$key] == 'ARRAY') {
                            // Add a new array.
                            if (!empty($keynameorig[$key])) {
                                $messages .= 'Existing key name `b' . $value . '`b has been turned into an array.`n';
                            } else {
                                $messages .= 'The key name `b' . $value . '`b has been added and made an array.`n';
                            }
                            $names[0][$value] = array('populate' => 'me');
                        } else {
                            // Only did this part for the messages.
                            if (!empty($keyvalueorig[$key])) {
                                // Old value exists, check to see if it matches the new.
                                if ($keyvalueorig[$key] != $keyvalue[$key]) {
                                    $names[0][$value] = $keyvalue[$key];
                                    $messages .= 'The value of key `b' . $value . '`b has been changed from `b' . $keyvalueorig[$key] . '`b to `b' . stripslashes($keyvalue[$key]) . '`b.`n';
                                }
                            } else {
                                // Again for the messages.
                                if (isset($names[0][$value]) && isset($keynameorig[$key])) {
                                    // Existing key has had it's value changed from nothing to something.
                                    $messages .= 'The value of key name `b' . $value . '`b has been changed from nothing to `b' . stripslashes($keyvalue[$key]) . '`b.`n';
                                } else {
                                    // New key has been added with a value.
                                    $messages .= 'The key name `b' . $value . '`b has been added with a value of `b' . stipslashes($keyvalue[$key]) . '`b.`n';
                                }
                                $names[0][$value] = $keyvalue[$key];
                            }
                        }
                    } else {
                        // Array keynames don't have any values so check before making null.
                        if (!is_array($names[0][$value])) {
                            if (empty($keyvalue[$key]) && !empty($keyvalueorig[$key])) {
                                // key had a value, but no it doesn't.
                                $messages .= 'The value of key name `b' . $value . '`b has been changed from `b' . $keyvalueorig[$key] . '`b to nothing.`n';
                            } elseif (empty($keynameorig[$key]) && empty($keyvalue[$key]) && empty($keyvalueorig[$key])) {
                                // New key has been added, but with no value.
                                $messages .= 'The key name `b' . $value . '`b has been created and saved with no value.`n';
                            }
                            $names[0][$value] = '';
                        }
                    }
                } else {
                    // Delete.
                    if (isset($names[0][$keynameorig[$key]])) {
                        unset($names[0][$keynameorig[$key]]);
                        $messages .= 'The key name `b' . $keynameorig[$key] . '`b and its value have been deleted.`n';
                    }
                }
            }
            // $names is used further down to build the display so make a copy and alter it instead.
            $pass_over = $names[0];
            if (!empty($keyids)) {
                $keyids = array_reverse($keyids);
                $count = count($names);
                for ($i = 0; $i < $count; $i++) {
                    if (isset($names[1])) {
                        $shift = array_shift($names);
                        $names[0][$keyids[$i]] = $shift;
                    }
                }
            }
            set_module_setting('array', serialize($names[0]), 'serialisededitor');
            $message .= 'Array has been serialized and saved.`0';
            $names[0] = $pass_over;
            debug($names[0]);
        }
        output('%s`0`n`n', translate_inline($messages));
        output('`n`c`#Do not use numbers to name the keys, use words only.`0`c`n`n');
        $trans = translate_inline(array('Key Name', 'Value', 'This value is an array.', 'Extra Boxes', 'Submit', 'Click to Edit', 'Array Tree Branch Links'));
        rawoutput('<form action="runmodule.php?module=serialisededitor&subop=save" method="POST">');
        addnav('', 'runmodule.php?module=serialisededitor&subop=save');
        rawoutput('<table border="0" width="450" cellpadding="1" cellspacing="1" align="center">');
        rawoutput('<tr class="trhead"><td>' . $trans[0] . '</td><td>' . $trans[1] . '</td></tr>');
        rawoutput('<tr class="' . (0 % 2 ? 'trlight' : 'trdark') . '"><td colspan="2">');
        output('`3To delete any of the following, simply delete the key name before submitting. Renaming a key will force it to the bottom.`0');
        rawoutput('</td></tr>');
        // Build the form for the current array tree branch.
        if (!empty($names[0])) {
            $i = 1;
            foreach ($names[0] as $key => $value) {
                rawoutput('<tr class="' . ($i % 2 ? 'trlight' : 'trdark') . '"><td><input type="text" name="keyname[]" value="' . $key . '" /><input type="hidden" name="keynameorig[]" value="' . $key . '" /></td>');
                if (is_array($value)) {
                    // Don't over write $keyid as it's used below!
                    $keyid2 = empty($keyid) ? '' : $keyid . '|';
                    rawoutput('<td>' . $trans[2] . ' <a href="runmodule.php?module=serialisededitor&key=' . $keyid2 . $key . '">' . $trans[5] . '</a><input type="hidden" name="keyvalue[]" value="" /><input type="hidden" name="keyvalueorig[]" value="" /></td></tr>');
                    addnav('', 'runmodule.php?module=serialisededitor&key=' . $keyid2 . $key);
                } else {
                    rawoutput('<td><textarea name="keyvalue[]" col="20" row="5">' . stripslashes($value) . '</textarea><input type="hidden" name="keyvalueorig[]" value="' . stripslashes($value) . '" /></td></tr>');
                }
                $i++;
            }
        } else {
            rawoutput('<tr class="trlight"><td><input type="text" name="keyname[]" value="" /></td><td><textarea name="keyvalue[]" col="20" row="5"></textarea></td></tr>');
        }
        rawoutput('<tr class="trhead"><td colspan="2">' . $trans[3] . '</td></tr>');
        rawoutput('<tr class="trdark"><td colspan="2">');
        output('`3To add another array, simply type `#`bARRAY`b `3into the box and submit. You can do this with existing values, but there\'s no way to convert back once this is done.`0');
        rawoutput('</td></tr><tr class="trlight"><td><input type="text" name="keyname[]" value="" /></td><td><textarea name="keyvalue[]" col="20" row="5"></textarea></td></tr>');
        rawoutput('<tr class="trdark"><td><input type="text" name="keyname[]" value="" /></td><td><textarea name="keyvalue[]" col="20" row="5"></textarea></td></tr>');
        rawoutput('<tr class="trhead"><td colspan="2">' . $trans[6] . '</td></tr>');
        rawoutput('<tr class="trlight"><td colspan="2"><a href="runmodule.php?module=serialisededitor">$array</a>' . $urls . '</td></tr>');
        addnav('', 'runmodule.php?module=serialisededitor');
        rawoutput('<tr class="trdark"><td align="center" colspan="2"><input type="hidden" name="key" value="' . $keyid . '" /><input type="submit" class="button" value="' . $trans[4] . '" /></td></tr></table></form><br /><br />');
        rawoutput('<table border="0" cellpadding="2" cellspacing="1" align="center">');
        $text = display_array($names[0]);
        rawoutput("{$text}");
        rawoutput('</table>');
    }
    addnav('Options');
    addnav('Array Editor', 'runmodule.php?module=serialisededitor');
    addnav('Find Array To Edit', 'runmodule.php?module=serialisededitor&op=find');
    addnav('View Array Source', 'runmodule.php?module=serialisededitor&op=source');
    addnav('Put Array Back', 'runmodule.php?module=serialisededitor&op=find&subop=pop');
    addnav('Back');
    addnav('Back to the Grotto', 'superuser.php');
    page_footer();
}
function breakin_run()
{
    global $session, $pvptimeout, $pvptime;
    $op = httpget("op");
    $danger = get_module_setting("danger");
    require_once "lib/partner.php";
    $partner = get_partner();
    // Need to include this in here so we pick up the pvptimeout/etc in
    // the right scope.
    require_once "lib/pvplist.php";
    // this is a variable in case an admin changes the name of the inn
    $iname = getsetting("innname", LOCATION_INN);
    page_header($iname);
    output("`&`c`bThe Ivy-Covered Door`b`c");
    if ($op == "") {
        addnav("D?Force the Door", "runmodule.php?module=breakin&op=force");
        addnav("F?Forget it", "runmodule.php?module=breakin&op=leave");
        output("`7As you approach the door, you hear the sounds of drunken revelry.");
        output("You realize that this door must be a back entrance to the Inn.`n`n");
        output("`7As you pull some of the vines away, you discover that the door is flimsy and moves as you push at it.");
        output("The realization dawns that you could sneak upstairs for free and slay another player as they sleep!");
        output("`7Merick tends to his animals and pays you no attention.");
        output("Will you break in?`n`n");
    } elseif ($op == "leave") {
        addnav("Return from whence you came", "stables.php");
        output("`7You really don't want to break the door down, so you quietly walk back over to the stables.`n`n");
    } elseif ($op == "go") {
        addnav("Return from whence you came", "stables.php");
        output("`7You really don't think it is worth the risk, so you quietly go back outside and walk over to the stables.`n`n");
    } elseif ($op == "ledger-safe") {
        output("You begin to scan the names in the ledger, trying to decide who to attack.`n`n");
        pvplist($iname, "pvp.php", "?act=attack&inn=1");
        addnav("List Warriors", "runmodule.php?module=breakin&op=ledger-safe");
        addnav("Forget it", "runmodule.php?module=breakin&op=go");
    } elseif ($op == "ledger") {
        $danger = get_module_setting("danger");
        $bchance = e_rand(0, 100);
        output("You begin to scan the names in the ledger, trying to decide who to attack.`n`n");
        if ($bchance > $danger) {
            // I hate doing a redirect here, but if we don't, the ledger list
            // won't be 'safe' if you view a bio and then return.
            redirect("runmodule.php?module=breakin&op=ledger-safe");
        } else {
            output("Before you can do anything, a powerful blow to the head knocks you to the ground.");
            output("Cedrik stands over you, a wine bottle in one hand, scowling angrily.`n`n");
            if (get_module_setting("stocks")) {
                output("He yells for a guard, and before you can collect your senses, the two of them have hoisted you out the front door of the Inn, and into the stocks.`n");
                set_module_setting("victim", $session['user']['acctid'], "stocks");
                set_module_setting("thisID", $session['user']['acctid']);
                invalidatedatacache("stocks");
            } else {
                output("He yells for a guard, and before you can collect your senses, the two of them have 'escorted' you out the front door of the Inn.`n");
            }
            if (get_module_setting("robloss")) {
                output("As you struggle to retain conciousness, you feel the guard relieving you of some of your possessions.`n");
                $losspercent = get_module_setting("robloss") / 100;
                $gems = round($session['user']['gems'] * $losspercent, 0);
                $gold = round($session['user']['gold'] * $losspercent, 0);
                if ($gems) {
                    if ($gems == 1) {
                        output("`&The guard `\$takes `%%s`& gem.`n", $gems);
                    } else {
                        output("`&The guard `\$takes `%%s`& gems.`n", $gems);
                    }
                    $session['user']['gems'] -= $gems;
                    debuglog("lost {$gems} gems to the gaurd when caught breaking in to the Inn");
                }
                if ($gold) {
                    output("`&The guard `\$takes `^%s`& gold.`n", $gold);
                    $session['user']['gold'] -= $gold;
                    debuglog("lost {$gold} gold to the gaurd when caught breaking in to the Inn");
                }
            }
            if (get_module_setting("losecharm")) {
                output("`7%s`7 watches the whole thing with a frown.`n`n", $partner);
                output("`^You `\$lose`^ some charm!`n");
                if ($session['user']['charm'] >= 3) {
                    $session['user']['charm'] -= 3;
                } else {
                    $session['user']['charm'] = 0;
                }
            }
            if (get_module_setting("hploss")) {
                output("`^Your head throbs, and you feel weak.`n");
                $hp = round($session['user']['hitpoints'] * get_module_setting("hploss") / 100, 0);
                $session['user']['hitpoints'] -= $hp;
                if ($session['user']['hitpoints'] < 1) {
                    $session['user']['hitpoints'] = 1;
                }
            }
            output("Moments later, you pass out from the pain in your head.`n`n");
            if (get_module_setting("wipepvp")) {
                $session['user']['playerfights'] = 0;
                output("`n`nYou don't feel like you can attack anyone today.`n`n");
                debuglog("lost all their player fights after being caught breaking into the Inn");
            }
            addnews("`&%s `7tried to break into the Inn, and was caught by Cedrik.", $session['user']['name']);
            addnav("Wake Up", "village.php");
            if (get_module_setting("guilt")) {
                set_module_pref("guilt", 2);
            }
        }
    } else {
        set_module_pref("breaktoday", 1);
        if (get_module_setting("guilt")) {
            set_module_pref("guilt", 2);
        }
        output("`7You lean on the door heavily with one shoulder, and it gives way with a crack as the wood splinters around the lock.`n`n");
        $ringchance = e_rand(1, 20);
        output("You find yourself in a small office.");
        if (get_module_pref("ring") == 0 && $ringchance == 1) {
            output("On the desk in front of you, there is a set of labeled keys, a diamond ring, and a small ledger listing the guests in each room. ");
            set_module_pref("ring", 1);
            output("You take the ring and slip it quickly into your pocket.`n`n");
            // need to check if module exists on this server
            if (is_module_active("matthias")) {
                $astute = get_module_pref("astuteness", "matthias");
                $astute++;
                set_module_pref("astuteness", $astute, "matthias");
            }
        } else {
            output("On the desk in front of you, there is a set of labeled keys and a small ledger listing the guests in each room. ");
        }
        output("Beyond an open doorway to one side, you hear the inn patrons talking, and you realize how dangerous this idea is!`n`n");
        addnav("Forget it", "runmodule.php?module=breakin&op=go");
        //		if (is_module_active("pvpimmunity") && !get_module_pref("check_willing","pvpimmunity")){
        //			output("You are repelled by the idea of sneaking into somebody else's room, so you find nothing else of interest here.`n`n");
        //		} else {
        addnav("Look at the Ledger", "runmodule.php?module=breakin&op=ledger");
        //		}
        // Help the superusers debug
        if ($session['user']['superuser'] & SU_EDIT_USERS) {
            addnav("Safe look", "runmodule.php?module=breakin&op=ledger-safe");
        }
    }
    page_footer();
}
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 oldchurch_run()
{
    global $session;
    page_header("Old Church");
    $op = httpget('op');
    $bloodgift = get_module_pref("bloodgift");
    if ($bloodgift == 1) {
        output("`7As you approach the old church, you are beset with troubling flashes of what happened last time you were here.");
        output("`n`nYou decide to come back another day.");
        villagenav();
    } elseif ($op == "") {
        output("`7An ancient church stands alone, apart from the other buildings, centuries-old scorchmarks marring the once grand walls and curling round the belltower.");
        output("`n`nA thin path winds its way up the hill between sinister-looking memorials covered in mist.");
        output("While the church has obviously been abandoned for a long time, the windows flicker with light from the inside and shadows can be seen dancing on the tall broken shards of glass which fill the windows.");
        addnav("Enter the Church", "runmodule.php?module=oldchurch&op=enter");
        addnav("Return to the Village", "village.php");
    } elseif ($op == "enter") {
        output("`3You make your way up the hill and edge through the sundered doors, taking in the wrecked interior.");
        output("A flickering torch inhabits an iron holder to one side, above a dusty font.");
        output("Beyond the shattered pews lies an altar which has fresh cloths on it and six candles burning dimly.`n`n");
        output("From out of a small door to one side of the altar walks a curiously hearty figure dressed in grey robes who, ignoring the desolate surroundings, opens his arms wide and bids you welcome to the church, \"`^Greetings, greetings, welcome to this little sanctuary. I am `5Capelthwaite`^, and it is good to see people once again visiting this holy place, feel free to look around. My apologies for the current... disarray... but the world is as the Gods decree it, and we must merely live with such things.`3\"");
        output("He casts an appraising eye over you and smiles even more broadly before continuing,");
        output("\"`^Naturally we are always in need of funds for various charitable projects, and if you wish to donate you will of course gain an appropriate reward.");
        output("For those as hardy an adventurer as you there are obviously other ways to earn a blessing if you are short of funds.`3\"");
        output("He smiles to himself and waits at the altar for your decision.");
        addnav("Climb to the Belfry", "runmodule.php?module=oldchurch&op=belfry");
        addnav("Examine the Font", "runmodule.php?module=oldchurch&op=font");
        addnav("Donate Gold", "runmodule.php?module=oldchurch&op=donate");
        addnav("Ask About \"Other Ways\"", "runmodule.php?module=oldchurch&op=ritual");
        addnav("Leave this Place", "village.php");
    } elseif ($op == "belfry") {
        output("`7You walk to the back of the church and climb the unsteady steps up to the belfry, where a large rusted bell hangs from rotting timbers.");
        output("Though you'd expect to get a great view from up here, even the nearby buildings seem shrouded in fog.");
        $random = e_rand(1, 3);
        if ($random >= 2) {
            output("`n`nAs you hurry down from the belfry, you accidentally knock into the bell, which makes an eerily resonant sound as it tolls.");
        }
        output("Spooked slightly, you hurry down the stairs and back into the church.");
        addnav("Examine the Font", "runmodule.php?module=oldchurch&op=font");
        addnav("Donate Gold", "runmodule.php?module=oldchurch&op=donate");
        addnav("Ask About \"Other Ways\"", "runmodule.php?module=oldchurch&op=ritual");
        addnav("Leave this Place", "village.php");
    } elseif ($op == "font") {
        output("`\$As you wander over to the alcove by the door and look inside, there seem to be dark stains inside the font, as though it was not usually used for water.");
        output("`n`n`^Slightly troubled by this, you return to the main part of the church.");
        addnav("Climb to the Belfry", "runmodule.php?module=oldchurch&op=belfry");
        addnav("Donate Gold", "runmodule.php?module=oldchurch&op=donate");
        addnav("Ask About \"Other Ways\"", "runmodule.php?module=oldchurch&op=ritual");
        addnav("Leave this Place", "village.php");
    } elseif ($op == "donate") {
        output("`5Capelthwaite `^grins as you walk over to the donation plate, waiting to see how much you will put in before making any preparations.");
        $donate = array("donation" => "Donation,int");
        require_once "lib/showform.php";
        rawoutput("<form action='runmodule.php?module=oldchurch&op=afterdonate' method='POST'>");
        showform($donate, array(), true);
        addnav("", "runmodule.php?module=oldchurch&op=afterdonate");
        $give = translate_inline("Give Money");
        rawoutput("<input type='submit' class='button' value='{$give}'>");
        rawoutput("</form><br>");
        addnav("Change your mind", "runmodule.php?module=oldchurch&op=enter");
        addnav("Leave this Place", "village.php");
    } elseif ($op == "afterdonate") {
        $donation = httppost('donation');
        if ($donation > $session['user']['gold'] || $donation < 0) {
            output("`5Capelthwaite `^looks somewhat grim as you try to persuade him that it is the spirit of giving which counts.`n`n");
            output("You are hastily ejected from the church.");
        } elseif ($donation >= $session['user']['level'] * 103) {
            output("`^As you put a hefty amount of gold in the bowl, `5Capelthwaite`^'s grin widens and he beckons you over to the altar for a blessing.");
            output("`n`nAfter muttering something a little too fast for you to catch, he places his hand on your head and blesses you.");
            output("`n`n`@You feel energy flowing through you!");
            $session['user']['gold'] -= $donation;
            debuglog("donated {$donation} gold at the old church");
            $donated = get_module_pref("donated");
            apply_buff('capelthwaite_blessing', array("name" => "`5Capelthwaite's Blessing", "rounds" => 15, "wearoff" => "The burst of energy passes.", "atkmod" => $donated ? 1.05 : 1.2, "defmod" => $donated ? 1.01 : 1.1, "roundmsg" => "Energy flows through you!", "schema" => "module-oldchurch"));
            output("Filled with energy you stumble out of the church.");
            set_module_pref("donated", 1);
        } else {
            output("`^As the few coins you decided to spare rattle into the bowl, `5Capelthwaite`^'s grin turns sickening as he beckons you over to the altar.`n`n");
            output("After muttering something too low for you to catch, he places his hand on your head and places the enchantment on you.`n`n");
            output("`4Dark energy flows through you!");
            apply_buff('capelthwaite_curse', array("name" => "`5Capelthwaite's \"Blessing\"", "rounds" => 10, "wearoff" => "The burst of energy passes.", "atkmod" => 0.8, "defmod" => 0.9, "roundmsg" => "Dark Energy flows through you!", "schema" => "module-oldchurch"));
            output("Filled with energy you stumble out of the church.");
            $session['user']['gold'] -= $donation;
            debuglog("donated {$donation} gold at the old church");
            set_module_pref("donated", 1);
        }
        villagenav();
    } elseif ($op == "ritual") {
        output("`3You nervously inquire about another way that you could earn a blessing as `5Capelthwaite`3 looks on you magnanimously.`n`n");
        output("\"`^No need to be so nervous my friend, simply a short rite to honour the master, you'll feel fine the next day. Just take this potion and I'll take care of everything.`3\".`n`n");
        output("He holds out a small black potion he produced from somewhere for you to drink and smiles encouragingly.");
        addnav("Take the Potion", "runmodule.php?module=oldchurch&op=darkritual");
        addnav("Leave this Place", "village.php");
    } elseif ($op == "darkritual") {
        output("`^Trusting in `5Capelthwaite`^'s friendly smile, you drink down the potion. You feel funny for a moment, then the world begins to swim before your eyes, and you black out.`n`n");
        $ritual = e_rand(1, 100);
        if ($ritual >= 100) {
            output("`7Though the potion sapped all will from your body, you remain conscious as you are dragged somewhere, hooded, by several people.");
            output("When the hood is removed you are in a cavern deep underground, trapped in what looks like some artist's rendition of the underworld.");
            output("You are dressed in a grey robe and placed on the edge of a smoke-filled circle with many others similarly outfitted.");
            output("For what seems like hours you are surrounded by chanting, smoke and the sensation of life being drained from your very soul.");
            output("Eventually you are dragged back up through some tunnels like a sack of grain before being dumped in front of the altar, where `5Capelthwaite`7 feeds you another potion.`n`n");
        } else {
            output("You dream of smoke and a glowing light.`n`n");
        }
        output("`^You regain your faculties with `5Capelthwaite`^ leaning over you, looking red-faced.");
        output("He quickly blesses you before helping you out of the church.`n`n");
        output("`@You feel energy flowing through you!`n`n");
        apply_buff('capelthwaite_blessing', array("name" => "`5Capelthwaite's Blessing", "rounds" => 15, "wearoff" => "The burst of energy passes.", "atkmod" => 1.2, "defmod" => 1.1, "roundmsg" => "Energy flows through you!", "schema" => "module-oldchurch"));
        output("You hurry away from this place as fast as your unsteady legs can take you.");
        $ritualenergy = get_module_setting("ritualenergy");
        $ritualenergy++;
        set_module_setting("ritualenergy", $ritualenergy);
        set_module_pref("bloodgift", 1);
        if ($session['user']['turns'] >= 5) {
            $session['user']['turns']--;
        }
        $session['user']['hitpoints'] *= 0.5;
        if ($session['user']['hitpoints'] < 1) {
            $sesson['user']['hitpoints'] = 1;
        }
        villagenav();
    }
    page_footer();
}
function timeandweather_update()
{
    $now = time();
    $last = get_module_setting("lastupdate", "timeandweather");
    $change = get_module_setting("changeevery", "timeandweather");
    $changeat = $last + $change;
    //debug($changeat);
    if ($now > $changeat) {
        set_module_setting("lastupdate", $now, "timeandweather");
        //time to change the weather
        $old = get_module_setting("currentweather", "timeandweather");
        set_module_setting("lastweather", $old, "timeandweather");
        $new = e_rand(-2, 2);
        increment_module_setting("currentweather", $new, "timeandweather");
        if (get_module_setting("currentweather", "timeandweather") > 7) {
            set_module_setting("currentweather", 7, "timeandweather");
        } else {
            if (get_module_setting("currentweather", "timeandweather") < 1) {
                set_module_setting("currentweather", 1, "timeandweather");
            }
        }
    }
}
function titans_kill_titan($titan)
{
    global $session;
    //debug("Killing Titan!");
    //debug($titan);
    if (!$titan['battlelog']['killed']) {
        //debug("Titan is not dead, let's fix that!");
        $titan['battlelog']['killingblow_name'] = $session['user']['name'];
        $titan['battlelog']['killingblow_acctid'] = $session['user']['acctid'];
        $titan['battlelog']['killed'] = 1;
        $now = time();
        $titan['battlelog']['timeofdeath'] = $now;
        //determine lifetime, update averages, alter maximum Titan hitpoints if necessary
        $lifetime = $now - $titan['battlelog']['timeofbirth'];
        $desiredlifetime = get_module_setting("desiredlifetime", "titans");
        $curhp = get_module_setting("titanhp", "titans");
        $curspawnchance = get_module_setting("spawnchance", "titans");
        $curtotaltitans = get_module_setting("totaltitans", "titans");
        $curtotaltime = get_module_setting("totallifetime", "titans");
        $newtotaltitans = $curtotaltitans + 1;
        $newtotaltime = $curtotaltime + $lifetime;
        $avglifetime = $newtotaltime / $newtotaltitans;
        //allow a large deviation in the current data before immediately changing
        if ($lifetime < $desiredlifetime * 0.5) {
            $newhp = $curhp * 1.05;
        } else {
            if ($lifetime > $desiredlifetime * 2) {
                $newhp = $curhp * 0.95;
            } else {
                $newhp = $curhp;
            }
        }
        //allow a small deviation in the historical data before changing
        if ($lifetime < $desiredlifetime * 0.95) {
            $newhp = round(ceil($curhp * 1.05), -2);
            increment_module_setting("spawnchance", 1, "titans");
        } else {
            if ($lifetime > $desiredlifetime * 1.05) {
                $newhp = round(floor($curhp * 0.95), -2);
                if ($curspawnchance > 1) {
                    increment_module_setting("spawnchance", -1, "titans");
                }
            }
        }
        if ($newhp > 1000000) {
            set_module_setting("titanhp", $newhp, "titans");
        }
        set_module_setting("totaltitans", $newtotaltitans, "titans");
        set_module_setting("totallifetime", $newtotaltime, "titans");
        titans_award_req($titan);
        titans_set_titan($titan);
    }
    output("`0The Titan falls to the earth with a mighty crash, and lies still.  All combatants are immediately issued a Requisition reward to their bank accounts.  Offshore, `4The Watcher`0 smiles.`n`n");
    addnav("Crisis averted!");
    addnav("Back to the Map", "runmodule.php?module=worldmapen&op=continue");
    return $titan;
}
function worldmapen_saveMap()
{
    global $worldmapen_globals;
    if (is_null($worldmapen_globals["map"])) {
        debug("Sorry, no map defined until now. Can't save a nonexisting map. Will generate a new world.");
        $worldmapen_globals["map"] = worldmapen_generateNewMap();
    }
    set_module_setting("TerrainDefinition", serialize($worldmapen_globals["map"]));
}
function hundredpointrally_startnextrally()
{
    $data = unserialize(get_module_setting("data", "hundredpointrally"));
    $data['last'] = $data['current'];
    $data['current'] = $data['next'];
    unset($data['next']);
    //set the current rally's points
    $xmax = get_module_setting("worldmapsizeX", "worldmapen");
    $ymax = get_module_setting("worldmapsizeY", "worldmapen");
    $pointstaken = array();
    //sequenced co-ordinates
    for ($i = 1; $i <= 50; $i++) {
        $proposedpoint = e_rand(1, $xmax) . "," . e_rand(1, $ymax) . ",1";
        //make sure we don't use the same point twice
        while ($pointstaken[$proposedpoint]) {
            debug("Point " . $proposedpoint . " already taken, choosing again");
            $proposedpoint = e_rand(1, $xmax) . "," . e_rand(1, $ymax) . ",1";
        }
        $pointstaken[$proposedpoint] = true;
        $data['current']['sequencedpoints'][$i] = $proposedpoint;
    }
    for ($i = 1; $i <= 50; $i++) {
        $proposedpoint = e_rand(1, $xmax) . "," . e_rand(1, $ymax) . ",1";
        //make sure we don't use the same point twice
        while ($pointstaken[$proposedpoint]) {
            debug("Point " . $proposedpoint . " already taken, choosing again");
            $proposedpoint = e_rand(1, $xmax) . "," . e_rand(1, $ymax) . ",1";
        }
        $pointstaken[$proposedpoint] = true;
        $data['current']['unorderedpoints'][$i] = $proposedpoint;
    }
    //unordered co-ordinates
    $data['current']['open'] = true;
    //notify the players lined up for the next rally that the rally has begun
    require_once "lib/systemmail.php";
    if (count($data['current']['competitors']) > 0) {
        foreach ($data['current']['competitors'] as $key => $vals) {
            $to = $key;
            $subj = "The next Hundred-Point Rally has begun!";
            $body = "This is just a quick message to let you know that the next Hundred-Point Rally has begun!  Head out into the wilderness to find the first Rally Point!";
            systemmail($to, $subj, $body);
            //set them up with the first point
            $player = array();
            $player['sequencedpoints'] = 1;
            $player['activecurrent'] = true;
            $player['activenext'] = false;
            set_module_pref("data", serialize($player), "hundredpointrally", $to);
        }
    }
    set_module_setting("data", serialize($data), "hundredpointrally");
}
function dag_run_private()
{
    require_once "modules/dag/misc_functions.php";
    global $session;
    if (httpget('manage') != "true") {
        page_header("Dag Durnick's Table");
        output("<span style='color: #9900FF'>", true);
        output("`c`bDag Durnick's Table`b`c");
    } else {
        dag_manage();
    }
    $op = httpget('op');
    addnav("Navigation");
    addnav("I?Return to the Inn", "inn.php");
    if ($op != '') {
        addnav("Talk to Dag Durnick", "runmodule.php?module=dag");
    }
    if ($op == "list") {
        output("Dag fishes a small leather bound book out from under his cloak, flips through it to a certain page and holds it up for you to see.");
        output("\"`7Deese ain't the most recent figgers, I ain't just had time to get th' other numbers put in.`0\"`n`n");
        // ***ADDED***
        // By Andrew Senger
        // Added for new Bounty Code
        output("`c`bThe Bounty List`b`c`n");
        $sql = "SELECT bountyid,amount,target,setter,setdate FROM " . db_prefix("bounty") . " WHERE status=0 AND setdate<='" . date("Y-m-d H:i:s") . "' ORDER BY bountyid ASC";
        $result = db_query($sql);
        rawoutput("<table border=0 cellpadding=2 cellspacing=1 bgcolor='#999999'>");
        $amount = translate_inline("Amount");
        $level = translate_inline("Level");
        $name = translate_inline("Name");
        $loc = translate_inline("Location");
        $sex = translate_inline("Sex");
        $alive = translate_inline("Alive");
        $last = translate_inline("Last On");
        rawoutput("<tr class='trhead'><td><b>{$amount}</b></td><td><b>{$level}</b></td><td><b>{$name}</b></td><td><b>{$loc}</b></td><td><b>{$sex}</b></td><td><b>{$alive}</b></td><td><b>{$last}</b></td>");
        $listing = array();
        $totlist = 0;
        for ($i = 0; $i < db_num_rows($result); $i++) {
            $row = db_fetch_assoc($result);
            $amount = (int) $row['amount'];
            $sql = "SELECT name,alive,sex,level,laston,loggedin,lastip,location FROM " . db_prefix("accounts") . " WHERE acctid={$row['target']}";
            $result2 = db_query($sql);
            if (db_num_rows($result2) == 0) {
                /* this person has been deleted, clear bounties */
                $sql = "UPDATE " . db_prefix("bounty") . " SET status=1 WHERE target={$row['target']}";
                db_query($sql);
                continue;
            }
            $row2 = db_fetch_assoc($result2);
            $yesno = 0;
            for ($j = 0; $j <= $i; $j++) {
                if (isset($listing[$j]) && $listing[$j]['Name'] == $row2['name']) {
                    $listing[$j]['Amount'] = $listing[$j]['Amount'] + $amount;
                    $yesno = 1;
                }
            }
            if ($yesno == 0) {
                $loggedin = date("U") - strtotime($row2['laston']) < getsetting("LOGINTIMEOUT", 900) && $row2['loggedin'];
                $listing[] = array('Amount' => $amount, 'Level' => $row2['level'], 'Name' => $row2['name'], 'Location' => $row2['location'], 'Sex' => $row2['sex'], 'Alive' => $row2['alive'], 'LastOn' => $row2['laston'], 'LoggedIn' => $loggedin);
                $totlist = $totlist + 1;
            }
        }
        $sort = httpget("sort");
        if ($sort == "level") {
            usort($listing, 'dag_sortbountieslevel');
        } elseif ($sort != "") {
            usort($listing, 'dag_sortbounties');
        } else {
            usort($listing, 'dag_sortbountieslevel');
        }
        for ($i = 0; $i < $totlist; $i++) {
            rawoutput("<tr class='" . ($i % 2 ? "trdark" : "trlight") . "'><td>");
            output_notl("`^%s`0", $listing[$i]['Amount']);
            rawoutput("</td><td>");
            output_notl("`^%s`0", $listing[$i]['Level']);
            rawoutput("</td><td>");
            output_notl("`^%s`0", $listing[$i]['Name']);
            rawoutput("</td><td>");
            output($listing[$i]['LoggedIn'] ? "`#Online`0" : $listing[$i]['Location']);
            rawoutput("</td><td>");
            output($listing[$i]['Sex'] ? "`!Female`0" : "`!Male`0");
            rawoutput("</td><td>");
            output($listing[$i]['Alive'] ? "`1Yes`0" : "`4No`0");
            rawoutput("</td><td>");
            $laston = relativedate($listing[$i]['LastOn']);
            output_notl("%s", $laston);
            rawoutput("</td></tr>");
        }
        rawoutput("</table>");
        // ***END ADDING***
    } else {
        if ($op == "addbounty") {
            if (get_module_pref("bounties") >= get_module_setting("maxbounties")) {
                output("Dag gives you a piercing look.");
                output("`7\"Ye be thinkin' I be an assassin or somewhat?  Ye already be placin' more than 'nuff bounties for t'day.  Now, be ye gone before I stick a bounty on yer head fer annoyin' me.\"`n`n");
            } else {
                $fee = get_module_setting("bountyfee");
                if ($fee < 0 || $fee > 100) {
                    $fee = 10;
                    set_module_setting("bountyfee", $fee);
                }
                $min = get_module_setting("bountymin");
                $max = get_module_setting("bountymax");
                output("Dag Durnick glances up at you and adjusts the pipe in his mouth with his teeth.`n");
                output("`7\"So, who ye be wantin' to place a hit on? Just so ye be knowing, they got to be legal to be killin', they got to be at least level %s, and they can't be having too much outstandin' bounty nor be getting hit too frequent like, so if they ain't be listed, they can't be contracted on!  We don't run no slaughterhouse here, we run a.....business.  Also, there be a %s%% listin' fee fer any hit ye be placin'.\"`n`n", get_module_setting("bountylevel"), get_module_setting("bountyfee"));
                rawoutput("<form action='runmodule.php?module=dag&op=finalize' method='POST'>");
                output("`2Target: ");
                rawoutput("<input name='contractname'>");
                output_notl("`n");
                output("`2Amount to Place: ");
                rawoutput("<input name='amount' id='amount' width='5'>");
                output_notl("`n`n");
                $final = translate_inline("Finalize Contract");
                rawoutput("<input type='submit' class='button' value='{$final}'>");
                rawoutput("</form>");
                addnav("", "runmodule.php?module=dag&op=finalize");
            }
        } elseif ($op == "finalize") {
            if (httpget('subfinal') == 1) {
                $sql = "SELECT acctid,name,login,level,locked,age,dragonkills,pk,experience FROM " . db_prefix("accounts") . " WHERE name='" . addslashes(rawurldecode(stripslashes(httppost('contractname')))) . "' AND locked=0";
            } else {
                $contractname = stripslashes(rawurldecode(httppost('contractname')));
                $name = "%";
                for ($x = 0; $x < strlen($contractname); $x++) {
                    $name .= substr($contractname, $x, 1) . "%";
                }
                $sql = "SELECT acctid,name,login,level,locked,age,dragonkills,pk,experience FROM " . db_prefix("accounts") . " WHERE name LIKE '" . addslashes($name) . "' AND locked=0";
            }
            $result = db_query($sql);
            if (db_num_rows($result) == 0) {
                output("Dag Durnick sneers at you, `7\"There not be anyone I be knowin' of by that name.  Maybe ye should come back when ye got a real target in mind?\"");
            } elseif (db_num_rows($result) > 100) {
                output("Dag Durnick scratches his head in puzzlement, `7\"Ye be describing near half th' town, ye fool?  Why don't ye be giving me a better name now?\"");
            } elseif (db_num_rows($result) > 1) {
                output("Dag Durnick searches through his list for a moment, `7\"There be a couple of 'em that ye could be talkin' about.  Which one ye be meaning?\"`n");
                rawoutput("<form action='runmodule.php?module=dag&op=finalize&subfinal=1' method='POST'>");
                output("`2Target: ");
                rawoutput("<select name='contractname'>");
                for ($i = 0; $i < db_num_rows($result); $i++) {
                    $row = db_fetch_assoc($result);
                    rawoutput("<option value=\"" . rawurlencode($row['name']) . "\">" . full_sanitize($row['name']) . "</option>");
                }
                rawoutput("</select>");
                output_notl("`n`n");
                $amount = httppost('amount');
                output("`2Amount to Place: ");
                rawoutput("<input name='amount' id='amount' width='5' value='{$amount}'>");
                output_notl("`n`n");
                $final = translate_inline("Finalize Contract");
                rawoutput("<input type='submit' class='button' value='{$final}'>");
                rawoutput("</form>");
                addnav("", "runmodule.php?module=dag&op=finalize&subfinal=1");
            } else {
                // Now, we have just the one, so check it.
                $row = db_fetch_assoc($result);
                if ($row['locked']) {
                    output("Dag Durnick sneers at you, `7\"There not be anyone I be knowin' of by that name.  Maybe ye should come back when ye got a real target in mind?\"");
                } elseif ($row['login'] == $session['user']['login']) {
                    output("Dag Durnick slaps his knee laughing uproariously, `7\"Ye be wanting to take out a contract on yerself?  I ain't be helping no suicider, now!\"");
                } elseif ($row['level'] < get_module_setting("bountylevel") || $row['age'] < getsetting("pvpimmunity", 5) && $row['dragonkills'] == 0 && $row['pk'] == 0 && $row['experience'] < getsetting("pvpminexp", 1500)) {
                    output("Dag Durnick stares at you angrily, `7\"I told ye that I not be an assassin.  That ain't a target worthy of a bounty.  Now get outta me sight!\"");
                } else {
                    // All good!
                    $amt = abs((int) httppost('amount'));
                    $min = get_module_setting("bountymin") * $row['level'];
                    $max = get_module_setting("bountymax") * $row['level'];
                    $fee = get_module_setting("bountyfee");
                    $cost = round($amt * ((100 + $fee) / 100), 0);
                    $curbounty = 0;
                    $sql = "SELECT sum(amount) AS total FROM " . db_prefix("bounty") . " WHERE status=0 AND target={$row['acctid']}";
                    $result = db_query($sql);
                    if (db_num_rows($result) > 0) {
                        $nrow = db_fetch_assoc($result);
                        $curbounty = $nrow['total'];
                    }
                    if ($amt < $min) {
                        output("Dag Durnick scowls, `7\"Ye think I be workin' for that pittance?  Be thinkin' again an come back when ye willing to spend some real coin.  That mark be needin' at least %s gold to be worth me time.\"", $min);
                    } elseif ($session['user']['gold'] < $cost) {
                        output("Dag Durnick scowls, `7\"Ye don't be havin enough gold to be settin' that contract.  Wastin' my time like this, I aught to be puttin' a contract on YE instead!");
                    } elseif ($amt + $curbounty > $max) {
                        if ($curbounty) {
                            output("Dag looks down at the pile of coin and just leaves them there.");
                            output("`7\"I'll just be passin' on that contract.  That's way more'n `^%s`7 be worth and ye know it.  I ain't no durned assassin. A bounty o' %s already be on their head, what with the bounties I ain't figgered in to th' book already.  I might be willin' t'up it to %s, after me %s%% listin' fee of course\"`n`n", $row['name'], $curbounty, $max, $fee);
                        } else {
                            output("Dag looks down at the pile of coin and just leaves them there.");
                            output("`7\"I'll just be passin' on that contract.  That's way more'n `^%s`7 be worth and ye know it.  I ain't no durned assassin.  I might be willin' t'let y' set one of %s, after me %s%% listin' fee of course\"`n`n", $row['name'], $max, $fee);
                        }
                    } else {
                        output("You slide the coins towards Dag Durnick, who deftly palms them from the table.");
                        output("`7\"I'll just be takin' me %s%% listin' fee offa the top.  The word be put out that ye be wantin' `^%s`7 taken care of. Be patient, and keep yer eyes on the news.\"`n`n", $fee, $row['name']);
                        set_module_pref("bounties", get_module_pref("bounties") + 1);
                        $session['user']['gold'] -= $cost;
                        // ***ADDED***
                        // By Andrew Senger
                        // Adding for new Bounty Code
                        $setdate = time();
                        // random set date up to 4 hours in the future.
                        $setdate += e_rand(0, 14400);
                        $sql = "INSERT INTO " . db_prefix("bounty") . " (amount, target, setter, setdate) VALUES ({$amt}, " . $row['acctid'] . ", " . (int) $session['user']['acctid'] . ", '" . date("Y-m-d H:i:s", $setdate) . "')";
                        db_query($sql);
                        // ***END ADD***
                        debuglog("spent {$cost} to place a {$amt} bounty on {$row['name']}");
                    }
                }
            }
        } else {
            output("You stroll over to Dag Durnick, who doesn't even bother to look up at you.");
            output("He takes a long pull on his pipe.`n");
            output("`7\"Ye probably be wantin' to know if there's a price on yer head, ain't ye.\"`n`n");
            // ***ADDED***
            // By Andrew Senger
            // Adding for new Bounty Code
            $sql = "SELECT sum(amount) as total FROM " . db_prefix("bounty") . " WHERE status=0 AND setdate<='" . date("Y-m-d H:i:s") . "' AND target=" . $session['user']['acctid'];
            $result = db_query($sql);
            $curbounty = 0;
            if (db_num_rows($result) != 0) {
                $row = db_fetch_assoc($result);
                $curbounty = $row['total'];
            }
            if ($curbounty == 0) {
                output("\"`3Ye don't have no bounty on ya.  I suggest ye be keepin' it that way.\"");
            } else {
                output("\"`3Well, it be lookin like ye have `^%s gold`3 on yer head currently. Ye might wanna be watchin yourself.\"", $curbounty);
            }
            // ***END ADD***
            addnav("Bounties");
            addnav("Check the Wanted List", "runmodule.php?module=dag&op=list");
            addnav("Set a Bounty", "runmodule.php?module=dag&op=addbounty");
        }
    }
    modulehook('dagnav');
    if ($op == "list") {
        addnav("Sort List");
        addnav("View by Bounty", "runmodule.php?module=dag&op=list&sort=bounty");
        addnav("View by Level", "runmodule.php?module=dag&op=list&sort=level");
    }
    rawoutput("</span>");
    page_footer();
}
<?php

// We only care about the names of locations.
if ($args['setting'] == "villagename") {
    $old = $args['old'];
    $new = $args['new'];
    // Handle any locations of the old name and convert them.
    $x = get_module_setting($old . 'X');
    $y = get_module_setting($old . 'Y');
    $z = get_module_setting($old . 'Z');
    set_module_setting('worldmapen' . $new . 'X', $x);
    set_module_setting('worldmapen' . $new . 'Y', $y);
    set_module_setting('worldmapen' . $new . 'Z', $z);
    set_module_setting('worldmapen' . $old . 'X', "");
    set_module_setting('worldmapen' . $old . 'Y', "");
    set_module_setting('worldmapen' . $old . 'Z', "");
    // Handle any players who last city was the old name.
    $sql = "UPDATE " . db_prefix("module_userprefs") . " SET value='" . addslashes($new) . "' WHERE value='" . addslashes($old) . "' AND modulename='worldmapen' AND setting = 'lastCity'";
    db_query($sql);
}
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();
}
<?php

page_header("Actions Management");
$op2 = httpget('op2');
if ($op2 == "del") {
    $act = actions_list();
    $key = httpget('key');
    $value = $act[$key];
    output("All values of the action \"" . $value . "\" were deleted.");
    $stamina = db_prefix("stamina");
    db_query("DELETE FROM {$stamina} WHERE action='{$key}'");
    unset($act[$key]);
    set_module_setting("actionsarray", serialize($act), "staminasystem");
    actions_list();
    $actiondebug = get_module_setting("actionsarray", "staminasystem");
    debug($actiondebug);
    addnav("Continue");
    addnav("Continue", "runmodule.php?module=staminasystem&op=superuser");
}
if ($op2 == "new") {
    $new = httppost('action');
    output("The action \"{$new}\" has been added.");
    $act = actions_list();
    $act[] = $new;
    set_module_setting("actionsarray", serialize($act), "staminasystem");
    $act = actions_list();
    addnav("Continue");
    addnav("Continue", "runmodule.php?module=staminasystem&op=superuser");
}
page_footer();
function remake_costs()
{
    $cost = array();
    $total = 0;
    if (get_module_setting("allowatk")) {
        $cost['atk']['active'] = get_module_setting("atkaprice");
        $cost['atk'][0] = 0;
        $cost['atk'][1] = get_module_setting("atkbase");
        for ($i = 2; $i <= get_module_setting("maxatk"); $i++) {
            $cost['atk'][$i] = $cost['atk'][$i - 1] + $i * get_module_setting("atkinc");
        }
        $total += $cost['atk'][get_module_setting("maxatk")] + $cost['atk']['active'];
    }
    if (get_module_setting("allowdef")) {
        $cost['def']['active'] = get_module_setting("defaprice");
        $cost['def'][0] = 0;
        $cost['def'][1] = get_module_setting("defbase");
        for ($i = 2; $i <= get_module_setting("maxdef"); $i++) {
            $cost['def'][$i] = $cost['def'][$i - 1] + $i * get_module_setting("definc");
        }
        $total += $cost['def'][get_module_setting("maxdef")] + $cost['def']['active'];
    }
    if (get_module_setting("allowdrain")) {
        $cost['drain']['active'] = get_module_setting("drainaprice");
        $cost['drain'][0] = 0;
        $cost['drain'][1] = get_module_setting("drainbase");
        for ($i = 2; $i <= get_module_setting("maxdrain"); $i++) {
            $cost['drain'][$i] = $cost['drain'][$i - 1] + $i * get_module_setting("draininc");
        }
        $total += $cost['drain'][get_module_setting("maxdrain")] + $cost['drain']['active'];
    }
    if (get_module_setting("allowthorn")) {
        $cost['thorn']['active'] = get_module_setting("thornaprice");
        $cost['thorn'][0] = 0;
        $cost['thorn'][1] = get_module_setting("thornbase");
        for ($i = 2; $i <= get_module_setting("maxthorn"); $i++) {
            $cost['thorn'][$i] = $cost['thorn'][$i - 1] + $i * get_module_setting("thorninc");
        }
        $total += $cost['thorn'][get_module_setting("maxthorn")] + $cost['thorn']['active'];
    }
    if (get_module_setting("allowregen")) {
        $cost['regen']['active'] = get_module_setting("regenaprice");
        $cost['regen'][0] = 0;
        $cost['regen'][1] = get_module_setting("regenbase");
        for ($i = 2; $i <= get_module_setting("maxregen"); $i++) {
            $cost['regen'][$i] = $cost['regen'][$i - 1] + $i * +get_module_setting("regeninc");
        }
        $total += $cost['regen'][get_module_setting("maxregen")] + $cost['regen']['active'];
    }
    $cost['round'][0] = 0;
    $cost['round'][1] = get_module_setting("roundbase");
    for ($i = 2; $i <= get_module_setting("maxround"); $i++) {
        $cost['round'][$i] = $cost['round'][$i - 1] + $i * +get_module_setting("roundinc");
    }
    $total += $cost['round'][get_module_setting("maxround")];
    if (get_module_setting("allowult")) {
        $cost['ult']['allow'] = $total;
        $cost['ult']['active'] = get_module_setting("ultaprice");
        $total += $cost['ult']['active'];
    }
    $cost['total'] = $total;
    set_module_setting("costarray", serialize($cost));
    set_module_setting("remakecost", 0);
}
function install_module($module, $force = true)
{
    global $mostrecentmodule, $session;
    $name = $session['user']['name'];
    if (!$name) {
        $name = '`@System`0';
    }
    require_once "lib/sanitize.php";
    if (modulename_sanitize($module) != $module) {
        output("Error, module file names can only contain alpha numeric characters and underscores before the trailing .php`n`nGood module names include 'testmodule.php', 'joesmodule2.php', while bad module names include, 'test.module.php' or 'joes module.php'`n");
        return false;
    } else {
        // If we are forcing an install, then whack the old version.
        if ($force) {
            $sql = "DELETE FROM " . db_prefix("modules") . " WHERE modulename='{$module}'";
            db_query($sql);
        }
        // We want to do the inject so that it auto-upgrades any installed
        // version correctly.
        if (injectmodule($module, true)) {
            // If we're not forcing and this is already installed, we are done
            if (!$force && is_module_installed($module)) {
                return true;
            }
            $info = get_module_info($module);
            //check installation requirements
            if (!module_check_requirements($info['requires'])) {
                output("`\$Module could not installed -- it did not meet its prerequisites.`n");
                return false;
            } else {
                $keys = "|" . join(array_keys($info), "|") . "|";
                $sql = "INSERT INTO " . db_prefix("modules") . " (modulename,formalname,moduleauthor,active,filename,installdate,installedby,category,infokeys,version,download,description) VALUES ('{$mostrecentmodule}','" . addslashes($info['name']) . "','" . addslashes($info['author']) . "',0,'{$mostrecentmodule}.php','" . date("Y-m-d H:i:s") . "','" . addslashes($name) . "','" . addslashes($info['category']) . "','{$keys}','" . addslashes($info['version']) . "','" . addslashes($info['download']) . "', '" . addslashes($info['description']) . "')";
                db_query($sql);
                $fname = $mostrecentmodule . "_install";
                if (isset($info['settings']) && count($info['settings']) > 0) {
                    foreach ($info['settings'] as $key => $val) {
                        if (is_array($val)) {
                            $x = explode("|", $val[0]);
                        } else {
                            $x = explode("|", $val);
                        }
                        if (isset($x[1])) {
                            $x[1] = trim($x[1]);
                            set_module_setting($key, $x[1]);
                            debug("Setting {$key} to default {$x[1]}");
                        }
                    }
                }
                if ($fname() === false) {
                    return false;
                }
                output("`^Module installed.  It is not yet active.`n");
                invalidatedatacache("inject-{$mostrecentmodule}");
                massinvalidate("moduleprepare");
                return true;
            }
        } else {
            output("`\$Module could not be injected.");
            output("Module not installed.");
            output("This is probably due to the module file having a parse error or not existing in the filesystem.`n");
            return false;
        }
    }
}
 if (injectmodule($module, true)) {
     $save = httpget('save');
     if ($save != "") {
         load_module_settings($module);
         $old = $module_settings[$module];
         $post = httpallpost();
         $post = modulehook("validatesettings", $post, true, $module);
         if (isset($post['validation_error'])) {
             $post['validation_error'] = translate_inline($post['validation_error']);
             output("Unable to change settings:`\$%s`0", $post['validation_error']);
         } else {
             reset($post);
             while (list($key, $val) = each($post)) {
                 $key = stripslashes($key);
                 $val = stripslashes($val);
                 set_module_setting($key, $val);
                 if (!isset($old[$key]) || $old[$key] != $val) {
                     output("Setting %s to %s`n", $key, $val);
                     // Notify modules
                     if ($key == "villagename") {
                         debug("Moving companions");
                         $sql = "UPDATE " . db_prefix("companions") . " SET companionlocation = '" . addslashes($val) . "' WHERE companionlocation = '" . addslashes($old[$key]) . "'";
                         db_query($sql);
                     }
                     $oldval = "";
                     if (isset($old[$key])) {
                         $oldval = $old[$key];
                     }
                     gamelog("`@changed module setting `^{$module}.{$key}`@ from `3{$oldval}`@ to `#{$val}`0", "settings");
                     modulehook("changesetting", array("module" => $module, "setting" => $key, "old" => $oldval, "new" => $val), true);
                 }