function addcommentary()
{
    global $session, $emptypost, $afk, $dni;
    $section = httppost('section');
    $talkline = httppost('talkline');
    $schema = httppost('schema');
    $comment = trim(httppost('insertcommentary'));
    $counter = httppost('counter');
    $remove = URLDecode(httpget('removecomment'));
    $restore = URLDecode(httpget('restorecomment'));
    //debug(httpallpost());
    if (httpget("bulkdelete")) {
        $everything = httpallpost();
        foreach ($everything as $key => $val) {
            if (substr($key, 0, 14) == "deletecomment_") {
                $del = str_replace("deletecomment_", "", $key);
                removecommentary($del, "Mass deletion by " . $session['user']['name'], $session['user']['acctid']);
            }
        }
    }
    if (!$comment) {
        return false;
    }
    if ($session['user']['chatloc'] == "DNI") {
        $dni = true;
    }
    if ($comment == strtoupper($comment)) {
        //this is an all-uppercase entry.  Do not add this comment to the database; instead, check it for built-in stuff like AFK and GREM, then run it through the commentarycommand hook
        if ($comment == "AFK" || $comment == "BRB") {
            $session['user']['chatloc'] = "AFK";
            $afk = true;
            output("`0`n`c`bYou are Away From the Keyboard until you load another page.`b`c`n");
            return false;
        }
        if ($comment == "DNI") {
            if ($session['user']['chatloc'] == "DNI") {
                $session['user']['chatloc'] = $section;
                $dni = false;
                output("`0`n`c`bYou are no longer in Do Not Interrupt status.`b`c`n");
            } else {
                $session['user']['chatloc'] = "DNI";
                $dni = true;
                output("`0`n`c`bYou are in Do Not Interrupt status.  Type DNI again to leave.`b`nDNI status is used for whenever you're doing or saying something that means other players shouldn't try to interact with you.  For example, when two or more characters are chatting just outside of the main group of characters, and other characters shouldn't be able to hear them.`c`n");
            }
            return false;
        }
        if ($comment == "GREM") {
            //handle deleting the player's last comment
            $sql = "SELECT * FROM " . db_prefix("commentary") . " WHERE author='" . $session['user']['acctid'] . "' ORDER BY commentid DESC LIMIT 1";
            $result = db_query($sql);
            while ($row = db_fetch_assoc($result)) {
                $now = time();
                $then = strtotime($row['postdate']);
                $ago = $now - $then;
                if ($ago < 120) {
                    removecommentary($row['commentid'], "Typo Gremlin", $session['user']['acctid']);
                    output("`0`n`c`bA nearby Typo Gremlin notices the peculiar tastiness of your previous comment.  Within moments, a small horde of them have descended upon your words, and consumed them.`b`c`n");
                } else {
                    output("`0`n`c`bThe Typo Gremlins turn up their nose at your latest comment - it's just too old.  They have no taste for stale words.`b`c`n");
                }
            }
            return false;
        }
        $hookcommand = array('command' => $comment, 'section' => $section);
        $returnedhook = modulehook("commentarycommand", $hookcommand);
        if (!$returnedhook['processed']) {
            debug($returnedhook);
            output("`c`b`JCommand Not Recognized`b`0`nWhen you type in ALL CAPS, the game doesn't think you're talking to other players; it thinks you're trying to perform an action within the game.  For example, typing `#GREM`0 will remove the last comment you posted, as long as you posted it less than two minutes ago.  Typing `#AFK`0 or `#BRB`0 will turn your online status bar grey, so that people know you're `#A`0way `#F`0rom the `#K`0eyboard (or, if you prefer, that you'll `#B`0e `#R`0ight `#B`0ack).  Typing `#DNI`0 will let other players know that you're busy talking to one particular player - maybe somewhere off-camera - and that you don't want to be interrupted right now.`nSome areas have special hidden commands or other easter eggs that you can hunt for.  This time around, you didn't trigger anything special.`c`0`n");
        }
        return false;
    }
    if ($remove > 0) {
        removecommentary($remove, "Moderated by " . $session['user']['name'], $session['user']['acctid']);
    }
    if ($restore > 0) {
        restorecommentary($restore, "Restored by " . $session['user']['name'], $session['user']['acctid']);
    }
    if (array_key_exists('commentcounter', $session) && $session['commentcounter'] == $counter) {
        if ($section || $talkline || $comment) {
            $tcom = color_sanitize($comment);
            if ($tcom == "" || $tcom == ":" || $tcom == "::" || $tcom == "/me") {
                $emptypost = 1;
            } else {
                injectcommentary($section, $talkline, $comment);
            }
        }
    }
}
function uniqueforests_dohook($hookname, $args)
{
    global $session;
    require_once "modules/cityprefs/lib.php";
    $cityid = get_cityprefs_cityid("location", $session['user']['location']);
    switch ($hookname) {
        case "collect-events":
            if (get_module_objpref("city", $cityid, "use")) {
                foreach ($args as $index => $event) {
                    $event['rawchance'] = 0;
                    $events[$index] = $event;
                }
                $args = $events;
            }
            break;
        case "village":
            if (get_module_objpref("city", $cityid, "use")) {
                addnav($args['gatenav']);
                $name = get_module_objpref("city", $cityid, "name");
                blocknav("forest.php");
                addnav(array("%s", $name), "forest.php?location=uniqueforests");
            }
            break;
        case "header-forest":
            if (httpget('location') == "uniqueforests" || get_module_objpref("city", $cityid, "use")) {
                if (httpget('op') == "") {
                    global $block_new_output;
                    $block_new_output = true;
                }
                blocknav("runmodule.php", true);
                blocknav("healer.php", true);
                tlschema("module-uniqueforests");
            }
            break;
        case "footer-forest":
            if (httpget('location') == "uniqueforests" || get_module_objpref("city", $cityid, "use")) {
                $name = get_module_objpref("city", $cityid, "name");
                page_header(color_sanitize($name));
            }
            break;
        case "forest-desc":
            if (httpget('location') == "uniqueforests" || get_module_objpref("city", $cityid, "use")) {
                page_header(color_sanitize($name));
                global $block_new_output;
                $block_new_output = false;
                output(get_module_objpref("city", $cityid, "desc"));
                $block_new_output = true;
            }
            break;
    }
    return $args;
}
function addcommentary()
{
    global $session, $emptypost;
    $section = httppost('section');
    $talkline = httppost('talkline');
    $schema = httppost('schema');
    $comment = trim(httppost('insertcommentary'));
    $counter = httppost('counter');
    $remove = URLDecode(httpget('removecomment'));
    if ($remove > 0) {
        $return = '/' . httpget('returnpath');
        $section = httpget('section');
        $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") . " INNER 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 commentid={$remove}";
        $row = db_fetch_assoc(db_query($sql));
        $sql = "INSERT LOW_PRIORITY INTO " . db_prefix("moderatedcomments") . " (moderator,moddate,comment) VALUES ('{$session['user']['acctid']}','" . date("Y-m-d H:i:s") . "','" . addslashes(serialize($row)) . "')";
        db_query($sql);
        $sql = "DELETE FROM " . db_prefix("commentary") . " WHERE commentid='{$remove}';";
        db_query($sql);
        invalidatedatacache("comments-{$section}");
        // *** DRAGONBG.COM CORE PATCH START ***
        invalidatedatacache("comments-");
        // *** DRAGONBG.COM CORE PATCH END ***
        $session['user']['specialinc'] == '';
        //just to make sure he was not in a special
        $return = cmd_sanitize($return);
        $return = substr($return, strrpos($return, "/") + 1);
        if (strpos($return, "?") === false && strpos($return, "&") !== false) {
            $x = strpos($return, "&");
            $return = substr($return, 0, $x - 1) . "?" . substr($return, $x + 1);
        }
        debug($return);
        redirect($return);
    }
    if (array_key_exists('commentcounter', $session) && $session['commentcounter'] == $counter) {
        if ($section || $talkline || $comment) {
            $tcom = color_sanitize($comment);
            if ($tcom == "" || $tcom == ":" || $tcom == "::" || $tcom == "/me") {
                $emptypost = 1;
            } else {
                injectcommentary($section, $talkline, $comment);
            }
        }
    }
}
function letteropener_run()
{
    global $session;
    page_header("Letter opener");
    require_once "common.php";
    require_once "lib/systemmail.php";
    require_once "lib/sanitize.php";
    require_once "lib/http.php";
    $maildb = "mail";
    if (get_module_setting("outbox")) {
        $maildb = "mailoutbox";
    }
    $op = httpget('op');
    $order = "acctid";
    if ($sort != "") {
        $order = "{$sort}";
    }
    $display = 0;
    $query = httppost('q');
    if ($query === false) {
        $query = httpget('q');
    }
    addnav("Back to the grotto", "superuser.php");
    addnav(array("Show last %s YOMs", get_module_setting("num")), "runmodule.php?module=letteropener&op=lastfew");
    if ($op == "read") {
        $id = httpget('id');
        $sql = "SELECT msgfrom,msgto from " . db_prefix($maildb) . " where messageid=\"" . $id . "\"";
        $result = db_query($sql);
        $row = db_fetch_assoc($result);
        $acctid = $row['msgto'];
        $sqlz = "SELECT login from " . db_prefix("accounts") . " where acctid=\"" . $acctid . "\"";
        $result = db_query($sqlz);
        $rowz = db_fetch_assoc($result);
        $login = $rowz['login'];
        addnav("Read Someone else's mail", "runmodule.php?module=letteropener");
        //addnav("~");
        addnav(array("All YOMs to %s", $login), "runmodule.php?module=letteropener&op=to&to={$login}");
        addnav(array("All YOMs from %s", $login), "runmodule.php?module=letteropener&op=from&from={$login}");
        $sql = "SELECT " . db_prefix($maildb) . ".*," . db_prefix("accounts") . ".name,login FROM " . db_prefix($maildb) . " LEFT JOIN " . db_prefix("accounts") . " ON " . db_prefix("accounts") . ".acctid=" . db_prefix($maildb) . ".msgfrom WHERE msgto=\"" . $acctid . "\" AND messageid=\"" . $id . "\"";
        $result = db_query($sql);
        if (db_num_rows($result) > 0) {
            $row = db_fetch_assoc($result);
            tlschema("mail");
            if ((int) $row['msgfrom'] == 0) {
                $row['name'] = translate_inline("`i`^System`0`i");
                if (is_array(unserialize($row['subject']))) {
                    $row['subject'] = unserialize($row['subject']);
                    $row['subject'] = call_user_func_array("sprintf_translate", $row['subject']);
                }
                if (is_array(unserialize($row['body']))) {
                    $row['body'] = unserialize($row['body']);
                    $row['body'] = call_user_func_array("sprintf_translate", $row['body']);
                }
            }
            tlschema();
            if (!$row['seen']) {
                output("`b`#NEW`b`n");
            } else {
                output("`n");
            }
            if ((int) $row['msgfrom'] != 0) {
                addnav("Or");
                //$othername=$row['msgfrom'];
                //$sql="select login from ".db_prefix("accounts")." where acctid=$othername";
                //$result = db_query($sql);
                $othername = $row['login'];
                addnav(array("All YOMs to %s", $othername), "runmodule.php?module=letteropener&op=to&to={$othername}");
                addnav(array("All YOMs from %s", $othername), "runmodule.php?module=letteropener&op=from&from={$othername}");
            }
            output("`b`2From:`b `^%s`n", $row['name']);
            output("`b`2Subject:`b `^%s`n", $row['subject']);
            output("`b`2Sent:`b `^%s`n", $row['sent']);
            output_notl("<hr>`n", true);
            output_notl(str_replace("\n", "`n", $row['body']));
            output_notl("`n<hr>`n", true);
            rawoutput("<table width='50%' border='0' cellpadding='0' cellspacing='5'><tr>");
            rawoutput("<td align='right'>&nbsp;</td>");
            rawoutput("</tr><tr>");
            $sql = "SELECT messageid FROM " . db_prefix($maildb) . " WHERE msgto='{$acctid}' AND messageid < '{$id}' ORDER BY messageid DESC LIMIT 1";
            $result = db_query($sql);
            if (db_num_rows($result) > 0) {
                $row = db_fetch_assoc($result);
                $pid = $row['messageid'];
            } else {
                $pid = 0;
            }
            $sql = "SELECT messageid FROM " . db_prefix($maildb) . " WHERE msgto='{$acctid}' AND messageid > '{$id}' ORDER BY messageid  LIMIT 1";
            $result = db_query($sql);
            if (db_num_rows($result) > 0) {
                $row = db_fetch_assoc($result);
                $nid = $row['messageid'];
            } else {
                $nid = 0;
            }
            $prev = translate_inline("< Previous");
            $next = translate_inline("Next >");
            rawoutput("<td nowrap='true'>");
            if ($pid > 0) {
                rawoutput("<a href='runmodule.php?module=letteropener&op=read&id={$pid}' class='motd'>" . htmlentities($prev) . "</a>");
                addnav("", "runmodule.php?module=letteropener&op=read&id={$pid}");
            } else {
                rawoutput(htmlentities($prev));
            }
            rawoutput("</td><td nowrap='true'>");
            if ($nid > 0) {
                rawoutput("<a href='runmodule.php?module=letteropener&op=read&id={$nid}' class='motd'>" . htmlentities($next) . "</a>");
                addnav("", "runmodule.php?module=letteropener&op=read&id={$nid}");
            } else {
                rawoutput(htmlentities($next));
            }
            rawoutput("</td>");
            rawoutput("</tr></table>");
        }
    } elseif ($op == "lastfew") {
        output("Here are the last %s non-system YOMs", get_module_setting("num"));
        $sql = "select * from " . db_prefix($maildb) . " where msgfrom>0 ORDER BY messageid DESC limit " . get_module_setting("num") . "";
        $res = db_query($sql);
        $to = translate_inline("To");
        $from = translate_inline("From");
        require_once "lib/sanitize.php";
        for ($i = 0; $i < db_num_rows($res); $i++) {
            $row = db_fetch_assoc($res);
            $sql2 = "select name from " . db_prefix("accounts") . " where acctid=" . $row['msgto'] . "";
            $res2 = db_query($sql2);
            $row2 = db_fetch_assoc($res2);
            $toname = color_sanitize($row2['name']);
            $sql3 = "select name from " . db_prefix("accounts") . " where acctid=" . $row['msgfrom'] . "";
            $res3 = db_query($sql3);
            $row3 = db_fetch_assoc($res3);
            $fromname = color_sanitize($row3['name']);
            rawoutput("<table border=1 width=100%><tr><td>{$from} :{$fromname} - " . date("M d, h:i a", strtotime($row['sent'])) . " - {$to} : {$toname}</td></tr><tr><td>" . $row['body'] . "</td></tr></table><br>");
        }
    } elseif ($op == "") {
        output("Whose mail would you like to read?`n");
        rawoutput("<form action='runmodule.php?module=letteropener' method='POST'>");
        rawoutput("<input name='q' id='q'>");
        $se = translate_inline("Search");
        rawoutput("<input type='submit' class='button' value='{$se}'>");
        rawoutput("</form>");
        rawoutput("<script language='JavaScript'>document.getElementById('q').focus();</script>");
        addnav("", "runmodule.php?module=letteropener");
        $searchresult = false;
        $where = "";
        $op = "";
        $sql = "SELECT acctid,login,name FROM " . db_prefix("accounts");
        if ($query != "") {
            $where = "WHERE login='******' OR name='{$query}'";
            $searchresult = db_query($sql . " {$where}  ORDER BY '{$order}' LIMIT 2");
        }
        if ($query !== false || $searchresult) {
            if (db_num_rows($searchresult) != 1) {
                $where = "WHERE login LIKE '%{$query}%' OR acctid LIKE '%{$query}%' OR name LIKE '%{$query}%' OR emailaddress LIKE '%{$query}%' OR lastip LIKE '%{$query}%' OR uniqueid LIKE '%{$query}%' OR gentimecount LIKE '%{$query}%' OR level LIKE '%{$query}%'";
                $searchresult = db_query($sql . " {$where}  ORDER BY '{$order}' LIMIT 101");
            }
            if (db_num_rows($searchresult) <= 0) {
                output("`\$No results found`0");
                $where = "";
            } elseif (db_num_rows($searchresult) > 100) {
                output("`\$Too many results found, narrow your search please.`0");
                $op = "";
                $where = "";
            } else {
                $op = "";
                $display = 1;
            }
        }
        if ($display == 1) {
            $q = "";
            if ($query) {
                $q = "&q={$query}";
            }
            $acid = translate_inline("AcctID");
            $login = translate_inline("Login");
            $nm = translate_inline("Name");
            $rn = 0;
            $oorder = "";
            while ($row = db_fetch_assoc($searchresult)) {
                $laston = relativedate($row['laston']);
                $loggedin = date("U") - strtotime($row['laston']) < getsetting("LOGINTIMEOUT", 900) && $row['loggedin'];
                if ($loggedin) {
                    $laston = translate_inline("`#Online`0");
                }
                $row['laston'] = $laston;
                if ($row[$order] != $oorder) {
                    $rn++;
                }
                $oorder = $row[$order];
                rawoutput("<table align=center border=1 width=350>");
                rawoutput("<tr class='trhead'><td>{$acid}: ");
                output_notl("`&%s`0", $row['acctid'], true);
                rawoutput("</td><td>{$login}: ");
                output_notl("`&%s`0", $row['login'], true);
                rawoutput("</td>");
                rawoutput("<td rowspan=2 align=left nowrap>");
                addnav("", "runmodule.php?module=letteropener&op=to&to={$row['login']}");
                addnav("", "runmodule.php?module=letteropener&op=from&from={$row['login']}");
                $to = translate_inline("All messages `#to`& this person");
                $from = translate_inline("All messages `#from`& this person");
                output_notl("<a href='runmodule.php?module=letteropener&op=to&to={$row['login']}'>`&&#149;%s`7</a>", $to, true);
                rawoutput("<br>");
                output_notl("<a href='runmodule.php?module=letteropener&op=from&from={$row['login']}'>`&&#149;%s`7</a>", $from, true);
                rawoutput("</td></tr><tr><td colspan=2>");
                output_notl("`&%s`7", $row['name'], true);
                rawoutput("</td></tr></table><Br>");
            }
        }
    } elseif ($op == "to") {
        $subject = "";
        $body = "";
        $row = "";
        addnav("Read someone else's mail", "runmodule.php?module=letteropener");
        $to = httpget('to');
        $from = httpget('from');
        if ($to != "") {
            $sql = "SELECT acctid,login,name superuser FROM " . db_prefix("accounts") . " WHERE login=\"{$to}\"";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            $sql = "SELECT acctid FROM " . db_prefix("accounts") . " WHERE login='******'login'] . "'";
            $result = db_query($sql);
            $row2 = db_fetch_assoc($result);
            $acctid = $row2['acctid'];
            rawoutput("<table>");
            $session['message'] = "";
            $sql = "SELECT subject,messageid," . db_prefix("accounts") . ".name,msgfrom,seen,sent FROM " . db_prefix($maildb) . " LEFT JOIN " . db_prefix("accounts") . " ON " . db_prefix("accounts") . ".acctid=" . db_prefix($maildb) . ".msgfrom WHERE msgto=\"" . $acctid . "\" ORDER BY sent DESC";
            $result = db_query($sql);
            if (db_num_rows($result) > 0) {
                while ($row = db_fetch_assoc($result)) {
                    tlschema("mail");
                    if ((int) $row['msgfrom'] == 0) {
                        $row['name'] = translate_inline("`i`^System`0`i");
                        if (is_array(unserialize($row['subject']))) {
                            $row['subject'] = unserialize($row['subject']);
                            $row['subject'] = call_user_func_array("sprintf_translate", $row['subject']);
                        }
                    }
                    tlschema();
                    $id = $row['messageid'];
                    output_notl("<tr>", true);
                    output_notl("<td nowrap><img src='images/" . ($row['seen'] ? "old" : "new") . "scroll.GIF' width='16' height='16' alt='" . ($row['seen'] ? "Old" : "New") . "'></td>", true);
                    output_notl("<td><a href='runmodule.php?module=letteropener&op=read&id={$id}&login={$to}'>", true);
                    addnav("", "runmodule.php?module=letteropener&op=read&id={$id}&login={$to}");
                    if (trim($row['subject']) == "") {
                        output("`i(No Subject)`i");
                    } else {
                        output_notl($row['subject']);
                    }
                    output_notl("</a></td><td><a href='runmodule.php?module=letteropener&op=read&id={$id}&login={$to}'>", true);
                    addnav("", "runmodule.php?module=letteropener&op=read&id={$id}&login={$to}");
                    output("- from %s", $row['name']);
                    output_notl("</a></td><td><a href='runmodule.php?module=letteropener&op=read&id={$id}&login={$to}'>" . date("M d, h:i a", strtotime($row['sent'])) . "</a></td>", true);
                    addnav("", "runmodule.php?module=letteropener&op=read&id={$id}&login={$to}");
                    output_notl("</tr>", true);
                }
                //}
            } else {
                output("`iThey have no mail.`i");
            }
        } elseif (db_num_rows($result) == 0) {
            output("`@No one was found who matches \"%s\".  ", stripslashes($to));
            $try = translate_inline("Please try again");
            output_notl("<a href='runmodule.php?module=letteropener'>{$try}</a>.", true);
            popup_footer();
            exit;
        } else {
            output_notl("<select name='to' id='to' onChange='check_su_warning();'>", true);
            $superusers = array();
            for ($i = 0; $i < db_num_rows($result); $i++) {
                $row = db_fetch_assoc($result);
                output_notl("<option value=\"" . HTMLEntities($row['login']) . "\">", true);
                output_notl("%s", full_sanitize($row['name']));
                if ($row['superuser'] & SU_GIVES_YOM_WARNING && !($row['superuser'] & SU_OVERRIDE_YOM_WARNING)) {
                    array_push($superusers, $row['login']);
                }
            }
            output_notl("</select>`n", true);
        }
        output_notl("</table>", true);
    } elseif ($op == "from") {
        $subject = "";
        $body = "";
        $row = "";
        addnav("Read someone else's mail", "runmodule.php?module=letteropener");
        $from = httpget('from');
        if ($from != "") {
            $sql = "SELECT acctid,login,name superuser FROM " . db_prefix("accounts") . " WHERE login=\"{$from}\"";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            $sql = "SELECT acctid FROM " . db_prefix("accounts") . " WHERE login='******'login'] . "'";
            $result = db_query($sql);
            $row2 = db_fetch_assoc($result);
            $acctid = $row2['acctid'];
            output_notl("<table>", true);
            $session['message'] = "";
            $sql = "SELECT subject,messageid," . db_prefix("accounts") . ".name,msgto,seen,sent FROM " . db_prefix($maildb) . " LEFT JOIN " . db_prefix("accounts") . " ON " . db_prefix("accounts") . ".acctid=" . db_prefix($maildb) . ".msgto WHERE msgfrom=\"" . $acctid . "\" ORDER BY sent DESC";
            $result = db_query($sql);
            if (db_num_rows($result) > 0) {
                for ($i = 0; $i < db_num_rows($result); $i++) {
                    $row = db_fetch_assoc($result);
                    $sql2 = "Select name from " . db_prefix("accounts") . " where acctid=" . $row['msgto'] . "";
                    $result2 = db_query($sql2);
                    $row2 = db_fetch_assoc($result2);
                    $toname = $row2['name'];
                    $id = $row['messageid'];
                    output_notl("<tr>", true);
                    output_notl("<td nowrap><img src='images/" . ($row['seen'] ? "old" : "new") . "scroll.GIF' width='16' height='16' alt='" . ($row['seen'] ? "Old" : "New") . "'></td>", true);
                    output_notl("<td><a href='runmodule.php?module=letteropener&op=read&id={$id}&login={$from}'>", true);
                    if (trim($row['subject']) == "") {
                        output("`i(No Subject)`i");
                    } else {
                        output_notl($row['subject']);
                    }
                    output_notl("</a></td><td><a href='runmodule.php?module=letteropener&op=read&id={$id}&login={$from}'>", true);
                    addnav("", "runmodule.php?module=letteropener&op=read&id={$id}&login={$from}");
                    output("- to %s", $toname);
                    output_notl("</a></td><td><a href='runmodule.php?module=letteropener&op=read&id={$id}&login={$from}'>" . date("M d, h:i a", strtotime($row['sent'])) . "</a></td>", true);
                    output_notl("</tr>", true);
                }
                //}
            } else {
                output("`iThey have not sent any mail.`i");
            }
        } elseif (db_num_rows($result) == 0) {
            output("`@No one was found who matches \"%s\".  ", stripslashes($from));
            $try = translate_inline("Please try again");
            output_notl("<a href='runmodule.php?module=letteropener'>{$try}</a>.", true);
            popup_footer();
            exit;
        } else {
            output_notl("<select name='to' id='to' onChange='check_su_warning();'>", true);
            $superusers = array();
            for ($i = 0; $i < db_num_rows($result); $i++) {
                $row = db_fetch_assoc($result);
                output_notl("<option value=\"" . HTMLEntities($row['login']) . "\">", true);
                output_notl("%s", full_sanitize($row['name']));
                if ($row['superuser'] & SU_GIVES_YOM_WARNING && !($row['superuser'] & SU_OVERRIDE_YOM_WARNING)) {
                    array_push($superusers, $row['login']);
                }
            }
            output_notl("</select>`n", true);
        }
        output_notl("</table>", true);
    }
    page_footer();
}
function pointstransfer_run()
{
    global $session;
    require_once "lib/systemmail.php";
    page_header("Hunter's Lodge");
    $op = httpget("op");
    $mint = get_module_setting("mint");
    addnav("L?Return to the Lodge", "lodge.php");
    if ($op == "") {
        $allowed = pointstransfer_pointscheck();
        if ($allowed < $mint) {
            output("`7.J. C. Petersen smiles at your generosity, but leaves the forms where they are.");
            $sallowed = ($allowed > 0 ? "`@" : "`\$") . $allowed;
            if (is_module_active("titlechange")) {
                output("`n`n\"`&I'm sorry, but counting any points used towards title changes, you have %s`& points available, which isn't enough for a transfer.", $sallowed);
            } else {
                output("`n`n\"`&I'm sorry, but you have %s`& points available, which isn't enough for a transfer.", $sallowed);
            }
            if ($mint) {
                output("You need at least `@%s`& points available.`7\"", $mint);
            } else {
                output_notl("`7\"");
            }
        } else {
            output("`7J. C. Petersen smiles at your generosity, and pulls out a form.");
            if (is_module_active("titlechange")) {
                output("`n`n\"`&Including any points used towards title changes, you have `@%s`& points available.", $allowed);
            } else {
                output("`n`n\"`&You have `@%s`& points available.", $allowed);
            }
            if ($mint) {
                output("You have the `@%s`& points needed for a minimum transfer.", $mint);
            }
            output("How many points would you like to transfer, and to whom?`7\"");
            $amount = get_module_pref("amount");
            $target = get_module_pref("target");
            $anon = get_module_pref("anon");
            $note = get_module_pref("note");
            $target = color_sanitize($target);
            rawoutput("<form action='runmodule.php?module=pointstransfer&op=confirm' method='POST'>");
            addnav("", "runmodule.php?module=pointstransfer&op=confirm");
            output("`n`nPoints: ");
            rawoutput("<input name='amount' width='8' value={$amount}>");
            output("`n`nRecipient: ");
            rawoutput("<input name='target' value={$target}>");
            output("`n`nAnonymous Transfer: ");
            rawoutput("<select name='anon'>");
            $no = translate_inline("No");
            $yes = translate_inline("Yes");
            rawoutput("<option value='0'" . ($anon == 0 ? " selected" : "") . ">{$no}</option>");
            rawoutput("<option value='1'" . ($anon == 1 ? " selected" : "") . ">{$yes}</option>");
            rawoutput("</select>");
            output("`n`nOptional Note:");
            rawoutput("<input size='75' name='note' value={$note}>");
            output_notl("`n`n");
            $click = translate_inline("Confirm");
            rawoutput("<input type='submit' class='button' value='{$click}'>");
            rawoutput("</form>");
        }
    } elseif ($op == "confirm") {
        $amount = abs((int) httppost("amount"));
        $target = httppost("target");
        $anon = httppost("anon");
        $note = preg_replace("/[`][bic]/", "", stripslashes(httppost("note")));
        set_module_pref("amount", $amount);
        set_module_pref("target", $target);
        set_module_pref("anon", $anon);
        set_module_pref("note", $note);
        if (!$amount) {
            output("`7J. C. Petersen gives you an odd look.");
            output("`n`n\"`&Why would you give someone zero points?");
            output("Perhaps you should try again when you're thinking more clearly?`7\"");
            addnav("Try Again", "runmodule.php?module=pointstransfer");
        } elseif ($amount < $mint) {
            output("`7J. C. Petersen gives you an odd look.");
            output("`n`n\"`&I'm sorry, but you need to donate at least `@%s`& points.", $mint);
            output("Perhaps you should try again, giving more?`7\"");
            addnav("Try Again", "runmodule.php?module=pointstransfer");
        } elseif ($amount > pointstransfer_pointscheck()) {
            output("`7J. C. Petersen gives you an odd look.");
            output("`n`n\"`&I'm sorry, but you don't have `@%s`& points to give.", $amount);
            output("Perhaps you should try again with less, or donate more?`7\"");
            addnav("Try Again", "runmodule.php?module=pointstransfer");
        } else {
            $newtarget = "";
            for ($x = 0; $x < strlen($target); $x++) {
                $newtarget .= substr($target, $x, 1) . "%";
                //Eric rocks.
            }
            $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE name LIKE '%" . addslashes($newtarget) . "' AND locked=0";
            $result = db_query($sql);
            if (!db_num_rows($result)) {
                output("`7J. C. Petersen gives you an odd lock.");
                output("`n`n\"`&I'm sorry, but I don't know anyone by that name.");
                output("Perhaps you should try again?`7\"");
                addnav("Try Again", "runmodule.php?module=pointstransfer");
            } elseif (db_num_rows($result) > 50) {
                output("`7J. C. Petersen gives you an odd lock.");
                output("`n`n\"`&I'm sorry, but there's way too many people who might go by that name.");
                output("Perhaps you should narrow it down, next time?`7\"");
                addnav("Try Again", "runmodule.php?module=pointstransfer");
            } elseif (db_num_rows($result) > 1) {
                rawoutput("<form action='runmodule.php?module=pointstransfer&op=send' method='POST'>");
                addnav("", "runmodule.php?module=pointstransfer&op=send");
                addnav("Start Over", "runmodule.php?module=pointstransfer");
                output("`7J. C. Petersen looks at you.");
                output("`n`n\"`&There's a few people I know by that name.");
                output("Tell me which one you mean, and I'll send those points right off.`7\"");
                output("`n`nPoints: `@%s`7", $amount);
                output("`n`nRecipient: ");
                rawoutput("<select name='target'>");
                for ($i = 0; $i < db_num_rows($result); $i++) {
                    $row = db_fetch_assoc($result);
                    $name = $row['name'];
                    rawoutput("<option value='{$name}'>" . full_sanitize($name) . "</option>");
                }
                rawoutput("</select>");
                output("`n`nAnonymous Transfer: `&%s`7", $anon ? "Yes" : "No");
                output("`n`nOptional Note: `&%s`7", $note);
                output_notl("`n`n");
                $send = translate_inline("Send");
                rawoutput("<input type='submit' class='button' value='{$send}'>");
                rawoutput("</form>");
            } else {
                addnav("Start Over", "runmodule.php?module=pointstransfer");
                $row = db_fetch_assoc($result);
                $name = $row['name'];
                output("`7J. C. Petersen smiles at you.");
                output("`n`n\"`&This all looks to be in order to me.");
                output("This is what you meant, right?`7\"");
                output("`n`nPoints: `@%s`7", $amount);
                output("`n`nRecipient: `&%s`7", $name);
                output("`n`nAnonymous Transfer: `&%s`7", $anon ? "Yes" : "No");
                output("`n`nOptional Note: `&%s`7", $note ? $note : "`inone`i");
                output_notl("`n`n");
                rawoutput("<form action='runmodule.php?module=pointstransfer&op=send' method='POST'>");
                addnav("", "runmodule.php?module=pointstransfer&op=send");
                rawoutput("<input type='hidden' value='{$name}' name='target'>");
                $send = translate_inline("Send");
                rawoutput("<input type='submit' class='button' value='{$send}'>");
                rawoutput("</form>");
            }
        }
    } elseif ($op == "send") {
        addnav("Send To Someone Else", "runmodule.php?module=pointstransfer");
        $amount = get_module_pref("amount");
        $target = httppost("target");
        if ($target == $session['user']['name']) {
            output("`7J. C. Petersen gives you a weird look and puts down his pen.");
            output("`n`n\"`&Why would you ever want to transfer points to yourself?");
            output("Perhaps you should try again when you're thinking more clearly?`7\"");
        } else {
            $anon = get_module_pref("anon");
            $note = get_module_pref("note");
            $note = $note ? "`n`nThey also added this note:`n" . $note : "";
            $sql = "SELECT acctid FROM " . db_prefix("accounts") . " WHERE name='{$target}'";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            $targetid = $row['acctid'];
            $sql = "UPDATE " . db_prefix("accounts") . " SET donation=donation+{$amount} WHERE acctid={$targetid}";
            db_query($sql);
            $session['user']['donation'] -= $amount;
            if ($anon) {
                systemmail($targetid, array("`@Donator Points Transfer`0"), array("`2Someone has gifted you with `@%s`2 donator points. %s", $amount, $note));
            } else {
                systemmail($targetid, array("`@Donator Points Transfer`0"), array("`&%s`2 has gifted you with `@%s`2 donator points. %s", $session['user']['name'], $amount, $note));
            }
            debuglog($session['user']['name'] . " sent {$amount} donator points to {$target}" . ($anon ? " anonymously." : "."));
            debuglog($session['user']['name'] . " sent {$amount} donator points to {$target}" . ($anon ? " anonymously." : "."), false, $targetid);
            output("`7J. C. Petersen finishes recording the transfer.");
            output("`n`n\"`&Okay, the points have been sent.");
            output("Have a nice day.`7\"");
        }
    }
    page_footer();
}
function injectcommentary($section, $talkline, $comment, $schema = false)
{
    global $session, $doublepost, $translation_namespace;
    if ($schema === false) {
        $schema = $translation_namespace;
    }
    // Make the comment pristine so that we match on it correctly.
    $comment = stripslashes($comment);
    tlschema("commentary");
    $doublepost = 0;
    $emptypost = 0;
    $colorcount = 0;
    if ($comment != "") {
        $commentary = str_replace("`n", "", soap($comment));
        $y = strlen($commentary);
        for ($x = 0; $x < $y; $x++) {
            if (substr($commentary, $x, 1) == "`") {
                $colorcount++;
                if ($colorcount >= getsetting("maxcolors", 10)) {
                    $commentary = substr($commentary, 0, $x) . color_sanitize(substr($commentary, $x));
                    $x = $y;
                }
                $x++;
            }
        }
        $args = array('commentline' => $commentary, 'commenttalk' => $talkline);
        $args = modulehook("commentary", $args);
        //Begin CMJ Patch to allow players to use the /special switch
        if ($args['ignore'] == 1) {
            //Ignore this comment, it is likely a side-effect of using the Special switch
            return;
        }
        $commentary = $args['commentline'];
        $talkline = $args['commenttalk'];
        tlschema($schema);
        $talkline = translate_inline($talkline);
        tlschema();
        $commentary = preg_replace("'([^[:space:]]{45,45})([^[:space:]])'", "\\1 \\2", $commentary);
        $commentary = addslashes($commentary);
        // do an emote if the area has a custom talkline and the user
        // isn't trying to emote already.
        if ($talkline != "says" && substr($commentary, 0, 1) != ":" && substr($commentary, 0, 2) != "::" && substr($commentary, 0, 3) != "/me" && substr($commentary, 0, 5) != "/game") {
            $commentary = ":`3{$talkline}, \\\"`#{$commentary}`3\\\"";
        }
        if (substr($commentary, 0, 5) == "/game" && ($session['user']['superuser'] & SU_IS_GAMEMASTER) == SU_IS_GAMEMASTER) {
            //handle game master inserts now, allow double posts
            injectsystemcomment($section, $commentary);
        } else {
            $sql = "SELECT comment,author FROM " . db_prefix("commentary") . " WHERE section='{$section}' ORDER BY commentid DESC LIMIT 1";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            db_free_result($result);
            if ($row['comment'] != stripslashes($commentary) || $row['author'] != $session['user']['acctid']) {
                injectrawcomment($section, $session['user']['acctid'], $commentary);
                $session['user']['laston'] = date("Y-m-d H:i:s");
            } else {
                $doublepost = 1;
            }
        }
        tlschema();
    }
}
 unset($session['user']['password']);
 $date = date("Y-m-d H:i:s");
 $post['cancelpetition'] = false;
 $post['cancelreason'] = 'The admins here decided they didn\'t like something about how you submitted your petition.  They were also too lazy to give a real reason.';
 $post = modulehook("addpetition", $post);
 if (!$post['cancelpetition']) {
     unset($post['cancelpetition'], $post['cancelreason']);
     $sql = "INSERT INTO " . db_prefix("petitions") . " (author,date,body,pageinfo,ip,id) VALUES (" . (int) $session['user']['acctid'] . ",'{$date}',\"" . addslashes(output_array($post)) . "\",\"" . addslashes(output_array($session, "Session:")) . "\",'{$_SERVER['REMOTE_ADDR']}','" . addslashes($_COOKIE['lgi']) . "')";
     db_query($sql);
     // Fix the counter
     invalidatedatacache("petition_counts");
     // If the admin wants it, email the petitions to them.
     if (getsetting("emailpetitions", 0)) {
         // Yeah, the format of this is ugly.
         require_once "lib/sanitize.php";
         $name = color_sanitize($session['user']['name']);
         $url = getsetting("serverurl", "http://" . $_SERVER['SERVER_NAME'] . ($_SERVER['SERVER_PORT'] == 80 ? "" : ":" . $_SERVER['SERVER_PORT']) . dirname($_SERVER['REQUEST_URI']));
         if (!preg_match("/\\/\$/", $url)) {
             $url = $url . "/";
             savesetting("serverurl", $url);
         }
         $tl_server = translate_inline("Server");
         $tl_author = translate_inline("Author");
         $tl_date = translate_inline("Date");
         $tl_body = translate_inline("Body");
         $tl_subject = sprintf_translate("New LoGD Petition at %s", $url);
         $msg = "{$tl_server}: {$url}\n";
         $msg .= "{$tl_author}: {$name}\n";
         $msg .= "{$tl_date} : {$date}\n";
         $msg .= "{$tl_body} :\n" . output_array($post) . "\n";
         mail(getsetting("gameadminemail", "*****@*****.**"), $tl_subject, $msg);
        $amtstr .= "%s gems";
    }
    if ($repaygold > 0 && $repaygems > 0) {
        $amtstr = sprintf_translate($amtstr, $repaygold, $repaygems);
    } elseif ($repaygold > 0) {
        $amtstr = sprintf_translate($amtstr, $repaygold);
    } else {
        $amtstr = sprintf_translate($amtstr, $repaygems);
    }
    tlschema($schemas['mountsold']);
    output($texts['mountsold'], $playermount['newname'] ? $playermount['newname'] : $playermount['mountname'], $amtstr);
    tlschema();
}
if ($confirm == 0) {
    if ($session['user']['hashorse'] > 0) {
        addnav(array("%s", color_sanitize($name)));
        tlschema($schemas['offer']);
        output($texts['offer'], $repaygold, $repaygems, $lcname);
        tlschema();
        addnav(array("Sell %s`0", $lcname), "stables.php?op=sellmount");
        if (getsetting("allowfeed", 0) && $session['user']['fedmount'] == 0) {
            addnav(array("Feed %s`0 (`^%s`0 gold)", $lcname, $grubprice), "stables.php?op=feed");
        }
    }
    $sql = "SELECT mountname,mountid,mountcategory,mountdkcost FROM " . db_prefix("mounts") . " WHERE mountactive=1 AND mountlocation IN ('all','{$session['user']['location']}') ORDER BY mountcategory,mountcostgems,mountcostgold";
    $result = db_query($sql);
    $category = "";
    $number = db_num_rows($result);
    for ($i = 0; $i < $number; $i++) {
        $row = db_fetch_assoc($result);
        if ($category != $row['mountcategory']) {
require_once "lib/superusernav.php";
superusernav();
addnav("Bans");
addnav("Add a ban", "user.php?op=setupban");
addnav("List/Remove bans", "user.php?op=removeban");
// This doesn't seem to be used, so I'm going to comment it out now
//$msg = httpget('msg');
//if ($msg>"") {
//	output("Message: %s`n", $msg);
//}
// Collect a list of the mounts
$mounts = "0," . translate_inline("None");
$sql = "SELECT mountid,mountname,mountcategory FROM " . db_prefix("mounts") . " ORDER BY mountcategory";
$result = db_query($sql);
while ($row = db_fetch_assoc($result)) {
    $mounts .= ",{$row['mountid']},{$row['mountcategory']}: " . color_sanitize($row['mountname']);
}
$specialties = array("" => translate_inline("Undecided"));
$specialties = modulehook("specialtynames", $specialties);
$enum = "";
foreach ($specialties as $key => $name) {
    if ($enum) {
        $enum .= ",";
    }
    $enum .= "{$key},{$name}";
}
//Inserted for v1.1.0 Dragonprime Edition to extend clan possibilities
$ranks = array(CLAN_APPLICANT => "`!Applicant`0", CLAN_MEMBER => "`#Member`0", CLAN_OFFICER => "`^Officer`0", CLAN_LEADER => "`&Leader`0", CLAN_FOUNDER => "`\$Founder");
$ranks = modulehook("clanranks", array("ranks" => $ranks, "clanid" => NULL, "userid" => $userid));
$ranks = $ranks['ranks'];
$rankstring = "";
function additionaltattoos_dohook($hookname, $args)
{
    global $session;
    switch ($hookname) {
        case "petraavail":
            // Make sure we have Petra.  We *should* but, just in case.
            require_once "modules/petra.php";
            // Resurrections are only per DK, so someone actually has to be
            // looking in order to get this one.
            if (!isset($args['tattoos']['phoenix']) && $session['user']['resurrections'] >= get_module_setting("reqphoenix")) {
                petra_addnav("phoenix", translate_inline("Phoenix"));
                $args['canbuy'] = 1;
            }
            if (!isset($args['tattoos']['dragon']) && $session['user']['dragonkills'] >= get_module_setting("reqdragon")) {
                petra_addnav("dragon", translate_inline("Dragon"));
                $args['canbuy'] = 1;
            }
            if (!isset($args['tattoos']['dragonfire']) && isset($args['tattoos']['dragon'])) {
                $bufflist = @unserialize($session['user']['bufflist']);
                if (isset($bufflist['buzz']['name']) && color_sanitize($bufflist['buzz']['name']) == get_module_setting("buffname")) {
                    petra_addnav("dragonfire", translate_inline("Dragonfire"));
                    $args['canbuy'] = 1;
                }
            }
            break;
        case "petraadded":
            if (isset($args['tattoos']['dragon']) && $args['tattoos']['dragon'] == 1 && isset($args['tattoos']['dragonfire']) && $args['tattoos']['dragonfire'] == 1) {
                // replace dragon and dragonfire tattoos with
                // the firebreathingdragon tattoo set,
                // but keep the two elements defined so that
                // they don't show up as available in the parlor
                $args['tattoos']['dragon'] = "hidden";
                $args['tattoos']['dragonfire'] = "hidden";
                // bonus of 1 for collecting set
                $args['tattoos']['firebreathingdragon'] = 3;
            }
            break;
        case "petradescr":
            if ($args['tname'] == "phoenix") {
                /* [add translated phoenix description] */
                $args['tattoodescr'] = "";
            } elseif ($args['tname'] == "dragon") {
                /* [add translated dragon description] */
                $args['tattoodescr'] = "";
            } elseif ($args['tname'] == "dragonfire") {
                /* [add translated fire-breathing dragon description] */
                $args['tattoodescr'] = "";
            }
            break;
        case "petracolor":
            if ($args['tname'] == "phoenix") {
                $args['colortat'] = "`\$p`Qh`^o`&e`^n`Qi`\$x";
            } elseif ($args['tname'] == "dragon") {
                $args['colortat'] = "`2dragon";
            } elseif ($args['tname'] == "firebreathingdragon") {
                $args['colortat'] = "`\$fi`Qre b`^rea`&thi`@ng `2dragon";
            }
            break;
    }
    return $args;
}
function mountupgrade_showform($keyout, $val, $info)
{
    $sql = "SELECT mountid,mountname,mountcategory FROM " . db_prefix("mounts") . " ORDER BY mountcategory, mountid";
    $result = db_query($sql);
    rawoutput("<select name='{$keyout}'><option value='0'>" . translate_inline("None") . "</option>");
    while ($row = db_fetch_assoc($result)) {
        $mountid = $row['mountid'];
        $mountcategory = $row['mountcategory'];
        $mountname = color_sanitize($row['mountname']);
        if ($val == $mountid) {
            rawoutput("<option value='{$mountid}' selected>" . htmlentities("{$mountcategory}: {$mountname}", ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "</option>");
        } else {
            rawoutput("<option value='{$mountid}'>" . htmlentities("{$mountcategory}: {$mountname}", ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "</option>");
        }
    }
    rawoutput("</select>");
}
        $addboxreplace = 1;
        output("Sorry, you've exhausted your posts in this section for now.`0`n");
    } elseif (!$session['loggedin']) {
        output("Sorry, your session has timed out.`0`n");
        output("<a href=\"home.php\">Log in again</a>", true);
    } else {
        $section = $_REQUEST['section'];
        $talkline = $_REQUEST['talkline'];
        //echo("talkline $talkline ");
        //$talkline = mb_convert_encoding($talkline,getsetting("charset", "ISO-8859-1"),'auto');
        //echo("talkline $talkline ");
        $schema = $_REQUEST['schema'];
        $comment = trim($_REQUEST['insertcommentary']);
        $comment = mb_convert_encoding($comment, getsetting("charset", "ISO-8859-1"), 'auto');
        if ($section || $talkline || $comment) {
            $tcom = color_sanitize($comment);
            if ($tcom == "" || $tcom == ":" || $tcom == "::" || $tcom == "/me") {
                $emptypost = 1;
            } else {
                injectcommentary($section, $talkline, $comment, $schema);
            }
            //echo("injectcommentary($section, $talkline, $comment, $schema)");
            //exit;
        }
        $output = '';
        $lastid = getcommentary($_REQUEST['section'], 25, $_REQUEST['talkline'], $_REQUEST['lastcommentid']);
    }
} else {
    $output = '';
    $lastid = getcommentary($_REQUEST['section'], 25, $_REQUEST['talkline'], $_REQUEST['lastcommentid']);
    if (array_key_exists("mute", $args) && $args['mute'] && !($session['user']['superuser'] & SU_EDIT_COMMENTS)) {
function brothel_run()
{
    global $session;
    $gemcost = get_module_setting("gemcost");
    $theygems = $session['user']['gems'];
    $done = get_module_pref("done");
    $times = get_module_setting("times");
    $owner = get_module_setting("owner");
    $allow = get_module_setting("allow");
    $shoppe = get_module_setting("shoppe");
    $m1 = get_module_setting("m1");
    $m2 = get_module_setting("m2");
    $m3 = get_module_setting("m3");
    $m4 = get_module_setting("m4");
    $f1 = get_module_setting("f1");
    $f2 = get_module_setting("f2");
    $f3 = get_module_setting("f3");
    $f4 = get_module_setting("f4");
    $op = httpget("op");
    page_header(array("%s", color_sanitize($shoppe)));
    if ($op == "enter" && $theygems >= $gemcost && $done < $times) {
        blocknav("runmodule.php?module=brothel&op=enter");
        output("`2As you walk into a large home behind thick foilage, you are greeted by `5%s`2.", $owner);
        output(" `5%s`2, is an elf of incredible beauty.", $owner);
        output(" Behind her a number of Men and Women bustle about.`n`n");
        output("`2\"`5Please come in and rest, while one of my staff sees to your needs for only %s gems.`2\" she says.", $gemcost);
        if ($allow == 1) {
            addnav("Girls");
            addnav(array("%s", $f1), "runmodule.php?module=brothel&op=f1");
            addnav(array("%s", $f2), "runmodule.php?module=brothel&op=f2");
            addnav(array("%s", $f3), "runmodule.php?module=brothel&op=f3");
            addnav(array("%s", $f4), "runmodule.php?module=brothel&op=f4");
            addnav("Guys");
            addnav(array("%s", $m1), "runmodule.php?module=brothel&op=m1");
            addnav(array("%s", $m2), "runmodule.php?module=brothel&op=m2");
            addnav(array("%s", $m3), "runmodule.php?module=brothel&op=m3");
            addnav(array("%s", $m4), "runmodule.php?module=brothel&op=m4");
        } else {
            if ($session['user']['sex'] == 0) {
                addnav("Girls");
                addnav(array("%s", $f1), "runmodule.php?module=brothel&op=f1");
                addnav(array("%s", $f2), "runmodule.php?module=brothel&op=f2");
                addnav(array("%s", $f3), "runmodule.php?module=brothel&op=f3");
                addnav(array("%s", $f4), "runmodule.php?module=brothel&op=f4");
            } else {
                addnav("Guys");
                addnav(array("%s", $m1), "runmodule.php?module=brothel&op=m1");
                addnav(array("%s", $m2), "runmodule.php?module=brothel&op=m2");
                addnav(array("%s", $m3), "runmodule.php?module=brothel&op=m3");
                addnav(array("%s", $m4), "runmodule.php?module=brothel&op=m4");
            }
        }
    } elseif ($theygems < $gemcost) {
        output("`5%s `2looks at you, with her stunning eyes.", $owner);
        output(" She motions for a large burly man.");
        output(" He grabs you by your coat and neck and tosses you out of the building.`n`n");
        output("\"`5I am sorry, but you do not have enough gems for my services.");
        blocknav("runmodule.php?module=brothel&op=enter");
    } elseif ($done >= $times) {
        output("I am quite sorry... but your libido can not handle that much in one day.");
        output(" Please come back tomorrow.");
        blocknav("runmodule.php?module=brothel&op=enter");
    }
    switch ($op) {
        case "f1":
            $done++;
            set_module_pref("done", $done);
            brothel_girldoes();
            $session['user']['gems'] -= $gemcost;
            brothel_outcome();
            break;
        case "f2":
            $done++;
            set_module_pref("done", $done);
            brothel_girldoes();
            $session['user']['gems'] -= $gemcost;
            brothel_outcome();
            break;
        case "f3":
            $done++;
            set_module_pref("done", $done);
            brothel_girldoes();
            $session['user']['gems'] -= $gemcost;
            brothel_outcome();
            break;
        case "f4":
            $done++;
            set_module_pref("done", $done);
            brothel_girldoes();
            $session['user']['gems'] -= $gemcost;
            brothel_outcome();
            break;
        case "m1":
            $done++;
            set_module_pref("done", $done);
            brothel_guydoes();
            $session['user']['gems'] -= $gemcost;
            brothel_outcome();
            break;
        case "m2":
            $done++;
            set_module_pref("done", $done);
            brothel_guydoes();
            $session['user']['gems'] -= $gemcost;
            brothel_outcome();
            break;
        case "m3":
            $done++;
            set_module_pref("done", $done);
            brothel_guydoes();
            $session['user']['gems'] -= $gemcost;
            brothel_outcome();
            break;
        case "m4":
            $done++;
            set_module_pref("done", $done);
            brothel_guydoes();
            $session['user']['gems'] -= $gemcost;
            brothel_outcome();
            break;
    }
    if ($done < $times) {
        addnav("Return to the Selection", "runmodule.php?module=brothel&op=enter");
    }
    addnav("Leave");
    villagenav();
    page_footer();
}
function addcommentary()
{
    global $session, $emptypost, $afk, $dni;
    $section = httppost('section');
    $talkline = httppost('talkline');
    $schema = httppost('schema');
    $comment = trim(httppost('insertcommentary'));
    $counter = httppost('counter');
    $remove = URLDecode(httpget('removecomment'));
    $restore = URLDecode(httpget('restorecomment'));
    //debug(httpallpost());
    if (httpget("bulkdelete")) {
        $everything = httpallpost();
        foreach ($everything as $key => $val) {
            if (substr($key, 0, 14) == "deletecomment_") {
                $del = str_replace("deletecomment_", "", $key);
                removecommentary($del, "Mass deletion by " . $session['user']['name'], $session['user']['acctid']);
            }
        }
    }
    if ($remove > 0) {
        removecommentary($remove, "Moderated by " . $session['user']['name'], $session['user']['acctid']);
    }
    if ($restore > 0) {
        restorecommentary($restore, "Restored by " . $session['user']['name'], $session['user']['acctid']);
    }
    if (!$comment) {
        return false;
    }
    if ($session['user']['chatloc'] == "DNI") {
        $dni = true;
    }
    $colors = array("1" => "colDkBlue", "2" => "colDkGreen", "3" => "colDkCyan", "4" => "colDkRed", "5" => "colDkMagenta", "6" => "colDkYellow", "7" => "colDkWhite", "~" => "colBlack", "!" => "colLtBlue", "@" => "colLtGreen", "#" => "colLtCyan", "\$" => "colLtRed", "%" => "colLtMagenta", "^" => "colLtYellow", "&" => "colLtWhite", ")" => "colLtBlack", "e" => "colDkRust", "E" => "colLtRust", "g" => "colXLtGreen", "G" => "colXLtGreen", "j" => "colMdGrey", "k" => "colaquamarine", "K" => "coldarkseagreen", "l" => "colDkLinkBlue", "L" => "colLtLinkBlue", "m" => "colwheat", "M" => "coltan", "p" => "collightsalmon", "P" => "colsalmon", "q" => "colDkOrange", "Q" => "colLtOrange", "R" => "colRose", "T" => "colDkBrown", "t" => "colLtBrown", "V" => "colBlueViolet", "v" => "coliceviolet", "x" => "colburlywood", "X" => "colbeige", "y" => "colkhaki", "Y" => "coldarkkhaki");
    if (substr($comment, 0, 9) == "/chatcol ") {
        $ucol = substr($comment, 9, 1);
        if (!isset($colors[$ucol])) {
            output("`c`b`4Invalid default talk colour`b`nYou entered an invalid colour code, please try again.`0`c`n");
            return false;
        } else {
            $session['user']['prefs']['ucol'] = $ucol;
            output_notl("`c`bDefault talk colour changed`b`n`" . $ucol . "This is your new default commentary dialogue colour.  When you type in commentary areas, this colour will show up automatically.  If you're an Extra-Awesome Site Supporter, you can also change the colour of your character's dialogue during quests, monster fights and other in-game areas using the /talkcol switch, in the same way you just used the /chatcol switch.`0`c`n");
            return false;
        }
    } else {
        if (substr($comment, 0, 9) == "/talkcol ") {
            $ucol = substr($comment, 9, 1);
            if (!isset($colors[$ucol])) {
                output("`c`b`4Invalid default talk colour`b`nYou entered an invalid colour code, please try again.`0`c`n");
                return false;
            } else {
                $session['user']['prefs']['ugcol'] = $ucol;
                if ($session['user']['donation'] >= 2000) {
                    output_notl("`c`bDefault talk colour changed`b`n`" . $ucol . "This is your new default in-game dialogue colour.  This is the colour we'll use to represent your character's dialogue during quests, monster encounters, and other in-game things.  If you choose a colour commonly used by monsters or other characters, you might have problems figuring out who's talking - if that's the case, you can reset to the default with \"/talkcol #\".  You can also change your default colour for commentary areas by using the /chatcol switch, in the same way you just used /talkcol.`0`c`n");
                } else {
                    output("`c`bNot enough Supporter Points`b`nSorry, but due to the extra system load that the /talkcol switch uses, this feature is restricted to players with more than 2,000 Supporter Points.`0`c`n");
                }
                return false;
            }
        }
    }
    if ($comment == strtoupper($comment)) {
        //this is an all-uppercase entry.  Do not add this comment to the database; instead, check it for built-in stuff like AFK and GREM, then run it through the commentarycommand hook
        if ($comment == "AFK" || $comment == "BRB") {
            $session['user']['chatloc'] = "AFK";
            $afk = true;
            output("`0`n`c`bYou are Away From the Keyboard until you load another page.`b`c`n");
            return false;
        }
        if ($comment == "DNI") {
            if ($session['user']['chatloc'] == "DNI") {
                $session['user']['chatloc'] = $section;
                $dni = false;
                output("`0`n`c`bYou are no longer in Do Not Interrupt status.`b`c`n");
            } else {
                $session['user']['chatloc'] = "DNI";
                $dni = true;
                output("`0`n`c`bYou are in Do Not Interrupt status.  Type DNI again to leave.`b`nDNI status is used for whenever you're doing or saying something that means other players shouldn't try to interact with you.  For example, when two or more characters are chatting just outside of the main group of characters, and other characters shouldn't be able to hear them.`c`n");
            }
            return false;
        }
        if ($comment == "GREM") {
            //handle deleting the player's last comment
            $sql = "SELECT * FROM " . db_prefix("commentary") . " WHERE author='" . $session['user']['acctid'] . "' ORDER BY commentid DESC LIMIT 1";
            $result = db_query($sql);
            while ($row = db_fetch_assoc($result)) {
                $now = time();
                $then = strtotime($row['postdate']);
                $ago = $now - $then;
                if ($ago < 120) {
                    removecommentary($row['commentid'], "Typo Gremlin", $session['user']['acctid']);
                    output("`0`n`c`bA nearby Typo Gremlin notices the peculiar tastiness of your previous comment.  Within moments, a small horde of them have descended upon your words, and consumed them.`b`c`n");
                } else {
                    output("`0`n`c`bThe Typo Gremlins turn up their nose at your latest comment - it's just too old.  They have no taste for stale words.`b`c`n");
                }
            }
            return false;
        }
        $hookcommand = array('command' => $comment, 'section' => $section);
        $returnedhook = modulehook("commentarycommand", $hookcommand);
        if (!$returnedhook['skipcommand']) {
            //if for some reason you're going to involve a command that can be a mix of upper and lower case, set $args['skipcommand'] and $args['ignore'] to true and handle it in postcomment instead.
            if (!$returnedhook['processed']) {
                output("`c`b`JCommand Not Recognized`b`0`nWhen you type in ALL CAPS, the game doesn't think you're talking to other players; it thinks you're trying to perform an action within the game.  For example, typing `#GREM`0 will remove the last comment you posted, as long as you posted it less than two minutes ago.  Typing `#AFK`0 or `#BRB`0 will turn your online status bar grey, so that people know you're `#A`0way `#F`0rom the `#K`0eyboard (or, if you prefer, that you'll `#B`0e `#R`0ight `#B`0ack).  Typing `#DNI`0 will let other players know that you're busy talking to one particular player - maybe somewhere off-camera - and that you don't want to be interrupted right now.`nSome areas have special hidden commands or other easter eggs that you can hunt for.  This time around, you didn't trigger anything special.`c`0`n");
            }
            return false;
        }
    }
    if ($section || $talkline || $comment) {
        $tcom = color_sanitize($comment);
        if ($tcom == "" || $tcom == ":" || $tcom == "::" || $tcom == "/me") {
            $emptypost = 1;
        } else {
            $comment = comment_sanitize($comment);
            injectcommentary($section, $talkline, $comment);
        }
    }
}