function scry_dohook($hookname, $args)
{
    global $session;
    switch ($hookname) {
        case "commentary":
            if (get_module_pref("speaking")) {
                set_module_pref("talks", get_module_pref("talks") + 1);
            }
            break;
        case "gypsy":
            set_module_pref("talks", 0);
            $cost = get_module_setting("cost") * $session['user']['level'];
            output("`n`nOff in the corner, you see a dark bowl of water sitting atop a silver tray.");
            output("Noticing your gaze, the old gypsy woman rasps, \"`!Ahh, perhaps you seek to talk to people in one of the other towns?  I could do that -- for the very small price of `^%s`! gold.`5\"", $cost);
            addnav(array("Scrying (%s gold)", $cost));
            $vloc = array();
            $vname = getsetting("villagename", LOCATION_FIELDS);
            $vloc[$vname] = "village";
            $vloc = modulehook("validlocation", $vloc);
            // this is a different modulehook call because
            // there is more than one "validlocation" modulehook
            $vloc = modulehook("scrylocation", $vloc);
            ksort($vloc);
            reset($vloc);
            foreach ($vloc as $loc => $val) {
                if ($loc == $session['user']['location']) {
                    continue;
                }
                addnav(array("Scry %s", $loc), "runmodule.php?module=scry&op=pay&area=" . htmlentities($val, ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "&village=" . htmlentities($loc, ENT_COMPAT, getsetting("charset", "ISO-8859-1")));
            }
            break;
    }
    return $args;
}
function mysticalshop_destroyitem($item_type, $rare_id = FALSE, $userid = FALSE)
{
    global $session;
    $id = "";
    if ($userid === FALSE) {
        $userid = $session['user']['acctid'];
        $id = get_module_pref($item_type . "id", "mysticalshop", $userid);
    }
    modulehook("mysticalshop-destroyitem", array("itemid" => $id));
    if ($rare_id) {
        $sql = "UPDATE " . db_prefix("magicitems") . " SET rarenum=rarenum+1 WHERE id='{$rare_id}'";
        db_query($sql);
        if (getsetting('usedatacache', false)) {
            invalidatedatacache('modules-mysticalshop-enter');
            require_once './modules/mysticalshop/libcoredup.php';
            mysticalshop_massinvalidate('modules-mysticalshop-viewgoods-');
        }
    }
    $sing_item_type = $item_type;
    if ($item_type == 'boot') {
        $item_type = 'boots';
    }
    // $id = FALSE; <-- What was that here for? --WK
    set_module_pref($item_type, 0, "mysticalshop", $userid);
    //set_module_pref($sing_item_type."id",0,"mysticalshop",$userid);
    set_module_pref($sing_item_type . "name", "None", "mysticalshop", $userid);
}
function oneshotteleporter_run()
{
    global $session;
    $to = httpget("to");
    if ($to == "") {
        page_header("The Void");
        output("You press the button on your One-Shot Teleporter.  One obligatory blinding flash of light and pain later, you find yourself floating around in empty black nothingness!`n`nA flashing red light and an annoying BEEPing noise from your device insists that you select a destination, and quickly, before you find yourself stuck here or imploded.");
        $vloc = array();
        $vname = getsetting("villagename", LOCATION_FIELDS);
        $vloc[$vname] = "village";
        $vloc = modulehook("validlocation", $vloc);
        ksort($vloc);
        reset($vloc);
        addnav("Choose a Destination");
        foreach ($vloc as $loc => $val) {
            addnav(array("Go to %s", $loc), "runmodule.php?module=oneshotteleporter&to=" . htmlentities($loc));
        }
    } else {
        page_header("Back to Reality");
        output("You quickly select an outpost from the list.  With a sudden jolt, you find yourself standing in the middle of your chosen outpost!  You look around for your teleporting device, but realise that it must have only teleported you, not itself.  What a piece of junk.");
        $session['user']['location'] = $to;
        $session['user']['specialinc'] = "";
        addnav("Continue");
        addnav("Back to the Outpost", "village.php");
    }
    page_footer();
    return true;
}
function avatar_showimages($set)
{
    $races = modulehook("racenames");
    rawoutput("<table cellpadding='0' cellspacing='0' border='0' bgcolor='#999999'>");
    $r = translate_inline("Race");
    $m = translate_inline("Male Image");
    $f = translate_inline("Female Image");
    rawoutput("<tr class='trhead'><th>{$r}</th><th>{$m}</th><th>{$f}</th></tr>");
    $i = 0;
    foreach ($races as $key => $race) {
        $r = strtolower($race);
        $imm = avatar_getimage($r, "male", $set);
        $imf = avatar_getimage($r, "female", $set);
        rawoutput("<tr class='" . ($i % 2 ? "trlight" : "trdark") . "'>");
        rawoutput("<th>");
        output_notl('`^');
        output($race);
        output_notl("`0");
        rawoutput("</th><td>");
        rawoutput($imm);
        rawoutput("</td><td>");
        rawoutput($imf);
        rawoutput("</td>");
        rawoutput("</tr>");
        $i++;
    }
    rawoutput("</table>");
}
function fightnav($allowspecial = true, $allowflee = true, $script = false)
{
    global $PHP_SELF, $session, $newenemies, $companions;
    tlschema("fightnav");
    if ($script === false) {
        $script = substr($PHP_SELF, strrpos($PHP_SELF, "/") + 1) . "?";
    } else {
        if (!strpos($script, "?")) {
            $script .= "?";
            //		}elseif (substr($script,strlen($script)-1)!="&" && !substr($script,strlen($script)-1)=="?"){
        } elseif (substr($script, strlen($script) - 1) != "&") {
            $script .= "&";
        }
    }
    $fight = "Fight";
    $run = "Run";
    if (!$session['user']['alive']) {
        $fight = "F?Torment";
        $run = "R?Flee";
    }
    addnav($fight, $script . "op=fight");
    if ($allowflee) {
        addnav($run, $script . "op=run");
    }
    if ($session['user']['superuser'] & SU_DEVELOPER) {
        addnav("Abort", $script);
    }
    if (getsetting("autofight", 0)) {
        addnav("Automatic Fighting");
        addnav("5?For 5 Rounds", $script . "op=fight&auto=five");
        addnav("1?For 10 Rounds", $script . "op=fight&auto=ten");
        $auto = getsetting("autofightfull", 0);
        if (($auto == 1 || $auto == 2 && !$allowflee) && count($newenemies) == 1) {
            addnav("U?Until End", $script . "op=fight&auto=full");
        } elseif ($auto == 1 || $auto == 2 && !$allowflee) {
            addnav("U?Until current enemy dies", $script . "op=fight&auto=full");
        }
    }
    if ($allowspecial) {
        addnav("Special Abilities");
        modulehook("fightnav-specialties", array("script" => $script));
        if ($session['user']['superuser'] & SU_DEVELOPER) {
            addnav("`&Super user`0", "");
            addnav("!?`&&#149; __GOD MODE", $script . "op=fight&skill=godmode", true);
        }
        modulehook("fightnav", array("script" => $script));
    }
    if (count($newenemies) > 1) {
        addnav("Targets");
        foreach ($newenemies as $index => $badguy) {
            if ($badguy['creaturehealth'] <= 0 || isset($badguy['dead']) && $badguy['dead'] == true) {
                continue;
            }
            addnav(array("%s%s`0", isset($badguy['istarget']) && $badguy['istarget'] ? "`#*`0" : "", $badguy['creaturename']), $script . "op=fight&newtarget={$index}");
        }
    }
    tlschema();
}
function dwellingseditor_run()
{
    global $session;
    tlschema("dwellingseditor");
    $op = httpget('op');
    if ($op != "lookup") {
        page_header("Dwellings Editor");
    }
    addnav("Navigation");
    addnav("Back to the Grotto", "superuser.php");
    if ($op != "") {
        addnav("Dwelling List", "runmodule.php?module=dwellingseditor");
    }
    addnav("Find Dwellings by User", "runmodule.php?module=dwellingseditor&op=usersearch");
    addnav("Operations");
    if ($op != "typsu") {
        addnav("Type Pref Editor", "runmodule.php?module=dwellingseditor&op=typesu");
    }
    modulehook("dwellingseditor-main");
    $typeid = httpget("typeid");
    $dwid = httpget('dwid');
    $type = httpget("type");
    if ($type == "" && $dwid > 0) {
        $sql = "SELECT type FROM " . db_prefix("dwellings") . " WHERE dwid={$dwid}";
        $result = db_query($sql);
        $row = db_fetch_assoc($result);
        $type = $row['type'];
    }
    if ($dwid > 0) {
        addnav("Operations");
        if ($op != "edit") {
            addnav("Edit Dwelling Details", "runmodule.php?module=dwellingseditor&op=edit&dwid={$dwid}");
        }
        if ($op != "keys") {
            addnav("Manage Keys", "runmodule.php?module=dwellingseditor&op=keys&dwid={$dwid}");
        }
        if ($session['user']['superuser'] & SU_EDIT_COMMENTS) {
            addnav("Moderate Commentary", "moderate.php?area=dwellings-{$dwid}&dwid={$dwid}");
        }
        if ($op != "delete") {
            addnav("Delete this Dwelling", "runmodule.php?module=dwellingseditor&op=delete&dwid={$dwid}");
        }
        modulehook("dwellingseditor", array("dwid" => $dwid));
        addnav("Navigation");
        if ($op != "coffers") {
            addnav("Coffer Log", "runmodule.php?module=dwellingseditor&op=coffers&dwid={$dwid}");
        }
        if ($op != "dwsu") {
            addnav("Dwelling  Viewer", "runmodule.php?module=dwellingseditor&op=dwsu&dwid={$dwid}");
        }
    }
    require_once "modules/dwellingseditor/case_{$op}.php";
    page_footer();
}
function forest($noshowmessage = false)
{
    global $session, $playermount;
    tlschema("forest");
    //	mass_module_prepare(array("forest", "validforestloc"));
    addnav("Heal");
    addnav("H?Hospital Tent", "healer.php");
    addnav("Fight");
    addnav("L?Look for Something to Kill", "forest.php?op=search");
    if ($session['user']['level'] > 1) {
        addnav("S?Go Slumming", "forest.php?op=search&type=slum");
    }
    addnav("T?Go Thrillseeking", "forest.php?op=search&type=thrill");
    if (getsetting("suicide", 0)) {
        if (getsetting("suicidedk", 10) <= $session['user']['dragonkills']) {
            addnav("*?Search `\$Suicidally`0", "forest.php?op=search&type=suicide");
        }
    }
    if ($session['user']['level'] >= 15 && $session['user']['seendragon'] == 0) {
        // Only put the green dragon link if we are a location which
        // should have a forest.   Don't even ask how we got into a forest()
        // call if we shouldn't have one.   There is at least one way via
        // a superuser link, but it shouldn't happen otherwise.. We just
        // want to make sure however.
        $isforest = 0;
        $vloc = modulehook('validforestloc', array());
        foreach ($vloc as $i => $l) {
            if ($session['user']['location'] == $i) {
                $isforest = 1;
                break;
            }
        }
        if ($isforest || count($vloc) == 0) {
            addnav("G?`@Seek Out the Green Dragon", "forest.php?op=dragon");
        }
    }
    addnav("Other");
    villagenav();
    if ($noshowmessage != true) {
        output("`c`7`bThe Forest`b`0`c");
        output("The Forest, home to evil creatures and evildoers of all sorts.`n`n");
        output("The thick foliage of the forest restricts your view to only a few yards in most places.");
        output("The paths would be imperceptible except for your trained eye.");
        output("You move as silently as a soft breeze across the thick moss covering the ground, wary to avoid stepping on a twig or any of the numerous pieces of bleached bone that populate the forest floor, lest you betray your presence to one of the vile beasts that wander the forest.`n");
        modulehook("forest-desc");
    }
    modulehook("forest", array());
    module_display_events("forest", "forest.php");
    addnav("Inventory");
    addnav("View your Inventory", "inventory.php?items_context=forest");
    tlschema();
}
/**
 * This function prepares the fight, sets up options and gives hook a hook to change options on a per-player basis.
 *
 * @param array $options The options given by a module or basics.
 * @return array The complete options.
 */
function prepare_fight($options = false)
{
    global $companions;
    $basicoptions = array("maxattacks" => getsetting("maxattacks", 4));
    if (!is_array($options)) {
        $options = array();
    }
    $fightoptions = $options + $basicoptions;
    $fightoptions = modulehook("fightoptions", $fightoptions);
    // We'll also reset the companions here...
    prepare_companions();
    return $fightoptions;
}
function holidayize($text, $type = 'unknown')
{
    global $session;
    if (!isset($session['user']['prefs']['ihavenocheer'])) {
        $session['user']['prefs']['ihavenocheer'] = 0;
    }
    if ($session['user']['prefs']['ihavenocheer']) {
        return $text;
    }
    $args = array('text' => $text, 'type' => $type);
    $args = modulehook("holiday", $args);
    $text = $args['text'];
    return $text;
}
function pvpwarning($dokill = false)
{
    global $session;
    $days = getsetting("pvpimmunity", 5);
    $exp = getsetting("pvpminexp", 1500);
    if ($session['user']['age'] <= $days && $session['user']['dragonkills'] == 0 && $session['user']['pk'] == 0 && $session['user']['experience'] <= $exp) {
        if ($dokill) {
            output("`\$Warning!`^ Since you were still under PvP immunity, but have chosen to attack another player, you have lost this immunity!!`n`n");
            $session['user']['pk'] = 1;
        } else {
            output("`\$Warning!`^ Players are immune from Player vs Player (PvP) combat for their first %s days in the game or until they have earned %s experience, or until they attack another player.  If you choose to attack another player, you will lose this immunity!`n`n", $days, $exp);
        }
    }
    modulehook("pvpwarning", array("dokill" => $dokill));
}
function extrarandom_dohook($hookname, $args)
{
    global $session;
    switch ($hookname) {
        case "choosebadguy":
            //If we've seen this creature before, choose a new one
            $pcreatures = @unserialize(get_module_pref("lastcreatures"));
            if (!is_array($pcreatures)) {
                $pcreatures = array();
            }
            if ($args['creatureid'] > 1) {
                global $attempts;
                if (in_array($args['creatureid'], $pcreatures)) {
                    if ($attempts < 3) {
                        //re-roll, getting a creature from the same level
                        debug("We've seen " . $args['creaturename'] . " too recently - switching monster");
                        $lvl = $args['creaturelevel'];
                        $id = $args['creatureid'];
                        if ($args['forest']) {
                            $sql = "SELECT * FROM " . db_prefix("creatures") . " WHERE creaturelevel = {$lvl} AND forest=1 AND creatureid != {$id} ORDER BY rand(" . e_rand() . ") LIMIT 1";
                        } else {
                            if ($args['graveyard']) {
                                $sql = "SELECT * FROM " . db_prefix("creatures") . " WHERE creaturelevel = {$lvl} AND forest=1 AND creatureid != {$id} ORDER BY rand(" . e_rand() . ") LIMIT 1";
                            }
                        }
                        $result = db_query($sql);
                        $args = db_fetch_assoc($result);
                        $attempts++;
                        $args = modulehook("choosebadguy", $args);
                    } else {
                        debug("Screw it!  Too many attempts!");
                    }
                }
                $pcreatures[] = $args['creatureid'];
                $count = count($pcreatures);
                $des = 8;
                if ($count > $des) {
                    for ($i = 0; $i < $count - $des; $i++) {
                        array_shift($pcreatures);
                    }
                }
                set_module_pref("lastcreatures", serialize($pcreatures));
            }
            break;
    }
    return $args;
}
function char_cleanup($id, $type)
{
    // this function handles the grunt work of character cleanup.
    // Run any modules hooks who want to deal with character deletion, or stop it
    $return = modulehook("delete_character", array("acctid" => $id, "deltype" => $type, "dodel" => true));
    if (!$return['dodel']) {
        return false;
    }
    //erase the player's items
    require_once "lib/items.php";
    items_delete_character($id);
    // delete the output field from the accounts_output table introduced in 1.1.1
    db_query("DELETE FROM " . db_prefix("accounts_output") . " WHERE acctid={$id};");
    // delete the comments the user posted, necessary to have the systemcomments with acctid 0 working
    db_query("DELETE FROM " . db_prefix("commentary") . " WHERE author={$id};");
    // Clean up any clan positions held by this character
    $sql = "SELECT clanrank,clanid FROM " . db_prefix("accounts") . " WHERE acctid={$id}";
    $res = db_query($sql);
    $row = db_fetch_assoc($res);
    if ($row['clanid'] != 0 && $row['clanrank'] == CLAN_LEADER) {
        $cid = $row['clanid'];
        // We need to auto promote or disband the clan.
        $sql = "SELECT name,acctid,clanrank FROM " . db_prefix("accounts") . " WHERE clanid={$cid} AND clanrank > " . CLAN_APPLICANT . " AND acctid<>{$id} ORDER BY clanrank DESC, clanjoindate";
        $res = db_query($sql);
        if (db_num_rows($res)) {
            // Okay, we can promote if needed
            $row = db_fetch_assoc($res);
            if ($row['clanrank'] != CLAN_LEADER) {
                // No other leaders, promote this one
                $id1 = $row['acctid'];
                $sql = "UPDATE " . db_prefix("accounts") . " SET clanrank=" . CLAN_LEADER . " WHERE acctid={$id1}";
                db_query($sql);
            }
        } else {
            // this clan needs to be disbanded.
            $sql = "DELETE FROM " . db_prefix("clans") . " WHERE clanid={$cid}";
            db_query($sql);
            // And just in case we goofed, no players associated with a
            // deleted clan  This shouldn't be important, but.
            $sql = "UPDATE " . db_prefix("accounts") . " SET clanid=0,clanrank=0,clanjoindate='0000-00-00 00:00;00' WHERE clanid={$cid}";
            db_query($sql);
        }
    }
    // Delete any module user prefs
    module_delete_userprefs($id);
    return true;
}
function increment_specialty($colorcode, $spec = false)
{
    global $session;
    if ($spec !== false) {
        $revertspec = $session['user']['specialty'];
        $session['user']['specialty'] = $spec;
    }
    tlschema("skills");
    if ($session['user']['specialty'] != "") {
        $specialties = modulehook("incrementspecialty", array("color" => $colorcode));
    } else {
        output("`7You have no direction in the world, you should rest and make some important decisions about your life.`0`n");
    }
    tlschema();
    if ($spec !== false) {
        $session['user']['specialty'] = $revertspec;
    }
}
function peerpressure_runevent($type)
{
    global $session;
    $session['user']['specialinc'] = "module:peerpressure";
    // For translation reasons, you cannot really substitute in his/her
    // since the gender can change other things
    if ($session['user']['sex']) {
        addnews("`&%s`7 heroically decided to seek out `@The Green Dragon`7 with cheers of encouragement from her peers ringing in her ears.", $session['user']['name']);
    } else {
        addnews("`&%s`7 heroically decided to seek out `@The Green Dragon`7 with cheers of encouragement from his peers ringing in his ears.", $session['user']['name']);
    }
    output("`2Wandering the village, going about your business, you are suddenly surrounded by a group of villagers.");
    output("They wonder why such an experienced adventurer as yourself hasn't slain a dragon yet.");
    output("You mutter some embarrassed excuses but they aren't listening.");
    output("They crowd around you closer, and lift you up on their shoulders.");
    $isforest = 0;
    $vloc = modulehook('validforestloc', array());
    foreach ($vloc as $i => $l) {
        if ($session['user']['location'] == $l) {
            $isforest = 1;
            break;
        }
    }
    if ($isforest || count($vloc) == 0) {
        output("`n`nCheering your name the whole way, they carry you into the forest, and right to the mouth of a cave outside the town!`n`n");
    } else {
        $key = array_rand($vloc);
        output("`n`nCheering your name the whole way, they carry you far into the forest, and right to the mouth of a cave outside the town of %s!`n`n", $key);
        $session['user']['location'] = $key;
    }
    output("Still cheering your name, they put you down and eagerly wait for you to enter and slay that dragon.`n`n");
    output("You know that you'd never live it down if you tried to back out now.");
    output("Swallowing your fear as best you can, you enter the cave.");
    if (is_module_active("dragonplace")) {
        addnav("Enter the cave", "runmodule.php?module=dragonplace&op=cave");
    } else {
        addnav("Enter the cave", "dragon.php?nointro=1");
    }
    $session['user']['specialinc'] = "";
    checkday();
    //increment buffs, newday buffs, and heal... and probably throw people off in general
    $session['user']['specialinc'] = "module:peerpressure";
    apply_buff('peerpressure', array("name" => "`2Heroic Valor", "rounds" => 20, "atkmod" => 1 + get_module_pref("dayspast") / 100, "defmod" => 1 + get_module_pref("dayspast") / 100, "startmsg" => "`2You fight bravely, considering the pressure you're under.", "wearoff" => "`@The Green Dragon`2 has beaten and burnt the bravery out of you.", "schema" => "module-peerpressure"));
}
function aitest_loadenemy($badguy)
{
    global $session;
    if (is_array($badguy)) {
        $badguy['creaturehealth'] = round($badguy['creaturehealth'] * get_module_setting("buffhp", "aitest") / 100);
        $badguy['creatureattack'] = round($badguy['creatureattack'] * get_module_setting("buffattack", "aitest") / 100);
        $badguy['creaturedefense'] = round($badguy['creaturedefense'] * get_module_setting("buffdefense", "aitest") / 100);
        if (!get_module_setting("allowgold")) {
            $badguy['creaturegold'] = 0;
        }
        if (!get_module_setting("allowexp")) {
            $badguy['creatureexp'] = 0;
        }
    } else {
        $badguy = array("creaturename" => "An Evil Doppelganger of " . $session['user']['name'], "creatureattack" => $session['user']['attack'], "creaturedefense" => $session['user']['defense'], "creaturehealth" => $session['user']['maxhitpoints'], "creaturegold" => 0, "creatureexp" => 0);
    }
    $badguy = modulehook("aitest", $badguy);
    return $badguy;
}
function villagenav($extra = false)
{
    global $session;
    $loc = $session['user']['location'];
    if ($extra === false) {
        $extra = "";
    }
    $args = modulehook("villagenav");
    if (array_key_exists('handled', $args) && $args['handled']) {
        return;
    }
    tlschema("nav");
    if ($session['user']['alive']) {
        addnav(array("V?Return to %s", $loc), "village.php{$extra}");
    } else {
        // user is dead
        addnav("S?Return to the Shades", "shades.php");
    }
    tlschema();
}
function superusernav()
{
    global $SCRIPT_NAME, $session;
    tlschema("nav");
    addnav("Navigation");
    if ($session['user']['superuser'] & ~SU_DOESNT_GIVE_GROTTO) {
        $script = substr($SCRIPT_NAME, 0, strpos($SCRIPT_NAME, "."));
        if ($script != "superuser") {
            $args = modulehook("grottonav");
            if (!array_key_exists('handled', $args) || !$args['handled']) {
                addnav("G?Return to the Grotto", "superuser.php");
            }
        }
    }
    $args = modulehook("mundanenav");
    if (!array_key_exists('handled', $args) || !$args['handled']) {
        addnav("M?Return to the Mundane", "village.php");
    }
    tlschema();
}
/**
 * Adds a news item for the current user
 *
 * @param string $text Line of text for the news.
 * @param array $options List of options, including replacements, to modify the acctid, date, or hide from biographies.
 * @todo Change the date format from Y-m-d to Y-m-d H:i:s.
 */
function addnews(string $text = '', array $options = [])
{
    global $translation_namespace, $session;
    $options = modulehook('addnews', $options);
    $news = db_prefix('news');
    $replacements = [];
    foreach ($options as $key => $val) {
        if (is_numeric($key)) {
            array_push($replacements, $val);
        }
    }
    $text = sprintf_translate($text, $replacements);
    $date = $options['date'] ?? date('Y-m-d');
    $acctid = $options['acctid'] ?? $session['user']['acctid'];
    if (!$options['hide']) {
        $sql = db_query("INSERT INTO {$news} (newstext, newsdate, accountid, tlschema)\n            VALUES ('{$text}', '{$date}', '{$acctid}', '{$translation_namespace}')");
    } else {
        $sql = db_query("INSERT INTO {$news} (newstext, newsdate, tlschema)\n            VALUES ('{$text}', '{$date}', '{$translation_namespace}')");
    }
}
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 char_cleanup(int $id, int $type) : bool
{
    $return = modulehook('delete_character', ['acctid' => $id, 'deltype' => $type, 'dodel' => true]);
    if (!$return['dodel']) {
        return false;
    }
    $accounts = db_prefix('accounts');
    $accountsOutput = db_prefix('accounts_output');
    $commentary = db_prefix('commentary');
    $mail = db_prefix('mail');
    $news = db_prefix('news');
    $clans = db_prefix('clans');
    db_query("DELETE FROM {$accountsOutput} WHERE acctid = '{$id}'");
    db_query("DELETE FROM {$commentary} WHERE author = '{$id}'");
    db_query("DELETE FROM {$mail} WHERE msgto = '{$id}' OR msgfrom = '{$id}'");
    db_query("DELETE FROM {$news} WHERE accountid = '{$id}'");
    module_delete_userprefs($id);
    $leader = CLAN_LEADER;
    $applicant = CLAN_APPLICANT;
    $sql = db_query("SELECT clanrank, clanid FROM {$accounts} WHERE acctid = '{$id}'");
    $row = db_fetch_assoc($sql);
    if ($row['clanid'] != 0 && $row['clanrank'] == $leader) {
        $cid = $row['clanid'];
        $sql = db_query("SELECT acctid, clanrank\n            FROM {$accounts}\n            WHERE clanid = '{$row['clanid']}'\n            AND clanrank > '{$applicant}'\n            AND acctid != '{$id}'\n            ORDER BY clanrank DESC, clanjoindate");
        if (db_num_rows($sql)) {
            $row = db_fetch_assoc($sql);
            if ($row['clanrank'] != $leader) {
                db_query("UPDATE {$accounts} SET clanrank = '{$leader}' WHERE acctid = {$row['acctid']}");
            }
        } else {
            db_query("DELETE FROM {$clans} WHERE clanid = '{$row['clanid']}'");
            db_query("UPDATE {$accounts}\n                SET clanid = '0',\n                clanrank = '0',\n                clanjoindate = '0000-00-00 00:00:00'\n                WHERE clanid = '{$row['clanid']}'");
        }
    }
    $sql = db_query("DELETE FROM {$accounts} WHERE acctid = '{$id}'");
    if (!$sql) {
        return false;
    }
    return true;
}
function counciloffices_run()
{
    global $session;
    page_header("Council Offices");
    switch (httpget('councilop')) {
        case "enter":
            switch ($session['user']['location']) {
                case "NewHome":
                    output("The \"Council Offices\" of this Outpost amount to a tiny hut with a man inside reading a newspaper behind a desk.  He looks up as you come in.`n`n\"`1Can I help you?`0\"`n`n");
                    break;
                case "Kittania":
                    output("The \"Council Offices\" of this Outpost amount to a tiny hut with a patient-looking KittyMorph sat behind a desk inside.  She looks up as you come in.`n`n\"`1What can I do for you?`0\"`n`n");
                    break;
                case "New Pittsburgh":
                    output("The \"Council Offices\" of this Outpost amount to a tiny hut with a patient-looking Zombie sat behind a desk inside.  She looks up as you come in.`n`n\"`1What can I do for you?`0\"`n`n");
                    break;
                case "Squat Hole":
                    output("You step into the dilapidated Council Offices.  For a moment, you believe yourself to be alone; then, you notice the shining bald head sat behind the desk.  A squeaky voice shouts \"`1Y'arright there chuck, what d'ya want?`0\"`n`n");
                    break;
                case "Pleasantville":
                    output("The \"Council Offices\" of this Outpost amount to a tiny hut with a patient-looking Mutant sat behind a desk inside.  He looks up as you come in.`n`n\"`1What can I do for you?`0\"`n`n");
                    break;
                case "Cyber City 404":
                    output("The \"Council Offices\" of this Outpost amount to a tiny hut with a stern-looking Robot sat behind a desk inside.  He looks up as you come in.`n`n\"`1State your request.`0\"`n`n");
                    break;
                case "AceHigh":
                    output("The \"Council Offices\" of this Outpost amount to a tiny hut with an immaculately-dressed woman sat reading a newspaper behind a desk.  She looks up as you come in, eyes giving off a faint green glow.`n`n\"`1What can I do for you?`0\"`n`n");
                    break;
                case "Improbable Central":
                    output("The \"Council Offices\" of this Outpost amount to a tiny hut with a man inside reading a newspaper behind a desk.  He looks up as you come in.`n`n\"`1Can I help you?`0\"`n`n");
                    break;
            }
            addnav("State your business.");
            addnav("O?You know, I don't have a clue what I came in here for.  Back to the Outpost.", "village.php");
            break;
    }
    modulehook("counciloffices");
    page_footer();
}
function rail_peddler_dohook($hookname, $args)
{
    global $session;
    switch ($hookname) {
        case "improbablehousing_interior":
            $hid = $args['hid'];
            $rid = $args['rid'];
            $loc = rail_peddler_getloc();
            if ($hid == $loc['peddlerhid'] && $rid == $loc['peddlerrid']) {
                // We're in the right place to meet the peddler
                $price = get_module_setting("peddlerprice");
                if ($session['user']['gems'] >= $price && !rail_hascard("cardcase")) {
                    // note: this is a one-time character event, so we won't restrict tries per day.
                    switch (e_rand(1, 5)) {
                        case 1:
                            output("Among hurrying crowds in the concourse, a scruffy figure approaches a distant passer-by. At first the contestant shakes his head, then looks more interested. He digs out his tobacco pouch and receives something, you can't quite make out what, in exchange for a handful of cigarettes.`n`n");
                            break;
                        case 2:
                            output("Behind you a far-off voice calls out, \"`2Best levver, best levver cases! Bloody `bbadass`b cases! Bleedin' ace! Brung in special fer yer, an' cheap at twice the price!`0\"`n`nWhen you turn around, though, you can't make out who it might have been.`n`n");
                            break;
                        case 3:
                            output("A voice at your elbow says, \"`2Ey mate, y'looks like yer knows what's o'clock. Looky 'ere. `bgen`b-oo-`bwine`b levver, hand tooled an' all, sale price today jus' special fer ye, on'y `b%s`b bleedin' ciggies. What d'yer say, hey?`0\"`n`nYou examine the small leather case thrust under your nose. It does seem quite well-made, though you're not sure what you'd use it for.`n`n\"`2C'mon mate, it's ace, all da badasses and Holy Cheese showoffs are buying 'em up. When dey're gone, dey're gone! Dis here's yer lucky chance, I haveta make a sale today b'fore I kin go home ta care fer me old muvver. I'm offring it ta yer b'low me bleedin' cost!`0\"`n`nYou eye the case, pondering. You do have the cigs. The seller doesn't `ilook`i much like the Shady Salesman...`n`n", $price);
                            addnav("What do you do?");
                            addnav("Buy the case", "runmodule.php?module=rail_peddler&op=buy");
                            addnav("Pass on the offer", "runmodule.php?module=rail_peddler&op=pass");
                            break;
                    }
                } else {
                    if (rail_hascard("cardcase")) {
                        // this hook lets the peddler have a continued existence as a rumormonger
                        $args = modulehook("railpeddler-hascase", $args);
                    }
                }
            }
            break;
    }
    return $args;
}
// case "key":
// arsort($gr);
// usort($gr, 'sortcarriers');
// break;
// case "alpha":
// usort($gr,'alphacompare');
// usort($gr, 'sortcarriers');
// break;
// case "qty":
// usort($gr,'qtycompare');
// usort($gr, 'sortcarriers');
// break;
// }
// //debug($gr);
$hook = array('inventory' => $gr, 'context' => $context, 'sort' => $sort);
$hook = modulehook("inventory", $hook);
$context = $hook['context'];
$inventory = $hook['inventory'];
$dinv = array();
$carriers = array();
//arrange display inventory
foreach ($inventory as $itemid => $vals) {
    if (!$vals['carrieritem']) {
        $dinv[$vals['inventorylocation']]['items'][$itemid] = $vals;
    } else {
        $dinv[$vals['carrieritem']]['carrier'] = $vals;
        $carriers[$vals['carrieritem']] = $vals;
    }
}
output("Jump to: ");
foreach ($carriers as $carrier => $vals) {
    unsuspend_companions("allowinshades");
    if (!getsetting("newdaycron", 0)) {
        //check last time we did this vs now to see if it was a different game day.
        $lastnewdaysemaphore = convertgametime(strtotime(getsetting("newdaySemaphore", "0000-00-00 00:00:00") . " +0000"));
        $gametoday = gametime();
        if (gmdate("Ymd", $gametoday) != gmdate("Ymd", $lastnewdaysemaphore)) {
            // it appears to be a different game day, acquire semaphore and
            // check again.
            $sql = "LOCK TABLES " . db_prefix("settings") . " WRITE";
            db_query($sql);
            clearsettings();
            $lastnewdaysemaphore = convertgametime(strtotime(getsetting("newdaySemaphore", "0000-00-00 00:00:00") . " +0000"));
            $gametoday = gametime();
            if (gmdate("Ymd", $gametoday) != gmdate("Ymd", $lastnewdaysemaphore)) {
                //we need to run the hook, update the setting, and unlock.
                savesetting("newdaySemaphore", gmdate("Y-m-d H:i:s"));
                $sql = "UNLOCK TABLES";
                db_query($sql);
                require "lib/newday/newday_runonce.php";
            } else {
                //someone else beat us to it, unlock.
                $sql = "UNLOCK TABLES";
                db_query($sql);
            }
        }
    }
    $args = modulehook("newday", array("resurrection" => $resurrection, "turnstoday" => $turnstoday));
    $turnstoday = $args['turnstoday'];
    debuglog("New Day Turns: {$turnstoday}");
}
page_footer();
function quester_cities()
{
    if (is_module_active("cities")) {
        $locarray = array();
        $locarray = modulehook("validlocation", $locarray);
        //unset the blocked cities
        $blocked = explode(";", get_module_setting("excludecities"));
        foreach ($locarray as $lockey => $locval) {
            foreach ($blocked as $block) {
                if ($lockey == $block) {
                    unset($locarray[$lockey]);
                }
            }
        }
        //unset the capital
        unset($locarray[getsetting("villagename", LOCATION_FIELDS)]);
        //if for some reason somthing went wrong, set the default city as the city
        if (count($locarray) == 0) {
            set_module_pref("levelloc", getsetting("villagename", LOCATION_FIELDS));
        } else {
            set_module_pref("levelloc", array_rand($locarray));
        }
    }
}
        $session['user']['gold'] -= $compcost;
        $companions[$name]['hitpoints'] = $companions[$name]['maxhitpoints'];
        output("`3With a grimace, %s`3 up-ends the potion from the creature.`n", $companions[$name]['name']);
        output("Muscles knit back together, cuts close and bruises fade. %s`3 is ready to battle once again!`n", $companions[$name]['name']);
        output("You hand the creature your gold and are ready to be out of here.");
    }
}
$playerheal = false;
if ($session['user']['hitpoints'] < $session['user']['maxhitpoints']) {
    $playerheal = true;
    addnav("Potions");
    addnav("`^Complete Healing`0", "healer.php?op=buy&pct=100{$returnline}");
    for ($i = 90; $i > 0; $i -= 10) {
        addnav(array("%s%% - %s gold", $i, round($cost * $i / 100, 0)), "healer.php?op=buy&pct={$i}{$returnline}");
    }
    modulehook('potion');
}
addnav("`bHeal Companions`b");
$compheal = false;
foreach ($companions as $name => $companion) {
    if (isset($companion['cannotbehealed']) && $companion['cannotbehealed'] == true) {
    } else {
        $points = $companion['maxhitpoints'] - $companion['hitpoints'];
        if ($points > 0) {
            $compcost = round(log($session['user']['level'] + 1) * ($points + 10) * 1.33);
            addnav(array("%s`0 (`^%s Gold`0)", $companion['name'], $compcost), "healer.php?op=companion&name=" . rawurlencode($name) . "&compcost={$compcost}{$returnline}");
            $compheal = true;
        }
    }
}
tlschema("nav");
function pvplist($location = false, $link = false, $extra = false, $sql = false)
{
    global $session, $pvptime, $pvptimeout;
    if ($location === false) {
        $location = $session['user']['location'];
    }
    if ($link === false) {
        $link = basename($_SERVER['SCRIPT_NAME']);
    }
    if ($extra === false) {
        $extra = "?act=attack";
    }
    $days = getsetting("pvpimmunity", 5);
    $exp = getsetting("pvpminexp", 1500);
    $clanrankcolors = array("`!", "`#", "`^", "`&", "`\$");
    if ($sql === false) {
        $lev1 = $session['user']['level'] - 1;
        $lev2 = $session['user']['level'] + 2;
        $last = date("Y-m-d H:i:s", strtotime("-" . getsetting("LOGINTIMEOUT", 900) . " sec"));
        $id = $session['user']['acctid'];
        $loc = addslashes($location);
        $sql = "SELECT acctid, name, alive, location, sex, level, laston, " . "loggedin, login, pvpflag, clanshort, clanrank, dragonkills, " . db_prefix("accounts") . ".clanid FROM " . db_prefix("accounts") . " LEFT JOIN " . db_prefix("clans") . " ON " . db_prefix("clans") . ".clanid=" . db_prefix("accounts") . ".clanid WHERE (locked=0) " . "AND (slaydragon=0) AND " . "(age>{$days} OR dragonkills>0 OR pk>0 OR experience>{$exp}) " . "AND (level>={$lev1} AND level<={$lev2}) AND (alive=1) " . "AND (laston<'{$last}' OR loggedin=0) AND (acctid<>{$id}) " . "ORDER BY location='{$loc}' DESC, location, level DESC, " . "experience DESC, dragonkills DESC";
    }
    $result = db_query($sql);
    $pvp = array();
    while ($row = db_fetch_assoc($result)) {
        $pvp[] = $row;
    }
    $pvp = modulehook("pvpmodifytargets", $pvp);
    tlschema("pvp");
    $n = translate_inline("Name");
    $l = translate_inline("Level");
    $loc = translate_inline("Location");
    $ops = translate_inline("Ops");
    $bio = translate_inline("Bio");
    $att = translate_inline("Attack");
    rawoutput("<table border='0' cellpadding='3' cellspacing='0'>");
    rawoutput("<tr class='trhead'><td>{$n}</td><td>{$l}</td><td>{$loc}</td><td>{$ops}</td></tr>");
    $loc_counts = array();
    $num = count($pvp);
    $j = 0;
    for ($i = 0; $i < $num; $i++) {
        $row = $pvp[$i];
        if (isset($row['invalid']) && $row['invalid']) {
            continue;
        }
        if (!isset($loc_counts[$row['location']])) {
            $loc_counts[$row['location']] = 0;
        }
        $loc_counts[$row['location']]++;
        if ($row['location'] != $location) {
            continue;
        }
        $j++;
        $biolink = "bio.php?char=" . $row['acctid'] . "&ret=" . urlencode($_SERVER['REQUEST_URI']);
        addnav("", $biolink);
        rawoutput("<tr class='" . ($j % 2 ? "trlight" : "trdark") . "'>");
        rawoutput("<td>");
        if ($row['clanshort'] > "" && $row['clanrank'] > CLAN_APPLICANT) {
            output_notl("%s&lt;`2%s%s&gt;`0 ", $clanrankcolors[$row['clanrank']], $row['clanshort'], $clanrankcolors[$row['clanrank']], true);
        }
        output_notl("`@%s`0", $row['name']);
        rawoutput("</td>");
        rawoutput("<td>");
        output_notl("%s", $row['level']);
        rawoutput("</td>");
        rawoutput("<td>");
        output_notl("%s", $row['location']);
        rawoutput("</td>");
        rawoutput("<td>[ <a href='{$biolink}'>{$bio}</a> | ");
        if ($row['pvpflag'] > $pvptimeout) {
            output("`i(Attacked too recently)`i");
        } elseif ($location != $row['location']) {
            output("`i(Can't reach them from here)`i");
        } else {
            rawoutput("<a href='{$link}{$extra}&name=" . $row['acctid'] . "'>{$att}</a>");
            addnav("", "{$link}{$extra}&name=" . $row['acctid']);
        }
        rawoutput(" ]</td>");
        rawoutput("</tr>");
    }
    if (!isset($loc_counts[$location]) || $loc_counts[$location] == 0) {
        $noone = translate_inline("`iThere are no available targets.`i");
        output_notl("<tr><td align='center' colspan='4'>{$noone}</td></tr>", true);
    }
    rawoutput("</table>", true);
    if ($num != 0 && (!isset($loc_counts[$location]) || $loc_counts[$location] != $num)) {
        output("`n`n`&As you listen to different people around you talking, you glean the following additional information:`n");
        foreach ($loc_counts as $loc => $count) {
            if ($loc == $location) {
                continue;
            }
            $args = modulehook("pvpcount", array('count' => $count, 'loc' => $loc));
            if (isset($args['handled']) && $args['handled']) {
                continue;
            }
            if ($count == 1) {
                output("`&There is `^%s`& person sleeping in %s whom you might find interesting.`0`n", $count, $loc);
            } else {
                output("`&There are `^%s`& people sleeping in %s whom you might find interesting.`0`n", $count, $loc);
            }
        }
    }
    tlschema();
}
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();
}
$commenting = httpget("commenting");
$comment = httppost('insertcommentary');
// Don't give people a chance at a special event if they are just browsing
// the commentary (or talking) or dealing with any of the hooks in the village.
if (!$op && $com == "" && !$comment && !$refresh && !$commenting) {
    if (module_events("gardens", getsetting("gardenchance", 0)) != 0) {
        if (checknavs()) {
            page_footer();
        } else {
            // Reset the special for good.
            $session['user']['specialinc'] = "";
            $session['user']['specialmisc'] = "";
            $skipgardendesc = true;
            $op = "";
            httpset("op", "");
        }
    }
}
if (!$skipgardendesc) {
    checkday();
    $gardentext = array("text" => "`n`nYou walk through a gate and on to one of the many winding paths that makes its way through the well-tended gardens.`n`nFrom the flowerbeds that bloom even in darkest winter, to the hedges whose shadows promise forbidden secrets, these gardens provide a refuge for those seeking out the Green Dragon; a place where they can forget their troubles for a while and just relax.`n`nOne of the fairies buzzing about the garden flies up to remind you that the garden is a place for roleplaying and peaceful conversation, and to confine out-of-character comments to the other areas of the game.`n`n");
    $gardentext = modulehook("gardentext", $gardentext);
    output_notl("%s", $gardentext['text']);
}
addnav("Places");
modulehook("gardens", array());
commentdisplay("", "gardens", "Chat with other players", 30, "says");
module_display_events("gardens", "gardens.php");
addnav("Leave");
villagenav();
page_footer();
function module_do_event($type, $module, $allowinactive = false, $baseLink = false)
{
    global $navsection;
    if ($baseLink === false) {
        global $PHP_SELF;
        $baseLink = substr($PHP_SELF, strrpos($PHP_SELF, "/") + 1) . "?";
    } else {
        //debug("Base link was specified as $baseLink");
        //debug(debug_backtrace());
    }
    // Save off the mostrecent module since having that change can change
    // behaviour especially if a module calls modulehooks itself or calls
    // library functions which cause them to be called.
    if (!isset($mostrecentmodule)) {
        $mostrecentmodule = "";
    }
    $mod = $mostrecentmodule;
    $_POST['i_am_a_hack'] = 'true';
    if (injectmodule($module, $allowinactive)) {
        $oldnavsection = $navsection;
        tlschema("module-{$module}");
        $fname = $module . "_runevent";
        $fname($type, $baseLink);
        tlschema();
        //hook into the running event, but only in *this* running event, not in all
        modulehook("runevent_{$module}", array("type" => $type, "baselink" => $baseLink, "get" => httpallget(), "post" => httpallpost()));
        //revert nav section after we're done here.
        $navsection = $oldnavsection;
    }
    $mostrecentmodule = $mod;
}