function viewcommentaryargs_dohook($hook, $args)
{
    global $currentCommentaryArea;
    switch ($hook) {
        case 'blockcommentarea':
            $currentCommentaryArea = $args['section'];
            break;
        case 'viewcommentary':
            $accounts = db_prefix('accounts');
            $commentary = db_prefix('commentary');
            preg_match("/bio.php\\?char=(.*)&ret/", $args['commentline'], $matches);
            $acctid = filter_var($matches[1], FILTER_SANITIZE_NUMBER_INT);
            $sql = db_query_cached("SELECT login, name FROM {$accounts} WHERE acctid = {$acctid}", "commentary-author_name-{$acctid}", 86400);
            $row = db_fetch_assoc($sql);
            $name = $row['name'];
            $login = $row['login'];
            $temp = explode($row['name'], $args['commentline']);
            $temp = str_replace('`3 says, "`#', '', $temp[1]);
            $temp = str_replace('`3"', '', $temp);
            $temp = str_replace('/me', '', $temp);
            $temp = str_replace(':', '', $temp);
            $temp = str_replace('</a>', '', $temp);
            $temp = full_sanitize($temp);
            $temp = addslashes(implode('%', str_split(trim($temp))));
            $sql = db_query("SELECT commentid, comment, postdate FROM {$commentary}\n                WHERE comment LIKE '%{$temp}%'\n                AND section = '{$currentCommentaryArea}'");
            $row = db_fetch_assoc($sql);
            $args = ['commentline' => $args['commentline'], 'section' => $currentCommentaryArea, 'commentid' => $row['commentid'], 'comment' => $row['comment'], 'author_acctid' => $acctid, 'author_login' => $login, 'author_name' => $name, 'date' => $row['postdate']];
            unset($row);
            unset($temp);
            break;
    }
    return $args;
}
function pollitem($id, $subject, $body, $author, $date, $showpoll = true)
{
    global $session;
    $sql = "SELECT count(resultid) AS c, MAX(choice) AS choice FROM " . db_prefix("pollresults") . " WHERE motditem='{$id}' AND account='{$session['user']['acctid']}'";
    $result = db_query($sql);
    $row = db_fetch_assoc($result);
    $choice = $row['choice'];
    $body = unserialize($body);
    $poll = translate_inline("Poll:");
    if ($session['user']['loggedin'] && $showpoll) {
        rawoutput("<form action='motd.php?op=vote' method='POST'>");
        rawoutput("<input type='hidden' name='motditem' value='{$id}'>", true);
    }
    output_notl("`b`&%s `^%s`0`b", $poll, $subject);
    if ($showpoll) {
        motd_admin($id, true);
    }
    output_notl("`n`3%s`0 &#150; `#%s`0`n", $author, $date, true);
    output_notl("`2%s`0`n", stripslashes($body['body']));
    $sql = "SELECT count(resultid) AS c, choice FROM " . db_prefix("pollresults") . " WHERE motditem='{$id}' GROUP BY choice ORDER BY choice";
    $result = db_query_cached($sql, "poll-{$id}");
    $choices = array();
    $totalanswers = 0;
    $maxitem = 0;
    while ($row = db_fetch_assoc($result)) {
        $choices[$row['choice']] = $row['c'];
        $totalanswers += $row['c'];
        if ($row['c'] > $maxitem) {
            $maxitem = $row['c'];
        }
    }
    while (list($key, $val) = each($body['opt'])) {
        if (trim($val) != "") {
            if ($totalanswers <= 0) {
                $totalanswers = 1;
            }
            $percent = 0;
            if (isset($choices[$key])) {
                $percent = round($choices[$key] / $totalanswers * 100, 1);
            }
            if ($session['user']['loggedin'] && $showpoll) {
                rawoutput("<input type='radio' name='choice' value='{$key}'" . ($choice == $key ? " checked" : "") . ">");
            }
            output_notl("%s (%s - %s%%)`n", stripslashes($val), isset($choices[$key]) ? (int) $choices[$key] : 0, $percent);
            if ($maxitem == 0 || !isset($choices[$key])) {
                $width = 1;
            } else {
                $width = round($choices[$key] / $maxitem * 400, 0);
            }
            $width = max($width, 1);
            rawoutput("<img src='images/rule.gif' width='{$width}' height='2' alt='{$percent}'><br>");
        }
    }
    if ($session['user']['loggedin'] && $showpoll) {
        $vote = translate_inline("Vote");
        rawoutput("<input type='submit' class='button' value='{$vote}'></form>");
    }
    rawoutput("<hr>", true);
}
function iitems_get_item_details($localname)
{
    $sql = "SELECT id,localname,data FROM " . db_prefix("iitems") . " WHERE localname = '{$localname}'";
    $result = db_query_cached($sql, "iitems-" . $localname);
    $row = db_fetch_assoc($result);
    $sarray = unserialize($row['data']);
    return $sarray;
}
function eboy_dohook($hookname, $args)
{
    global $session;
    switch ($hookname) {
        case "village":
            tlschema($args['schemas']['marketnav']);
            addnav($args['marketnav']);
            tlschema();
            addnav("eBoy's Trading Station", "runmodule.php?module=eboy&op=start");
            break;
        case "newday-runonce":
            $eboyitems = get_items_with_settings("eboy");
            //get number of players
            $sql = "SELECT count(acctid) AS c FROM " . db_prefix("accounts") . " WHERE locked=0";
            $result = db_query_cached($sql, "numplayers", 600);
            $row = db_fetch_assoc($result);
            $numplayers = $row['c'];
            $sql = "SELECT * from " . db_prefix("cityprefs");
            $result = db_query($sql);
            $numrows = db_num_rows($result);
            for ($i = 0; $i < $numrows; $i++) {
                $row = db_fetch_assoc($result);
                $cid = $row['cityid'];
                foreach ($eboyitems as $item => $settings) {
                    //Advance Multiplier
                    if ($settings['eboy_multiplier_' . $cid]) {
                        if ($settings['eboy_stock_' . $cid] < $numplayers / 10) {
                            increment_item_setting("eboy_multiplier_" . $cid, 0.1, $item);
                        } else {
                            if ($settings['stock_' . $cid] > $numplayers / 5) {
                                increment_item_setting("eboy_multiplier_" . $cid, -0.1, $item);
                            }
                        }
                        //stop prices staying ridiculously low
                        if (get_item_setting("eboy_multiplier_" . $cid, $item) < 0.1) {
                            set_item_setting("eboy_multiplier_" . $cid, 0.1, $item);
                        }
                        //or going ridiculously high
                        if (get_item_setting("eboy_multiplier_" . $cid, $item) > 50) {
                            set_item_setting("eboy_multiplier_" . $cid, 50, $item);
                        }
                    } else {
                        set_item_setting("eboy_multiplier_" . $cid, 1, $item);
                    }
                    if (!isset($settings['eboy_stock_' . $cid])) {
                        set_item_setting("eboy_stock_" . $cid, 1, $item);
                    }
                    increment_item_setting("eboy_stock_" . $cid, $settings['eboy_dailyadd'], $item);
                }
            }
            break;
        case "items-returnlinks":
            $args['eboy'] = "runmodule.php?module=eboy&op=start";
            break;
    }
    return $args;
}
function getmount($horse = 0)
{
    $sql = "SELECT * FROM " . db_prefix("mounts") . " WHERE mountid='{$horse}'";
    $result = db_query_cached($sql, "mountdata-{$horse}", 3600);
    if (db_num_rows($result) > 0) {
        return db_fetch_assoc($result);
    } else {
        return array();
    }
}
function good_word_list() : array
{
    $nastyWords = db_prefix('nastywords');
    $sql = db_query_cached("SELECT * FROM {$nastyWords} WHERE type = 'good'", 'goodwordlist');
    $row = db_fetch_assoc($sql);
    if (!empty($row['words'])) {
        return explode(' ', $row['words']);
    } else {
        return [];
    }
}
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 get_cityprefs_cityname($lookup, $value, $player = false)
{
    if ($player > 0) {
        $sql1 = "select location from " . db_prefix("accounts") . " where acctid={$player}";
        $res1 = db_query($sql1);
        $row1 = db_fetch_assoc($res1);
        return $row1['location'];
    }
    if ($lookup == 'module') {
        $where = "module='" . addslashes($value) . "'";
    } else {
        $where = "cityid={$value}";
    }
    $sql = "select cityname from " . db_prefix("cityprefs") . " where {$where}";
    $res = db_query_cached($sql, "cityid_" . $value);
    $row = db_fetch_assoc($res);
    return $row['cityname'];
}
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 funddrive_getpercent()
{
    $targetmonth = get_module_setting("targetmonth");
    if ($targetmonth == "") {
        $targetmonth = date("m");
    }
    $start = date("Y") . "-" . $targetmonth . "-01";
    $end = date("Y-m-d", strtotime("+1 month", strtotime($start)));
    $result = db_query_cached("SELECT sum(amount) AS gross, sum(txfee) AS fees FROM " . db_prefix("paylog") . " WHERE processdate >= '{$start}' AND processdate < '{$end}'", "mod_funddrive_totals", 10);
    $goal = get_module_setting("goalamount");
    $base = get_module_setting("baseamount");
    $row = db_fetch_assoc($result);
    $current = $row['gross'] + $base;
    if (get_module_setting("deductfees")) {
        $current -= $row['fees'];
    }
    $pct = round($current / $goal * 100, 0);
    $ret = array('percent' => $pct, 'goal' => $goal, 'current' => $current);
    return $ret;
}
function improbablehousing_getnearbyhouses($loc)
{
    global $session;
    //$sql = "SELECT hid,ownedby FROM " . db_prefix("buildings") . " WHERE location = '$loc'";
    $sql = "SELECT * FROM " . db_prefix("buildings") . " WHERE location = '{$loc}'";
    $result = db_query_cached($sql, "housing/housing_location_" . $loc);
    //$result = db_query($sql);
    //todo: cache this query, or rather, invalidate the cache properly after staking a claim
    $n = db_num_rows($result);
    //debug($n);
    if (!$n) {
        return null;
    } else {
        $r = array();
        for ($i = 0; $i < $n; $i++) {
            $row = db_fetch_assoc($result);
            $house = improbablehousing_gethousedata($row['hid']);
            $r[] = $house;
        }
    }
    return $r;
}
 if (!$race) {
     $race = RACE_UNKNOWN;
 }
 tlschema("race");
 $race = translate_inline($race);
 tlschema();
 // output("`^Race: `@%s`n",$race);
 $genders = array("Male", "Female");
 $genders = translate_inline($genders);
 output("`^Gender: `@%s`n", $genders[$target['sex']]);
 $specialties = modulehook("specialtynames", array("" => translate_inline("Unspecified")));
 if (isset($specialties[$target['specialty']])) {
     output("`^Specialty: `@%s`n", $specialties[$target['specialty']]);
 }
 $sql = "SELECT * FROM " . db_prefix("mounts") . " WHERE mountid='{$target['hashorse']}'";
 $result = db_query_cached($sql, "mountdata-{$target['hashorse']}", 3600);
 $mount = db_fetch_assoc($result);
 $mount['acctid'] = $target['acctid'];
 $mount = modulehook("bio-mount", $mount);
 $none = translate_inline("`iNone`i");
 if (!isset($mount['mountname']) || $mount['mountname'] == "") {
     $mount['mountname'] = $none;
 }
 output("`^Creature: `@%s`0`n", $mount['mountname']);
 modulehook("biostat", $target);
 if ($target['dragonkills'] > 0) {
     output("`^Dragon Kills: `@%s`n", $target['dragonkills']);
 }
 if ($target['bio'] > "") {
     output("`^Bio: `@`n%s`n", soap($target['bio']));
 }
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;
}
$iname = getsetting("innname", LOCATION_INN);
$valid_loc[$vname] = "village";
$valid_loc = modulehook("validlocation", $valid_loc);
if (!isset($valid_loc[$session['user']['location']])) {
    $session['user']['location'] = $vname;
}
$newestname = "";
$newestplayer = getsetting("newestplayer", "");
if ($newestplayer == $session['user']['acctid']) {
    $newtext = "`nYou're the newest member of the village.  As such, you wander around, gaping at the sights, and generally looking lost.";
    $newestname = $session['user']['name'];
} else {
    $newtext = "`n`2Wandering near the inn is `&%s`2, looking completely lost.";
    if ((int) $newestplayer != 0) {
        $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid='{$newestplayer}'";
        $result = db_query_cached($sql, "newest");
        if (db_num_rows($result) == 1) {
            $row = db_fetch_assoc($result);
            $newestname = $row['name'];
        } else {
            $newestplayer = "";
        }
    } else {
        if ($newestplayer > "") {
            $newestname = $newestplayer;
        } else {
            $newestname = "";
        }
    }
}
$basetext = array("`@`c`b%s Square`b`cThe village of %s hustles and bustles.  No one really notices that you're standing there.  " . "You see various shops and businesses along main street.  There is a curious looking rock to one side.  " . "On every side the village is surrounded by deep dark forest.`n`n", $vname, $vname);
checkday();
page_header("%s", sanitize($name));
set_module_pref("dwelling_saver", $dwid, "dwellings");
output_notl("`c`b%s`b`n`n%s`n`n`c`0", $row['name'], $row['description']);
if (get_module_setting("ownersleep", $type) && $session['user']['acctid'] == $row['ownerid']) {
    addnav("Leave");
    addnav("Go to Sleep (Log Out)", "runmodule.php?module=dwellings&op=logout&dwid={$dwid}&type={$type}&owner=1");
}
if (get_module_setting("othersleep", $type)) {
    if ($session['user']['acctid'] != $row['ownerid']) {
        addnav("Go to Sleep (Log Out)", "runmodule.php?module=dwellings&op=logout&dwid={$dwid}&type={$type}");
    }
    $ac = db_prefix("accounts");
    $mu = db_prefix("module_userprefs");
    $sql = "SELECT {$ac}.name AS name,\r\n\t\t\t\t{$ac}.acctid AS acctid,\r\n\t\t\t\t{$mu}.userid FROM {$mu} \r\n\t\t\t\tINNER JOIN {$ac} ON {$ac}.acctid = {$mu}.userid \r\n\t\t\t\tWHERE {$mu}.setting = 'dwelling_saver'\r\n\t\t\t\tand {$mu}.value = {$dwid} \r\n\t\t\t\tand {$ac}.loggedin = 0";
    $res = db_query_cached($sql, "dwellings-sleepers-{$dwid}");
    $i = 0;
    $num = db_num_rows($res);
    while ($row1 = db_fetch_assoc($res)) {
        $pre = "";
        $suf = "";
        if ($i == 0) {
            $pre = translate_inline("`nThe following people are sleeping here: ");
        } elseif ($i > 0 && $num > 2) {
            $pre = ", ";
        }
        if ($i > 0 && $i == $num - 1) {
            $pre = $pre . "" . translate_inline("and ");
        }
        if ($i == $num - 1) {
            $suf = ".`n`n";
function improbablehousing_sleeplinks($house, $rid)
{
    global $session;
    $hid = $house['id'];
    if (!$house['data']['rooms'][$rid]['blocksleep']) {
        $sleepslots = $house['data']['rooms'][$rid]['sleepslots'];
        if (count($sleepslots)) {
            foreach ($sleepslots as $slot => $vals) {
                if ($vals['occupier']) {
                    $acctid = $vals['occupier'];
                    $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid='{$acctid}'";
                    $result = db_query_cached($sql, "playernames/playername_" . $acctid);
                    $row = db_fetch_assoc($result);
                    addnav("Sleeping spaces");
                    addnav(array("%s occupied by %s`0", $vals['name'], $row['name']), "");
                    //do kickout navs if the player is the house owner
                    if (improbablehousing_getkeytype($house, $rid) >= 100) {
                        addnav("Kick out Sleepers");
                        addnav(array("Kick out %s`0", $row['name']), "runmodule.php?module=improbablehousing&op=sleep&sub=kickout&hid=" . $house['id'] . "&rid=" . $rid . "&slot=" . $slot);
                    }
                } else {
                    //it's an empty slot, shall we kip in it?
                    addnav("Sleeping spaces");
                    addnav(array("%s available`0", $vals['name']), "runmodule.php?module=improbablehousing&op=sleep&sub=start&hid={$hid}&rid={$rid}&slot={$slot}");
                }
            }
        }
    }
}
function racekittymorph_dohook($hookname, $args)
{
    global $session, $resline;
    $city = "Kittania";
    $race = "Kittymorph";
    switch ($hookname) {
        case "racenames":
            $args[$race] = $race;
            break;
        case "changesetting":
            // Ignore anything other than villagename setting changes
            if ($args['setting'] == "villagename" && $args['module'] == "racekittymorph") {
                if ($session['user']['location'] == $args['old']) {
                    $session['user']['location'] = $args['new'];
                }
                $sql = "UPDATE " . db_prefix("accounts") . " SET location='" . addslashes($args['new']) . "' WHERE location='" . addslashes($args['old']) . "'";
                db_query($sql);
                if (is_module_active("cities")) {
                    $sql = "UPDATE " . db_prefix("module_userprefs") . " SET value='" . addslashes($args['new']) . "' WHERE modulename='cities' AND setting='homecity'" . "AND value='" . addslashes($args['old']) . "'";
                    db_query($sql);
                }
            }
            break;
        case "chooserace":
            if ($session['user']['dragonkills'] == 0) {
                break;
            }
            output("`0You smile, and turn around to show the gatekeeper your tail.  <a href='newday.php?setrace={$race}{$resline}'>\"Um... notice anything unusual?\"</a>`n`n", true);
            addnav("`&Kittymorph`0", "newday.php?setrace={$race}{$resline}");
            addnav("", "newday.php?setrace={$race}{$resline}");
            break;
        case "setrace":
            if ($session['user']['race'] == $race) {
                output("\"`6Oh, I see, right,`0\" says the gatekeeper, looking down at his ledger.  \"`6A kittymorph, then, okay, let's see, here...  Kay, eye, tee, ee, em, oh, are, eff.  Kittymorph.`0\"  He looks up again.  \"`6Um.  You can turn around again, now.`0\"`n`nYou oblige.  \"`#Sorry.`0\"`n`n\"`6Don't worry about it.  Have you always been like this?`0\"`n`n\"`#Since I was a kitten,`0\" you reply.  \"`#I don't know what that crazy woman back there was talking about; she says I fell out of a plane and hit my head.  Rubbish.`0\"`n`n\"`6Of course,`0\" says the gatekeeper, smiling.  \"`6You would have landed on your feet, wouldn't you?`0\"`n`n\"`#That's right.  Although...`0\"  You look down, puzzled.  \"`#Some things just don't add up...`0\" you mutter.`n`n\"`6Well, don't worry,`0\" says the gatekeeper.  \"`6Just head into town and get some nice clothes, and you'll sort everything out, I'm sure.  If you wear clothes, that is.`0\"`n`nYou grin.  \"`#When it suits me.`0\"  You saunter off through the gates.  You don't really know how to walk any other way.");
                if (is_module_active("cities")) {
                    set_module_pref("homecity", $city, "cities");
                    if ($session['user']['age'] == 0) {
                        $session['user']['location'] = $city;
                    }
                }
            }
            break;
        case "alternativeresurrect":
        case "stamina-newday":
            if ($session['user']['race'] == $race) {
                racekittymorph_checkcity();
                //Stamina buffs
                require_once "modules/staminasystem/lib/lib.php";
                apply_stamina_buff('kittymorph3', array("name" => "KittyMorph Bonus: Travelling Speed", "class" => "Travelling", "costmod" => 0.8, "expmod" => 1, "rounds" => -1, "roundmsg" => "", "wearoffmsg" => ""));
                apply_stamina_buff('kittymorph4', array("name" => "KittyMorph Bonus: Cooking and Carcass Cleaning Expertise", "class" => "Meat", "costmod" => 0.7, "expmod" => 1.2, "rounds" => -1, "roundmsg" => "", "wearoffmsg" => ""));
                apply_stamina_buff('kittymorph1', array("name" => "KittyMorph Penalty: Hunting Indifference", "class" => "Hunting", "costmod" => 1.1, "expmod" => 1, "rounds" => -1, "roundmsg" => "", "wearoffmsg" => ""));
                apply_stamina_buff('kittymorph2', array("name" => "KittyMorph Penalty: Combat Indifference", "class" => "Combat", "costmod" => 1.1, "expmod" => 1, "rounds" => -1, "roundmsg" => "", "wearoffmsg" => ""));
                apply_stamina_buff('kittymorph5', array("name" => "KittyMorph Penalty: Technical Ineptitude", "class" => "ScrapBots", "costmod" => 1.1, "expmod" => 0.8, "rounds" => -1, "roundmsg" => "", "wearoffmsg" => ""));
                apply_stamina_buff('raceclassy', array("name" => "KittyMorph Bonus: Classy Insults Proficiency", "action" => "Insults - Classy", "costmod" => 0.9, "expmod" => 1, "rounds" => -1, "roundmsg" => "", "wearoffmsg" => ""));
                apply_stamina_buff('raceconfusing', array("name" => "KittyMorph Bonus: Confusing Insults Proficiency", "action" => "Insults - Confusing", "costmod" => 0.5, "expmod" => 1, "rounds" => -1, "roundmsg" => "", "wearoffmsg" => ""));
                //combat buffs
                apply_buff("racialbenefit1", array("name" => "`7KittyMorph Penalty: Slender`0", "defmod" => "0.8", "allowinpvp" => 1, "allowintrain" => 1, "rounds" => -1, "schema" => "module-racekittymorph"));
                apply_buff("racialbenefit2", array("name" => "`7KittyMorph Bonus: Claws`0", "atkmod" => "1.2", "allowinpvp" => 1, "allowintrain" => 1, "rounds" => -1, "schema" => "module-racekittymorph"));
            }
            break;
        case "creatureencounter":
            if ($session['user']['race'] == $race) {
                //get those folks who haven't manually chosen a race
                racekittymorph_checkcity();
                if ($session['user']['armordef'] == 0) {
                    apply_buff("nudekitty", array("name" => "`7KittyMorph Bonus: Nude Fighting`0", "badguyatkmod" => 0.7, "badguydefmod" => 0.7, "allowinpvp" => 1, "allowintrain" => 1, "rounds" => -1, "roundmsg" => "Because you are fighting completely starkers, {badguy} is hilariously distracted and cannot attack or defend as effectively!", "expireafterfight" => 1, "schema" => "module-racekittymorph"));
                }
            }
            break;
        case "battle-victory":
            if ($session['user']['race'] == $race) {
                if (!$session['user']['alive']) {
                    debug($args['creatureexp']);
                    $args['creatureexp'] = round($args['creatureexp'] * 1.3);
                    debug($args['creatureexp']);
                }
            }
            break;
        case "validforestloc":
        case "validlocation":
            if (is_module_active("cities")) {
                $args[$city] = "village-{$race}";
            }
            break;
        case "moderate":
            if (is_module_active("cities")) {
                tlschema("commentary");
                $args["village-{$race}"] = sprintf_translate("City of %s", $city);
                tlschema();
            }
            break;
        case "villagetext":
            racekittymorph_checkcity();
            if ($session['user']['location'] == $city) {
                $args['text'] = array("`0You are standing in the heart of Kittania.  Though officially registered as a city, it only earned that title because there were so many sentient creatures living there.`n`nIn reality, the city is a very basic affair, little more than a pack living together in common conditions.  Kittymorphs are a little too lazy to build much.`n");
                $args['schemas']['text'] = "module-racekittymorph";
                $args['clock'] = "`n`0From the position of the sun in the sky, you reckon it's about `&%s`0.`n";
                $args['schemas']['clock'] = "module-racekittymorph";
                if (is_module_active("calendar")) {
                    $args['calendar'] = "`n`0Scrawled in dust on the floor is the current date, `&%s`0, `&%s %s %s`0.`n";
                    $args['schemas']['calendar'] = "module-racekittymorph";
                }
                $args['title'] = array("%s, Home of the Kittymorphs", $city);
                $args['schemas']['title'] = "module-racekittymorph";
                $args['sayline'] = "says";
                $args['schemas']['sayline'] = "module-racekittymorph";
                $args['talk'] = "`n`&Nearby some kittymorphs talk:`n";
                $args['schemas']['talk'] = "module-racekittymorph";
                $new = get_module_setting("newest-{$city}", "cities");
                if ($new != 0) {
                    $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid='{$new}'";
                    $result = db_query_cached($sql, "newest-{$city}");
                    $row = db_fetch_assoc($result);
                    $args['newestplayer'] = $row['name'];
                    $args['newestid'] = $new;
                } else {
                    $args['newestplayer'] = $new;
                    $args['newestid'] = "";
                }
                if ($new == $session['user']['acctid']) {
                    $args['newest'] = "`n`0As you wander your new home, you feel your jaw dropping at the wonderful smells around you.";
                } else {
                    $args['newest'] = "`n`0Wandering the village, jaw agape and buck naked, is `&%s`0.";
                }
                $args['schemas']['newest'] = "module-racekittymorph";
                $args['section'] = "village-{$race}";
                $args['stablename'] = "Mike's Chop Shop";
                $args['schemas']['stablename'] = "module-racekittymorph";
                $args['gatenav'] = "Outpost Gates";
                $args['fightnav'] = "Toothclaw Close";
                $args['marketnav'] = "The Cul-De-Sac of Sparkly Things";
                $args['tavernnav'] = "Distraction Avenue";
                $args['schemas']['gatenav'] = "module-racekittymorph";
                unblocknav("stables.php");
            }
            break;
        case "stablelocs":
            tlschema("mounts");
            $args[$city] = sprintf_translate("The Village of %s", $city);
            tlschema();
            break;
        case "stabletext":
            if ($session['user']['location'] != $city) {
                break;
            }
            $args['title'] = "Mike's Chop Shop";
            $args['schemas']['title'] = "module-racekittymorph";
            $args['desc'] = array("`6Just next door to the Clan Halls, a rather basic-looking set of stables has been erected.`n`n", array("As you head inside, you notice an obvious lack of the typical stable smell.  Apparently KittyMorphs, for all their laziness, like to keep things clean.`n`n\"`^Well hello there!  What can I do for you, my good %s?`6\" asks a grey-furred KittyMorph male whose name you're absolutely `icertain`i is not \"Mike.\"", translate_inline($session['user']['sex'] ? 'lady' : 'man', 'stables')));
            $args['schemas']['desc'] = "module-racekittymorph";
            $args['lad'] = "friend";
            $args['schemas']['lad'] = "module-racekittymorph";
            $args['lass'] = "friend";
            $args['schemas']['lass'] = "module-racekittymorph";
            $args['nosuchbeast'] = "`6\"`^Hmm.  Not heard of that one,`6\" Mike says apologetically.";
            $args['schemas']['nosuchbeast'] = "module-racekittymorph";
            $args['toolittle'] = "`6Mike looks over the handful of currency you offered.  \"`^Aha.  Well, the price for this %s, you see, was actually `&%s `^Requisition  and `%%s`^ cigarettes.  Maybe you miscounted?`6\"";
            $args['schemas']['toolittle'] = "module-racekittymorph";
            $args['replacemount'] = "`6You sadly watch Mike lead your %s`6 away, along with your cigarettes.  However, when he returns, he brings with him a nice new `&%s`6 which makes you feel a little better.";
            $args['schemas']['replacemount'] = "module-racekittymorph";
            $args['newmount'] = "`6You hand over your currency.  Within moments, you become the proud recipient of a lovely new `&%s`6!";
            $args['schemas']['newmount'] = "module-racekittymorph";
            $args['confirmsale'] = "`n`n`6Mike eyes your mount up and down, checking it over carefully.  \"`^Yes, yes, that's a really nice example, right there - are you quite sure you want to part with it?`6\"";
            $args['schemas']['confirmsale'] = "module-racekittymorph";
            $args['mountsold'] = "`6With but a single tear, you hand your %s`6 over to Mike.  The tear dries quickly, and the %s in hand helps you quickly overcome your sorrow.";
            $args['schemas']['mountsold'] = "module-racekittymorph";
            $args['offer'] = "`n`n`6Mike offers you `&%s`6 Requisition and `%%s`6 Cigarettes for %s`6.";
            $args['schemas']['offer'] = "module-racekittymorph";
            break;
    }
    return $args;
}
addnav("Pages");
for ($i = 0; $i < $totalplayers; $i += $playersperpage) {
    $pnum = $i / $playersperpage + 1;
    if ($page == $pnum) {
        addnav(array(" ?`b`#Page %s`0 (%s-%s)`b", $pnum, $i + 1, min($i + $playersperpage, $totalplayers)), "list.php?page={$pnum}");
    } else {
        addnav(array(" ?Page %s (%s-%s)", $pnum, $i + 1, min($i + $playersperpage, $totalplayers)), "list.php?page={$pnum}");
    }
}
// Order the list by level, dragonkills, name so that the ordering is total!
// Without this, some users would show up on multiple pages and some users
// wouldn't show up
if ($page == "" && $op == "") {
    $title = translate_inline("Warriors Currently Online");
    $sql = "SELECT acctid,name,login,alive,location,race,sex,level,laston,loggedin,lastip,uniqueid FROM " . db_prefix("accounts") . " WHERE locked=0 AND loggedin=1 AND laston>'" . date("Y-m-d H:i:s", strtotime("-" . getsetting("LOGINTIMEOUT", 900) . " seconds")) . "' ORDER BY level DESC, dragonkills DESC, login ASC";
    $result = db_query_cached($sql, "list.php-warsonline");
} elseif ($op == 'clan') {
    $title = translate_inline("Clan Members Online");
    $sql = "SELECT acctid,name,login,alive,location,race,sex,level,laston,loggedin,lastip,uniqueid FROM " . db_prefix("accounts") . " WHERE locked=0 AND loggedin=1 AND laston>'" . date("Y-m-d H:i:s", strtotime("-" . getsetting("LOGINTIMEOUT", 900) . " seconds")) . "' AND clanid='{$session['user']['clanid']}' ORDER BY level DESC, dragonkills DESC, login ASC";
    $result = db_query($sql);
} else {
    if ($totalplayers > $playersperpage && $op != "search") {
        $title = sprintf_translate("Warriors of the realm (Page %s: %s-%s of %s)", $pageoffset / $playersperpage + 1, $from, $to, $totalplayers);
    } else {
        $title = sprintf_translate("Warriors of the realm");
    }
    rawoutput(tlbutton_clear());
    $sql = "SELECT acctid,name,login,alive,hitpoints,location,race,sex,level,laston,loggedin,lastip,uniqueid FROM " . db_prefix("accounts") . " WHERE locked=0 {$search} ORDER BY level DESC, dragonkills DESC, login ASC {$limit}";
    $result = db_query($sql);
}
if ($session['user']['loggedin']) {
    $to = min($pageoffset + $playersperpage, $totalplayers);
}
$limit = " LIMIT {$pageoffset},{$playersperpage} ";
addnav("Pages");
for ($i = 0; $i < $totalplayers; $i += $playersperpage) {
    addnav(array("Page %s (%s-%s)", $i / $playersperpage + 1, $i + 1, min($i + $playersperpage, $totalplayers)), "runmodule.php?module=marriage&op=newlyweds&page=" . ($i / $playersperpage + 1));
}
if ($page == "" && $action == "") {
    $title = translate_inline("Married Warriors Currently Online");
    $sql = "SELECT a.name as name,b.name as partnername,a.acctid as acctid,a.login as login,a.alive as alive,a.location as location,a.race as race,a.sex as sex,a.marriedto as marriedto,a.laston as laston,a.loggedin as loggedin,a.lastip as lastip,a.uniqueid as uniqueid FROM " . db_prefix("accounts") . " as a LEFT JOIN " . db_prefix("accounts") . " as b ON a.marriedto=b.acctid WHERE a.locked=0 AND (a.marriedto<>0 AND a.marriedto<>4294967295) AND a.loggedin=1 AND a.laston>'" . date("Y-m-d H:i:s", strtotime("-" . getsetting("LOGINTIMEOUT", 900) . " seconds")) . "' ORDER BY a.level DESC, a.dragonkills DESC, a.login ASC";
    $result = db_query_cached($sql, "marriage-marriedonline");
} else {
    $title = sprintf_translate("Married Warriors in the realm (Page %s: %s-%s of %s)", $pageoffset / $playersperpage + 1, $from, $to, $totalplayers);
    rawoutput(tlbutton_clear());
    $sql = "SELECT a.name as name,b.name as partnername,a.acctid as acctid,a.login as login,a.alive as alive,a.location as location,a.race as race,a.sex as sex,a.marriedto as marriedto,a.laston as laston,a.loggedin as loggedin,a.lastip as lastip,a.uniqueid as uniqueid FROM " . db_prefix("accounts") . " as a LEFT JOIN " . db_prefix("accounts") . " as b ON a.marriedto=b.acctid WHERE a.locked=0 AND (a.marriedto<>0 AND a.marriedto<>4294967295) {$search}" . "ORDER BY a.level DESC, a.dragonkills DESC, a.login ASC {$limit}";
    $result = db_query_cached($sql, "marriage-marriedrealm{$page}");
}
$max = db_num_rows($result);
if ($max > 100) {
    output("`\$Too many names match that.  Showing only the first 100.`0`n");
    $max = 100;
}
output_notl("`c`b" . $title . "`b");
$alive = translate_inline("Alive");
$name = translate_inline("Name");
$clan = translate_inline("Clan");
$loc = translate_inline("Location");
$race = translate_inline("Race");
$sex = translate_inline("Sex");
$who = translate_inline("Married To");
$marriagedate = translate_inline("Marriage Date");
function mountprereq_run()
{
    global $session;
    $op = httpget('op');
    $id = httpget("id");
    if ($op == "bestiary") {
        page_header("Bestiary");
        if (get_module_setting('viewactiveonly') == 1) {
            $sql = "SELECT mountname,mountid,mountdkcost FROM " . db_prefix("mounts") . " WHERE mountactive=1 ORDER BY mountdkcost,mountcostgems,mountcostgold";
        } else {
            $sql = "SELECT mountname,mountid,mountdkcost FROM " . db_prefix("mounts") . " ORDER BY mountdkcost,mountcostgems,mountcostgold";
        }
        $result = db_query($sql);
        $end = "";
        if (get_module_pref('viewed') == 0) {
            $wonder = "You briefly wonder why you never noticed this here before.";
            set_module_pref('viewed', 1);
            set_module_pref('vieweddk', 1);
        } elseif (get_module_pref('vieweddk') == 0) {
            $wonder = "It seems to have changed somewhat since you last saw it.";
            $end = "Feeling a little more confident since the last time you were here, you also decide to look up on some of the entries that you previously ignored.";
            set_module_pref('vieweddk', 1);
        } else {
            $wonder = "It does not seem to have changed since you last saw it.";
            $end = "`nAs the list descends down the page, more and more fantasic creatures make their appearance. Feeling a little overwhelmed, you decide to ignore the entries of the beasts that seem out of your league.";
        }
        output("You discover a dusty tome left on a stool. %s `nGingerly, you prise open the heavy cover, and discover a Table of Contents page. How helpful!`n%s", $wonder, $end);
        addnav("View the entry on...");
        for ($i = 0; $i < db_num_rows($result); $i++) {
            $row = db_fetch_assoc($result);
            if ($row['mountdkcost'] <= $session['user']['dragonkills'] && get_module_objpref("mounts", $row['mountid'], "boolshow") != 0) {
                addnav(array("View %s`0", $row['mountname']), "runmodule.php?module=mountprereq&op=browse&id={$row['mountid']}");
            }
        }
        addnav("Close the book");
        addnav("Return from whence you came", "stables.php");
    }
    if ($op == "browse") {
        page_header("Bestiary");
        $sql = "SELECT * FROM " . db_prefix("mounts") . " WHERE mountid='{$id}'";
        $result = db_query_cached($sql, "mountdata-{$id}", 3600);
        if (db_num_rows($result) <= 0) {
            output("You find that the book is actually full of empty pages!");
        } else {
            $mount = db_fetch_assoc($result);
            $buff = unserialize($mount['mountbuff']);
            if (get_module_setting('boolshowcost') == 1) {
                output("`c`&-=%s`&=-`7`c`n`n", $mount['mountname']);
                output("`b`c`#Costs`b`c`7");
                $goldcost = "";
                $gemcost = "";
                $donationcost = "";
                $favorcost = "";
                $upgrade = "";
                if (get_module_objpref("mounts", $id, "favorcost") != 0) {
                    $favorcost = '`n' . get_module_objpref("mounts", $id, "favorcost") . ' `$Favor`7';
                }
                if (get_module_objpref("mounts", $id, "donationcost") != 0) {
                    $donationcost = '`n' . get_module_objpref("mounts", $id, "donationcost") . ' Donation Point(s)';
                }
                if ($mount['mountcostgold'] != "" && $mount['mountcostgold'] != 0) {
                    $goldcost = '`n' . $mount['mountcostgold'] . ' `^Gold`7';
                }
                if ($mount['mountcostgems'] != "" && $mount['mountcostgems'] != 0) {
                    $gemcost = '`n' . $mount['mountcostgems'] . ' `%Gem(s)`7';
                }
                if ($mount['mountfeedcost'] != "" && $mount['mountfeedcost'] != 0 && $buff['rounds'] > 0) {
                    $cost = $mount['mountfeedcost'] * $session['user']['level'];
                    $feedcost = '`nFeeding costs ' . $cost . ' `6Gold`7';
                }
                output("`c{$goldcost} {$gemcost} {$favorcost} {$donationcost} {$feedcost}`c`n");
            }
            if (get_module_objpref("mounts", $id, "buffatkmod") == "") {
                if ($buff['atkmod'] != "" && get_module_setting('toggleatkmod') == 1) {
                    $var = mountprereq_calc($buff['atkmod']);
                    $atkmod = round($var * 100 - 100, 2);
                    if ($atkmod != 0) {
                        if ($atkmod > 0) {
                            $sign1 = '+';
                        }
                        $atk = '`n' . $sign1 . $atkmod . '% attack';
                    }
                }
            } else {
                $atk = "`nAttack Modifier: " . get_module_objpref("mounts", $id, "buffatkmod");
            }
            if (get_module_objpref("mounts", $id, "buffdefmod") == "") {
                if ($buff['defmod'] != "" && get_module_setting('toggledefmod') == 1) {
                    $var0 = mountprereq_calc($buff['defmod']);
                    $defmod = round($var0 * 100 - 100, 2);
                    if ($defmod != 0) {
                        if ($defmod > 0) {
                            $sign2 = '+';
                        }
                        $def = '`n' . $sign2 . $defmod . '% defense';
                    }
                }
            } else {
                $def = "`nDefense Modifier: " . get_module_objpref("mounts", $id, "buffdefmod");
            }
            if (get_module_objpref("mounts", $id, "buffregen") == "") {
                if ($buff['regen'] != "" && get_module_setting('toggleregen') == 1) {
                    $var1 = round(mountprereq_calc($buff['regen']), 0);
                    if ($var1 != 0) {
                        if ($var1 > 0) {
                            $sign3 = '+';
                        }
                        $regen = '`n' . $sign3 . $var1 . 'HP regeneration per round';
                    }
                }
            } else {
                $regen = "`nRegen: " . get_module_objpref("mounts", $id, "buffregen");
            }
            if (get_module_objpref("mounts", $id, "buffdamageshield") == "") {
                if ($buff['damageshield'] != "" && get_module_setting('toggledamageshield') == 1) {
                    $var2 = mountprereq_calc($buff['damageshield']);
                    $damageshieldmod = round($var2 * 100, 2);
                    if ($damageshieldmod != 0) {
                        if ($damageshieldmod >= 0) {
                            $sign4 = '+';
                        }
                        $damageshield = '`n' . $sign4 . $damageshieldmod . '% damage shield';
                    }
                }
            } else {
                $damageshield = "`nDamageshield: " . get_module_objpref("mounts", $id, "buffdamageshield");
            }
            if (get_module_objpref("mounts", $id, "bufflifetap") == "") {
                if ($buff['lifetap'] != "" && get_module_setting('togglelifetap') == 1) {
                    $var3 = mountprereq_calc($buff['lifetap']);
                    $lifetapmod = round($var3 * 100, 2);
                    if ($lifetapmod != 0) {
                        if ($lifetapmod >= 0) {
                            $sign5 = '+';
                        }
                        $lifetap = '`n' . $sign5 . $lifetapmod . '% HP leech';
                    }
                }
            } else {
                $lifetap = "`nLifetap: " . get_module_objpref("mounts", $id, "bufflifetap");
            }
            if (get_module_objpref("mounts", $id, "buffminioncount") == "") {
                if ($buff['minioncount'] != "" && get_module_setting('toggleminioncount') == 1) {
                    $var4 = round(mountprereq_calc($buff['minioncount']), 0);
                    if ($var4 != 0) {
                        $minioncount = '`n' . $var4 . ' attack(s) maximum per round';
                    }
                }
            } else {
                $minioncount = "`nMaximum number of Attacks per round: " . get_module_objpref("mounts", $id, "buffminioncount");
            }
            if (get_module_objpref("mounts", $id, "buffmaxbadguydamage") == "") {
                if ($buff['maxbadguydamage'] != "" && get_module_setting('togglemaxbadguydamage') == 1) {
                    $var5 = round(mountprereq_calc($buff['maxbadguydamage']), 0);
                    if ($var5 != 0) {
                        $maxbadguydamage = '`n' . $var5 . ' maximum damage per attack';
                    }
                }
            } else {
                $maxbadguydamage = "`nMaximum damage per Attack per round: " . get_module_objpref("mounts", $id, "buffmaxbadguydamage");
            }
            if (get_module_objpref("mounts", $id, "buffbadguyatkmod") == "") {
                if ($buff['badguyatkmod'] != "" && get_module_setting('togglebadguyatkmod') == 1) {
                    $var6 = mountprereq_calc($buff['badguyatkmod']);
                    $badguyatk = round($var6 * 100 - 100, 2);
                    if ($badguyatk != 0) {
                        if ($badguyatk >= 0) {
                            $sign6 = '+';
                        }
                        $badguyatkmod = '`n' . $sign6 . $badguyatk . '% enemy attack';
                    }
                }
            } else {
                $badguyatkmod = "`nEnemy Attack Modifier: " . get_module_objpref("mounts", $id, "buffbadguyatkmod");
            }
            if (get_module_objpref("mounts", $id, "buffbadguydefmod") == "") {
                if ($buff['badguydefmod'] != "" && get_module_setting('togglebadguydefmod') == 1) {
                    $var7 = mountprereq_calc($buff['badguydefmod']);
                    $badguydef = round($var7 * 100 - 100, 2);
                    if ($badguydef != 0) {
                        if ($badguydef >= 0) {
                            $sign7 = '+';
                        }
                        $badguydefmod = '`n' . $sign7 . $badguydef . '% enemy defense';
                    }
                }
            } else {
                $badguydefmod = "`nEnemy Defense Modifier: " . get_module_objpref("mounts", $id, "buffbadguydefmod");
            }
            if (get_module_objpref("mounts", $id, "buffbadguydmgmod") == "") {
                if ($buff['badguydmgmod'] != "" && get_module_setting('togglebadguydmgmod') == 1) {
                    $var8 = mountprereq_calc($buff['badguydmgmod']);
                    $badguydmg = round($var8 * 100 - 100, 2);
                    if ($badguydmg != 0) {
                        if ($badguydmg >= 0) {
                            $sign8 = '+';
                        }
                        $badguydmgmod = '`n' . $sign8 . $badguydmg . '% enemy damage modifier';
                    }
                }
            } else {
                $badguydmgmod = "`nEnemy Damage Modifier: " . get_module_objpref("mounts", $id, "badguydmgmod");
            }
            if (get_module_objpref("mounts", $id, "buffinv") == "") {
                if ($buff['invulnerable'] != "" && get_module_setting('toggleinv') == 1) {
                    $var9 = round(mountprereq_calc($buff['invulnerable']), 0);
                    if ($var9 == 1) {
                        $var9 = "INVULNERABLE!!";
                        $inv = '`n' . $var9;
                    }
                }
            } else {
                $inv = "`nInvulnerability: " . get_module_objpref("mounts", $id, "buffinv");
            }
            if (get_module_objpref("mounts", $id, "ffs") == "") {
                if ($mount['mountforestfights'] != "" && $mount['mountforestfights'] != 0 && get_module_setting('toggleffs') == 1) {
                    $ffs = '`n' . $mount[mountforestfights] . ' extra turn(s) per day';
                }
            } else {
                $ffs = "`nExtra Forest Fights each day: " . get_module_objpref("mounts", $id, "ffs");
            }
            if (get_module_objpref("mounts", $id, "mountspd", "speed") < 0) {
                $spd = '`n' . abs(get_module_objpref("mounts", $id, "mountspd", "speed")) . ' Agility penalty';
            } elseif (get_module_objpref("mounts", $id, "mountspd", "speed") > 0) {
                $spd = '`n' . get_module_objpref("mounts", $id, "mountspd", "speed") . ' Agility bonus';
            } else {
                $spd = '';
            }
            if (get_module_objpref("mounts", $id, "buffrounds") == "") {
                if ($buff['rounds'] != "" && $buff['rounds'] != 0 && get_module_setting('toggleround') == 1) {
                    $round = $buff['rounds'];
                    if ($round < 0) {
                        $round = 'Permanent';
                    }
                    $rounds = '`n' . $round . ' Rounds';
                }
            } else {
                $rounds = "`nRounds: " . get_module_objpref("mounts", $id, "buffrounds");
            }
            if (get_module_objpref("mounts", $id, "buffname") == "") {
                if ($buff['name'] != "" && get_module_setting('togglename') == 1) {
                    $name = $buff['name'];
                }
            } else {
                $name = get_module_objpref("mounts", $id, "buffname");
            }
            if (is_module_active('mountupgrade') && get_module_setting('boolmountupgrade') == 1 && get_module_objpref("mounts", $id, "upgradeto", "mountupgrade") > 0) {
                $upgradeto = get_module_objpref("mounts", $id, "upgradeto", "mountupgrade");
                $sql = "SELECT mountname FROM " . db_prefix("mounts") . " WHERE mountid='{$upgradeto}'";
                $result = db_query($sql);
                $upgrademount = db_fetch_assoc($result);
                $upgrade = '`n`nupgrades to ' . $upgrademount['mountname'] . '`7';
                if (get_module_objpref("mounts", $id, "upgradedks") == "") {
                    if (get_module_objpref("mounts", $id, "reqdks", "mountupgrade") != "" && get_module_objpref("mounts", $id, "reqdks", "mountupgrade") != 0 && get_module_setting('toggleupgradedks') == 1) {
                        $upgradedks = '`n' . get_module_objpref("mounts", $id, "reqdks", "mountupgrade") . ' DKs required to upgrade';
                    }
                } else {
                    $upgradedks = "`nDKs required for upgrade: " . get_module_objpref("mounts", $id, "upgradedks");
                }
                if (get_module_objpref("mounts", $id, "upgradelevels") == "") {
                    if (get_module_objpref("mounts", $id, "reqlevels", "mountupgrade") != "" && get_module_objpref("mounts", $id, "reqlevels", "mountupgrade") != 0 && get_module_setting('toggleupgradelevels') == 1) {
                        $upgradelevels = '`n' . get_module_objpref("mounts", $id, "reqdks", "mountupgrade") . ' levelss required to upgrade';
                    }
                } else {
                    $upgradelevels = "`nLevels required for upgrade: " . get_module_objpref("mounts", $id, "upgradelevels");
                }
                if (get_module_objpref("mounts", $id, "upgradedays") == "") {
                    if (get_module_objpref("mounts", $id, "reqdays", "mountupgrade") != "" && get_module_objpref("mounts", $id, "reqdays", "mountupgrade") != 0 && get_module_setting('toggleupgradedays') == 1) {
                        $upgradedays = '`n' . get_module_objpref("mounts", $id, "reqdays", "mountupgrade") . ' Days required to upgrade';
                    }
                } else {
                    $upgradedays = "`nDays required for upgrade: " . get_module_objpref("mounts", $id, "upgradedays");
                }
                if (get_module_objpref("mounts", $id, "upgradeffs") == "") {
                    if (get_module_objpref("mounts", $id, "reqffs", "mountupgrade") != "" && get_module_objpref("mounts", $id, "reqffs", "mountupgrade") != 0 && get_module_setting('toggleupgradeffs') == 1) {
                        $upgradeffs = '`n' . get_module_objpref("mounts", $id, "reqffs", "mountupgrade") . ' forest fights required to upgrade';
                    }
                } else {
                    $upgradeffs = "`nForest fights required for upgrade: " . get_module_objpref("mounts", $id, "upgradeffs");
                }
                if (getmodulesetting('toggleupgradeview') && get_module_objpref("mounts", $id, "boolshowupgrade") == 1) {
                    addnav("View Upgrade");
                    addnav(array("View %s`0", $upgrademount['mountname']), "runmodule.php?module=mountprereq&op=browse&id={$upgradeto}");
                }
            }
            output("`n`b`c`@Special Abilities`7`b`c");
            output("`c`7{$name}`7 {$rounds} {$atk} {$def} {$regen} {$damageshield} {$lifetap} {$minioncount} {$maxbadguydamage} {$badguyatkmod} {$badguydefmod} {$badguydmgmod} {$ffs} {$spd} {$upgrade} {$upgradedks} {$upgradelevels} {$upgradedays} {$upgradeffs}`c`n");
            output("`n`c`b`^Ownership Requirements`7`b`c");
            $dkreq = "";
            $charmreq = "";
            $recareq = "";
            $sexreq = "";
            $donationreq = "";
            $favorreq = "";
            $alignreq = "";
            if ($mount['mountdkcost'] != 0 && $mount['mountdkcost'] != "") {
                $dkreq = "`nDragonkills: " . $mount['mountdkcost'];
            }
            if (get_module_objpref("mounts", $id, "charmreq") != 0) {
                $charmreq = "`nCharm: " . get_module_objpref("mounts", $id, "charmreq");
            }
            if (get_module_objpref("mounts", $id, "racereq") != "") {
                $racereq = "`n" . get_module_objpref("mounts", $id, "racereq") . " `0Race";
            }
            if (get_module_objpref("mounts", $id, "sexreq") != 2) {
                if (get_module_objpref("mounts", $id, "sexreq") == 0) {
                    $sex = "`!Male`7";
                } else {
                    $sex = "`rFemale`7";
                }
                $sexreq = "`n{$sex} owners";
            }
            if (get_module_objpref("mounts", $id, "favorreq") != 0) {
                $favorreq = "`nFavor: " . get_module_objpref("mounts", $id, "favorreq");
            }
            if (get_module_objpref("mounts", $id, "donationreq") != 0) {
                $donationreq = "`nDonation Points: " . get_module_objpref("mounts", $id, "donationreq");
            }
            if (is_module_active('alignment') && get_module_objpref("mounts", $id, "boolalign") != 0) {
                if (get_module_objpref("mounts", $id, "boolalign") == 1) {
                    $align = "`nBelow `4" . get_module_objpref("mounts", $id, "alignlo") . "`7 alignment.`n";
                } elseif (get_module_objpref("mounts", $id, "boolalign") == 3) {
                    $align = "`nAbove `@" . get_module_objpref("mounts", $id, "alignhi") . "`7 alignment.`n";
                } else {
                    $align = "`nBetween `4" . get_module_objpref("mounts", $id, "alignlo") . "`7 and `@" . get_module_objpref("mounts", $id, "alignhi") . "`7 alignment.";
                }
            }
            output("`c{$dkreq} {$charmreq} {$favorreq} {$alignreq} {$donationreq} {$racereq} {$sexreq}`7 {$align}`0`c`n");
            if (is_module_active('mountrarity') && get_module_setting('boolmountrarity') == 1 && get_module_objpref("mounts", $id, "rarity", "mountrarity") != 100) {
                $rare = get_module_objpref("mounts", $id, "rarity", "mountrarity");
                if ($rare <= 20) {
                    $raretext = '`b`$extremely rare`b`7!!';
                } elseif ($rare <= 40) {
                    $raretext = '`@rare`7!';
                } elseif ($rare <= 60) {
                    $raretext = 'uncommon.';
                } elseif ($rare <= 80) {
                    $raretext = 'common.';
                } else {
                    $raretext = 'very common.';
                }
                output("`n`c`b`&Miscellaneous Infomation`c`b");
                output("`c`7The`& %s`7 is %s`c`n", $mount['mountname'], $raretext);
            }
            if (get_module_objpref("mounts", $id, "outputtext") != "") {
                output("`n`c`Q`i%s`7`i`c`n", stripslashes(get_module_objpref("mounts", $id, "outputtext")));
            }
            addnav("Go Back");
            addnav("Flip back to the Contents page", "runmodule.php?module=mountprereq&op=bestiary");
        }
    }
    page_footer();
}
function meatsystem_run()
{
    global $session;
    require_once "modules/staminasystem/lib/lib.php";
    page_header("Meat!");
    addnav("Meat Skills");
    $from = httpget('from');
    switch (httpget('op')) {
        case "devour":
            //special ability for Zombies only - Zombies can eat raw meat, so we're giving them the ability to simply devour the carcass where it lies.
            $carcasses = unserialize(get_module_pref("carcasses"));
            if (!is_array($carcasses)) {
                $carcasses = array();
            }
            debug($carcasses);
            foreach ($carcasses as $carcassnum => $creatureid) {
                $sql = "SELECT creaturename FROM " . db_prefix("creatures") . " WHERE creatureid = " . $creatureid . " ";
                $result = db_query_cached($sql, "creaturename-" . $creatureid, 86400);
                $creature = db_fetch_assoc($result);
                output("Giving in to your primal urges, you lean down and begin ripping meat from the still-twitching %s with your teeth.`n`n", $creature['creaturename']);
                $meat1 = get_module_objpref("creatures", $creatureid, "meat1");
                $meat2 = get_module_objpref("creatures", $creatureid, "meat2");
                $meat3 = get_module_objpref("creatures", $creatureid, "meat3");
                for ($i = 0; $i < $meat1; $i++) {
                    increment_module_pref("nutrition", 1, "staminafood");
                    increment_module_pref("fat", 3, "staminafood");
                    increment_module_pref("fullness", 1, "staminafood");
                    addstamina(1000);
                }
                for ($i = 0; $i < $meat2; $i++) {
                    increment_module_pref("nutrition", 2, "staminafood");
                    increment_module_pref("fat", 2, "staminafood");
                    increment_module_pref("fullness", 1, "staminafood");
                    addstamina(2000);
                }
                for ($i = 0; $i < $meat3; $i++) {
                    increment_module_pref("nutrition", 3, "staminafood");
                    increment_module_pref("fat", 1, "staminafood");
                    increment_module_pref("fullness", 1, "staminafood");
                    addstamina(5000);
                }
                output("For the record, and since it's nice to know these things even if you're too busy tearing cartilage and muscle from the bone to really pay attention to them, in this meal you have eaten %s bite's-worth of Crap Meat, %s bite's-worth of Half-Decent Meat, and %s bite's-worth of Tasty Meat.`n", $meat1, $meat2, $meat3);
                $full = get_module_pref("fullness", "staminafood");
                if ($full < 0) {
                    output("You still feel as though you haven't eaten in days.`n`n");
                }
                if ($full >= 0 && $full < 50) {
                    output("You feel a little less hungry.`n`n");
                }
                if ($full >= 50 && $full < 100) {
                    output("You still feel as though you've got room for more!`n`n");
                }
                if ($full >= 100) {
                    output("You're stuffed!  You feel as though you can't possibly eat anything more today.`n`n");
                }
                unset($carcasses[$carcassnum]);
                set_module_pref("carcasses", serialize($carcasses));
            }
            break;
        case "clean":
            $creatureid = httpget('creatureid');
            $carcass = httpget('carcass');
            $meat1 = get_module_objpref("creatures", $creatureid, "meat1");
            $meat2 = get_module_objpref("creatures", $creatureid, "meat2");
            $meat3 = get_module_objpref("creatures", $creatureid, "meat3");
            $amber = get_stamina();
            $return = process_action("Cleaning the Carcass");
            if ($return['lvlinfo']['levelledup'] == true) {
                output("`n`c`b`0You gained a level in Cleaning Carcasses!  You are now level %s!  This action will cost fewer Stamina points now, so you can butcher more creatures each day!`b`c`n", $return['lvlinfo']['newlvl']);
            }
            $failchance = e_rand(0, 100);
            if ($failchance > $amber) {
                //failure - the nice meat gets turned into Crap Meat
                $meat1 += $meat2;
                $meat1 += $meat3;
                output("`4You sit down to clean the carcass.  Your exhausted, clumsy incisions make a mockery of the choicest cuts - what is left over can only be described as Crap Meat.  %s bite's-worth, to be precise.  It looks like it was hacked into chunks by a blind woodsman.", $meat1);
                //todo
                for ($i = 0; $i < $meat1; $i++) {
                    give_item("meat_low", false, false, true);
                }
                load_inventory();
                $carcasses = unserialize(get_module_pref("carcasses"));
                unset($carcasses[$carcass]);
                $carcasses = array_values($carcasses);
                set_module_pref("carcasses", serialize($carcasses));
            } else {
                //success - all meat is sorted
                output("You spend a few minutes up to your elbows in gore, and getting rather hungry.`n");
                if ($meat1 > 0) {
                    output("You tear off enough to make %s rough bite's-worth of what the locals affectionately call Crap Meat.  It's mostly wobbling chunks of stinking yellow fat, intermingled with the occasional squirmy tendon.`n", $meat1);
                }
                if ($meat2 > 0) {
                    output("You make swift work of the fattier muscle, and before too long you have %s rough bite's-worth of Half-Decent Meat.`n", $meat2);
                }
                if ($meat3 > 0) {
                    output("The red, tender slivers of muscle slide easily from the bone, and you wind up with %s rough bite's-worth of Tasty Meat.`n", $meat3);
                }
                //todo
                for ($i = 0; $i < $meat1; $i++) {
                    give_item("meat_low", false, false, true);
                }
                for ($i = 0; $i < $meat2; $i++) {
                    give_item("meat_medium", false, false, true);
                }
                for ($i = 0; $i < $meat3; $i++) {
                    give_item("meat_high", false, false, true);
                }
                load_inventory();
                $carcasses = unserialize(get_module_pref("carcasses"));
                unset($carcasses[$carcass]);
                $carcasses = array_values($carcasses);
                set_module_pref("carcasses", serialize($carcasses));
                $pmeat1 = has_item("meat_low");
                $pmeat2 = has_item("meat_medium");
                $pmeat3 = has_item("meat_high");
                if (($pmeat1 || $pmeat2 || $pmeat3) && $session['user']['race'] != "Robot") {
                    if (get_module_pref("fullness", "staminafood") < 100) {
                        $cookcost = stamina_getdisplaycost("Cooking");
                        addnav(array("Cook up some meat (`Q%s%%`0)", $cookcost), "runmodule.php?module=meatsystem&op=cook&from=" . $from);
                    } else {
                        addnav("You're too full to cook, let alone eat", "");
                    }
                }
            }
            break;
        case "cook":
            $pmeat1qty = has_item_quantity("meat_low");
            $pmeat2qty = has_item_quantity("meat_medium");
            $pmeat3qty = has_item_quantity("meat_high");
            output("You whip out your camping stove.  It's time to cook!`n`nWhat will you put in the pan?  You can fit up to 20 bite's-worth of meat in there.  Right now you have %s bite's-worth of Crap Meat, %s bite's-worth of Half-Decent Meat, and %s bite's-worth of Tasty Meat.`n`n", $pmeat1qty, $pmeat2qty, $pmeat3qty);
            rawoutput("<form action='runmodule.php?module=meatsystem&op=cookfinal&from=" . $from . "' method='POST'>");
            rawoutput("Put in <input name='meat1' width='2' value='0'> bite's-worth of Crap Meat.<br />");
            rawoutput("Put in <input name='meat2' width='2' value='0'> bite's-worth of Half-Decent Meat.<br />");
            rawoutput("Put in <input name='meat3' width='2' value='0'> bite's-worth of Tasty Meat.<br />");
            rawoutput("<input type='submit' class='button' value='" . translate_inline("Cook!") . "'>");
            rawoutput("</form>");
            addnav("", "runmodule.php?module=meatsystem&op=cookfinal&from=" . $from);
            break;
        case "cookfinal":
            $pmeat1qty = has_item_quantity("meat_low");
            $pmeat2qty = has_item_quantity("meat_medium");
            $pmeat3qty = has_item_quantity("meat_high");
            $meat1 = httppost("meat1");
            $meat2 = httppost("meat2");
            $meat3 = httppost("meat3");
            //check for the dumbass player cooking meat that they don't have
            if ($meat1 > $pmeat1qty || $meat2 > $pmeat2qty || $meat3 > $pmeat3qty) {
                output("You don't `ihave`i that much meat!`n`n");
                addnav("Whoops");
                addnav("Sorry, I forgot how to count for a second there.  Let's try this again.", "runmodule.php?module=meatsystem&op=cook&from=" . $from);
                break;
            }
            //check for the dumbass player inputting a negative number
            if ($meat1 < 0 || $meat2 < 0 || $meat3 < 0) {
                page_header("Either taking vegetarianism to whole new levels, or trying to grow meat from an empty pan");
                output("You want to cook `inegative`i meat?  How very Zen of you.`n`n");
                addnav("You sneaky bugger");
                addnav("Abandon your efforts to produce the opposite of meat and try again, pretending that you weren't just trying to cheat.", "runmodule.php?module=meatsystem&op=cook&from=" . $from);
                break;
            }
            //check for the dumbass player trying to put too much meat in the pan
            $totalmeat = $meat1 + $meat2 + $meat3;
            if ($totalmeat > 20) {
                output("Your pan can't hold that much meat, pal.`n`n");
                addnav("Whoops");
                addnav("Try again, without filling the pan up so much", "runmodule.php?module=meatsystem&op=cook&from=" . $from);
                break;
            }
            //check for the dumbass player trying to cook no meat at all
            $totalmeat = $meat1 + $meat2 + $meat3;
            if ($totalmeat == 0) {
                output("You start the process of cooking up your tasty meat.  After a few minutes of poking around in your pan, growing hungrier by the second, you realise that you've forgotten something.`n`n");
                addnav("Whoops");
                addnav("Try again, with meat this time", "runmodule.php?module=meatsystem&op=cook&from=" . $from);
                break;
            }
            //Stamina interaction, including consequences and level-up details.
            $amber = get_stamina();
            $return = process_action("Cooking");
            if ($return['lvlinfo']['levelledup'] == true) {
                output("`n`c`b`0You gained a level in Cooking!  You are now level %s!  This action will cost fewer Stamina points now, so you can cook more tasty meals each day!`b`c`n", $return['lvlinfo']['newlvl']);
            }
            $failchance = e_rand(0, 100);
            if ($failchance > $amber) {
                output("`4You put your meat into the pan, and sit down to stir-fry it.  The hypnotic motion and white-noise sizzling, combined with your tiredness, sends you staring into space.  While your concentration is impaired, the meat bursts into flames.  You jerk back into awareness, and look down sadly at the flaming chunks.  Bummer.");
                for ($i = 0; $i < $meat1; $i++) {
                    delete_item(has_item("meat_low"));
                }
                for ($i = 0; $i < $meat2; $i++) {
                    delete_item(has_item("meat_medium"));
                }
                for ($i = 0; $i < $meat3; $i++) {
                    delete_item(has_item("meat_high"));
                }
                break;
            }
            //we can now assume that the player is not some sort of cheating reprobate, or trying to cook while dog-tired, and do some cooking!
            for ($i = 0; $i < $meat1; $i++) {
                increment_module_pref("nutrition", 1, "staminafood");
                increment_module_pref("fat", 3, "staminafood");
                increment_module_pref("fullness", 1, "staminafood");
                delete_item(has_item("meat_low"));
                addstamina(1000);
            }
            for ($i = 0; $i < $meat2; $i++) {
                increment_module_pref("nutrition", 2, "staminafood");
                increment_module_pref("fat", 2, "staminafood");
                increment_module_pref("fullness", 1, "staminafood");
                delete_item(has_item("meat_medium"));
                addstamina(2000);
            }
            for ($i = 0; $i < $meat3; $i++) {
                increment_module_pref("nutrition", 3, "staminafood");
                increment_module_pref("fat", 1, "staminafood");
                increment_module_pref("fullness", 1, "staminafood");
                delete_item(has_item("meat_high"));
                addstamina(5000);
            }
            output("You fry up your lovely meaty loveliness, and sit down to eat.  You gain some Stamina!`n`n");
            $full = get_module_pref("fullness", "staminafood");
            if ($full < 0) {
                output("You still feel as though you haven't eaten in days.`n`n");
            }
            if ($full >= 0 && $full < 50) {
                output("You feel a little less hungry.`n`n");
            }
            if ($full >= 50 && $full < 100) {
                output("You still feel as though you've got room for more!`n`n");
            }
            if ($full >= 100) {
                output("You're stuffed!  You feel as though you can't possibly eat anything more today.`n`n");
            }
            break;
    }
    $carcasses = unserialize(get_module_pref("carcasses"));
    if (!is_array($carcasses)) {
        $carcasses = array();
    }
    if (count($carcasses) > 0) {
        output("You look at the spoils of your most recent battle.  They lie bloodied and broken on the ground.  What will you do with them?");
        foreach ($carcasses as $carcassnum => $creatureid) {
            $sql = "SELECT creaturename FROM " . db_prefix("creatures") . " WHERE creatureid = " . $creatureid . " ";
            $result = db_query_cached($sql, "creaturename-" . $creatureid, 86400);
            $creature = db_fetch_assoc($result);
            $cleancost = stamina_getdisplaycost("Cleaning the Carcass");
            addnav(array("Clean the carcass of %s (`Q%s%%`0)", $creature['creaturename'], $cleancost), "runmodule.php?module=meatsystem&op=clean&creatureid=" . $creatureid . "&carcass=" . $carcassnum . "&from=" . $from);
        }
    } else {
        if (httpget('op') != "cook" && httpget('op') != "cookfinal") {
            output("Now only bloody bones lie strewn around the area.`n`n");
        }
    }
    addnav("Ah, screw it.");
    if ($from == "forest") {
        addnav("Return to the Jungle", "forest.php");
    } else {
        if ($from == "world") {
            addnav("Return to the World Map", "runmodule.php?module=worldmapen&op=continue");
        }
    }
    page_footer();
    return true;
}
function racezombie_dohook($hookname, $args)
{
    global $session, $resline;
    $city = "New Pittsburgh";
    $race = "Zombie";
    switch ($hookname) {
        case "racenames":
            $args[$race] = $race;
            break;
        case "changesetting":
            // Ignore anything other than villagename setting changes
            if ($args['setting'] == "villagename" && $args['module'] == "racezombie") {
                if ($session['user']['location'] == $args['old']) {
                    $session['user']['location'] = $args['new'];
                }
                $sql = "UPDATE " . db_prefix("accounts") . " SET location='" . addslashes($args['new']) . "' WHERE location='" . addslashes($args['old']) . "'";
                db_query($sql);
                if (is_module_active("cities")) {
                    $sql = "UPDATE " . db_prefix("module_userprefs") . " SET value='" . addslashes($args['new']) . "' WHERE modulename='cities' AND setting='homecity'" . "AND value='" . addslashes($args['old']) . "'";
                    db_query($sql);
                }
            }
            break;
        case "chooserace":
            if ($session['user']['dragonkills'] == 0) {
                break;
            }
            output("`0<a href='newday.php?setrace={$race}{$resline}'>\"BRAAAAAAAAAAAAINS.\"</a>`n`n", true);
            addnav("`0Zombie`0", "newday.php?setrace={$race}{$resline}");
            addnav("", "newday.php?setrace={$race}{$resline}");
            break;
        case "setrace":
            if ($session['user']['race'] == $race) {
                output("`0The hairy man nods.  \"`6All right, all right, a simple \"I'm a zombie\" would have done.`0\"  He looks down and writes in his ledger.  \"`6Zed, oh, em, bee, why.  Zombie.  There.`0\"`n`nYou give the man a sheepish look.  \"`#I didn't actually mean to say that.  It just slipped out.`0\"`n`nHe smiles.  \"`6That's okay, I know how it is.  So, how did you get here?`0\"`n`n\"`#As far as I know, it was on a jet PLAAAAAAAAINS oh God!`0\"  You clap your hands over your mouth.`n`nThe gatekeeper chuckles.  \"`6Works every time.`0\"`n`nYou scowl at him.  \"`#Get on with the form.`0\"`n`n\"`6So, have you been a zombie all your life?`0\"`n`nYou pause.  \"`#I think so.  I mean...  Growing up, I think I played with the other zombie kids in zombie school, but...  Hmm.  It's amazing that there would have `ibeen`i a zombie school in the first place.`0\"  You give the man a very serious look.  \"`#This really doesn't make much sense at all, does it?`0\"`n`n\"`6Few things do around here, sunshine.  Do yourself a favour and don't think about it too much.  Unless you want your head to explode.`0\"`n`nThe word rushes up your throat like vomit.  \"`#BRAAAAAAAAAINS!`0\"`n`n\"`6Yes, that's right, brains.  Lovely juicy brains, splattering around all over the shop.  Yum!`0\"`n`nYou scowl at the gatekeeper while convulsing again, your mouth operating of its own accord.  \"`#BRAAAAAAAAAINS you know, that's really not funny.`0\"`n`n\"`6I know.  I shouldn't make fun.  It's a tough life for zombies.  You have it very hard, don't you?  Bits falling off all the time?  Uncontrollable larynx and primeval, base reactions if something sets you off?`0\"`n`n\"`#That's not true.`0\"  You shoot the gatekeeper a withering glare.  \"`#You've just been perpetuating the tired old Zombie stereotype.  And I, for one, am sick of the constant prejudice that comes from people like you.`0\"`n`n\"`6All right, all right, I meant no offense.  I was just having a little joke.`0\"`n`nGrudgingly, you remember your manners.  \"`#Apology accepted.  I didn't mean to get angry.  It's just hard, you know?`0\"`n`n\"`6I know,`0\" says the gatekeeper with a twinkle in his eye.  \"`6You don't need to explain.`0\"`n`n\"`#EXPLAAAAAAAAAAAAAAAAAAINS!  Oh, `ifuck you`i.`0\"  You storm off towards the gate.`n`nBehind you, the gatekeeper cries \"`6You know what, I think it might rain!`0\"`n`n\"`#RAAAAAAAAAINS!`0\" says your mouth.  \"`3`iFuck you, old man,`i`0\" says your internal monologue.  \"`3`iFuck you and your tasty, tasty brains.`i`0\"");
                if (is_module_active("cities")) {
                    set_module_pref("homecity", $city, "cities");
                    if ($session['user']['age'] == 0) {
                        $session['user']['location'] = $city;
                    }
                }
            }
            break;
        case "alternativeresurrect":
        case "stamina-newday":
            if ($session['user']['race'] == $race) {
                racezombie_checkcity();
                //Stamina buffs
                require_once "modules/staminasystem/lib/lib.php";
                apply_stamina_buff('Zombie2', array("name" => "Zombie Bonus: Combat Endurance", "class" => "Combat", "costmod" => 0.8, "expmod" => 1, "rounds" => -1, "roundmsg" => "", "wearoffmsg" => ""));
                apply_stamina_buff('Zombie1', array("name" => "Zombie Bonus: Hunting Endurance", "class" => "Hunting", "costmod" => 0.8, "expmod" => 1, "rounds" => -1, "roundmsg" => "", "wearoffmsg" => ""));
                apply_stamina_buff('Zombie8', array("name" => "Zombie Bonus: Carcass Cleaning Skills", "action" => "Cleaning the Carcass", "costmod" => 0.8, "expmod" => 1, "rounds" => -1, "roundmsg" => "", "wearoffmsg" => ""));
                apply_stamina_buff('Zombie0', array("name" => "Zombie Penalty: Slow of Mind", "class" => "Global", "costmod" => 1, "expmod" => 0.8, "rounds" => -1, "roundmsg" => "", "wearoffmsg" => ""));
                apply_stamina_buff('Zombie3', array("name" => "Zombie Penalty: Slow-Moving", "class" => "Travelling", "costmod" => 1.2, "expmod" => 1, "rounds" => -1, "roundmsg" => "", "wearoffmsg" => ""));
                apply_stamina_buff('Zombie4', array("name" => "Zombie Penalty: Scavenging Slowness", "action" => "Scavenging for Scrap", "costmod" => 1.2, "expmod" => 1, "rounds" => -1, "roundmsg" => "", "wearoffmsg" => ""));
                apply_stamina_buff('Zombie5', array("name" => "Zombie Penalty: Metalwork Ineptitude", "action" => "Metalworking", "costmod" => 1.4, "expmod" => 1, "rounds" => -1, "roundmsg" => "", "wearoffmsg" => ""));
                apply_stamina_buff('Zombie6', array("name" => "Zombie Penalty: Soldering Ineptitude", "action" => "Soldering", "costmod" => 1.4, "expmod" => 1, "rounds" => -1, "roundmsg" => "", "wearoffmsg" => ""));
                apply_stamina_buff('Zombie7', array("name" => "Zombie Penalty: Programming Ineptitude", "action" => "Programming", "costmod" => 1.4, "expmod" => 1, "rounds" => -1, "roundmsg" => "", "wearoffmsg" => ""));
                apply_stamina_buff('Zombie9', array("name" => "Zombie Penalty: Cooking Ineptitude", "action" => "Cooking", "costmod" => 1.2, "expmod" => 1, "rounds" => -1, "roundmsg" => "", "wearoffmsg" => ""));
                apply_stamina_buff('raceclassy', array("name" => "Zombie Bonus: Insults Proficiency", "class" => "Insults", "costmod" => 0.8, "expmod" => 1, "rounds" => -1, "roundmsg" => "", "wearoffmsg" => ""));
                //Combat Buffs
                apply_buff("racialbenefit1", array("name" => "`0Zombie Bonus: No Pain`0", "defmod" => "1.2", "allowinpvp" => 1, "allowintrain" => 1, "rounds" => -1, "schema" => "module-racezombie"));
                apply_buff("racialbenefit2", array("name" => "`0Zombie Bonus: Leathery Fists`0", "atkmod" => "1.1", "allowinpvp" => 1, "allowintrain" => 1, "rounds" => -1, "schema" => "module-racezombie"));
            }
            break;
        case "creatureencounter":
            if ($session['user']['race'] == $race) {
                //get those folks who haven't manually chosen a race
                racezombie_checkcity();
                $args['creaturegold'] = round($args['creaturegold'] * 1.2, 0);
            }
            break;
        case "battle-victory":
            if ($session['user']['race'] == $race && $session['user']['alive'] == false) {
                if (!$session['user']['alive']) {
                    $args['creatureexp'] = round($args['creatureexp'] * 0.8);
                }
            }
            break;
        case "validforestloc":
        case "validlocation":
            if (is_module_active("cities")) {
                $args[$city] = "village-{$race}";
            }
            break;
        case "moderate":
            if (is_module_active("cities")) {
                tlschema("commentary");
                $args["village-{$race}"] = sprintf_translate("City of %s", $city);
                tlschema();
            }
            break;
        case "villagetext":
            racezombie_checkcity();
            if ($session['user']['location'] == $city) {
                $args['text'] = array("`0You are standing in the heart of New Pittsburgh.  This place used to be populated almost entirely by humans, but... well, you know zombies.`n`nThe stench of rotten flesh hangs in the air, and cries of \"BRAAAAAINS\" can be heard every now and then.`n`nYou notice a group of zombies conversing in grunts and moans around an old horse trough, idly picking at the flappy bits of skin on their necks.`n");
                $args['schemas']['text'] = "module-racezombie";
                $args['clock'] = "`n`0From the strength of the overpowering odour, you reason that it is approximately `0%s`0.`n";
                $args['schemas']['clock'] = "module-racezombie";
                if (is_module_active("calendar")) {
                    $args['calendar'] = "`n`0Written in blood on a nearby wall is `0%s`0, `0%s %s %s`0.`n";
                    $args['schemas']['calendar'] = "module-racezombie";
                }
                $args['title'] = array("%s, Home of the Zombies", $city);
                $args['schemas']['title'] = "module-racezombie";
                $args['sayline'] = "says";
                $args['schemas']['sayline'] = "module-racezombie";
                $args['talk'] = "`n`0Nearby some zombies talk:`n";
                $args['schemas']['talk'] = "module-racezombie";
                $new = get_module_setting("newest-{$city}", "cities");
                if ($new != 0) {
                    $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid='{$new}'";
                    $result = db_query_cached($sql, "newest-{$city}");
                    $row = db_fetch_assoc($result);
                    $args['newestplayer'] = $row['name'];
                    $args['newestid'] = $new;
                } else {
                    $args['newestplayer'] = $new;
                    $args['newestid'] = "";
                }
                if ($new == $session['user']['acctid']) {
                    $args['newest'] = "`n`0As you wander your new home, you feel your jaw dropping at the wonderful smells around you.  The smells of BRAAAAAAINS.";
                } else {
                    $args['newest'] = "`n`0Wandering the village, jaw agape and eyeballs swivelling in their sockets, is `0%s`0.";
                }
                $args['schemas']['newest'] = "module-racezombie";
                $args['section'] = "village-{$race}";
                $args['stablename'] = "Mike's Chop Shop";
                $args['schemas']['stablename'] = "module-racezombie";
                $args['gatenav'] = "Outpost Gates";
                $args['fightnav'] = "Brains Avenue";
                $args['marketnav'] = "Shiny Street";
                $args['tavernnav'] = "Hugs Boulevard";
                $args['schemas']['gatenav'] = "module-racezombie";
                unblocknav("stables.php");
            }
            break;
        case "stablelocs":
            tlschema("mounts");
            $args[$city] = sprintf_translate("The Village of %s", $city);
            tlschema();
            break;
        case "stabletext":
            if ($session['user']['location'] != $city) {
                break;
            }
            $args['title'] = "Mike's Chop Shop";
            $args['schemas']['title'] = "module-racezombie";
            $args['desc'] = array("`0Just next door to the Clan Halls, a scruffy-looking warehouse has been erected.  It looks pretty similar to the other buildings - blood splattered along every wall, groups of undead monsters shambling around, cries of \"BRAAAAAAAAINS!\" emanating from within - you know, the usual.  You head inside.`n`n", array("As you venture inside the building, a young Zombie woman shuffles towards you on her one good leg.  \"`^Good day to you, %s - my name is Mike, and what may I do for you today?`0\" You reason that \"Mike\" must be short for \"Michelle\" or something - or perhaps this whole franchise thing is going a bit too far.", translate_inline($session['user']['sex'] ? 'madam' : 'sir', 'stables')));
            $args['schemas']['desc'] = "module-racezombie";
            $args['lad'] = "friend";
            $args['schemas']['lad'] = "module-racezombie";
            $args['lass'] = "friend";
            $args['schemas']['lass'] = "module-racezombie";
            $args['nosuchbeast'] = "`0\"`^I'm sorry, I've never heard of such a thing,`0\" Mike says apologetically.";
            $args['schemas']['nosuchbeast'] = "module-racezombie";
            $args['toolittle'] = "`0Mike looks over the handful of currency you offered.  \"`^Hmm.  Well, you see, the price for this %s was actually `0%s `^Requisition tokens and `%%s`^ cigarettes.  My apologies for any misunderstandings.`0\"";
            $args['schemas']['toolittle'] = "module-racezombie";
            $args['replacemount'] = "`0You sadly watch Mike lead your %s`0 away, along with your cigarettes.  However, when she returns, she brings with her a nice new `0%s`0 which makes you feel a little better.";
            $args['schemas']['replacemount'] = "module-racezombie";
            $args['newmount'] = "`0You hand over your currency.  Within moments, you become the proud recipient of a lovely new `0%s`0!";
            $args['schemas']['newmount'] = "module-racezombie";
            $args['confirmsale'] = "`n`n`0Mike eyes your mount up and down, checking it over carefully.  \"`^My, this is indeed a fine specimen.  Are you quite sure you wish to part with it?`0\"";
            $args['schemas']['confirmsale'] = "module-racezombie";
            $args['mountsold'] = "`0With but a single tear, you hand your %s`0 over to Mike.  The tear dries quickly, and the %s in hand helps you quickly overcome your sorrow.";
            $args['schemas']['mountsold'] = "module-racezombie";
            $args['offer'] = "`n`n`0Mike offers you `0%s`0 Requisition and `%%s`0 Cigarettes for %s`0.";
            $args['schemas']['offer'] = "module-racezombie";
            break;
    }
    return $args;
}
function translate_loadnamespace($namespace, $language = false)
{
    if ($language === false) {
        $language = LANGUAGE;
    }
    $page = translator_page($namespace);
    $uri = translator_uri($namespace);
    if ($page == $uri) {
        $where = "uri = '{$page}'";
    } else {
        $where = "(uri='{$page}' OR uri='{$uri}')";
    }
    $sql = "\n\t\tSELECT intext,outtext\n\t\tFROM " . db_prefix("translations") . "\n\t\tWHERE language='{$language}'\n\t\t\tAND {$where}";
    /*	debug(nl2br(htmlentities($sql, ENT_COMPAT, getsetting("charset", "ISO-8859-1")))); */
    if (!getsetting("cachetranslations", 0)) {
        $result = db_query($sql);
    } else {
        $result = db_query_cached($sql, "translations-" . $namespace . "-" . $language, 600);
        //store it for 10 Minutes, normally you don't need to refresh this often
    }
    $out = array();
    while ($row = db_fetch_assoc($result)) {
        $out[$row['intext']] = $row['outtext'];
    }
    return $out;
}
        addnav("", $file);
        rawoutput("</a></div>");
        rawoutput("</td></tr>");
        $count++;
    }
    rawoutput("</table>");
    output("`nIf you wish to delete a mount, you have to deactivate it first.");
    output("If there are any owners of the mount when it is deleted, they will no longer have a mount, but they will get a FULL refund of the price of the mount at the time of deletion.");
} elseif ($op == "add") {
    output("Add a mount:`n");
    addnav("Mount Editor Home", "mounts.php");
    mountform(array());
} elseif ($op == "edit") {
    addnav("Mount Editor Home", "mounts.php");
    $sql = "SELECT * FROM " . db_prefix("mounts") . " WHERE mountid='{$id}'";
    $result = db_query_cached($sql, "mountdata-{$id}", 3600);
    if (db_num_rows($result) <= 0) {
        output("`iThis mount was not found.`i");
    } else {
        addnav("Mount properties", "mounts.php?op=edit&id={$id}");
        module_editor_navs("prefs-mounts", "mounts.php?op=edit&subop=module&id={$id}&module=");
        $subop = httpget("subop");
        if ($subop == "module") {
            $module = httpget("module");
            rawoutput("<form action='mounts.php?op=save&subop=module&id={$id}&module={$module}' method='POST'>");
            module_objpref_edit("mounts", $module, $id);
            rawoutput("</form>");
            addnav("", "mounts.php?op=save&subop=module&id={$id}&module={$module}");
        } else {
            output("Mount Editor:`n");
            $row = db_fetch_assoc($result);
function viewcommentary($section, $message = "Interject your own commentary?", $limit = 10, $talkline = "says", $schema = false)
{
    global $session, $REQUEST_URI, $doublepost, $translation_namespace;
    global $emptypost;
    rawoutput("<a name='{$section}'></a>");
    // Let's add a hook for modules to block commentary sections
    $args = modulehook("blockcommentarea", array("section" => $section));
    if (isset($args['block']) && $args['block'] == "yes") {
        return;
    }
    if ($schema === false) {
        $schema = $translation_namespace;
    }
    tlschema("commentary");
    $nobios = array("motd.php" => true);
    if (!array_key_exists(basename($_SERVER['SCRIPT_NAME']), $nobios)) {
        $nobios[basename($_SERVER['SCRIPT_NAME'])] = false;
    }
    if ($nobios[basename($_SERVER['SCRIPT_NAME'])]) {
        $linkbios = false;
    } else {
        $linkbios = true;
    }
    if ($message == "X") {
        $linkbios = true;
    }
    if ($doublepost) {
        output("`\$`bDouble post?`b`0`n");
    }
    if ($emptypost) {
        output("`\$`bWell, they say silence is a virtue.`b`0`n");
    }
    $clanrankcolors = array("`!", "`#", "`^", "`&", "`\$");
    // Needs to be here because scrolling through the commentary pages, entering a bio, then scrolling again forward
    // then re-entering another bio will lead to $com being smaller than 0 and this will lead to an SQL error later on.
    $com = (int) httpget("comscroll");
    if ($com < 0) {
        $com = 0;
    }
    $cc = false;
    if (httpget("comscroll") !== false && (int) $session['lastcom'] == $com + 1) {
        $cid = (int) $session['lastcommentid'];
    } else {
        $cid = 0;
    }
    $session['lastcom'] = $com;
    if ($com > 0 || $cid > 0) {
        // Find newly added comments.
        $sql = "SELECT COUNT(commentid) AS newadded FROM " . db_prefix("commentary") . " LEFT JOIN " . db_prefix("accounts") . " ON " . db_prefix("accounts") . ".acctid = " . db_prefix("commentary") . ".author WHERE section='{$section}' AND " . "(" . db_prefix("accounts") . ".locked=0 or " . db_prefix('accounts') . ".locked is null) AND commentid > '{$cid}'";
        $result = db_query($sql);
        $row = db_fetch_assoc($result);
        $newadded = $row['newadded'];
    } else {
        $newadded = 0;
    }
    $commentbuffer = array();
    if ($cid == 0) {
        $sql = "SELECT " . db_prefix("commentary") . ".*, " . db_prefix("accounts") . ".name, " . db_prefix("accounts") . ".acctid, " . db_prefix("accounts") . ".clanrank, " . db_prefix("clans") . ".clanshort FROM " . db_prefix("commentary") . " LEFT JOIN " . db_prefix("accounts") . " ON " . db_prefix("accounts") . ".acctid = " . db_prefix("commentary") . ".author LEFT JOIN " . db_prefix("clans") . " ON " . db_prefix("clans") . ".clanid=" . db_prefix("accounts") . ".clanid WHERE section = '{$section}' AND " . "( " . db_prefix("accounts") . ".locked=0 OR " . db_prefix("accounts") . ".locked is null ) " . "ORDER BY commentid DESC LIMIT " . $com * $limit . ",{$limit}";
        if ($com == 0 && strstr($_SERVER['REQUEST_URI'], "/moderate.php") !== $_SERVER['REQUEST_URI']) {
            $result = db_query_cached($sql, "comments-{$section}");
        } else {
            $result = db_query($sql);
        }
        while ($row = db_fetch_assoc($result)) {
            $commentbuffer[] = $row;
        }
    } else {
        $sql = "SELECT " . db_prefix("commentary") . ".*, " . db_prefix("accounts") . ".name, " . db_prefix("accounts") . ".acctid, " . db_prefix("accounts") . ".clanrank, " . db_prefix("clans") . ".clanshort FROM " . db_prefix("commentary") . " LEFT JOIN " . db_prefix("accounts") . " ON " . db_prefix("accounts") . ".acctid = " . db_prefix("commentary") . ".author LEFT JOIN " . db_prefix("clans") . " ON " . db_prefix("clans") . ".clanid=" . db_prefix("accounts") . ".clanid WHERE section = '{$section}' AND " . "( " . db_prefix("accounts") . ".locked=0 OR " . db_prefix("accounts") . ".locked is null ) " . "AND commentid > '{$cid}' " . "ORDER BY commentid ASC LIMIT {$limit}";
        $result = db_query($sql);
        while ($row = db_fetch_assoc($result)) {
            $commentbuffer[] = $row;
        }
        $commentbuffer = array_reverse($commentbuffer);
    }
    $rowcount = count($commentbuffer);
    if ($rowcount > 0) {
        $session['lastcommentid'] = $commentbuffer[0]['commentid'];
    }
    $counttoday = 0;
    for ($i = 0; $i < $rowcount; $i++) {
        $row = $commentbuffer[$i];
        $row['comment'] = comment_sanitize($row['comment']);
        $commentids[$i] = $row['commentid'];
        if (date("Y-m-d", strtotime($row['postdate'])) == date("Y-m-d")) {
            if ($row['name'] == $session['user']['name']) {
                $counttoday++;
            }
        }
        $x = 0;
        $ft = "";
        for ($x = 0; strlen($ft) < 5 && $x < strlen($row['comment']); $x++) {
            if (substr($row['comment'], $x, 1) == "`" && strlen($ft) == 0) {
                $x++;
            } else {
                $ft .= substr($row['comment'], $x, 1);
            }
        }
        $link = "bio.php?char=" . $row['acctid'] . "&ret=" . URLEncode($_SERVER['REQUEST_URI']);
        if (substr($ft, 0, 2) == "::") {
            $ft = substr($ft, 0, 2);
        } elseif (substr($ft, 0, 1) == ":") {
            $ft = substr($ft, 0, 1);
        } elseif (substr($ft, 0, 3) == "/me") {
            $ft = substr($ft, 0, 3);
        }
        $row['comment'] = holidayize($row['comment'], 'comment');
        $row['name'] = holidayize($row['name'], 'comment');
        if ($row['clanrank']) {
            $row['name'] = ($row['clanshort'] > "" ? "{$clanrankcolors[ceil($row['clanrank'] / 10)]}&lt;`2{$row['clanshort']}{$clanrankcolors[ceil($row['clanrank'] / 10)]}&gt; `&" : "") . $row['name'];
        }
        if ($ft == "::" || $ft == "/me" || $ft == ":") {
            $x = strpos($row['comment'], $ft);
            if ($x !== false) {
                if ($linkbios) {
                    $op[$i] = str_replace("&amp;", "&", HTMLEntities(substr($row['comment'], 0, $x), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0<a href='{$link}' style='text-decoration: none'>\n`&{$row['name']}`0</a>\n`& " . str_replace("&amp;", "&", HTMLEntities(substr($row['comment'], $x + strlen($ft)), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0`n";
                } else {
                    $op[$i] = str_replace("&amp;", "&", HTMLEntities(substr($row['comment'], 0, $x), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0`&{$row['name']}`0`& " . str_replace("&amp;", "&", HTMLEntities(substr($row['comment'], $x + strlen($ft)), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0`n";
                }
                $rawc[$i] = str_replace("&amp;", "&", HTMLEntities(substr($row['comment'], 0, $x), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0`&{$row['name']}`0`& " . str_replace("&amp;", "&", HTMLEntities(substr($row['comment'], $x + strlen($ft)), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0`n";
            }
        }
        if ($ft == "/game" && !$row['name']) {
            $x = strpos($row['comment'], $ft);
            if ($x !== false) {
                $op[$i] = str_replace("&amp;", "&", HTMLEntities(substr($row['comment'], 0, $x), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0`&" . str_replace("&amp;", "&", HTMLEntities(substr($row['comment'], $x + strlen($ft)), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0`n";
            }
        }
        if (!isset($op) || !is_array($op)) {
            $op = array();
        }
        if (!array_key_exists($i, $op) || $op[$i] == "") {
            if ($linkbios) {
                $op[$i] = "`0<a href='{$link}' style='text-decoration: none'>`&{$row['name']}`0</a>`3 says, \"`#" . str_replace("&amp;", "&", HTMLEntities($row['comment'], ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`3\"`0`n";
            } elseif (substr($ft, 0, 5) == '/game' && !$row['name']) {
                $op[$i] = str_replace("&amp;", "&", HTMLEntities($row['comment'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")));
            } else {
                $op[$i] = "`&{$row['name']}`3 says, \"`#" . str_replace("&amp;", "&", HTMLEntities($row['comment'], ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`3\"`0`n";
            }
            $rawc[$i] = "`&{$row['name']}`3 says, \"`#" . str_replace("&amp;", "&", HTMLEntities($row['comment'], ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`3\"`0`n";
        }
        if (!array_key_exists('timestamp', $session['user']['prefs'])) {
            $session['user']['prefs']['timestamp'] = 0;
        }
        $session['user']['prefs']['timeoffset'] = round($session['user']['prefs']['timeoffset'], 1);
        if ($session['user']['prefs']['timestamp'] == 1) {
            if (!isset($session['user']['prefs']['timeformat'])) {
                $session['user']['prefs']['timeformat'] = "[m/d h:ia]";
            }
            $time = strtotime($row['postdate']) + $session['user']['prefs']['timeoffset'] * 60 * 60;
            $s = date("`7" . $session['user']['prefs']['timeformat'] . "`0 ", $time);
            $op[$i] = $s . $op[$i];
        } elseif ($session['user']['prefs']['timestamp'] == 2) {
            $s = reltime(strtotime($row['postdate']));
            $op[$i] = "`7({$s})`0 " . $op[$i];
        }
        if ($message == "X") {
            $op[$i] = "`0({$row['section']}) " . $op[$i];
        }
        if ($row['postdate'] >= $session['user']['recentcomments']) {
            $op[$i] = "<img src='images/new.gif' alt='&gt;' width='3' height='5' align='absmiddle'> " . $op[$i];
        }
        addnav("", $link);
        $auth[$i] = $row['author'];
        if (isset($rawc[$i])) {
            $rawc[$i] = full_sanitize($rawc[$i]);
            $rawc[$i] = htmlentities($rawc[$i], ENT_QUOTES, getsetting("charset", "ISO-8859-1"));
        }
    }
    $i--;
    $outputcomments = array();
    $sect = "x";
    $moderating = false;
    if ($session['user']['superuser'] & SU_EDIT_COMMENTS && $message == "X") {
        $moderating = true;
    }
    $del = translate_inline("Del");
    $scriptname = substr($_SERVER['SCRIPT_NAME'], strrpos($_SERVER['SCRIPT_NAME'], "/") + 1);
    $pos = strpos($_SERVER['REQUEST_URI'], "?");
    $return = $scriptname . ($pos == false ? "" : substr($_SERVER['REQUEST_URI'], $pos));
    $one = strstr($return, "?") == false ? "?" : "&";
    for (; $i >= 0; $i--) {
        $out = "";
        if ($moderating) {
            if ($session['user']['superuser'] & SU_EDIT_USERS) {
                $out .= "`0[ <input type='checkbox' name='comment[{$commentids[$i]}]'> | <a href='user.php?op=setupban&userid=" . $auth[$i] . "&reason=" . rawurlencode($rawc[$i]) . "'>Ban</a> ]&nbsp;";
                addnav("", "user.php?op=setupban&userid={$auth[$i]}&reason=" . rawurlencode($rawc[$i]));
            } else {
                $out .= "`0[ <input type='checkbox' name='comment[{$commentids[$i]}]'> ]&nbsp;";
            }
            $matches = array();
            preg_match("/[(]([^)]*)[)]/", $op[$i], $matches);
            $sect = trim($matches[1]);
            if (substr($sect, 0, 5) != "clan-" || $sect == $section) {
                if (substr($sect, 0, 4) != "pet-") {
                    $out .= $op[$i];
                    if (!isset($outputcomments[$sect]) || !is_array($outputcomments[$sect])) {
                        $outputcomments[$sect] = array();
                    }
                    array_push($outputcomments[$sect], $out);
                }
            }
        } else {
            if ($session['user']['superuser'] & SU_EDIT_COMMENTS) {
                $out .= "`2[<a href='" . $return . $one . "removecomment={$commentids[$i]}&section={$section}&returnpath=" . URLEncode($return) . "'>{$del}</a>`2]`0&nbsp;";
                addnav("", $return . $one . "removecomment={$commentids[$i]}&section={$section}&returnpath=" . URLEncode($return) . "");
            }
            $out .= $op[$i];
            if (!array_key_exists($sect, $outputcomments) || !is_array($outputcomments[$sect])) {
                $outputcomments[$sect] = array();
            }
            array_push($outputcomments[$sect], $out);
        }
    }
    if ($moderating) {
        $scriptname = substr($_SERVER['SCRIPT_NAME'], strrpos($_SERVER['SCRIPT_NAME'], "/") + 1);
        addnav("", "{$scriptname}?op=commentdelete&return=" . URLEncode($_SERVER['REQUEST_URI']));
        $mod_Del1 = htmlentities(translate_inline("Delete Checked Comments"), ENT_COMPAT, getsetting("charset", "ISO-8859-1"));
        $mod_Del2 = htmlentities(translate_inline("Delete Checked & Ban (3 days)"), ENT_COMPAT, getsetting("charset", "ISO-8859-1"));
        $mod_Del_confirm = addslashes(htmlentities(translate_inline("Are you sure you wish to ban this user and have you specified the exact reason for the ban, i.e. cut/pasted their offensive comments?"), ENT_COMPAT, getsetting("charset", "ISO-8859-1")));
        $mod_reason = translate_inline("Reason:");
        $mod_reason_desc = htmlentities(translate_inline("Banned for comments you posted."), ENT_COMPAT, getsetting("charset", "ISO-8859-1"));
        output_notl("<form action='{$scriptname}?op=commentdelete&return=" . URLEncode($_SERVER['REQUEST_URI']) . "' method='POST'>", true);
        output_notl("<input type='submit' class='button' value=\"{$mod_Del1}\">", true);
        output_notl("<input type='submit' class='button' name='delnban' value=\"{$mod_Del2}\" onClick=\"return confirm('{$mod_Del_confirm}');\">", true);
        output_notl("`n{$mod_reason} <input name='reason0' size='40' value=\"{$mod_reason_desc}\" onChange=\"document.getElementById('reason').value=this.value;\">", true);
    }
    //output the comments
    ksort($outputcomments);
    reset($outputcomments);
    $sections = commentarylocs();
    $needclose = 0;
    while (list($sec, $v) = each($outputcomments)) {
        if ($sec != "x") {
            if ($needclose) {
                modulehook("}collapse");
            }
            output_notl("`n<hr><a href='moderate.php?area=%s'>`b`^%s`0`b</a>`n", $sec, isset($sections[$sec]) ? $sections[$sec] : "({$sec})", true);
            addnav("", "moderate.php?area={$sec}");
            modulehook("collapse{", array("name" => "com-" . $sec));
            $needclose = 1;
        } else {
            modulehook("collapse{", array("name" => "com-" . $section));
            $needclose = 1;
        }
        reset($v);
        while (list($key, $val) = each($v)) {
            $args = array('commentline' => $val);
            $args = modulehook("viewcommentary", $args);
            $val = $args['commentline'];
            output_notl($val, true);
        }
    }
    if ($moderating && $needclose) {
        modulehook("}collapse");
        $needclose = 0;
    }
    if ($moderating) {
        output_notl("`n");
        rawoutput("<input type='submit' class='button' value=\"{$mod_Del1}\">");
        rawoutput("<input type='submit' class='button' name='delnban' value=\"{$mod_Del2}\" onClick=\"return confirm('{$mod_Del_confirm}');\">");
        output_notl("`n%s ", $mod_reason);
        rawoutput("<input name='reason' size='40' id='reason' value=\"{$mod_reason_desc}\">");
        rawoutput("</form>");
        output_notl("`n");
    }
    if ($session['user']['loggedin']) {
        $args = modulehook("insertcomment", array("section" => $section));
        if (array_key_exists("mute", $args) && $args['mute'] && !($session['user']['superuser'] & SU_EDIT_COMMENTS)) {
            output_notl("%s", $args['mutemsg']);
        } elseif ($counttoday < $limit / 2 || $session['user']['superuser'] & ~SU_DOESNT_GIVE_GROTTO || !getsetting('postinglimit', 1)) {
            if ($message != "X") {
                $message = "`n`@{$message}`n";
                output($message);
                talkform($section, $talkline, $limit, $schema);
            }
        } else {
            $message = "`n`@{$message}`n";
            output($message);
            output("Sorry, you've exhausted your posts in this section for now.`0`n");
        }
    }
    $jump = false;
    if (!isset($session['user']['prefs']['nojump']) || $session['user']['prefs']['nojump'] == false) {
        $jump = true;
    }
    $firstu = translate_inline("&lt;&lt; First Unseen");
    $prev = translate_inline("&lt; Previous");
    $ref = translate_inline("Refresh");
    $next = translate_inline("Next &gt;");
    $lastu = translate_inline("Last Page &gt;&gt;");
    if ($rowcount >= $limit || $cid > 0) {
        $sql = "SELECT count(commentid) AS c FROM " . db_prefix("commentary") . " WHERE section='{$section}' AND postdate > '{$session['user']['recentcomments']}'";
        $r = db_query($sql);
        $val = db_fetch_assoc($r);
        $val = round($val['c'] / $limit + 0.5, 0) - 1;
        if ($val > 0) {
            $first = comscroll_sanitize($REQUEST_URI) . "&comscroll=" . $val;
            $first = str_replace("?&", "?", $first);
            if (!strpos($first, "?")) {
                $first = str_replace("&", "?", $first);
            }
            $first .= "&refresh=1";
            if ($jump) {
                $first .= "#{$section}";
            }
            output_notl("<a href=\"{$first}\">{$firstu}</a>", true);
            addnav("", $first);
        } else {
            output_notl($firstu, true);
        }
        $req = comscroll_sanitize($REQUEST_URI) . "&comscroll=" . ($com + 1);
        $req = str_replace("?&", "?", $req);
        if (!strpos($req, "?")) {
            $req = str_replace("&", "?", $req);
        }
        $req .= "&refresh=1";
        if ($jump) {
            $req .= "#{$section}";
        }
        output_notl("<a href=\"{$req}\">{$prev}</a>", true);
        addnav("", $req);
    } else {
        output_notl("{$firstu} {$prev}", true);
    }
    $last = appendlink(comscroll_sanitize($REQUEST_URI), "refresh=1");
    // Okay.. we have some smart-ass (or stupidass, you guess) players
    // who think that the auto-reload firefox plugin is a good way to
    // avoid our timeouts.  Won't they be surprised when I take that little
    // hack away.
    $last = appendcount($last);
    $last = str_replace("?&", "?", $last);
    if ($jump) {
        $last .= "#{$section}";
    }
    //if (!strpos($last,"?")) $last = str_replace("&","?",$last);
    //debug($last);
    output_notl("&nbsp;<a href=\"{$last}\">{$ref}</a>&nbsp;", true);
    addnav("", $last);
    if ($com > 0 || $cid > 0 && $newadded > $limit) {
        $req = comscroll_sanitize($REQUEST_URI) . "&comscroll=" . ($com - 1);
        $req = str_replace("?&", "?", $req);
        if (!strpos($req, "?")) {
            $req = str_replace("&", "?", $req);
        }
        $req .= "&refresh=1";
        if ($jump) {
            $req .= "#{$section}";
        }
        output_notl(" <a href=\"{$req}\">{$next}</a>", true);
        addnav("", $req);
        output_notl(" <a href=\"{$last}\">{$lastu}</a>", true);
    } else {
        output_notl("{$next} {$lastu}", true);
    }
    if (!$cc) {
        db_free_result($result);
    }
    tlschema();
    if ($needclose) {
        modulehook("}collapse");
    }
}
    }
    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");
    $save = translate_inline("Save");
    rawoutput("<input type='submit' class='button' value=\"{$save}\">");
    $snu = htmlentities(translate_inline("Save & UNblock public description"), ENT_COMPAT, getsetting("charset", "ISO-8859-1"));
    $snb = htmlentities(translate_inline("Save & Block public description"), ENT_COMPAT, getsetting("charset", "ISO-8859-1"));
    $itemarray_extra_vals = array();
    foreach ($itemarray_extra as $var => $desc) {
        $itemarray_extra_data = explode('|', $desc);
        $itemarray_extra_fields[$var] = trim($itemarray_extra_data[0]);
        if (array_key_exists(1, $itemarray_extra_data)) {
            $extra_data = trim($itemarray_extra_data[1]);
            if ($extra_data != '') {
                $itemarray_extra_vals[$var] = $extra_data;
            }
        }
    }
    //debug($itemarray_extra_fields);
    $itemarray = array_merge($itemarray, $itemarray_extra_fields);
}
require_once "modules/mysticalshop/run/editor_what/{$what}.php";
//here's a module hook, if anyone ever needs it
modulehook("mysticalshop-editor", array());
addnav("Actions");
//let's just display items that are actually available.
$sql = 'SELECT category FROM ' . db_prefix('magicitems') . ' GROUP BY category ORDER BY category';
$result = db_query_cached($sql, 'modules-mysticalshop-editorcats', 3600);
$shortcuts = array('g', 't', 'W', 'o', 'C', 'H', 'v', 'B', 'M');
while ($row = db_fetch_assoc($result)) {
    $category = $row['category'];
    addnav(array('%s?Examine %s`0', $shortcuts[$category], $names[$category]), $fromeditor . 'view&cat=' . $category);
}
addnav("Admin Tools");
addnav('Add an Item', $fromeditor . 'add&cat=' . $cat);
addnav("Refresh List", $fromeditor . "view&cat={$cat}");
addnav("Other");
addnav("Return to the Grotto", "superuser.php");
function extbio_run()
{
    $char = httpget('char');
    //Legacy support
    if (is_numeric($char)) {
        $where = "acctid = {$char}";
    } else {
        $where = "login = '******'";
    }
    $sql = "SELECT login, name, level, sex, title, specialty, hashorse, acctid, resurrections, bio, dragonkills, race, clanname, clanshort, clanrank, " . db_prefix("accounts") . ".clanid, laston, loggedin FROM " . db_prefix("accounts") . " LEFT JOIN " . db_prefix("clans") . " ON " . db_prefix("accounts") . ".clanid = " . db_prefix("clans") . ".clanid WHERE {$where}";
    $result = db_query($sql);
    if ($target = db_fetch_assoc($result)) {
        $target['login'] = rawurlencode($target['login']);
        $id = $target['acctid'];
        $target['return_link'] = $return;
        page_header("Character Biography: %s", full_sanitize($target['name']));
        modulehook("biotop", $target);
        output("`^Biography for %s`^.", $target['name']);
        if ($target['clanname'] > "" && getsetting("allowclans", false)) {
            $ranks = array(CLAN_APPLICANT => "`!Applicant`0", CLAN_MEMBER => "`3Member`0", CLAN_OFFICER => "`^Officer`0", CLAN_LEADER => "`&Leader`0", CLAN_FOUNDER => "`\$Founder");
            $ranks = modulehook("clanranks", array("ranks" => $ranks, "clanid" => $target['clanid']));
            tlschema("clans");
            //just to be in the right schema
            array_push($ranks['ranks'], "`\$Founder");
            $ranks = translate_inline($ranks['ranks']);
            tlschema();
            output("`@%s`2 is a %s`2 to `%%s`2`n", $target['name'], $ranks[$target['clanrank']], $target['clanname']);
        }
        output("`^Title: `@%s`n", $target['title']);
        output("`^Level: `@%s`n", $target['level']);
        $loggedin = false;
        if ($target['loggedin'] && date("U") - strtotime($target['laston']) < getsetting("LOGINTIMEOUT", 900)) {
            $loggedin = true;
        }
        $status = translate_inline($loggedin ? "`3Online`0" : "`\$Offline`0");
        output("`^Status: %s`n", $status);
        output("`^Resurrections: `@%s`n", $target['resurrections']);
        $race = $target['race'];
        if (!$race) {
            $race = RACE_UNKNOWN;
        }
        tlschema("race");
        $race = translate_inline($race);
        tlschema();
        output("`^Race: `@%s`n", $race);
        $genders = array("Male", "Female");
        $genders = translate_inline($genders);
        output("`^Gender: `@%s`n", $genders[$target['sex']]);
        $specialties = modulehook("specialtynames", array("" => translate_inline("Unspecified")));
        if (isset($specialties[$target['specialty']])) {
            output("`^Specialty: `@%s`n", $specialties[$target['specialty']]);
        }
        $sql = "SELECT * FROM " . db_prefix("mounts") . " WHERE mountid='{$target['hashorse']}'";
        $result = db_query_cached($sql, "mountdata-{$target['hashorse']}", 3600);
        $mount = db_fetch_assoc($result);
        $mount['acctid'] = $target['acctid'];
        $mount = modulehook("bio-mount", $mount);
        $none = translate_inline("`iNone`i");
        if (!isset($mount['mountname']) || $mount['mountname'] == "") {
            $mount['mountname'] = $none;
        }
        output("`^Creature: `@%s`0`n", $mount['mountname']);
        modulehook("biostat", $target);
        if ($target['dragonkills'] > 0) {
            output("`^Dragon Kills: `@%s`n", $target['dragonkills']);
        }
        if ($target['bio'] > "") {
            output("`^Bio: `@`n%s`n", soap($target['bio']));
        }
        modulehook("bioinfo", $target);
        output("`n`^Recent accomplishments (and defeats) of %s`^", $target['name']);
        $result = db_query("SELECT * FROM " . db_prefix("news") . " WHERE accountid={$target['acctid']} ORDER BY newsdate DESC,newsid ASC LIMIT 100");
        $odate = "";
        tlschema("news");
        while ($row = db_fetch_assoc($result)) {
            tlschema($row['tlschema']);
            if ($row['arguments'] > "") {
                $arguments = array();
                $base_arguments = unserialize($row['arguments']);
                array_push($arguments, $row['newstext']);
                while (list($key, $val) = each($base_arguments)) {
                    array_push($arguments, $val);
                }
                $news = call_user_func_array("sprintf_translate", $arguments);
                rawoutput(tlbutton_clear());
            } else {
                $news = translate_inline($row['newstext']);
                rawoutput(tlbutton_clear());
            }
            tlschema();
            if ($odate != $row['newsdate']) {
                output_notl("`n`b`@%s`0`b`n", date("D, M d", strtotime($row['newsdate'])));
                $odate = $row['newsdate'];
            }
            output_notl("`@{$news}`0`n");
        }
        tlschema();
        modulehook("bioend", $target);
    }
    page_footer();
}
function module_collect_events($type, $allowinactive = false)
{
    global $session, $playermount;
    global $blocked_modules, $block_all_modules, $unblocked_modules;
    $active = "";
    $events = array();
    if (!$allowinactive) {
        $active = " active=1 AND";
    }
    $sql = "SELECT " . db_prefix("module_event_hooks") . ".* FROM " . db_prefix("module_event_hooks") . " INNER JOIN " . db_prefix("modules") . " ON " . db_prefix("modules") . ".modulename = " . db_prefix("module_event_hooks") . ".modulename WHERE {$active} event_type='{$type}' ORDER BY RAND(" . e_rand() . ")";
    $result = db_query_cached($sql, "event-" . $type);
    while ($row = db_fetch_assoc($result)) {
        // The event_chance bit needs to return a value, but it can do that
        // in any way it wants, and can have if/then or other logical
        // structures, so we cannot just force the 'return' syntax unlike
        // with buffs.
        ob_start();
        $chance = eval($row['event_chance'] . ";");
        $err = ob_get_contents();
        ob_end_clean();
        if ($err > "") {
            debug(array("error" => $err, "Eval code" => $row['event_chance']));
        }
        if ($chance < 0) {
            $chance = 0;
        }
        if ($chance > 100) {
            $chance = 100;
        }
        if (($block_all_modules || array_key_exists($row['modulename'], $blocked_modules) && $blocked_modules[$row['modulename']]) && (!array_key_exists($row['modulename'], $unblocked_modules) || !$unblocked_modules[$row['modulename']])) {
            $chance = 0;
        }
        $events[] = array('modulename' => $row['modulename'], 'rawchance' => $chance);
    }
    // Now, normalize all of the event chances
    $sum = 0;
    reset($events);
    foreach ($events as $event) {
        $sum += $event['rawchance'];
    }
    reset($events);
    foreach ($events as $index => $event) {
        if ($sum == 0) {
            $events[$index]['normchance'] = 0;
        } else {
            $events[$index]['normchance'] = round($event['rawchance'] / $sum * 100, 3);
            // If an event requests 1% chance, don't give them more!
            if ($events[$index]['normchance'] > $event['rawchance']) {
                $events[$index]['normchance'] = $event['rawchance'];
            }
        }
    }
    return modulehook("collect-events", $events);
}
function viewcommentary($section, $message = "Interject your own commentary?", $limit = 10, $talkline = "says", $schema = false)
{
    global $session, $REQUEST_URI, $doublepost, $translation_namespace;
    global $emptypost;
    // *** DRAGONBG.COM CORE PATCH START ***
    if ($section) {
        rawoutput("<a name='{$section}'></a>");
        // Let's add a hook for modules to block commentary sections
        $args = modulehook("blockcommentarea", array("section" => $section));
        if (isset($args['block']) && $args['block'] == "yes") {
            return;
        }
    }
    // *** DRAGONBG.COM CORE PATCH END ***
    if ($schema === false) {
        $schema = $translation_namespace;
    }
    tlschema("commentary");
    $nobios = array("motd.php" => true);
    if (!array_key_exists(basename($_SERVER['SCRIPT_NAME']), $nobios)) {
        $nobios[basename($_SERVER['SCRIPT_NAME'])] = false;
    }
    if ($nobios[basename($_SERVER['SCRIPT_NAME'])]) {
        $linkbios = false;
    } else {
        $linkbios = true;
    }
    if ($message == "X") {
        $linkbios = true;
    }
    if ($doublepost) {
        output("`\$`bDouble post?`b`0`n");
    }
    if ($emptypost) {
        output("`\$`bWell, they say silence is a virtue.`b`0`n");
    }
    // *** DRAGONBG.COM CORE PATCH START ***
    $clanrankcolors = array(CLAN_APPLICANT => "`!", CLAN_MEMBER => "`#", CLAN_OFFICER => "`^", CLAN_LEADER => "`&", CLAN_FOUNDER => "`\$");
    $args = modulehook("clanrankcolors", array("clanrankcolors" => $clanrankcolors, "clanid" => $session['user']['clanid']));
    $clanrankcolors = $args['clanrankcolors'];
    // *** DRAGONBG.COM CORE PATCH END ***
    // Needs to be here because scrolling through the commentary pages, entering a bio, then scrolling again forward
    // then re-entering another bio will lead to $com being smaller than 0 and this will lead to an SQL error later on.
    $com = (int) httpget("comscroll");
    if ($com < 0) {
        $com = 0;
    }
    $cc = false;
    if (httpget("comscroll") !== false && (int) $session['lastcom'] == $com + 1) {
        $cid = (int) $session['lastcommentid'];
    } else {
        $cid = 0;
    }
    $session['lastcom'] = $com;
    if ($com > 0 || $cid > 0) {
        // Find newly added comments.
        // *** DRAGONBG.COM CORE PATCH START ***
        $sql = "SELECT COUNT(commentid) AS newadded FROM " . db_prefix("commentary") . " LEFT JOIN " . db_prefix("accounts") . " ON " . db_prefix("accounts") . ".acctid = " . db_prefix("commentary") . ".author WHERE " . ($section ? "section='{$section}' AND " : '') . "(" . db_prefix("accounts") . ".locked=0 or " . db_prefix('accounts') . ".locked is null) AND commentid > '{$cid}'";
        $result = db_query($sql);
        $row = db_fetch_assoc($result);
        $newadded = $row['newadded'];
        // *** DRAGONBG.COM CORE PATCH END ***
    } else {
        $newadded = 0;
    }
    $commentbuffer = array();
    if ($cid == 0) {
        $sql = "SELECT " . db_prefix("commentary") . ".*, " . db_prefix("accounts") . ".name, " . db_prefix("accounts") . ".acctid, " . db_prefix("accounts") . ".clanrank, " . db_prefix("clans") . ".clanshort FROM " . db_prefix("commentary") . " LEFT JOIN " . db_prefix("accounts") . " ON " . db_prefix("accounts") . ".acctid = " . db_prefix("commentary") . ".author LEFT JOIN " . db_prefix("clans") . " ON " . db_prefix("clans") . ".clanid=" . db_prefix("accounts") . ".clanid WHERE " . ($section ? "section='{$section}' AND " : '') . "( " . db_prefix("accounts") . ".locked=0 OR " . db_prefix("accounts") . ".locked is null ) " . "ORDER BY commentid DESC LIMIT " . $com * $limit . ",{$limit}";
        // *** DRAGONBG.COM CORE PATCH END ***
        if ($com == 0 && strstr($_SERVER['REQUEST_URI'], "/moderate.php") !== $_SERVER['REQUEST_URI']) {
            $result = db_query_cached($sql, "comments-{$section}");
        } else {
            $result = db_query($sql);
        }
        while ($row = db_fetch_assoc($result)) {
            $commentbuffer[] = $row;
        }
    } else {
        // *** DRAGONBG.COM CORE PATCH START ***
        $sql = "SELECT " . db_prefix("commentary") . ".*, " . db_prefix("accounts") . ".name, " . db_prefix("accounts") . ".acctid, " . db_prefix("accounts") . ".clanrank, " . db_prefix("clans") . ".clanshort FROM " . db_prefix("commentary") . " LEFT JOIN " . db_prefix("accounts") . " ON " . db_prefix("accounts") . ".acctid = " . db_prefix("commentary") . ".author LEFT JOIN " . db_prefix("clans") . " ON " . db_prefix("clans") . ".clanid=" . db_prefix("accounts") . ".clanid WHERE " . ($section ? "section='{$section}' AND " : '') . "( " . db_prefix("accounts") . ".locked=0 OR " . db_prefix("accounts") . ".locked is null ) " . "AND commentid > '{$cid}' " . "ORDER BY commentid ASC LIMIT {$limit}";
        // *** DRAGONBG.COM CORE PATCH END ***
        $result = db_query($sql);
        while ($row = db_fetch_assoc($result)) {
            $commentbuffer[] = $row;
        }
        $commentbuffer = array_reverse($commentbuffer);
    }
    $rowcount = count($commentbuffer);
    if ($rowcount > 0) {
        $session['lastcommentid'] = $commentbuffer[0]['commentid'];
    }
    $counttoday = 0;
    $commentbuffer = modulehook("pagecommentary", $commentbuffer);
    // debug($commentbuffer);
    for ($i = 0; $i < $rowcount; $i++) {
        $row = $commentbuffer[$i];
        $row['comment'] = comment_sanitize($row['comment']);
        $commentids[$i] = $row['commentid'];
        if (date("Y-m-d", strtotime($row['postdate'])) == date("Y-m-d")) {
            if ($row['name'] == $session['user']['name']) {
                $counttoday++;
            }
        }
        $x = 0;
        $ft = "";
        for ($x = 0; strlen($ft) < 5 && $x < strlen($row['comment']); $x++) {
            if (substr($row['comment'], $x, 1) == "`" && strlen($ft) == 0) {
                $x++;
            } else {
                $ft .= substr($row['comment'], $x, 1);
            }
        }
        $link = "bio.php?char=" . $row['acctid'] . "&ret=" . URLEncode($_SERVER['REQUEST_URI']);
        if (substr($ft, 0, 2) == "::") {
            $ft = substr($ft, 0, 2);
        } elseif (substr($ft, 0, 1) == ":") {
            $ft = substr($ft, 0, 1);
        } elseif (substr($ft, 0, 3) == "/me") {
            $ft = substr($ft, 0, 3);
        }
        if ($row['clanrank']) {
            $row['name'] = ($row['clanshort'] > "" ? "{$clanrankcolors[$row['clanrank']]}&lt;`2{$row['clanshort']}{$clanrankcolors[$row['clanrank']]}&gt; `&" : "") . $row['name'];
        }
        if ($ft == "::" || $ft == "/me" || $ft == ":") {
            $x = strpos($row['comment'], $ft);
            if ($x !== false) {
                if ($linkbios) {
                    $op[$i] = str_replace("&amp;", "&", htmlentities(substr($row['comment'], 0, $x), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0<a href='{$link}' style='text-decoration: none'>\n`&{$row['name']}`0</a>\n`& " . str_replace("&amp;", "&", htmlentities(substr($row['comment'], $x + strlen($ft)), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0`n";
                } else {
                    $op[$i] = str_replace("&amp;", "&", htmlentities(substr($row['comment'], 0, $x), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0`&{$row['name']}`0`& " . str_replace("&amp;", "&", htmlentities(substr($row['comment'], $x + strlen($ft)), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0`n";
                }
                $rawc[$i] = str_replace("&amp;", "&", htmlentities(substr($row['comment'], 0, $x), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0`&{$row['name']}`0`& " . str_replace("&amp;", "&", htmlentities(substr($row['comment'], $x + strlen($ft)), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0`n";
            }
        }
        if ($ft == "/game" && !$row['name']) {
            $x = strpos($row['comment'], $ft);
            if ($x !== false) {
                $op[$i] = str_replace("&amp;", "&", htmlentities(substr($row['comment'], 0, $x), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0`&" . str_replace("&amp;", "&", htmlentities(substr($row['comment'], $x + strlen($ft)), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0`n";
            }
        }
        if (!isset($op) || !is_array($op)) {
            $op = array();
        }
        if (!array_key_exists($i, $op) || $op[$i] == "") {
            if ($linkbios) {
                $op[$i] = "`0<a href='{$link}' style='text-decoration: none'>`&{$row['name']}`0</a>`3 says, \"`#" . str_replace("&amp;", "&", htmlentities($row['comment'], ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`3\"`0`n";
            } elseif (substr($ft, 0, 5) == '/game' && !$row['name']) {
                $op[$i] = str_replace("&amp;", "&", htmlentities($row['comment'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")));
            } else {
                $op[$i] = "`&{$row['name']}`3 says, \"`#" . str_replace("&amp;", "&", htmlentities($row['comment'], ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`3\"`0`n";
            }
            $rawc[$i] = "`&{$row['name']}`3 says, \"`#" . str_replace("&amp;", "&", htmlentities($row['comment'], ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`3\"`0`n";
        }
        if (!array_key_exists('timestamp', $session['user']['prefs'])) {
            $session['user']['prefs']['timestamp'] = 0;
        }
        $session['user']['prefs']['timeoffset'] = round($session['user']['prefs']['timeoffset'], 1);
        if ($session['user']['prefs']['timestamp'] == 1) {
            if (!isset($session['user']['prefs']['timeformat'])) {
                $session['user']['prefs']['timeformat'] = "[m/d h:ia]";
            }
            $time = strtotime($row['postdate']) + $session['user']['prefs']['timeoffset'] * 60 * 60;
            $s = date("`7" . $session['user']['prefs']['timeformat'] . "`0 ", $time);
            $op[$i] = $s . $op[$i];
        } elseif ($session['user']['prefs']['timestamp'] == 2) {
            $s = reltime(strtotime($row['postdate']));
            $op[$i] = "`7({$s})`0 " . $op[$i];
        }
        if ($message == "X") {
            $op[$i] = "`0({$row['section']}) " . $op[$i];
        }
        if ($row['postdate'] >= $session['user']['recentcomments']) {
            $op[$i] = "<img src='images/new.gif' alt='&gt;' width='3' height='5' align='absmiddle'> " . $op[$i];
        }
        addnav("", $link);
        $auth[$i] = $row['author'];
        if (isset($rawc[$i])) {
            $rawc[$i] = full_sanitize($rawc[$i]);
            $rawc[$i] = htmlentities($rawc[$i], ENT_QUOTES, getsetting("charset", "ISO-8859-1"));
        }
    }
    $i--;
    $outputcomments = array();
    $sect = "x";
    $moderating = false;
    if ($session['user']['superuser'] & SU_EDIT_COMMENTS && $message == "X") {
        $moderating = true;
    }
    $del = translate_inline("Del");
    $scriptname = substr($_SERVER['SCRIPT_NAME'], strrpos($_SERVER['SCRIPT_NAME'], "/") + 1);
    $pos = strpos($_SERVER['REQUEST_URI'], "?");
    $return = $scriptname . ($pos == false ? "" : substr($_SERVER['REQUEST_URI'], $pos));
    $one = strstr($return, "?") == false ? "?" : "&";
    for (; $i >= 0; $i--) {
        $out = "";
        if ($moderating) {
            if ($session['user']['superuser'] & SU_EDIT_USERS) {
                $out .= "`0[ <input type='checkbox' name='comment[{$commentids[$i]}]'> | <a href='user.php?op=setupban&userid=" . $auth[$i] . "&reason=" . rawurlencode($rawc[$i]) . "'>Ban</a> ]&nbsp;";
                addnav("", "user.php?op=setupban&userid={$auth[$i]}&reason=" . rawurlencode($rawc[$i]));
            } else {
                $out .= "`0[ <input type='checkbox' name='comment[{$commentids[$i]}]'> ]&nbsp;";
            }
            $matches = array();
            preg_match("/[(]([^)]*)[)]/", $op[$i], $matches);
            $sect = trim($matches[1]);
            if (substr($sect, 0, 5) != "clan-" || $sect == $section) {
                if (substr($sect, 0, 4) != "pet-") {
                    $out .= $op[$i];
                    if (!isset($outputcomments[$sect]) || !is_array($outputcomments[$sect])) {
                        $outputcomments[$sect] = array();
                    }
                    array_push($outputcomments[$sect], $out);
                }
            }
        } else {
            if ($session['user']['superuser'] & SU_EDIT_COMMENTS) {
                $out .= "`2[<a href='" . $return . $one . "removecomment={$commentids[$i]}&section={$section}&returnpath=" . URLEncode($return) . "'>{$del}</a>`2]`0&nbsp;";
                addnav("", $return . $one . "removecomment={$commentids[$i]}&section={$section}&returnpath=" . URLEncode($return) . "");
            }
            $out .= $op[$i];
            if (!array_key_exists($sect, $outputcomments) || !is_array($outputcomments[$sect])) {
                $outputcomments[$sect] = array();
            }
            array_push($outputcomments[$sect], $out);
        }
    }
    if ($moderating) {
        $scriptname = substr($_SERVER['SCRIPT_NAME'], strrpos($_SERVER['SCRIPT_NAME'], "/") + 1);
        addnav("", "{$scriptname}?op=commentdelete&return=" . URLEncode($_SERVER['REQUEST_URI']));
        $mod_Del1 = htmlentities(translate_inline("Delete Checked Comments"), ENT_COMPAT, getsetting("charset", "ISO-8859-1"));
        $mod_Del2 = htmlentities(translate_inline("Delete Checked & Ban (3 days)"), ENT_COMPAT, getsetting("charset", "ISO-8859-1"));
        $mod_Del_confirm = addslashes(htmlentities(translate_inline("Are you sure you wish to ban this user and have you specified the exact reason for the ban, i.e. cut/pasted their offensive comments?"), ENT_COMPAT, getsetting("charset", "ISO-8859-1")));
        $mod_reason = translate_inline("Reason:");
        $mod_reason_desc = htmlentities(translate_inline("Banned for comments you posted."), ENT_COMPAT, getsetting("charset", "ISO-8859-1"));
        // *** DRAGONBG.COM CORE PATCH START ***
        output_notl("<form action='{$scriptname}?op=commentdelete&return=" . URLEncode($_SERVER['REQUEST_URI']) . "' method='POST' id='comments'>", true);
        // *** DRAGONBG.COM CORE PATCH END ***
        output_notl("<input type='submit' class='button' value=\"{$mod_Del1}\">", true);
        output_notl("<input type='submit' class='button' name='delnban' value=\"{$mod_Del2}\" onClick=\"return confirm('{$mod_Del_confirm}');\">", true);
        // *** DRAGONBG.COM CORE PATCH START ***
        $mod_checkall = htmlspecialchars(translate_inline("Check all"));
        // Check all - by Pr0t3ct0r
        output_notl('<script type="text/javascript">function checkall() { 
			var isChecked = document.getElementById("CheckAllID").checked 
			var f = document.getElementById("comments") 
			for (var i=0;i<f.length;i++) { 
			  if (f.elements[i].type == "checkbox"){ 
				  f.elements[i].checked = isChecked 
			  }
			} 
		}</script>', true);
        output_notl("<input type='checkbox' id='CheckAllID' onclick='checkall()' /> {$mod_checkall}", true);
        output_notl("`n{$mod_reason} <input name='reason0' id='reason0' size='40' value=\"{$mod_reason_desc}\" onChange=\"document.getElementById('reason').value=this.value;\">", true);
        // *** DRAGONBG.COM CORE PATCH END ***
    }
    //output the comments
    ksort($outputcomments);
    reset($outputcomments);
    $sections = commentarylocs();
    $needclose = 0;
    while (list($sec, $v) = each($outputcomments)) {
        if ($sec != "x") {
            output_notl("`n<hr><a href='moderate.php?area=%s'>`b`^%s`0`b</a>`n", $sec, isset($sections[$sec]) ? $sections[$sec] : "({$sec})", true);
            addnav("", "moderate.php?area={$sec}");
        }
        reset($v);
        while (list($key, $val) = each($v)) {
            $args = array('commentline' => $val, 'area' => $section);
            $args = modulehook("viewcommentary", $args);
            $val = $args['commentinfo'] . $args['commentline'];
            output_notl($val, true);
        }
    }
    $sql = "SELECT count(commentid) AS c FROM " . db_prefix("commentary") . " WHERE section='{$section}'";
    $r = db_query($sql);
    $val = db_fetch_assoc($r);
    $val = round($val['c'] / $limit + 0.5, 0) - 1;
    rawoutput("<table cellpadding=0 cellspacing=5 width=100%><tr><td valign=\"top\" width=50%>");
    // *** AJAX CHAT MOD START ***
    if (round($limit / 2, 0) - $counttoday < 3) {
        output("`)(You have %s posts left today)`n`0", round($limit / 2, 0) - $counttoday);
    }
    rawoutput('</div>');
    // *** AJAX CHAT MOD END ***
    if ($moderating && $needclose) {
        modulehook("}collapse");
        $needclose = 0;
    }
    if ($moderating) {
        output_notl("`n");
        rawoutput("<input type='submit' class='button' value=\"{$mod_Del1}\">");
        rawoutput("<input type='submit' class='button' name='delnban' value=\"{$mod_Del2}\" onClick=\"return confirm('{$mod_Del_confirm}');\">");
        output_notl("`n%s ", $mod_reason);
        // *** DRAGONBG.COM CORE PATCH START ***
        rawoutput("<input name='reason' size='40' id='reason' value=\"{$mod_reason_desc}\" onchange=\"document.getElementById('reason0').value=this.value;\">");
        // *** DRAGONBG.COM CORE PATCH END ***
        rawoutput("</form>");
        output_notl("`n");
    }
    if ($session['user']['loggedin']) {
        $args = modulehook("insertcomment", array("section" => $section));
        if (array_key_exists("mute", $args) && $args['mute'] && !($session['user']['superuser'] & SU_EDIT_COMMENTS)) {
            output_notl("%s", $args['mutemsg']);
        } elseif ($counttoday < $limit / 2 || $session['user']['superuser'] & ~SU_DOESNT_GIVE_GROTTO || !getsetting('postinglimit', 1)) {
            if ($message != "X") {
                $message = "`n`@{$message}`n";
                output($message);
                talkform($section, $talkline, $limit, $schema);
            }
        } else {
            $message = "`n`@{$message}`n";
            output($message);
            output("Sorry, you've exhausted your posts in this section for now.`0`n");
        }
    }
    $jump = false;
    if (!isset($session['user']['prefs']['nojump']) || $session['user']['prefs']['nojump'] == false) {
        $jump = true;
    }
    //new-style commentary display with page numbers
    if (!$cc) {
        db_free_result($result);
    }
    tlschema();
    if ($needclose) {
        modulehook("}collapse");
    }
    rawoutput("</td><td valign=\"top\" width=50%>");
    $nlink = comscroll_sanitize($REQUEST_URI);
    $nlink = str_replace("?&", "?", $nlink);
    if (!strpos($nlink, "?")) {
        $nlink = str_replace("&", "?", $nlink);
    }
    $nlink .= "&refresh=1";
    //reinstating back and forward links
    output_notl("`n");
    $prev = translate_inline("&lt;&lt;");
    $next = translate_inline("&gt;&gt;");
    if ($rowcount >= $limit || $cid > 0) {
        $req = comscroll_sanitize($REQUEST_URI) . "&comscroll=" . ($com + 1);
        $req = str_replace("?&", "?", $req);
        if (!strpos($req, "?")) {
            $req = str_replace("&", "?", $req);
        }
        $req .= "&refresh=1";
        if ($jump) {
            $req .= "#{$section}";
        }
        output_notl("<a href=\"{$req}\">{$prev}</a> ", true);
        addnav("", $req);
    }
    output_notl("<a href=\"{$nlink}\">Refresh Commentary</a>", true);
    if ($com > 0 || $cid > 0 && $newadded > $limit) {
        $req = comscroll_sanitize($REQUEST_URI) . "&comscroll=" . ($com - 1);
        $req = str_replace("?&", "?", $req);
        if (!strpos($req, "?")) {
            $req = str_replace("&", "?", $req);
        }
        $req .= "&refresh=1";
        if ($jump) {
            $req .= "#{$section}";
        }
        output_notl(" <a href=\"{$req}\">{$next}</a>", true);
        addnav("", $req);
    }
    //
    addnav("", $nlink);
    output("`n`n`0Jump to commentary page:");
    for ($i = $val; $i >= 0; $i--) {
        $nlink = comscroll_sanitize($REQUEST_URI) . "&comscroll=" . $i;
        $nlink = str_replace("?&", "?", $nlink);
        if (!strpos($nlink, "?")) {
            $nlink = str_replace("&", "?", $nlink);
        }
        $nlink .= "&refresh=1";
        if ($jump) {
            $nlink .= "#{$section}";
        }
        $ndisp = 1 + $val - $i;
        if (httpget('comscroll') != $i) {
            output_notl("<a href=\"{$nlink}\">{$ndisp}</a> ", true);
            addnav("", $nlink);
        } else {
            output_notl("`@{$ndisp}`0 ", true);
        }
    }
    modulehook("commentaryoptions");
    rawoutput("</td></tr></table");
    // *** AJAX CHAT MOD START ***
    modulehook("viewcommentaryfooter");
    // *** AJAX CHAT MOD END ***
}