function funddrive_dohook($hookname, $args)
{
    if ($hookname == "donation") {
        invalidatedatacache("mod_funddrive_totals");
    } elseif ($hookname == "funddrive_getpercent") {
        $prog = funddrive_getpercent();
        $args['percent'] = $prog['percent'];
    } elseif ($hookname == "everyfooter") {
        if (!array_key_exists('paypal', $args) || !is_array($args['paypal'])) {
            $args['paypal'] = array();
        }
        $prog = funddrive_getpercent();
        $out = "{$prog['percent']}%";
        $goal = $prog['goal'];
        $pct = $prog['percent'];
        $current = $prog['current'];
        if (get_module_setting("usetext")) {
            $res = "" . str_replace(' ', '&nbsp;', get_module_setting("indicatorText")) . "Improbable Island coffer status: <font color=#AF5E00>{$out}</font> of McDonald's Cashier Wages! :D" . (get_module_setting("showdollars") ? " (\${$current}/\${$goal})" : "");
        }
        switch (get_module_setting("usebar")) {
            case 1:
                $nonpct = 100 - $pct;
                if ($pct < 100) {
                    $res = "<div align='center'><table align='center' style='border: solid 1px #000000;' bgcolor='#FF0000' cellpadding='0' cellspacing='0' width='100' height='8'><caption align='bottom'>{$res}</caption><tr><td width='{$pct}%' bgcolor='#FFFF00'></td><td width='{$nonpct}%'></td></tr></table></div>";
                } else {
                    $res = "<div align='center'><table align='center' style='border: solid 1px #000000;' bgcolor='#00FF00' cellpadding='0' cellspacing='0' width='100' height='8'><caption align='bottom'>{$res}</caption><tr><td width='100%'></td></tr></table></div>";
                }
                break;
            case 2:
                $nonpct = 100 - $pct;
                $imgwidth = 140;
                $imgheight = 140;
                $topheight = round($imgheight * $nonpct / 100);
                $bottomheight = $imgheight - $topheight;
                if ($pct < 100) {
                    $res = "<table border='0' cellpadding='0' cellspacing='0' width='{$imgwidth}' height='{$imgheight}'>" . "<tr>" . "<td style=\"background-image: url(images/Medallion-Red.gif); background-position: top left; background-repeat: no-repeat;\" height='{$topheight}'><img src='images/trans.gif' width='{$imgwidth}' height='{$topheight}' alt=''></td>" . "</tr><tr>" . "<td style=\"background-image: url(images/Medallion-Yellow.gif); background-position: bottom left; background-repeat: no-repeat;\" height='{$bottomheight}'><img src='images/trans.gif' width='{$imgwidth}' height='{$bottomheight}' alt=''></td>" . "</tr>" . "</table><br><div align='center'>{$res}</div>";
                } else {
                    $res = "<table border='0' cellpadding='0' cellspacing='0' width='{$imgwidth}' height='{$imgheight}'>" . "<tr>" . "<td style=\"background-image: url(images/Medallion-Green.gif); background-position: top left; background-repeat: no-repeat;\" height='{$topheight}'><img src='images/trans.gif' width='{$imgwidth}' height='{$imgheight}' alt=''></td>" . "</tr>" . "</table><br><div align='center'>{$res}</div>";
                }
        }
        if ($res) {
            array_push($args['paypal'], $res);
        }
    }
    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 mysticalshop_massinvalidate($name)
{
    if (getsetting('usedatacache', false)) {
        $name = DATACACHE_FILENAME_PREFIX . $name;
        global $datacachefilepath;
        if ($datacachefilepath == '') {
            $datacachefilepath = getsetting('datacachepath', '/tmp');
        }
        if (@is_dir($datacachefilepath)) {
            $dir = dir($datacachefilepath);
            while (($file = $dir->read()) !== false) {
                if (strpos($file, $name) !== false) {
                    invalidatedatacache(str_replace(DATACACHE_FILENAME_PREFIX, '', $file));
                }
            }
            $dir->close();
        }
    }
}
function innchat_dohook($hookname, $args)
{
    global $session;
    switch ($hookname) {
        case "innchatter":
            $id = $session['user']['acctid'];
            if (e_rand(1, 2) == 1) {
                $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE locked=0 AND acctid != '{$id}' ORDER BY rand(" . e_rand() . ") LIMIT 1";
            } else {
                $sql = "SELECT creaturename AS name FROM " . db_prefix("masters") . " WHERE 1 ORDER BY rand(" . e_rand() . ") LIMIT 1";
            }
            // Only let this hit the database once every 10 minute if we're
            // using data caching.  Otherwise it could be expensive.  If they
            // hit it multiple times within ten minutes, it'll use the same
            // random name of player or master.  We'll invalidate the name when someone's name changes
            // for any reason.
            $res = db_query_cached($sql, "innchat-names");
            $row = db_fetch_assoc($res);
            // Give 2 out of X (currently 7 (5+these 2)) chances of hearing about
            // a player.
            $noplayers = translate_inline("loneliness in town");
            if ($row['name'] == "") {
                $row['name'] = $noplayers;
            }
            $args[] = $row['name'];
            $args[] = $row['name'];
            $args[] = translate_inline("Frequently Asked Questions");
            $args[] = translate_inline("dwarf tossing");
            $args[] = translate_inline("YOU");
            $args[] = getsetting("villagename", LOCATION_FIELDS);
            $args[] = translate_inline("today's weather");
            $args[] = translate_inline("the elementary discord of being");
            // "Das elementare Zerwürfnis des Seins" no idea if that makes any sense in english. (Ok, it doesn't make sense in german too.) It's from a "Jägermeister" commercial spot :)
            break;
        case "namechange":
        case "dragonkill":
            // Someone just did a dragonkill or had their name changed.  Since it
            // it could have been this person, we'll just invalidate the cache
            invalidatedatacache("innchat-names");
            break;
    }
    return $args;
}
function friendlist_ignore()
{
    global $session;
    $iveignored = rexplode(get_module_pref('iveignored'));
    $friends = rexplode(get_module_pref('friends'));
    $request = rexplode(get_module_pref('request'));
    $ac = httpget('ac');
    $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid={$ac} AND locked=0";
    $result = db_query($sql);
    if (db_num_rows($result) > 0 && in_array($ac, $friends)) {
        $row = db_fetch_assoc($result);
        require_once "lib/systemmail.php";
        $t = "`\$Friend List Ignore";
        $mailmessage = array("%s`0`@ has added you to %s ignore list.", $session['user']['name'], $session['user']['sex'] ? translate_inline("her") : translate_inline("his"));
        systemmail($ac, $t, $mailmessage);
        $friends = array_diff($friends, array($ac));
        invalidatedatacache("friendliststat-" . $session['user']['acctid']);
        invalidatedatacache("friendliststat-" . $ac);
    }
    $friends = rimplode($friends);
    set_module_pref('friends', $friends);
    $ignored = rexplode(get_module_pref('ignored', 'friendlist', $ac));
    $ignored[] = $session['user']['acctid'];
    $ignored = rimplode($ignored);
    set_module_pref('ignored', $ignored, 'friendlist', $ac);
    $act = $session['user']['acctid'];
    $friends = rexplode(get_module_pref('friends', 'friendlist', $ac));
    $friends = array_diff($friends, array($act));
    $friends = rimplode($friends);
    set_module_pref('friends', $friends, 'friendlist', $ac);
    if (in_array($ac, $request)) {
        $request = array_diff($request, array($ac));
        $request = rimplode($request);
        set_module_pref('request', $request);
    }
    $iveignored[] = $ac;
    $iveignored = rimplode($iveignored);
    set_module_pref('iveignored', $iveignored);
    output("You have ignored that user, they can no longer YoM you");
}
function friendlist_deny()
{
    global $session;
    $ignored = rexplode(get_module_pref('ignored'));
    $friends = rexplode(get_module_pref('friends'));
    $request = rexplode(get_module_pref('request'));
    $ac = httpget('ac');
    $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid={$ac} AND locked=0";
    $result = db_query($sql);
    if (in_array($ac, $friends)) {
        $info = translate_inline("That user has been removed.");
        require_once "lib/systemmail.php";
        $t = "`\$Friend List Removal";
        $mailmessage = array("%s`0`@ has deleted you from %s Friend List.", $session['user']['name'], $session['user']['sex'] ? translate_inline("her") : translate_inline("his"));
        $friends = array_diff($friends, array($ac));
        $friends = rimplode($friends);
        set_module_pref('friends', $friends);
        $act = $session['user']['acctid'];
        $friends = rexplode(get_module_pref('friends', 'friendlist', $ac));
        $friends = array_diff($friends, array($act));
        $friends = rimplode($friends);
        set_module_pref('friends', $friends, 'friendlist', $ac);
        invalidatedatacache("friendliststat-" . $session['user']['acctid']);
        invalidatedatacache("friendliststat-" . $ac);
    } else {
        $info = translate_inline("That user has been denied.");
        require_once "lib/systemmail.php";
        $t = "`\$Friend Request Denied";
        $mailmessage = array("%s`0`@ has denied you your Friend Request.", $session['user']['name']);
        $request = array_diff($request, array($ac));
        $request = rimplode($request);
        set_module_pref('request', $request);
    }
    if (db_num_rows($result) > 0) {
        systemmail($ac, $t, $mailmessage);
        $row = db_fetch_assoc($result);
        $info = sprintf_translate("%s has been removed", $row['name']);
    }
    output_notl($info);
}
function friendlist_accept()
{
    global $session;
    $ignored = rexplode(get_module_pref('ignored'));
    $request = rexplode(get_module_pref('request'));
    $friends = rexplode(get_module_pref('friends'));
    $ac = httpget('ac');
    if (in_array($ac, $ignored)) {
        $info = translate_inline("This user has ignored you.");
    } elseif (in_array($ac, $friends)) {
        $info = translate_inline("This user is already in your list.");
    } elseif (in_array($ac, $request)) {
        $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid={$ac} AND locked=0";
        $result = db_query($sql);
        if (db_num_rows($result) > 0) {
            $row = db_fetch_assoc($result);
            invalidatedatacache("friendliststat-" . $session['user']['acctid']);
            invalidatedatacache("friendliststat-" . $ac);
            $friends[] = $ac;
            $info = sprintf_translate("%s`Q has been added to your list.", $row['name']);
            require_once "lib/systemmail.php";
            $t = "`\$Friend Request Accepted";
            $mailmessage = array("%s`0`@ has accepted your Friend Request.", $session['user']['name']);
            systemmail($ac, $t, $mailmessage);
            $friends = rimplode($friends);
            set_module_pref('friends', $friends);
            $friends = rexplode(get_module_pref('friends', 'friendlist', $ac));
            $friends[] = $session['user']['acctid'];
            $friends = rimplode($friends);
            set_module_pref('friends', $friends, 'friendlist', $ac);
            $request = array_diff($request, array($ac));
            $request = rimplode($request);
            set_module_pref('request', $request);
        } else {
            $info = translate_inline("That user no longer exists...");
        }
    }
    output_notl($info);
}
function savesetting(string $settingname, $value)
{
    global $settings;
    $table = db_prefix('settings');
    loadsettings();
    if (!isset($settings[$settingname])) {
        $sql = db_query("INSERT INTO {$table} (setting, value)\n                VALUES ('" . addslashes($settingname) . "', '" . addslashes($value) . "')");
    } else {
        if (isset($settings[$settingname])) {
            $sql = db_query("UPDATE {$table} SET value = '" . addslashes($value) . "' WHERE setting = '" . addslashes($settingname) . "'");
        } else {
            return false;
        }
    }
    $settings[$settingname] = $value;
    invalidatedatacache('game-settings');
    if (db_affected_rows() > 0) {
        return true;
    } else {
        return false;
    }
}
function savesetting($settingname, $value)
{
    global $settings;
    loadsettings();
    if (!isset($settings[$settingname]) && $value) {
        $sql = "INSERT INTO " . db_prefix("settings") . " (setting,value) VALUES (\"" . addslashes($settingname) . "\",\"" . addslashes($value) . "\")";
    } else {
        if (isset($settings[$settingname])) {
            $sql = "UPDATE " . db_prefix("settings") . " SET value=\"" . addslashes($value) . "\" WHERE setting=\"" . addslashes($settingname) . "\"";
        } else {
            return false;
        }
    }
    db_query($sql);
    $settings[$settingname] = $value;
    invalidatedatacache("game-settings");
    if (db_affected_rows() > 0) {
        return true;
    } else {
        return false;
    }
}
    require_once "lib/newday/dragonpointspend.php";
} elseif (!$session['user']['race'] || $session['user']['race'] == RACE_UNKNOWN) {
    require_once "lib/newday/setrace.php";
} elseif ($session['user']['specialty'] == "") {
    require_once "lib/newday/setspecialty.php";
} else {
    page_header("It is a new day!");
    rawoutput("<font size='+1'>");
    output("`c`b`#It is a New Day!`0`b`c");
    rawoutput("</font>");
    $resurrection = httpget('resurrection');
    if ($session['user']['alive'] != true) {
        $session['user']['resurrections']++;
        output("`@You are resurrected!  This is resurrection number %s.`0`n", $session['user']['resurrections']);
        $session['user']['alive'] = true;
        invalidatedatacache("list.php-warsonline");
    }
    $session['user']['age']++;
    $session['user']['seenmaster'] = 0;
    output("You open your eyes to discover that a new day has been bestowed upon you. It is day number `^%s.`0", $session['user']['age']);
    output("You feel refreshed enough to take on the world!`n");
    output("`2Turns for today set to `^%s`2.`n", $turnsperday);
    $turnstoday = "Base: {$turnsperday}";
    $args = modulehook("pre-newday", array("resurrection" => $resurrection, "turnstoday" => $turnstoday));
    $turnstoday = $args['turnstoday'];
    $interestrate = e_rand($mininterest * 100, $maxinterest * 100) / (double) 100;
    if ($session['user']['turns'] > getsetting("fightsforinterest", 4) && $session['user']['goldinbank'] >= 0) {
        $interestrate = 1;
        output("`2Today's interest rate: `^0% (Bankers in this village only give interest to those who work for it)`2.`n");
    } elseif (getsetting("maxgoldforinterest", 100000) && $session['user']['goldinbank'] >= getsetting("maxgoldforinterest", 100000)) {
        $interestrate = 1;
} elseif ($op == "process") {
    $msg = httppost('msg');
    if (!is_array($msg) || count($msg) < 1) {
        $session['message'] = "`\$`bYou cannot delete zero messages!  What does this mean?  You pressed \"Delete Checked\" but there are no messages checked!  What sort of world is this that people press buttons that have no meaning?!?`b`0";
        header("Location: mail.php");
    } else {
        $sql = "DELETE FROM " . db_prefix("mail") . " WHERE msgto='" . $session['user']['acctid'] . "' AND messageid IN ('" . join("','", $msg) . "')";
        db_query($sql);
        invalidatedatacache("mail/mail-{$session['user']['acctid']}");
        header("Location: mail.php");
        exit;
    }
} elseif ($op == "unread") {
    $sql = "UPDATE " . db_prefix("mail") . " SET seen=0 WHERE msgto='" . $session['user']['acctid'] . "' AND messageid='{$id}'";
    db_query($sql);
    invalidatedatacache("mail/mail-{$session['user']['acctid']}");
    header("Location: mail.php");
    exit;
}
popup_header("Ye Olde Poste Office");
$inbox = translate_inline("Inbox");
$write = translate_inline("Write");
// Build the initial args array
$args = array();
array_push($args, array("mail.php", $inbox));
array_push($args, array("mail.php?op=address", $write));
// to use this hook,
// just call array_push($args, array("pagename", "functionname"));,
// where "pagename" is the name of the page to forward the user to,
// and "functionname" is the name of the mail function to add
$mailfunctions = modulehook("mailfunctions", $args);
     $claninfo['motdauthor'] = $session['user']['acctid'];
 }
 $clandesc = httppost('clandesc');
 if (httppostisset('clandesc') && stripslashes($clandesc) != $claninfo['clandesc'] && $claninfo['descauthor'] != 4294967295) {
     $sql = "UPDATE " . db_prefix("clans") . " SET clandesc='" . addslashes(substr(stripslashes($clandesc), 0, 4096)) . "',descauthor={$session['user']['acctid']} WHERE clanid={$claninfo['clanid']}";
     db_query($sql);
     invalidatedatacache("clandata-{$claninfo['clanid']}");
     output("Updating description`n");
     $claninfo['clandesc'] = stripslashes($clandesc);
     $claninfo['descauthor'] = $session['user']['acctid'];
 }
 $customsay = httppost('customsay');
 if (httppostisset('customsay') && $customsay != $claninfo['customsay'] && $session['user']['clanrank'] >= CLAN_LEADER) {
     $sql = "UPDATE " . db_prefix("clans") . " SET customsay='{$customsay}' WHERE clanid={$claninfo['clanid']}";
     db_query($sql);
     invalidatedatacache("clandata-{$claninfo['clanid']}");
     output("Updating custom say line`n");
     $claninfo['customsay'] = stripslashes($customsay);
 }
 $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid={$claninfo['motdauthor']}";
 $result = db_query($sql);
 $row = db_fetch_assoc($result);
 $motdauthname = $row['name'];
 $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid={$claninfo['descauthor']}";
 $result = db_query($sql);
 $row = db_fetch_assoc($result);
 $descauthname = $row['name'];
 output("`&`bCurrent MoTD:`b `#by %s`2`n", $motdauthname);
 output_notl(nltoappon($claninfo['clanmotd']) . "`n");
 output("`&`bCurrent Description:`b `#by %s`2`n", $descauthname);
 output_notl(nltoappon($claninfo['clandesc']) . "`n");
 $uri = httppost('uri');
 $text = httppost('text');
 $trans = httppost('trans');
 $page = $uri;
 if (strpos($page, "?") !== false) {
     $page = substr($page, 0, strpos($page, "?"));
 }
 if ($trans == "") {
     $sql = "DELETE ";
 } else {
     $sql = "SELECT * ";
 }
 $sql .= "\r\n\t\tFROM " . db_prefix("translations") . "\r\n\t\tWHERE language='" . LANGUAGE . "'\r\n\t\t\tAND intext='{$text}'\r\n\t\t\tAND (uri='{$page}' OR uri='{$uri}')";
 if ($trans > "") {
     $result = db_query($sql);
     invalidatedatacache("translations/translations-" . $namespace . "-" . $language);
     if (db_num_rows($result) == 0) {
         $sql = "INSERT INTO " . db_prefix("translations") . " (language,uri,intext,outtext,author,version) VALUES ('" . LANGUAGE . "','{$uri}','{$text}','{$trans}','{$session['user']['login']}','{$logd_version} ')";
         $sql1 = "DELETE FROM " . db_prefix("untranslated") . " WHERE intext='{$text}' AND language='" . LANGUAGE . "' AND namespace='{$url}'";
         db_query($sql1);
     } elseif (db_num_rows($result) == 1) {
         $row = db_fetch_assoc($result);
         // MySQL is case insensitive so we need to do it here.
         if ($row['intext'] == $text) {
             $sql = "UPDATE " . db_prefix("translations") . " SET author='{$session['user']['login']}', version='{$logd_version}', uri='{$uri}', outtext='{$trans}' WHERE tid={$row['tid']}";
         } else {
             $sql = "INSERT INTO " . db_prefix("translations") . " (language,uri,intext,outtext,author,version) VALUES ('" . LANGUAGE . "','{$uri}','{$text}','{$trans}','{$session['user']['login']}','{$logd_version} ')";
             $sql1 = "DELETE FROM " . db_prefix("untranslated") . " WHERE intext='{$text}' AND language='" . LANGUAGE . "' AND namespace='{$url}'";
             db_query($sql1);
         }
     } elseif (db_num_rows($result) > 1) {
function motd_del($id)
{
    $sql = "DELETE FROM " . db_prefix("motd") . " WHERE motditem=\"{$id}\"";
    db_query($sql);
    invalidatedatacache("motd");
    invalidatedatacache("lastmotd");
    invalidatedatacache("motddate");
    header("Location: motd.php");
    exit;
}
    $gold_cost = get_module_objpref("dwellingtypes", $typeid, "cost-gold", "dwellings_pvp");
    $gems_cost = get_module_objpref("dwellingtypes", $typeid, "cost-gems", "dwellings_pvp");
    $daysleft = get_module_objpref("dwellings", $dwid, "run-out", "dwellings_pvp");
    $isauto = get_module_objpref("dwellings", $dwid, "isauto", "dwellings_pvp");
    set_module_objpref("dwellings", $dwid, "run-out", $daysleft - 1, "dwellings_pvp");
    $subj = translate_inline("Concerning Dwellings Guard");
    if ($daysleft == 1) {
        if ($gold_coffer >= $gold_cost && $gems_coffer >= $gems_cost && (get_module_setting("whatif") && $isauto)) {
            $extra = translate_inline("However, you have enough gold and gems inside of your coffers to purchase another Guard. So, we will go ahead and place a guard order when they expire.");
        } else {
            $extra = "";
        }
        $body = sprintf("`@We are sorry to inform you, but your establishment, %s`@, in `^%s`@ will lose the usage of it's personal guard in `\$1 day`@. This is due to the rental time running out. %s`n`nDwellings Commission.", $row['name'], $row['location'], $extra);
        require_once "lib/systemmail.php";
        systemmail($row['ownerid'], $subj, $body);
    } elseif ($daysleft <= 0) {
        if ($gold_coffer >= $gold_cost && $gems_coffer >= $gems_cost && (get_module_setting("whatif") && $isauto)) {
            require_once "modules/dwellings/lib.php";
            dwellings_modify_coffers($dwid, "gold", "-" . $gold_cost);
            dwellings_modify_coffers($dwid, "gems", "-" . $gems_cost);
            $days = get_module_objpref("dwellingtypes", $typeid, "guard-length", "dwellings_pvp");
            invalidatedatacache("objpref-dwellings-{$dwid}-run-out-dwellings_pvp");
            invalidatedatacache("objpref-dwellings-{$dwid}-bought-dwellings_pvp");
            set_module_objpref("dwellings", $dwid, "run-out", $days, "dwellings_pvp");
            set_module_objpref("dwellings", $dwid, "bought", 1, "dwellings_pvp");
        } else {
            invalidatedatacache("objpref-dwellings-{$dwid}-bought-dwellings_pvp");
            set_module_objpref("dwellings", $dwid, "bought", 0, "dwellings_pvp");
        }
    }
}
     }
     debug("Moving companions");
     $sql = "UPDATE " . db_prefix("companions") . " SET companionlocation = '" . httppost("villagename") . "' WHERE companionlocation = '" . addslashes($settings['villagename']) . "'";
     db_query($sql);
 }
 $tmp = stripslashes(httppost("innname"));
 if ($tmp && $tmp != $settings['innname']) {
     debug("Updating inn name -- moving players");
     $sql = "UPDATE " . db_prefix("accounts") . " SET location='" . httppost("innname") . "' WHERE location='" . addslashes($settings['innname']) . "'";
     db_query($sql);
     if ($session['user']['location'] == $settings['innname']) {
         $session['user']['location'] = stripslashes(httppost('innname'));
     }
 }
 if (stripslashes(httppost("motditems")) != $settings['motditems']) {
     invalidatedatacache("motd");
 }
 $post = httpallpost();
 reset($post);
 $old = $settings;
 while (list($key, $val) = each($post)) {
     if (!isset($settings[$key]) || stripslashes($val) != $settings[$key]) {
         if (!isset($old[$key])) {
             $old[$key] = "";
         }
         savesetting($key, stripslashes($val));
         output("Setting %s to %s`n", $key, stripslashes($val));
         gamelog("`@changed core setting `^{$key}`@ from `3{$old[$key]}`@ to `#{$val}`0", "settings");
         // Notify every module
         modulehook("changesetting", array("module" => "core", "setting" => $key, "old" => $old[$key], "new" => $val), true);
     }
        $sql = "UPDATE " . db_prefix("clans") . " SET clanname='{$clanname}',clanshort='{$clanshort}' WHERE clanid='{$detail}'";
        output("Updating clan names`n");
        db_query($sql);
        invalidatedatacache("clandata-{$detail}");
    }
    if (httppost('block') > "") {
        $blockdesc = translate_inline("Description blocked for inappropriate usage.");
        $sql = "UPDATE " . db_prefix("clans") . " SET descauthor=4294967295, clandesc='{$blockdesc}' where clanid='{$detail}'";
        output("Blocking public description`n");
        db_query($sql);
        invalidatedatacache("clandata-{$detail}");
    } elseif (httppost('unblock') > "") {
        $sql = "UPDATE " . db_prefix("clans") . " SET descauthor=0, clandesc='' where clanid='{$detail}'";
        output("UNblocking public description`n");
        db_query($sql);
        invalidatedatacache("clandata-{$detail}");
    }
}
$sql = "SELECT * FROM " . db_prefix("clans") . " WHERE clanid='{$detail}'";
$result1 = db_query_cached($sql, "clandata-{$detail}", 3600);
$row1 = db_fetch_assoc($result1);
if ($session['user']['superuser'] & SU_EDIT_COMMENTS) {
    rawoutput("<div id='hidearea'>");
    rawoutput("<form action='clan.php?detail={$detail}' method='POST'>");
    addnav("", "clan.php?detail={$detail}");
    output("Superuser / Moderator renaming:`n");
    output("Long Name: ");
    rawoutput("<input name='clanname' value=\"" . htmlentities($row1['clanname'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "\" maxlength=50 size=50>");
    output("`nShort Name: ");
    rawoutput("<input name='clanshort' value=\"" . htmlentities($row1['clanshort'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "\" maxlength=5 size=5>");
    output_notl("`n");
         reset($mount['mountbuff']);
         while (list($key, $val) = each($mount['mountbuff'])) {
             if ($val > "") {
                 $buff[$key] = stripslashes($val);
             }
         }
         $buff['schema'] = "mounts";
         httppostset('mount', $buff, 'mountbuff');
         list($sql, $keys, $vals) = postparse(false, 'mount');
         if ($id > "") {
             $sql = "UPDATE " . db_prefix("mounts") . " SET {$sql} WHERE mountid='{$id}'";
         } else {
             $sql = "INSERT INTO " . db_prefix("mounts") . " ({$keys}) VALUES ({$vals})";
         }
         db_query($sql);
         invalidatedatacache("mountdata-{$id}");
         if (db_affected_rows() > 0) {
             output("`^Mount saved!`0`n");
         } else {
             output("`^Mount `\$not`^ saved: `\$%s`0`n", $sql);
         }
     }
 } elseif ($subop == "module") {
     // Save modules settings
     $module = httpget("module");
     $post = httpallpost();
     reset($post);
     while (list($key, $val) = each($post)) {
         set_module_objpref("mounts", $id, $key, $val, $module);
     }
     output("`^Saved!`0`n");
         rawoutput("<tr class='" . ($i % 2 ? "trlight" : "trdark") . "'>");
         $row = db_fetch_assoc($result);
         $buffid = $row['buffid'];
         $sqla = "SELECT buffid, buffname FROM " . db_prefix("magicitembuffs") . "  WHERE buffid = {$buffid} ORDER BY buffid ASC";
         $resulta = db_query($sqla);
         $rowa = db_fetch_assoc($resulta);
         output("<td>%s.) `2%s</td><td>`3%s</td>", $i, $row['name'], $rowa['buffname'], true);
         rawoutput("</tr>");
     }
     rawoutput("</table>");
     break;
 case "delbuff":
     $id = httpget('id');
     $sql = "DELETE FROM " . db_prefix("magicitembuffs") . " WHERE buffid = {$id} LIMIT 1";
     $result = db_query($sql);
     invalidatedatacache("magicitem-buff-{$id}");
     if (db_affected_rows($result)) {
         output("`^Buff has been succesfully deleted.`n`n");
     } else {
         output("`3While deleting this buff, an error occured. Probably someone else already deleted this buff.`n`n");
     }
     $sql = "UPDATE " . db_prefix("magicitems") . " SET buffid = 0 WHERE buffid = '{$id}'";
     db_query($sql);
     break;
 case "newitem":
     require_once "modules/mysticalshop_buffs/newitem.php";
     break;
 case "newitem2":
     $id = httppost('id');
     $buffid = httppost('buffid');
     if ($buffid == 0 or $buffid == "") {
			if($owner==1){
				$kickout = translate_inline("`$(Kick out)");
				rawoutput("<a href='runmodule.php?module=dwellings&op=kickout&who={$row['acctid']}&dwid=$dwid>$kickout</a>");
				addnav("","runmodule.php?module=dwellings&op=kickout&who={$row['acctid']}&dwid=$dwid");
			}
			rawoutput("</td><td>");
			output_notl("%s",$row['level']);
			rawoutput("</td><td>");
			output_notl("%s",$row['dragonkills']);
			rawoutput("</td><td>");
			$laston = relativedate($row['laston']);
			output_notl("%s", $laston);
			rawoutput("</td></tr>");
			$i++;
		}
		rawoutput("</table>");
	}else{
		$loc = get_module_setting("logoutlocation");
		if ($session['user']['loggedin']){
			$session['user']['restorepage'] = "runmodule.php?module=dwellings&op=enter&dwid=$dwid";
			$sql = "UPDATE " . db_prefix("accounts") . " SET loggedin=0, location='".get_module_setting("logoutlocation")."', restorepage='{$session['user']['restorepage']}' WHERE acctid = ".$session['user']['acctid'];
			db_query($sql);
			invalidatedatacache("charlisthomepage");
			invalidatedatacache("list.php-warsonline");
			invalidatedatacache("dwellings-sleepers-$dwid");
			modulehook("player-logout");
		}
		$session = array();
		redirect("index.php");
	}
?>
superusernav();
if ($op == "") {
    $sql = "DELETE FROM " . db_prefix("petitions") . " WHERE status=2 AND closedate<'" . date("Y-m-d H:i:s", strtotime("-7 days")) . "'";
    db_query($sql);
    if (db_affected_rows()) {
        invalidatedatacache("petition_counts");
    }
    $setstat = httpget("setstat");
    if ($setstat != "") {
        $sql = "SELECT status FROM " . db_prefix("petitions") . " WHERE petitionid='{$id}'";
        $result = db_query($sql);
        $row = db_fetch_assoc($result);
        if ($row['status'] != $setstat) {
            $sql = "UPDATE " . db_prefix("petitions") . " SET status='{$setstat}',closeuserid='{$session['user']['acctid']}',closedate='" . date("Y-m-d H:i:s") . "' WHERE petitionid='{$id}'";
            db_query($sql);
            invalidatedatacache("petition_counts");
        }
    }
    reset($statuses);
    $sort = "";
    $pos = 0;
    while (list($key, $val) = each($statuses)) {
        $sort .= " WHEN {$key} THEN {$pos}";
        $pos++;
    }
    $petitionsperpage = 50;
    $sql = "SELECT count(petitionid) AS c from " . db_prefix("petitions");
    $result = db_query($sql);
    $row = db_fetch_assoc($result);
    $totalpages = ceil($row['c'] / $petitionsperpage);
    $page = httpget("page");
 case "decorate_exterior":
     require_once "modules/staminasystem/lib/lib.php";
     $actinfo = process_action("Decorating");
     if ($actinfo['lvlinfo']['levelledup']) {
         output("`n`c`b`0You gained a level in Decorating!  You are now level %s!  This action will cost fewer Stamina points now.`b`c`n", $actinfo['lvlinfo']['newlvl']);
     }
     $house['data']['dec']['done'] += 1;
     //check if the job's done
     if ($house['data']['dec']['done'] == $house['data']['dec']['req']) {
         output("The decorating job is completed!  You step back and admire your work.  Pretty nice!`n`n");
         $house['data']['desc_exterior'] = $house['data']['dec']['desc'];
         unset($house['data']['dec']);
         $erasedec = "DELETE FROM " . db_prefix("building_prefs") . " WHERE pref = 'dec' AND hid = '{$hid}'";
         db_query($erasedec);
         $loc = $house['location'];
         invalidatedatacache("housing/housing_location_" . $loc);
     } else {
         output("You set about painting and decorating.  Before too long, the dwelling is one step closer to being fully decorated.`n`n");
         require_once "lib/bars.php";
         $bar = fadebar($house['data']['dec']['done'], $house['data']['dec']['req'], 150, 5);
         rawoutput("Decoration completion status: " . $bar);
         addnav("Decorate some more?");
         require_once "modules/staminasystem/lib/lib.php";
         if (get_stamina() == 100) {
             $cost = stamina_getdisplaycost("Decorating");
             addnav(array("Decorate the dwelling's exterior (`Q%s%%`0)", $cost), "runmodule.php?module=improbablehousing&op=decorate&subop=decorate_exterior&hid={$hid}");
         } else {
             addnav("You're too tired to do any more sprucing up right now.", "");
         }
     }
     improbablehousing_sethousedata($house);
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;
}
    // false if not found
    $removekey = array_search(stripslashes(httppost('word')), $words);
    // $removekey can be 0
    if ($removekey !== false) {
        unset($words[$removekey]);
    }
    //unset($words[array_search(stripslashes(httppost('word')),$words)]);
}
show_word_list($words);
output_notl("`0");
if ($op == "add" || $op == "remove") {
    $sql = "DELETE FROM " . db_prefix("nastywords") . " WHERE type='nasty'";
    db_query($sql);
    $sql = "INSERT INTO " . db_prefix("nastywords") . " (words,type) VALUES ('" . addslashes(join(" ", $words)) . "','nasty')";
    db_query($sql);
    invalidatedatacache("nastywordlist");
}
page_footer();
function show_word_list($words)
{
    sort($words);
    $lastletter = "";
    while (list($key, $val) = each($words)) {
        if (trim($val) == "") {
            unset($words[$key]);
        } else {
            if (substr($val, 0, 1) != $lastletter) {
                $lastletter = substr($val, 0, 1);
                output_notl("`n`n`^`b%s`b`@`n", strtoupper($lastletter));
            }
            output_notl("%s ", $val);
function petitionfixnavs_run()
{
    global $session;
    page_header("Fixed Navs");
    $id = httpget('id');
    $op = httpget('op');
    switch ($op) {
        case "cnext":
            $nextid = httpget('nextid');
            $sql = "UPDATE " . db_prefix("petitions") . " SET status=2,closeuserid='{$session['user']['acctid']}',closedate='" . date("Y-m-d H:i:s") . "' WHERE petitionid='{$id}'";
            db_query($sql);
            pt_insert(translate_inline("/me has closed the petition"));
            invalidatedatacache("petition_counts");
            redirect("viewpetition.php?op=view&id={$nextid}");
            break;
        case "cfnext":
            $sql = "SELECT author FROM " . db_prefix("petitions") . " WHERE petitionid='{$id}'";
            $result = db_query($sql);
            $author = db_fetch_assoc($result);
            debug($author);
            if (!$author) {
                output_notl("Error! Please give a detailed error report to the Petition Fixnavs Module Author!");
                page_footer();
                return;
            }
            $author = $author['author'];
            $sql = "UPDATE " . db_prefix("accounts") . " SET allowednavs='',specialinc='' WHERE acctid={$author}";
            $result = db_query($sql);
            $sql = "UPDATE " . db_prefix("accounts_everypage") . " SET allowednavs='' WHERE acctid={$author}";
            $result = db_query($sql);
            invalidatedatacache("accounts/account_" . $author);
            $sql = "DELETE FROM " . db_prefix("accounts_output") . " WHERE acctid={$author}";
            $result = db_query($sql);
            $nextid = httpget('nextid');
            $sql = "UPDATE " . db_prefix("petitions") . " SET status=2,closeuserid='{$session['user']['acctid']}',closedate='" . date("Y-m-d H:i:s") . "' WHERE petitionid='{$id}'";
            db_query($sql);
            pt_insert(translate_inline("/me has fixed navs and closed the petition"));
            require_once "lib/systemmail.php";
            systemmail($author, array("Your petition"), array("Your navs have been fixed, you should be able to navigate from the stuck page now. If not, please petition again. (This is an automatic message).`n`nRegards %s", $session['user']['name']));
            invalidatedatacache("petition_counts");
            redirect("viewpetition.php?op=view&id={$nextid}");
            break;
        default:
            $sql = "SELECT author FROM " . db_prefix("petitions") . " WHERE petitionid='{$id}'";
            $result = db_query($sql);
            $author = db_fetch_assoc($result);
            debug($author);
            if (!$author) {
                output_notl("Error! Could not find that user!!");
                page_footer();
                return;
            }
            $author = $author['author'];
            $sql = "UPDATE " . db_prefix("accounts") . " SET allowednavs='',specialinc='' WHERE acctid={$author}";
            $result = db_query($sql);
            $sql = "UPDATE " . db_prefix("accounts_everypage") . " SET allowednavs='' WHERE acctid={$author}";
            $result = db_query($sql);
            invalidatedatacache("accounts/account_" . $author);
            pt_insert(translate_inline("/me has fixed this users navs"));
            require_once "lib/systemmail.php";
            systemmail($author, array("Your petition"), array("Your navs have been fixed, you should be able to navigate from the stuck page now. If not, please petition again. (This is an automatic message).`n`nRegards %s", $session['user']['name']));
            redirect("viewpetition.php?op=view&id={$id}");
            break;
    }
    page_footer();
}
function injectrawcomment($section, $author, $comment)
{
    $sql = "INSERT INTO " . db_prefix("commentary") . " (postdate,section,author,comment) VALUES ('" . date("Y-m-d H:i:s") . "','{$section}',{$author},\"{$comment}\")";
    db_query($sql);
    invalidatedatacache("comments-{$section}");
    // invalidate moderation screen also.
    // *** DRAGONBG.COM CORE PATCH START ***
    invalidatedatacache("comments-");
    // *** DRAGONBG.COM CORE PATCH END ***
}
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();
}
        $op = "";
        httpset('op', "");
        invalidatedatacache("injections/inject_{$module}");
    } elseif ($op == "deactivate") {
        deactivate_module($module);
        $op = "";
        httpset('op', "");
        invalidatedatacache("injections/inject_{$module}");
    } elseif ($op == "reinstall") {
        $sql = "UPDATE " . db_prefix("modules") . " SET filemoddate='0000-00-00 00:00:00' WHERE modulename='{$module}'";
        db_query($sql);
        // We don't care about the return value here at all.
        injectmodule($module, true);
        $op = "";
        httpset('op', "");
        invalidatedatacache("injections/inject_{$module}");
    }
}
$install_status = get_module_install_status();
$uninstmodules = $install_status['uninstalledmodules'];
$seencats = $install_status['installedcategories'];
$ucount = $install_status['uninstcount'];
ksort($seencats);
addnav(array(" ?Uninstalled - (%s modules)", $ucount), "modules.php");
reset($seencats);
foreach ($seencats as $cat => $count) {
    addnav(array(" ?%s - (%s modules)", $cat, $count), "modules.php?cat={$cat}");
}
$cat = httpget('cat');
if ($op == "") {
    if ($cat) {
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;
        }
    }
}
         output("A marriage is not to be taken lightly and you feel the truth of that deep in your heart. After a short but emotional ceremony, `^%s`@ looks up at both of you.`n`n", $vicar);
         output("`^%s `3says \"`&And I pronounce thee %s and %s.`3\"", $vicar, $first, $second);
     } else {
         output("`^%s `3says \"`&And I pronounce thee %s and %s.`3\"", $vicar, $first, $second);
         output("`n`^%s `3says \"`&Don't look so surprised! Nothing is sacred anymore...`3\"", $vicar);
     }
     $allprefs = unserialize(get_module_pref('allprefs'));
     $allprefs['counsel'] = 0;
     $allprefs['buyring'] = 0;
     set_module_pref('allprefs', serialize($allprefs));
     $allprefsm = unserialize(get_module_pref('allprefs', 'marriage', $session['user']['marriedto']));
     $allprefsm['counsel'] = 0;
     $allprefsm['buyring'] = 0;
     set_module_pref('allprefs', serialize($allprefsm), 'marriage', $session['user']['marriedto']);
     invalidatedatacache("marriage-marriedonline");
     invalidatedatacache("marriage-marriedrealm");
     require_once "lib/datetime.php";
     $time = date("Y-m-d H:i:s");
     set_module_objpref("marriage", $session['user']['marriedto'], "marriagedate", $time);
     set_module_objpref("marriage", $session['user']['acctid'], "marriagedate", $time);
     apply_buff('marriage-start', array("name" => "`@Marriage", "rounds" => 100, "wearoff" => "`&The elation wears off.", "defmod" => 1.83, "survivenewday" => 1, "roundmsg" => "`@You are elated at your marriage"));
     debuglog("proposal accepted from {$row['name']}");
     break;
 case "reject":
     $stuff = explode(',', get_module_pref('proposals'));
     $i = "";
     foreach ($stuff as $val) {
         if ($val != "" && $val != $target && $val != $session['user']['acctid']) {
             $i .= "," . $val;
         }
     }