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 mysticalshop_run()
{
    global $session;
    $shop = get_module_setting('shopname');
    $op = httpget('op');
    $from = 'runmodule.php?module=mysticalshop&';
    page_header(full_sanitize($shop));
    $what = httpget('what');
    $cat = httpget('cat');
    if (!is_numeric($cat)) {
        $cat = 0;
    }
    $names = translate_inline(array(0 => 'Rings', 1 => 'Amulets', 2 => 'Weapons', 3 => 'Armor', 4 => 'Cloaks', 5 => 'Helmets', 6 => 'Gloves', 7 => 'Boots', 8 => 'Miscellanea'));
    require_once "./modules/mysticalshop/run/case_{$op}.php";
    page_footer();
}
function textme_sendmail($post = [], $from = 'LotGD Staff')
{
    $accounts = db_prefix('accounts');
    $post['to'] = filter_var($post['to'], FILTER_SANITIZE_STRING);
    $post['body'] = trim(explode("---Original", $post['body'])[0]);
    $body = "From {$from}: \n{$post['body']}";
    $sql = db_query("SELECT acctid FROM {$accounts} WHERE login = '******'to']}'");
    $row = db_fetch_assoc($sql);
    $prefs = get_all_module_prefs('textme', $row['acctid']);
    foreach ($prefs as $key => $val) {
        $prefs[$key] = trim($val);
    }
    if ($prefs['user_number'] != '' && $prefs['user_carrier'] != 'none') {
        require_once 'lib/sanitize.php';
        $checkSent = mail("{$prefs['user_number']}@{$prefs['user_carrier']}", '', stripslashes(full_sanitize($body)), "From: textme@{$_SERVER['HTTP_HOST']}");
        if (!$checkSent) {
            debuglog("failed to send a message to {$post['to']} ({$prefs['user_number']}@{$prefs['user_carrier']})");
        }
    }
}
if (db_num_rows($result) > 0) {
    output("`7You ask %s`7 for the clan listings.  She points you toward a marquee board near the entrance of the lobby that lists the clans.`0`n`n", $registrar);
    $v = 0;
    $memb_n = translate_inline("(%s members)");
    $memb_1 = translate_inline("(%s member)");
    rawoutput('<table cellspacing="0" cellpadding="2" align="left">');
    while ($row = db_fetch_assoc($result)) {
        if ($row['c'] == 0) {
            $sql = "DELETE FROM " . db_prefix("clans") . " WHERE clanid={$row['clanid']}";
            db_query($sql);
        } else {
            rawoutput('<tr class="' . ($v % 2 ? "trlight" : "trdark") . '"><td>', true);
            if ($row['c'] == 1) {
                $memb = sprintf($memb_1, $row['c']);
            } else {
                $memb = sprintf($memb_n, $row['c']);
            }
            output_notl("&#149; &#60;%s&#62; <a href='clan.php?detail=%s'>%s</a> %s`n", $row['clanshort'], $row['clanid'], full_sanitize(htmlentities($row['clanname']), ENT_COMPAT, getsetting("charset", "ISO-8859-1")), $memb, true);
            rawoutput('</td></tr>');
            addnav("", "clan.php?detail={$row['clanid']}");
            $v++;
        }
    }
    rawoutput("</table>", true);
    addnav("Return to the Lobby", "clan.php");
} else {
    output("`7You ask %s`7 for the clan listings.  She stares at you blankly for a few moments, then says, \"`5Sorry pal, no one has had enough gumption to start up a clan yet.  Maybe that should be you, eh?`7\"", $registrar);
    addnav("Apply for a New Clan", "clan.php?op=new");
    addnav("Return to the Lobby", "clan.php");
}
page_footer();
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 getcommentary($section, $limit = 25, $talkline = "says", $commentid = 0)
{
    global $session, $REQUEST_URI, $doublepost, $translation_namespace, $counttoday;
    $textreturn = "";
    if ((int) getsetting("expirecontent", 180) > 0 && e_rand(1, 1000) == 1) {
        $sql = "DELETE FROM " . db_prefix("commentary") . " WHERE postdate<'" . date("Y-m-d H:i:s", strtotime("-" . getsetting("expirecontent", 180) . " days")) . "'";
        db_query($sql);
    }
    $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 AND commentid > '{$commentid}'";
    $result = db_query($sql);
    $row = db_fetch_assoc($result);
    if ($row['newadded'] < 1) {
        return $commentid;
    }
    $newadded = $row['newadded'];
    $commentbuffer = array();
    //		if ($commentid == 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 ) " . "AND commentid > '{$cid}' " . "ORDER BY commentid DESC LIMIT {$limit}";
    $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").".login, " . 
    				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 section = '$section' AND " .
    				db_prefix("accounts") . ".locked=0 AND commentid > '$commentid' 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'];
        $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);
            }
        }
        $location = get_module_pref("location", "ajaxcommentary");
        if ($location) {
            $link = "bio.php?char=" . $row['author'] . "&ret=" . $location;
            addnav("", $link);
        } else {
            $link = '';
        }
        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');
        $clanrankcolors = array(CLAN_APPLICANT => "`!", CLAN_MEMBER => "`#", CLAN_OFFICER => "`^", CLAN_LEADER => "`&", CLAN_FOUNDER => "`\$");
        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) {
                $op[$i] = str_replace("&amp;", "&", HTMLEntities(substr($row['comment'], 0, $x), ENT_COMPAT, getsetting("charset", "ISO-8859-1"))) . "`0" . ($link ? "<a href='{$link}' style='text-decoration: none'>\n" : "") . "`&{$row['name']}`0" . ($link ? "</a>" : "") . "\n`& " . 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] == "") {
            $op[$i] = "`0" . ($link ? "<a href='{$link}' style='text-decoration: none'>\n" : "") . "`&{$row['name']}`0" . ($link ? "</a>" : "") . "`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;
        }
        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 = "`7" . date($session['user']['prefs']['timeformat'], $time) . "`0 ";
            $op[$i] = $s . $op[$i];
        } elseif ($session['user']['prefs']['timestamp'] == 2) {
            $s = reltime(strtotime($row['postdate']));
            $op[$i] = "`7({$s})`0 " . $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];
        }
        $auth[$i] = $row['author'];
        $rawc[$i] = full_sanitize($rawc[$i]);
        $rawc[$i] = htmlentities($rawc[$i], ENT_QUOTES, getsetting("charset", "ISO-8859-1"));
    }
    $outputcomments = array();
    $sect = "x";
    for (; $i > -1; $i--) {
        $out = "";
        $out .= $op[$i];
        if (!array_key_exists($sect, $outputcomments) || !is_array($outputcomments[$sect])) {
            $outputcomments[$sect] = array();
        }
        array_push($outputcomments[$sect], $out);
    }
    ksort($outputcomments);
    reset($outputcomments);
    $sections = commentarylocs();
    while (list($sec, $v) = each($outputcomments)) {
        reset($v);
        while (list($key, $val) = each($v)) {
            $args = array('commentline' => $val);
            $args = modulehook("viewcommentary", $args);
            $val = $args['commentline'];
            output_notl($val, true);
        }
    }
    return $lastcommentid;
}
        output("Transfer how much: ");
        rawoutput("<input name='amount' id='amount' width='5' value='{$amt}'><br>");
        output("To: ");
        rawoutput("<input name='to' value='{$to}'>");
        output(" (partial names are ok, you will be asked to confirm the transaction before it occurs).`n");
        rawoutput("<input type='submit' class='button' value='{$msg}'></form>");
        rawoutput("<script language='javascript'>document.getElementById('amount').focus();</script>", true);
        addnav("", "bank.php?op=transfer2");
    } elseif (db_num_rows($result) > 1) {
        rawoutput("<form action='bank.php?op=transfer3' method='POST'>");
        output("`6Transfer `^%s`6 to ", $amt);
        rawoutput("<select name='to' class='input'>");
        $number = db_num_rows($result);
        for ($i = 0; $i < $number; $i++) {
            $row = db_fetch_assoc($result);
            rawoutput("<option value=\"" . HTMLEntities($row['login'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "\">" . full_sanitize($row['name']) . "</option>");
        }
        $msg = translate_inline("Complete Transfer");
        rawoutput("</select><input type='hidden' name='amount' value='{$amt}'><input type='submit' class='button' value='{$msg}'></form>", true);
        addnav("", "bank.php?op=transfer3");
    } else {
        output("`@Elessa`6 blinks at you from behind her spectacles, \"`@I'm sorry, but I can find no one matching that name who does business with our bank!  Please try again.`6\"");
    }
} elseif ($op == "transfer3") {
    $amt = abs((int) httppost('amount'));
    $to = httppost('to');
    output("`6`bTransfer Completion`b`n");
    if ($session['user']['gold'] + $session['user']['goldinbank'] < $amt) {
        output("`@Elessa`6 stands up to her full, but still diminutive height and glares at you, \"`@How can you transfer `^%s`@ gold when you only possess `^%s`@?`6\"", $amt, $session['user']['gold'] + $session['user']['goldinbank']);
    } else {
        $sql = "SELECT name,acctid,level,transferredtoday FROM " . db_prefix("accounts") . " WHERE login='******'";
         if ($row['superuser'] & SU_GIVES_YOM_WARNING && !($row['superuser'] & SU_OVERRIDE_YOM_WARNING)) {
             array_push($superusers, $row['login']);
         }
     } 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=\"mail.php?op=address&prepop=" . rawurlencode(stripslashes(htmlentities($to))) . "\">{$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);
     }
 }
 rawoutput("<script language='JavaScript'>\r\n\tvar superusers = new Array();");
 while (list($key, $val) = each($superusers)) {
     rawoutput("\tsuperusers['" . addslashes($val) . "'] = true;");
 }
 rawoutput("</script>");
 output("`2Subject:");
 rawoutput("<input name='subject' value=\"" . HTMLEntities($subject) . HTMLEntities(stripslashes(httpget('subject'))) . "\"><br>");
 rawoutput("<div id='warning' style='visibility: hidden; display: none;'>");
<?php

$apply = httpget('apply');
if ($apply == 1) {
    $ocn = httppost('clanname');
    $ocs = httppost('clanshort');
    $clanname = stripslashes($ocn);
    $clanname = full_sanitize($clanname);
    $clanname = preg_replace("'[^[:alpha:] \\'-]'", "", $clanname);
    $clanname = addslashes($clanname);
    httppostset('clanname', $clanname);
    $clanshort = full_sanitize($ocs);
    $clanshort = preg_replace("'[^[:alpha:]]'", "", $clanshort);
    httppostset('clanshort', $clanshort);
    $sql = "SELECT * FROM " . db_prefix("clans") . " WHERE clanname='{$clanname}'";
    $result = db_query($sql);
    $e = array(translate_inline("%s`7 looks over your form but informs you that your clan name must consist only of letters, spaces, apostrophes, or dashes.  Also, your short name can consist only of letters. She hands you a blank form."), translate_inline("%s`7 looks over your form but informs you that you must have at least 5 and no more than 50 characters in your clan's name (and they must consist only of letters, spaces, apostrophes, or dashes), then hands you a blank form."), translate_inline("%s`7 looks over your form but informs you that you must have at least 2 and no more than 5 characters in your clan's short name (and they must all be letters), then hands you a blank form."), translate_inline("%s`7 looks over your form but informs you that the clan name %s is already taken, and hands you a blank form."), translate_inline("%s`7 looks over your form but informs you that the short name %s is already taken, and hands you a blank form."), translate_inline("%s`7 asks for the %s gold to start the clan, but you seem to be unable to produce the fees."), translate_inline("%s`7 asks for the %s gold and %s gems to start the clan, but you seem to be unable to produce the fees."), translate_inline("%s`7 asks for the %s gems to start the clan, but you seem to be unable to produce the fees."), translate_inline("She takes your application, and stamps it \"`\$DENIED`7\"."));
    if ($clanname != $ocn || $clanshort != $ocs) {
        output_notl($e[0], $registrar);
        clanform();
        addnav("Return to the Lobby", "clan.php");
    } elseif (strlen($clanname) < 5 || strlen($clanname) > 50) {
        output_notl($e[1], $registrar);
        clanform();
        addnav("Return to the Lobby", "clan.php");
    } elseif (strlen($clanshort) < 2 || strlen($clanshort) > 5) {
        output_notl($e[2], $registrar);
        clanform();
        addnav("Return to the Lobby", "clan.php");
    } elseif (db_num_rows($result) > 0) {
        output_notl($e[3], $registrar, stripslashes($clanname));
        for ($i = 0; $i < db_num_rows($result); $i++) {
            $row = db_fetch_assoc($result);
            if ($row['c'] == 0) {
                $sql = "DELETE FROM " . db_prefix("clans") . " WHERE clanid={$row['clanid']}";
                db_query($sql);
            } else {
                /*//*/
                $row = modulehook("clan-applymember", $row);
                /*//*/
                if (isset($row['handled']) && $row['handled']) {
                    continue;
                }
                $memb_n = translate_inline("(%s members)");
                $memb_1 = translate_inline("(%s member)");
                if ($row['c'] == 1) {
                    $memb = sprintf($memb_1, $row['c']);
                } else {
                    $memb = sprintf($memb_n, $row['c']);
                }
                output_notl("&#149; <a href='clan.php?op=apply&to=%s'>%s</a> %s`n", $row['clanid'], full_sanitize(htmlentities($row['clanname'], ENT_COMPAT, getsetting("charset", "ISO-8859-1"))), $memb, true);
                addnav("", "clan.php?op=apply&to={$row['clanid']}");
            }
        }
        addnav("Return to the Lobby", "clan.php");
    } else {
        output("`7You ask %s`7 for a clan membership application form.", $registrar);
        output("She stares at you blankly for a few moments, then says, \"`5Sorry pal, no one has had enough gumption to start up a clan yet.  Maybe that should be you, eh?`7\"");
        addnav("Apply for a New Clan", "clan.php?op=new");
        addnav("Return to the Lobby", "clan.php");
    }
}
    } else {
        rawoutput("<input type='submit' name='block' value=\"{$snb}\" class='button'>");
    }
    rawoutput("</form>");
    rawoutput("</div>");
    rawoutput("<script language='JavaScript'>var hidearea = document.getElementById('hidearea');hidearea.style.visibility='hidden';hidearea.style.display='none';</script>", true);
    $e = translate_inline("Edit Clan Info");
    rawoutput("<a href='#' onClick='hidearea.style.visibility=\"visible\"; hidearea.style.display=\"inline\"; return false;'>{$e}</a>", true);
    output_notl("`n");
}
output_notl(nltoappon($row1['clandesc']));
if (nltoappon($row1['clandesc']) != "") {
    output("`n`n");
}
output("`0This is the current clan membership of %s < %s >:`n", $row1['clanname'], $row1['clanshort']);
page_header("Clan Membership for %s &lt;%s&gt;", full_sanitize($row1['clanname']), full_sanitize($row1['clanshort']));
addnav("Clan Options");
$rank = translate_inline("Rank");
$name = translate_inline("Name");
$dk = translate_inline("Dragon Kills");
$jd = translate_inline("Join Date");
rawoutput("<table border='0' cellpadding='2' cellspacing='0'>");
rawoutput("<tr class='trhead'><td>{$rank}</td><td>{$name}</td><td>{$dk}</td><td>{$jd}</td></tr>");
$i = 0;
$sql = "SELECT acctid,name,login,clanrank,clanjoindate,dragonkills FROM " . db_prefix("accounts") . " WHERE clanid={$detail} ORDER BY clanrank DESC,clanjoindate";
$result = db_query($sql);
$tot = 0;
//little hack with the hook...can't think of any other way
$ranks = array(CLAN_APPLICANT => "`!Applicant`0", CLAN_MEMBER => "`#Member`0", CLAN_OFFICER => "`^Officer`0", CLAN_LEADER => "`&Leader`0", CLAN_FOUNDER => "`\$Founder");
$args = modulehook("clanranks", array("ranks" => $ranks, "clanid" => $detail));
$ranks = translate_inline($args['ranks']);
function soap($input, $debug = false, $skiphook = false)
{
    global $session;
    require_once "lib/sanitize.php";
    $final_output = $input;
    // $output is the color code-less (fully sanitized) input against which
    // we search.
    $output = full_sanitize($input);
    // the mask of displayable chars that should be masked out;
    // X displays, _ masks.
    $mix_mask = str_pad("", strlen($output), "X");
    if (getsetting("soap", 1)) {
        $search = nasty_word_list();
        $exceptions = array_flip(good_word_list());
        $changed_content = false;
        while (list($key, $word) = each($search)) {
            do {
                if ($word > "") {
                    $times = preg_match_all($word, $output, $matches);
                } else {
                    $times = 0;
                }
                for ($x = 0; $x < $times; $x++) {
                    if (strlen($matches[0][$x]) < strlen($matches[1][$x])) {
                        $shortword = $matches[0][$x];
                        $longword = $matches[1][$x];
                    } else {
                        $shortword = $matches[1][$x];
                        $longword = $matches[0][$x];
                    }
                    if (isset($exceptions[strtolower($longword)])) {
                        $x--;
                        $times--;
                        if ($debug) {
                            output("This word is ok because it was caught by an exception: `b`^%s`7`b`n", $longword);
                        }
                    } else {
                        if ($debug) {
                            output("`7This word is not ok: \"`%%s`7\"; it blocks on the pattern `i%s`i at \"`\$%s`7\".`n", $longword, $word, $shortword);
                        }
                        // if the word should be filtered, drop it from the
                        // search terms ($output), and mask its bytes out of
                        // the output mask.
                        $len = strlen($shortword);
                        $pad = str_pad("", $len, "_");
                        //while (($p = strpos($output,$shortword))!==false){
                        $p = strpos($output, $shortword);
                        $output = substr($output, 0, $p) . $pad . substr($output, $p + $len);
                        $mix_mask = substr($mix_mask, 0, $p) . $pad . substr($mix_mask, $p + $len);
                        //}
                        $changed_content = true;
                    }
                    //end if
                }
                //end for
            } while ($times > 0);
        }
        $y = 0;
        //position within final output
        $pad = '#@%$!';
        for ($x = 0; $x < strlen($mix_mask); $x++) {
            while (substr($final_output, $y, 1) == "`") {
                $y += 2;
                //when encountering appo encoding, skip over it.
            }
            //this character should be masked out.
            if (substr($mix_mask, $x, 1) == "_") {
                $final_output = substr($final_output, 0, $y) . substr($pad, $x % strlen($pad), 1) . substr($final_output, $y + 1);
            }
            $y++;
        }
        if ($session['user']['superuser'] & SU_EDIT_COMMENTS && $changed_content) {
            output("`0The filter would have tripped on \"`#%s`0\" but since you're a moderator, I'm going to be lenient on you.  The text would have read, \"`#%s`0\"`n`n", $input, $final_output);
            return $input;
        } else {
            if ($changed_content && !$skiphook) {
                modulehook("censor", array("input" => $input));
            }
            return $final_output;
        }
    } else {
        return $final_output;
    }
}
function soap(string $input, bool $debug = false, bool $skiphook = false) : string
{
    global $session;
    require_once "lib/sanitize.php";
    require_once 'lib/sanitize.php';
    $final_output = $input;
    $output = full_sanitize($input);
    $mix_mask = str_pad('', strlen($output), 'X');
    if (getsetting('soap', 1)) {
        $search = nasty_word_list();
        $exceptions = array_flip(good_word_list());
        $changed_content = false;
        while (list($key, $word) = each($search)) {
            do {
                if ($word > '') {
                    $times = @preg_match_all($word, $output, $matches);
                } else {
                    $times = 0;
                }
                for ($x = 0; $x < $times; $x++) {
                    if (strlen($matches[0][$x]) < strlen($matches[1][$x])) {
                        $shortword = $matches[0][$x];
                        $longword = $matches[1][$x];
                    } else {
                        $shortword = $matches[1][$x];
                        $longword = $matches[0][$x];
                    }
                    if (isset($exceptions[strtolower($longword)])) {
                        $x--;
                        $times--;
                        if ($debug) {
                            output("This word is ok because it was caught by an exception: `b`^%s`7`b`n", $longword);
                        }
                    } else {
                        if ($debug) {
                            output("`7This word is not ok: \"`%%s`7\"; it blocks on the pattern `i%s`i at \"`\$%s`7\".`n", $longword, $word, $shortword);
                        }
                        $len = strlen($shortword);
                        $pad = str_pad('', $len, '_');
                        $p = strpos($output, $shortword);
                        $output = substr($output, 0, $p) . $pad . substr($output, $p + $len);
                        $mix_mask = substr($mix_mask, 0, $p) . $pad . substr($mix_mask, $p + $len);
                        $changed_content = true;
                    }
                }
            } while ($times > 0);
        }
        $y = 0;
        $pad = '#@%$!';
        for ($x = 0; $x < strlen($mix_mask); $x++) {
            while (substr($final_output, $y, 1) == '`') {
                $y += 2;
            }
            if (substr($mix_mask, $x, 1) == '_') {
                $final_output = substr($final_output, 0, $y) . substr($pad, $x % strlen($pad), 1) . substr($final_output, $y + 1);
            }
            $y++;
        }
        if ($session['user']['superuser'] & SU_EDIT_COMMENTS && $changed_content) {
            output("`0The filter would have tripped on \"`#%s`0\" but since you're a moderator, I'm going to be lenient on you.  The text would have read, \"`#%s`0\"`n`n", $input, $final_output);
            return $input;
        } else {
            if ($changed_content && !$skiphook) {
                modulehook('censor', ['input' => $input]);
            }
            return $final_output;
        }
    } else {
        return $final_output;
    }
}
$petition = modulehook('petition-form', ['header' => $petitionHeader, 'form' => $petitionForm, 'footnote' => $petitionFootNote]);
if (empty($post)) {
    output("`^%s `n`n`@%s`0 `n`Q%s`0", $petition['header'], $petition['form'], $petition['footnote'], true);
} else {
    $ip = substr($session['user']['lastip'], 0, -2);
    $sql = db_query("SELECT count(petitionid) AS count FROM {$petitions}\n        WHERE (ip LIKE '{$ip}%' OR id = '" . addslashes($_COOKIE['lgi']) . "')\n        AND date > '" . date('Y-m-d H:i:s', strtotime('-1 day')) . "'\n        AND status != '0'");
    $row = db_fetch_assoc($sql);
    if ($row['count'] >= 5 && !($session['user']['superuser'] & SU_EDIT_PETITIONS)) {
        output("`4We are sorry, but in an effort to keep spamming of the petitions to a minimum, we ask that users limit themselves to five petitions a day. Please try again tomorrow, or when one of your current issues is resolved.");
    } else {
        $date = date('Y-m-d H:i:s');
        $post['cancelpetition'] = false;
        $post['cancelreason'] = '';
        $post = modulehook('addpetition', $post);
        if ($post['cancelpetition'] == true) {
            output($post['cancelreason']);
        } else {
            db_query("INSERT INTO {$petitions} (author, date, body, pageinfo, ip, id)\n                VALUES ('{$session['user']['acctid']}', '{$date}', '" . addslashes($post['body']) . "', '" . addslashes($sessionJson) . "', '{$ip}', '" . addslashes($_COOKIE['lgi']) . "')");
            invalidatedatacache('petition_counts');
            output("`@Your petition has been sent!`n");
            output("As soon as the administration sees your petition for help, they will answer it immediately. Please give time for them to handle your issue and have a nice day!");
            if (getsetting('emailpetitions', 0)) {
                $name = translate_inline(full_sanitize($post['name']));
                $url = getsetting('serverurl', 'http://lotgd.net');
                $body = translate_inline($post['body']);
                mail(getsetting('gameadminemail', '*****@*****.**'), "New petition from {$name}!", $body);
            }
        }
    }
}
popup_footer();
function claneditor_run()
{
    global $session;
    tlschema("claneditor");
    $dt = httpget("dt");
    $op = httpget('op');
    if ($dt != "") {
        $sql = "SELECT * FROM " . db_prefix("clans") . " WHERE clanid='{$dt}'";
        $result = db_query($sql);
        $claninfo = db_fetch_assoc($result);
        if (db_num_rows($result) == 0) {
            $op = "";
        }
    }
    addcommentary();
    $ranks = array(CLAN_APPLICANT => "`!Applicant`0", CLAN_MEMBER => "`#Member`0", CLAN_OFFICER => "`^Officer`0", CLAN_LEADER => "`&Leader`0", CLAN_FOUNDER => "`\$Founder");
    $args = modulehook("clanranks", array("ranks" => $ranks, "clanid" => $dt));
    $ranks = translate_inline($args['ranks'], "clan");
    superusernav();
    addnav("Clans");
    addnav("List Clans", "runmodule.php?module=claneditor&op=list");
    addnav("Create a New Clan", "runmodule.php?module=claneditor&op=new");
    if ($op == "" || $op == "list") {
        page_header("Clan Listing");
        rawoutput("<table border='0' padding='0'><tr><td>");
        $sql = "SELECT MAX(" . db_prefix("clans") . ".clanid) AS clanid, MAX(clanname) AS clanname,count(" . db_prefix("accounts") . ".acctid) AS c FROM " . db_prefix("clans") . " LEFT JOIN " . db_prefix("accounts") . " ON " . db_prefix("clans") . ".clanid=" . db_prefix("accounts") . ".clanid AND clanrank>" . CLAN_APPLICANT . " GROUP BY " . db_prefix("clans") . ".clanid ORDER BY c DESC";
        $result = db_query($sql);
        if (db_num_rows($result) > 0) {
            output("`%Karissa`7 steps in as if by magic, listing the clans for you.`n");
            output("`@`bList of Clans:`b`0`n`n");
            $v = 0;
            $memb_n = translate_inline("(%s members)");
            $memb_1 = translate_inline("(%s member)");
            rawoutput('<table cellspacing="0" cellpadding="2" align="left">');
            output_notl("<tr class='trhead'><td>%s</td><td>%s</td></tr>", translate_inline("`b`&Name of Clan`b"), translate_inline("`&`iNumber of Members`i"), true);
            for ($i = 0; $i < db_num_rows($result); $i++) {
                $row = db_fetch_assoc($result);
                if ($row['c'] == 0) {
                    $sql = "DELETE FROM " . db_prefix("clans") . " WHERE clanid={$row['clanid']}";
                    db_query($sql);
                } else {
                    rawoutput('<tr class="' . ($v % 2 ? "trlight" : "trdark") . '"><td>', true);
                    if ($row['c'] == 1) {
                        $memb = sprintf($memb_1, $row['c']);
                    } else {
                        $memb = sprintf($memb_n, $row['c']);
                    }
                    output_notl("&#149; <a href='runmodule.php?module=claneditor&op=mview&dt=%s'>%s</a></td><td>%s`n", $row['clanid'], full_sanitize(htmlentities($row['clanname']), ENT_COMPAT, getsetting("charset", "ISO-8859-1")), $memb, true);
                    rawoutput('</td></tr>');
                    addnav("", "runmodule.php?module=claneditor&op=mview&dt={$row['clanid']}");
                    $v++;
                }
            }
            rawoutput("</table>", true);
        } else {
            output("`7There are no clans in the database.`n`c");
        }
        rawoutput("</td></tr><tr><td>");
        output_notl("<br>[<a href='runmodule.php?module=claneditor&op=new'>%s</a>]", translate_inline("Create a New Clan"), true);
        addnav("", "runmodule.php?module=claneditor&op=new");
        rawoutput("</td></tr></table>");
        page_footer();
    } elseif ($op == "new") {
        page_header("Clan Creation");
        $apply = httpget('apply');
        if ($apply == 1) {
            $id = httpget("id");
            $ocn = httppost('clanname');
            $ocs = httppost('clanshort');
            $clanname = stripslashes($ocn);
            $clanname = full_sanitize($clanname);
            $clanname = preg_replace("'[^[:alpha:] \\'-]'", "", $clanname);
            $clanname = addslashes($clanname);
            httppostset('clanname', $clanname);
            $clanshort = full_sanitize($ocs);
            $clanshort = preg_replace("'[^[:alpha:]]'", "", $clanshort);
            httppostset('clanshort', $clanshort);
            $sql = "SELECT * FROM " . db_prefix("clans") . " WHERE clanname='{$clanname}'";
            $result = db_query($sql);
            $e = translate_inline("`%Karissa`7 hands you a form to start a clan.");
            $e1 = translate_inline("`%Karissa`7 looks over your form but informs you that your clan name must consist only of letters, spaces, apostrophes, or dashes.  Also, your short name can consist only of letters. She hands you a blank form.");
            $e2 = translate_inline("`%Karissa`7 looks over your form but informs you that you must have at least 5 and no more than 50 characters in your clan's name (and they must consist only of letters, spaces, apostrophes, or dashes), then hands you a blank form.");
            $e3 = translate_inline("`%Karissa`7 looks over your form but informs you that you must have at least 2 and no more than 5 characters in your clan's short name (and they must all be letters), then hands you a blank form.");
            $e4 = translate_inline("`%Karissa`7 looks over your form but informs you that the clan name %s is already taken, and hands you a blank form.");
            $e5 = translate_inline("`%Karissa`7 looks over your form but informs you that the short name %s is already taken, and hands you a blank form.");
            if ($ocs == "" && $ocn == "" && !httppostisset('clanname') && !httppostisset('clanshort')) {
                output_notl($e);
                clanform();
            } elseif ($clanname != $ocn || $clanshort != $ocs) {
                output_notl($e1);
                clanform();
            } elseif (strlen($clanname) < 5 || strlen($clanname) > 50) {
                output_notl($e2);
                clanform();
            } elseif (strlen($clanshort) < 2 || strlen($clanshort) > 5) {
                output_notl($e3);
                clanform();
            } elseif (db_num_rows($result) > 0) {
                output_notl($e4, stripslashes($clanname));
                clanform();
            } else {
                $sql = "SELECT * FROM " . db_prefix("clans") . " WHERE clanshort='{$clanshort}'";
                $result = db_query($sql);
                if (db_num_rows($result) > 0) {
                    output_notl($e5, stripslashes($clanshort));
                    clanform();
                } else {
                    $sql = "INSERT INTO " . db_prefix("clans") . " (clanname,clanshort) VALUES ('{$clanname}','{$clanshort}')";
                    db_query($sql);
                    $clid = db_insert_id();
                    $sql = "UPDATE " . db_prefix("accounts") . " SET clanid='{$clid}',clanrank='" . CLAN_LEADER . "' WHERE acctid='{$id}'";
                    db_query($sql);
                    $subj = "New Clan!";
                    $msg = array("%s`0`^ has made you a new clan!", $session['user']['name']);
                    systemmail($id, $subj, $msg);
                    output("`%Karissa`7 looks over your form, and finding that everything seems to be in order, she takes your fees, stamps the form \"`\$APPROVED`7\" and files it in a drawer.`n`n");
                    output("Congratulations, you've created a new clan named %s!", stripslashes($clanname));
                }
            }
        } elseif ($apply == 0) {
            clanuserform();
        } else {
            output("`7You teleport to the Clan Hall...");
            output("`7You approach `%Karissa`7 and mention that you would like to start a new clan.");
            output("She tells you that there are three requirements to starting a clan.");
            output("First, you have to decide on a full name for your clan.");
            output("Second, you have to decide on an abbreviation for your clan.");
            output("Third you have to decide on the person that should run the clan.");
            $e = translate_inline("`n`n\"`5If you're ok with these three requirements, please fill out the following form,`7\" she says, handing you a sheet of paper.");
            output_notl($e);
            clanuserform();
        }
    } else {
        if ($op != "deleteclan") {
            page_header("The Clan of %s", full_sanitize($claninfo['clanname']));
            output("`n`c`^`bThe Clan of %s`b`c`n`n", full_sanitize($claninfo['clanname']));
        } else {
            page_header("Clan Deletion");
        }
        if ($op == "mview") {
            $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid={$claninfo['motdauthor']}";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            $motdauthname = $row['name'];
            $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid={$claninfo['descauthor']}";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            $descauthname = $row['name'];
            output("`&`bCurrent MoTD:`b `#by %s`2`n", $motdauthname);
            output_notl(nltoappon($claninfo['clanmotd']) . "`n`n");
            commentdisplay("", "clan-{$claninfo['clanid']}", "Speak into their Clan", 25, "projects");
            output_notl("`n`n");
            modulehook("collapse{", array("name" => "collapsedesc"));
            output("`&`bCurrent Description:`b `#by %s`2`n", $descauthname);
            output_notl(nltoappon($claninfo['clandesc']) . "`n");
            modulehook("}collapse");
            $sql = "SELECT count(*) AS c, clanrank FROM " . db_prefix("accounts") . " WHERE clanid={$claninfo['clanid']} GROUP BY clanrank DESC";
            $result = db_query($sql);
            // begin collapse
            modulehook("collapse{", array("name" => "clanmemberdet"));
            output("`n`bMembership Details:`b`n");
            $leaders = 0;
            while ($row = db_fetch_assoc($result)) {
                output_notl($ranks[$row['clanrank']] . ": " . $row['c'] . "`n");
                if ($row['clanrank'] >= CLAN_OFFICER) {
                    $leaders += $row['c'];
                }
            }
            output("`n");
            $noleader = translate_inline("`^There is currently no leader!  Promoting %s`^ to leader as they are the highest ranking member (or oldest member in the event of a tie).`n`n");
            if ($leaders == 0) {
                //There's no leader here, probably because the leader's account
                //expired.
                $sql = "SELECT name,acctid,clanrank FROM " . db_prefix("accounts") . " WHERE clanid={$dt} ORDER BY clanrank DESC, clanjoindate";
                $result = db_query($sql);
                $row = db_fetch_assoc($result);
                $sql = "UPDATE " . db_prefix("accounts") . " SET clanrank=" . CLAN_LEADER . " WHERE acctid='" . $row['acctid'] . "'";
                db_query($sql);
                output_notl($noleader, $row['name']);
            }
            // end collapse
            modulehook("}collapse");
        } elseif ($op == "deleteclan") {
            if (httpget("sop") == "yes") {
                //notify users of the deletion of the clan
                $sql = "SELECT acctid FROM " . db_prefix("accounts") . " WHERE clanid={$dt}";
                $result = db_query($sql);
                $subj = array("Deletion of %s", $claninfo['clanname']);
                $msg = array("The clan you were in, %s, has closed its doors.\nSorry for any inconvenience.", $claninfo['clanname']);
                while ($row = db_fetch_assoc($result)) {
                    systemmail($row['acctid'], $subj, $msg);
                }
                //change the clan if a user is in this clan
                $sql = "UPDATE " . db_prefix("accounts") . " SET clanid=0,clanrank=" . CLAN_APPLICANT . ",clanjoindate='0000-00-00 00:00:00' WHERE clanid={$dt}";
                db_query($sql);
                //change the current users clan if this user was in that clan
                if ($session['user']['clanid'] == $dt) {
                    $session['user']['clanid'] = 0;
                    $session['user']['clanrank'] = CLAN_APPLICANT;
                    $session['user']['clanjoindate'] = '0000-00-00 00:00:00';
                }
                //drop the clan.
                $sql = "DELETE FROM " . db_prefix("clans") . " WHERE clanid={$dt}";
                db_query($sql);
                module_delete_objprefs('clans', $dt);
                $op = "";
                httpset("op", "");
                unset($claninfo);
                $dt = "";
                output("That clan has been wiped.`n");
                output("`@Users within the clan have been notified.");
            } else {
                output("`%`c`bAre you SURE you want to delete this clan?`b`c`n");
                $dc = translate_inline("Delete this clan? Are you sure!");
                rawoutput("[<a href='runmodule.php?module=claneditor&op=deleteclan&sop=yes&dt={$dt}' onClick='return confirm(\"{$dc}\");'>{$dc}</a>]");
                addnav("", "runmodule.php?module=claneditor&op=deleteclan&sop=yes&dt={$dt}");
            }
        } elseif ($op == "editmodule" || $op == "editmodulesave") {
            $mdule = httpget("mdule");
            if ($op == "editmodulesave") {
                // Save module prefs
                $post = httpallpost();
                reset($post);
                while (list($key, $val) = each($post)) {
                    set_module_objpref("clans", $dt, $key, $val, $mdule);
                }
                output("`^Saved!`0`n");
            }
            rawoutput("<form action='runmodule.php?module=claneditor&op=editmodulesave&dt={$dt}&mdule={$mdule}' method='POST'>");
            module_objpref_edit("clans", $mdule, $dt);
            rawoutput("</form>");
            addnav("", "runmodule.php?module=claneditor&op=editmodulesave&dt={$dt}&mdule={$mdule}");
        } elseif ($op == "updinfo") {
            page_header("Update Clan Information");
            $clanmotd = substr(httppost('clanmotd'), 0, 4096);
            if (httppostisset('clanmotd') && $clanmotd != $claninfo['clanmotd']) {
                if ($clanmotd == "") {
                    $mauthor = 0;
                } else {
                    $mauthor = $session['user']['acctid'];
                }
                $sql = "UPDATE " . db_prefix("clans") . " SET clanmotd='{$clanmotd}',motdauthor={$mauthor} WHERE clanid={$claninfo['clanid']}";
                db_query($sql);
                invalidatedatacache("clandata-{$claninfo['clanid']}");
                $claninfo['clanmotd'] = stripslashes($clanmotd);
                output("Updating MoTD`n");
                $claninfo['motdauthor'] = $mauthor;
            }
            $clandesc = httppost('clandesc');
            if (httppostisset('clandesc') && $clandesc != $claninfo['clandesc']) {
                if ($clandesc == "") {
                    $claninfo['descauthor'] = 0;
                    $dauthor = 0;
                } else {
                    $dauthor = $session['user']['acctid'];
                }
                $sql = "UPDATE " . db_prefix("clans") . " SET clandesc='" . addslashes(substr(stripslashes($clandesc), 0, 4096)) . "',descauthor={$dauthor} WHERE clanid={$claninfo['clanid']}";
                db_query($sql);
                invalidatedatacache("clandata-{$claninfo['clanid']}");
                output("Updating description`n");
                $claninfo['clandesc'] = stripslashes($clandesc);
                $claninfo['descauthor'] = $session['user']['acctid'];
            }
            $customsay = httppost('customsay');
            if (httppostisset('customsay') && $customsay != $claninfo['customsay']) {
                $sql = "UPDATE " . db_prefix("clans") . " SET customsay='{$customsay}' WHERE clanid={$claninfo['clanid']}";
                db_query($sql);
                invalidatedatacache("clandata-{$claninfo['clanid']}");
                output("Updating custom say line`n");
                $claninfo['customsay'] = stripslashes($customsay);
            }
            $clanname = httppost('clanname');
            if ($clanname) {
                $clanname = full_sanitize($clanname);
            }
            $clanshort = httppost('clanshort');
            if ($clanshort) {
                $clanshort = full_sanitize($clanshort);
            }
            if (httppostisset('clanname') && $clanname != $claninfo['clanname']) {
                $sql = "UPDATE " . db_prefix("clans") . " SET clanname='{$clanname}' WHERE clanid={$claninfo['clanid']}";
                output("Updating the clan name`n");
                db_query($sql);
                invalidatedatacache("clandata-{$detail}");
                $claninfo['clanname'] = $clanname;
            }
            if (httppostisset('clanshort') && $clanshort != $claninfo['clanshort']) {
                $sql = "UPDATE " . db_prefix("clans") . " SET clanshort='{$clanshort}' WHERE clanid={$claninfo['clanid']}";
                output("Updating the short clan name`n");
                db_query($sql);
                invalidatedatacache("clandata-{$detail}");
                $claninfo['clanshort'] = $clanshort;
            }
            $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid={$claninfo['motdauthor']}";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            $motdauthname = $row['name'];
            $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid={$claninfo['descauthor']}";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            $descauthname = $row['name'];
            output("`&`bCurrent MoTD:`b `#by %s`2`n", $motdauthname);
            output_notl(nltoappon($claninfo['clanmotd']) . "`n");
            output("`&`bCurrent Description:`b `#by %s`2`n", $descauthname);
            output_notl(nltoappon($claninfo['clandesc']) . "`n");
            rawoutput("<form action='runmodule.php?module=claneditor&op=updinfo&dt={$dt}' method='POST'>");
            addnav("", "runmodule.php?module=claneditor&op=updinfo&dt={$dt}");
            output("`&`bMoTD:`b `7(4096 chars)`n");
            rawoutput("<textarea name='clanmotd' cols='50' rows='10'>" . htmlentities($claninfo['clanmotd'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "</textarea><br>");
            output("`bRenaming:`b`n");
            output("`iLong Name:`i ");
            rawoutput("<input name='clanname' value=\"" . htmlentities($claninfo['clanname'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "\" maxlength=50 size=50>");
            output("`n`iShort Name:`i ");
            rawoutput("<input name='clanshort' value=\"" . htmlentities($claninfo['clanshort'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "\" maxlength=5 size=5>");
            output_notl("`n");
            output("`n`&`bDescription:`b `7(4096 chars)`n");
            if (httppost('block') > "") {
                $blockdesc = translate_inline("Description blocked for inappropriate usage.");
                $sql = "UPDATE " . db_prefix("clans") . " SET descauthor=4294967295, clandesc='{$blockdesc}' where clanid='" . $claninfo['clanid'] . "'";
                output("Blocking public description`n");
                db_query($sql);
                invalidatedatacache("clandata-" . $claninfo['clanid'] . "");
                $claninfo['blockdesc'] = "";
                $claninfo['descauthor'] = 4294967295.0;
            } elseif (httppost('unblock') > "") {
                $sql = "UPDATE " . db_prefix("clans") . " SET descauthor=0, clandesc='' where clanid='" . $claninfo['clanid'] . "'";
                output("Unblocking public description`n");
                db_query($sql);
                invalidatedatacache("clandata-" . $claninfo['clanid'] . "");
                $claninfo['clandesc'] = "";
                $claninfo['descauthor'] = 0;
            }
            $blocked = translate_inline("The clan has been blocked from posting a description.`n");
            if ($claninfo['descauthor'] == 4294967295.0) {
                output_notl("`b`%" . $blocked . "`b");
            }
            rawoutput("<textarea name='clandesc' cols='50' rows='10'>" . htmlentities($claninfo['clandesc'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "</textarea><br>");
            output("`n`&`bCustom Talk Line`b `7(blank means \"says\" -- 15 chars max)`n");
            rawoutput("<input name='customsay' value=\"" . htmlentities($claninfo['customsay'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "\" maxlength=\"15\"><br/>");
            $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"));
            if ($claninfo['descauthor'] == "4294967295") {
                rawoutput("<input type='submit' name='unblock' value=\"{$snu}\" class='button'>");
            } else {
                rawoutput("<input type='submit' name='block' value=\"{$snb}\" class='button'>");
            }
            rawoutput("</form>");
        } elseif ($op == "membership") {
            output("This is the clans current membership:`n");
            $setrank = httpget('setrank');
            $who = httpget('who');
            if ($setrank > "") {
                $sql = "UPDATE " . db_prefix("accounts") . " SET clanrank={$setrank} WHERE login='******'";
                db_query($sql);
            }
            $remove = httpget('remove');
            if ($remove > "") {
                $sql = "UPDATE " . db_prefix("accounts") . " SET clanrank=" . CLAN_APPLICANT . ",clanid=0,clanjoindate='0000-00-00 00:00:00' WHERE login='******' AND clanrank<={$session['user']['clanrank']}";
                db_query($sql);
                //delete unread application emails from this user.
                //breaks if the applicant has had their name changed via
                //dragon kill, superuser edit, or lodge color change
                $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE login='******'";
                $row = db_fetch_assoc(db_query($sql));
                $subj = serialize(array($apply_short, $row['name']));
                $sql = "DELETE FROM " . db_prefix("mail") . " WHERE msgfrom=0 AND seen=0 AND subject='{$subj}'";
                db_query($sql);
            }
            $sql = "SELECT acctid,name,login,clanrank,laston,clanjoindate,dragonkills,level FROM " . db_prefix("accounts") . " WHERE clanid={$claninfo['clanid']} ORDER BY clanrank DESC,clanjoindate";
            $result = db_query($sql);
            rawoutput("<table border='0' cellpadding='2' cellspacing='0'>");
            $rank = translate_inline("Rank");
            $name = translate_inline("Name");
            $lev = translate_inline("Level");
            $dk = translate_inline("Dragon Kills");
            $jd = translate_inline("Join Date");
            $lo = translate_inline("Last On");
            $ops = translate_inline("Operations");
            $promote = translate_inline("Promote");
            $demote = translate_inline("Demote");
            $remove = translate_inline("Remove From The Clan");
            $confirm = translate_inline("Are you sure you wish to remove this member from the clan?");
            rawoutput("<tr class='trhead'><td>{$rank}</td><td>{$name}</td><td>{$lev}</td><td>{$dk}</td><td>{$jd}</td><td>{$lo}</td>" . ($session['user']['clanrank'] > CLAN_MEMBER ? "<td>{$ops}</td>" : "") . "</tr>", true);
            $i = 0;
            $tot = 0;
            while ($row = db_fetch_assoc($result)) {
                $i++;
                $tot += $row['dragonkills'];
                rawoutput("<tr class='" . ($i % 2 ? "trlight" : "trdark") . "'>");
                rawoutput("<td>");
                output_notl($ranks[$row['clanrank']]);
                rawoutput("</td><td>");
                $link = "bio.php?char=" . $row['acctid'] . "&ret=" . urlencode($_SERVER['REQUEST_URI']);
                rawoutput("<a href='{$link}'>", true);
                addnav("", $link);
                output_notl("`&%s`0", $row['name']);
                rawoutput("</a>");
                rawoutput("</td><td align='center'>");
                output_notl("`^%s`0", $row['level']);
                rawoutput("</td><td align='center'>");
                output_notl("`\$%s`0", $row['dragonkills']);
                rawoutput("</td><td>");
                output_notl("`3%s`0", $row['clanjoindate']);
                rawoutput("</td><td>");
                output_notl("`#%s`0", reltime(strtotime($row['laston'])));
                rawoutput("</td>");
                rawoutput("<td>");
                rawoutput("[ <a href='runmodule.php?module=claneditor&op=membership&dt={$dt}&setrank=" . ($row['clanrank'] + 1) . "&who=" . rawurlencode($row['login']) . "'>{$promote}</a> | ");
                addnav("", "runmodule.php?module=claneditor&op=membership&dt={$dt}&setrank=" . ($row['clanrank'] + 1) . "&who=" . rawurlencode($row['login']));
                rawoutput("<a href='runmodule.php?module=claneditor&op=membership&dt={$dt}&setrank=" . ($row['clanrank'] - 1) . "&who=" . rawurlencode($row['login']) . "'>{$demote}</a> | ");
                addnav("", "runmodule.php?module=claneditor&op=membership&dt={$dt}&setrank=" . ($row['clanrank'] - 1) . "&who=" . rawurlencode($row['login']));
                rawoutput("<a href='runmodule.php?module=claneditor&op=membership&dt={$dt}&remove=" . rawurlencode($row['login']) . "' onClick=\"return confirm('{$confirm}');\">{$remove}</a> ]");
                addnav("", "runmodule.php?module=claneditor&op=membership&dt={$dt}&remove=" . rawurlencode($row['login']));
                rawoutput("</td>");
                rawoutput("</tr>");
            }
            rawoutput("</table>");
            output("`n`n`^This clan has a total of `\$%s`^ dragon kills.", $tot);
        }
        if ($dt != "" && isset($claninfo)) {
            addnav("Clan Options");
            addnav("Main View", "runmodule.php?module=claneditor&op=mview&dt={$dt}");
            addnav("Update Clan Information", "runmodule.php?module=claneditor&op=updinfo&dt={$dt}");
            addnav("Delete this Clan", "runmodule.php?module=claneditor&op=deleteclan&dt={$dt}");
            addnav("Update Members", "runmodule.php?module=claneditor&op=membership&dt={$dt}");
            addnav("Module Prefs");
            module_editor_navs("prefs-clans", "runmodule.php?module=claneditor&op=editmodule&dt=" . $claninfo['clanid'] . "&mdule=");
        }
    }
    page_footer();
}
    $tconfirm = translate_inline("Confirm");
    output("`QBefore your answer passes through your lips he continues `#\"`3Oh, I see you only got one.`#\"`n`n");
    output("`#\"`3So, we will deliver it to your dwelling `5%s`3, right?`#\"", $name);
    rawoutput("<form action='runmodule.php?module=dwitems&op=buy2' method='POST'>");
    rawoutput("<input type='hidden' name='id' value='{$itemid}'>");
    rawoutput("<input type='hidden' name='dwid' value='{$dwid}'>");
    rawoutput("<input type='submit' class='button' value='{$tconfirm}'></form>");
    addnav("", "runmodule.php?module=dwitems&op=buy2");
} else {
    rawoutput("<form action='runmodule.php?module=dwitems&op=buy2' method='POST'>");
    output("`QSend it to ");
    rawoutput("<select name='dwid' class='input'>");
    $number = db_num_rows($result);
    for ($i = 0; $i < $number; $i++) {
        $row = db_fetch_assoc($result);
        if ($row['name'] == "") {
            $name = translate_inline("Unnamed");
        } else {
            require_once "lib/sanitize.php";
            $name = full_sanitize($row['name']);
        }
        rawoutput("<option value='" . $row['dwid'] . "'>" . $name . "</option>");
    }
    $tsubmit = translate_inline("Submit");
    rawoutput("</select>");
    rawoutput("<input type='hidden' name='id' value='{$itemid}'>");
    rawoutput("<input type='submit' class='button' value='{$tsubmit}'></form>", true);
    addnav("", "runmodule.php?module=dwitems&op=buy2");
}
addnav("Back to the store", "runmodule.php?module=dwitems&op=shop");
addnav("Return to the city", "village.php");
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 ***
}
    output("`iClosed`i petitions are for you have dealt with an issue, these will auto delete when they have been closed for 7 days.");
    modulehook("petitions-descriptions", array());
    rawoutput("</li></ul>");
} elseif ($op == "view") {
    $viewpageinfo = (int) httpget("viewpageinfo");
    if ($viewpageinfo == 1) {
        addnav("Hide Details", "viewpetition.php?op=view&id={$id}}");
    } else {
        addnav("D?Show Details", "viewpetition.php?op=view&id={$id}&viewpageinfo=1");
    }
    addnav("V?Petition Viewer", "viewpetition.php");
    addnav("User Ops");
    addnav("Petition Ops");
    reset($statuses);
    while (list($key, $val) = each($statuses)) {
        $plain = full_sanitize($val);
        addnav(array("%s?Mark %s", substr($plain, 0, 1), $val), "viewpetition.php?setstat={$key}&id={$id}");
    }
    $sql = "SELECT " . db_prefix("accounts") . ".name," . db_prefix("accounts") . ".login," . db_prefix("accounts") . ".acctid," . "date,closedate,status,petitionid,ip,body,pageinfo," . "accts.name AS closer FROM " . db_prefix("petitions") . " LEFT JOIN " . db_prefix("accounts ") . "ON " . db_prefix("accounts") . ".acctid=author LEFT JOIN " . db_prefix("accounts") . " AS accts ON accts.acctid=" . "closeuserid WHERE petitionid='{$id}' ORDER BY date ASC";
    $result = db_query($sql);
    $row = db_fetch_assoc($result);
    addnav("User Ops");
    if (isset($row['login'])) {
        addnav("View User Biography", "bio.php?char=" . $row['acctid'] . "&ret=%2Fviewpetition.php%3Fop%3Dview%26id=" . $id);
    }
    if ($row['acctid'] > 0 && $session['user']['superuser'] & SU_EDIT_USERS) {
        addnav("User Ops");
        addnav("R?Edit User Record", "user.php?op=edit&userid={$row['acctid']}&returnpetition={$id}");
    }
    if ($row['acctid'] > 0 && $session['user']['superuser'] & SU_EDIT_DONATIONS) {
        addnav("User Ops");
     //test if the file is a valid module or a lib file/whatever that got in, maybe even malcode that does not have module form
     $shortnamelower = strtolower($shortname);
     $file = strtolower(file_get_contents("modules/{$shortname}.php"));
     if (strpos($file, $shortnamelower . "_getmoduleinfo") === false || strpos($file, $shortnamelower . "_install") === false || strpos($file, $shortnamelower . "_uninstall") === false) {
         //here the files has neither do_hook nor getinfo, which means it won't execute as a module here --> block it + notify the admin who is the manage modules section
         $temp = array_merge($invalidmodule, array("name" => $shortname . ".php " . appoencode(translate_inline("(`\$Invalid Module! Contact Author or check file!`0)"))));
     } else {
         $temp = get_module_info($shortname);
     }
     //end of testing
     if (!$temp || empty($temp)) {
         continue;
     }
     $temp['shortname'] = $shortname;
     array_push($moduleinfo, $temp);
     array_push($sortby, full_sanitize($temp[$sorting]));
     array_push($numberarray, $count);
     $count++;
 }
 array_multisort($sortby, $order ? SORT_DESC : SORT_ASC, $numberarray, $order ? SORT_DESC : SORT_ASC);
 for ($a = 0; $a < count($moduleinfo); $a++) {
     $i = $numberarray[$a];
     rawoutput("<tr class='" . ($i % 2 ? "trlight" : "trdark") . "'>");
     if (isset($moduleinfo[$i]['invalid']) && $moduleinfo[$i]['invalid'] === true) {
         rawoutput("<td></td><td nowrap valign='top'>");
         output("Not installable");
         rawoutput("</td>");
     } else {
         rawoutput("<td><input type='checkbox' name='module[]' value='{$moduleinfo[$i]['shortname']}'></td>");
         rawoutput("<td nowrap valign='top'>");
         rawoutput("[ <a href='modules.php?op=install&module={$moduleinfo[$i]['shortname']}&cat={$moduleinfo[$i]['category']}'>");
        httpset('prepop', $to, true);
        rawoutput("</form>");
        require_once 'lib/mail/case_address.php';
        popup_footer();
    } else {
        if ($numRows > 1) {
            output_notl("<select name='to' id='to' onchange='check_su_warning();'>", true);
        }
    }
    while ($row = db_fetch_assoc($sql)) {
        if ($numRows == 1) {
            rawoutput("<input type='hidden' name='to' id='to' value='{$row['login']}'>");
            output_notl("{$row['name']}`0`n");
        } else {
            $rowNum++;
            $row['name'] = htmlent(full_sanitize($row['name']));
            output_notl("<option value='%s' data-superuser='******'>%s</option>", $row['login'], $row['superuser'], $row['name'], true);
            if ($numRows == $rowNum) {
                output_notl("</select>`0`n", true);
            }
            if ($row['superuser'] & SU_GIVES_YOM_WARNING && !($row['superuser'] & SU_OVERRIDE_YOM_WARNING)) {
                array_push($superusers, $row['login']);
                debug('su');
            }
        }
    }
}
rawoutput("<script type='text/javascript'>var superusers = new Array();");
foreach ($superusers as $val) {
    rawoutput(" superusers['" . addslashes($val) . "'] = true;");
}
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 rss_xmlencode($input)
{
    require_once "lib/sanitize.php";
    return str_replace(array("&", "<", ">"), array("&amp;", "&lt;", "&gt;"), full_sanitize($input));
}
    $return = cmd_sanitize($ret);
}
$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']));
    tlschema("nav");
    addnav("Return");
    tlschema();
    if ($session['user']['superuser'] & SU_EDIT_USERS) {
        addnav("Superuser");
        addnav("Edit User", "user.php?op=edit&userid={$id}");
    }
    modulehook("biotop", $target);
    output("`^Biography for %s`^.", $target['name']);
    $write = translate_inline("Write Mail");
    if ($session['user']['loggedin']) {
        rawoutput("<a href=\"mail.php?op=write&to={$target['login']}\" target=\"_blank\" onClick=\"" . popup("mail.php?op=write&to={$target['login']}") . ";return false;\"><img src='images/newscroll.GIF' width='16' height='16' alt='{$write}' border='0'></a>");
    }
    output_notl("`n`n");
    if ($target['clanname'] > "" && getsetting("allowclans", false)) {
/**
 * Brings all the output elements together and terminates the rendering of the page.  Saves the current user info and updates the rendering statistics
 * Hooks provided:
 *	footer-{$script name}
 *	everyfooter
 *
 */
function page_footer($saveuser = true)
{
    global $output, $nestedtags, $header, $nav, $session, $REMOTE_ADDR, $REQUEST_URI, $pagestarttime, $quickkeys, $template, $y2, $z2, $logd_version, $copyright, $SCRIPT_NAME, $nopopups, $footer, $dbinfo;
    $z = $y2 ^ $z2;
    $footer = $template['footer'];
    //page footer module hooks
    $script = substr($SCRIPT_NAME, 0, strpos($SCRIPT_NAME, "."));
    $replacementbits = array();
    $replacementbits = modulehook("footer-{$script}", $replacementbits);
    if ($script == "runmodule" && ($module = httpget('module')) > "") {
        // This modulehook allows you to hook directly into any module without
        // the need to hook into footer-runmodule and then checking for the
        // required module.
        modulehook("footer-{$module}", $replacementbits);
    }
    // Pass the script file down into the footer so we can do something if
    // we need to on certain pages (much like we do on the header.
    // Problem is 'script' is a valid replacement token, so.. use an
    // invalid one which we can then blow away.
    $replacementbits['__scriptfile__'] = $script;
    $replacementbits = modulehook("everyfooter", $replacementbits);
    if ($session['user']['loggedin']) {
        $replacementbits = modulehook("everyfooter-loggedin", $replacementbits);
    }
    unset($replacementbits['__scriptfile__']);
    //output any template part replacements that above hooks need (eg,
    //advertising)
    reset($replacementbits);
    while (list($key, $val) = each($replacementbits)) {
        $header = str_replace("{" . $key . "}", "{" . $key . "}" . join($val, ""), $header);
        $footer = str_replace("{" . $key . "}", "{" . $key . "}" . join($val, ""), $footer);
    }
    $builtnavs = buildnavs();
    restore_buff_fields();
    calculate_buff_fields();
    tlschema("common");
    $charstats = charstats();
    restore_buff_fields();
    $sql = "SELECT motddate FROM " . db_prefix("motd") . " ORDER BY motditem DESC LIMIT 1";
    $result = db_query_cached($sql, "motd-dates");
    $row = db_fetch_assoc($result);
    db_free_result($result);
    $headscript = "";
    if (isset($session['user']['lastmotd']) && $row['motddate'] > $session['user']['lastmotd'] && (!isset($nopopup[$SCRIPT_NAME]) || $nopopups[$SCRIPT_NAME] != 1) && $session['user']['loggedin']) {
        // $headscript.=popup("motd.php");
        $session['needtoviewmotd'] = true;
    } else {
        $session['needtoviewmotd'] = false;
    }
    $pre_headscript = "<LINK REL=\"shortcut icon\" HREF=\"favicon.ico\" TYPE=\"image/x-icon\"/>";
    if ($headscript > "") {
        $header = str_replace("{headscript}", $pre_headscript . "<script language='JavaScript'>" . $headscript . "</script>", $header);
    } else {
        $header = str_replace("{headscript}", $pre_headscript, $header);
    }
    $script = "";
    if (!isset($session['user']['name'])) {
        $session['user']['name'] = "";
    }
    if (!isset($session['user']['login'])) {
        $session['user']['login'] = "";
    }
    //clean up unclosed output tags.
    while (list($key, $val) = each($nestedtags)) {
        if ($nestedtags[$key] === true) {
            $output .= "</{$key}>";
        }
        unset($nestedtags[$key]);
    }
    //output keypress script
    $script .= "<script language='JavaScript'>\r\n\t<!--\r\n\tdocument.onkeypress=keyevent;\r\n\tfunction keyevent(e){\r\n\t\tvar c;\r\n\t\tvar target;\r\n\t\tvar altKey;\r\n\t\tvar ctrlKey;\r\n\t\tif (window.event != null) {\r\n\t\t\tc=String.fromCharCode(window.event.keyCode).toUpperCase();\r\n\t\t\taltKey=window.event.altKey;\r\n\t\t\tctrlKey=window.event.ctrlKey;\r\n\t\t}else{\r\n\t\t\tc=String.fromCharCode(e.charCode).toUpperCase();\r\n\t\t\taltKey=e.altKey;\r\n\t\t\tctrlKey=e.ctrlKey;\r\n\t\t}\r\n\t\tif (window.event != null)\r\n\t\t\ttarget=window.event.srcElement;\r\n\t\telse\r\n\t\t\ttarget=e.originalTarget;\r\n\t\tif (target.nodeName.toUpperCase()=='INPUT' || target.nodeName.toUpperCase()=='TEXTAREA' || altKey || ctrlKey){\r\n\t\t}else{";
    reset($quickkeys);
    while (list($key, $val) = each($quickkeys)) {
        $script .= "\n\t\t\tif (c == '" . strtoupper($key) . "') { {$val}; return false; }";
    }
    $script .= "\r\n\t\t}\r\n\t}\r\n\t//-->\r\n\t</script>";
    //handle paypal
    if (strpos($footer, "{paypal}") || strpos($header, "{paypal}")) {
        $palreplace = "{paypal}";
    } else {
        $palreplace = "{stats}";
    }
    //NOTICE |
    //NOTICE | Although under the license, you're not required to keep this
    //NOTICE | paypal link, I do request, as the author of this software
    //NOTICE | which I have made freely available to you, that you leave it in.
    //NOTICE |
    $paypalstr = '<table align="center"><tr><td>';
    $currency = getsetting("paypalcurrency", "USD");
    if (!isset($_SESSION['logdnet']) || !isset($_SESSION['logdnet']['']) || $_SESSION['logdnet'][''] == "" || !isset($session['user']['laston']) || date("Y-m-d H:i:s", strtotime("-1 hour")) > $session['user']['laston']) {
        $already_registered_logdnet = false;
    } else {
        $already_registered_logdnet = true;
    }
    if (getsetting("logdnet", 0) && $session['user']['loggedin'] && !$already_registered_logdnet) {
        //account counting, just for my own records, I don't use this in the calculation for server order.
        $sql = "SELECT count(*) AS c FROM " . db_prefix("accounts");
        $result = db_query_cached($sql, "acctcount", 600);
        $row = db_fetch_assoc($result);
        $c = $row['c'];
        $a = getsetting("serverurl", "http://" . $_SERVER['SERVER_NAME'] . ($_SERVER['SERVER_PORT'] == 80 ? "" : ":" . $_SERVER['SERVER_PORT']) . dirname($_SERVER['REQUEST_URI']));
        if (!preg_match("/\\/\$/", $a)) {
            $a = $a . "/";
            savesetting("serverurl", $a);
        }
        $l = getsetting("defaultlanguage", "en");
        $d = getsetting("serverdesc", "Another LoGD Server");
        $e = getsetting("gameadminemail", "*****@*****.**");
        $u = getsetting("logdnetserver", "http://logdnet.logd.com/");
        if (!preg_match("/\\/\$/", $u)) {
            $u = $u . "/";
            savesetting("logdnetserver", $u);
        }
        global $logd_version;
        $v = $logd_version;
        $c = rawurlencode($c);
        $a = rawurlencode($a);
        $l = rawurlencode($l);
        $d = rawurlencode($d);
        $e = rawurlencode($e);
        $v = rawurlencode($v);
        $u = rawurlencode($u);
        $paypalstr .= "<script language='JavaScript' src='images/logdnet.php?op=register&c={$c}&l={$l}&v={$v}&a={$a}&d={$d}&e={$e}&u={$u}'></script>";
    } else {
        $paypalstr .= '<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_blank">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="business" value="*****@*****.**">
<input type="hidden" name="item_name" value="Legend of the Green Dragon Author Donation from ' . full_sanitize($session['user']['name']) . '">
<input type="hidden" name="item_number" value="' . htmlentities($session['user']['login'] . ":" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . '">
<input type="hidden" name="no_shipping" value="1">
<input type="hidden" name="notify_url" value="http://lotgd.net/payment.php">
<input type="hidden" name="cn" value="Your Character Name">
<input type="hidden" name="cs" value="1">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="tax" value="0">
<input type="image" src="images/paypal1.gif" border="0" name="submit" alt="Donate!">
</form>';
    }
    $paysite = getsetting("paypalemail", "");
    if ($paysite != "") {
        $paypalstr .= '</td></tr><tr><td colspan=\'2\' align=\'center\'>';
        $paypalstr .= '<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_blank">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="business" value="' . $paysite . '">
<input type="hidden" name="item_name" value="' . getsetting("paypaltext", "Legend of the Green Dragon Site Donation from") . ' ' . full_sanitize($session['user']['name']) . '">
<input type="hidden" name="item_number" value="' . htmlentities($session['user']['login'] . ":" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . '">
<input type="hidden" name="no_shipping" value="1">';
        if (file_exists("payment.php")) {
            $paypalstr .= '<input type="hidden" name="notify_url" value="http://' . $_SERVER["HTTP_HOST"] . dirname($_SERVER['REQUEST_URI']) . '/payment.php">';
        }
        $paypalstr .= '<input type="hidden" name="cn" value="Your Character Name">
<input type="hidden" name="cs" value="1">
<input type="hidden" name="currency_code" value="' . $currency . '">
<input type="hidden" name="lc" value="' . getsetting("paypalcountry-code", "US") . '">
<input type="hidden" name="bn" value="PP-DonationsBF">
<input type="hidden" name="tax" value="0">
<input type="image" src="images/paypal2.gif" border="0" name="submit" alt="Donate!">
</form>';
    }
    $paypalstr .= '</td></tr></table>';
    $footer = str_replace($palreplace, (strpos($palreplace, "paypal") ? "" : "{stats}") . $paypalstr, $footer);
    $header = str_replace($palreplace, (strpos($palreplace, "paypal") ? "" : "{stats}") . $paypalstr, $header);
    //NOTICE |
    //NOTICE | Although I will not deny you the ability to remove the above
    //NOTICE | paypal link, I do request, as the author of this software
    //NOTICE | which I made available for free to you that you leave it in.
    //NOTICE |
    //output the nav
    $footer = str_replace("{" . $z . "}", ${$z}, $footer);
    $header = str_replace("{nav}", $builtnavs, $header);
    $footer = str_replace("{nav}", $builtnavs, $footer);
    //output the motd
    $header = str_replace("{motd}", motdlink(), $header);
    $footer = str_replace("{motd}", motdlink(), $footer);
    //output the mail link
    if (isset($session['user']['acctid']) && $session['user']['acctid'] > 0 && $session['user']['loggedin']) {
        $header = str_replace("{mail}", maillink(), $header);
        $footer = str_replace("{mail}", maillink(), $footer);
    } else {
        $header = str_replace("{mail}", "", $header);
        $footer = str_replace("{mail}", "", $footer);
    }
    //output petition count
    $header = str_replace("{petition}", "<a href='petition.php' onClick=\"" . popup("petition.php") . ";return false;\" target='_blank' align='right' class='motd'>" . translate_inline("Petition for Help") . "</a>", $header);
    $footer = str_replace("{petition}", "<a href='petition.php' onClick=\"" . popup("petition.php") . ";return false;\" target='_blank' align='right' class='motd'>" . translate_inline("Petition for Help") . "</a>", $footer);
    if ($session['user']['superuser'] & SU_EDIT_PETITIONS) {
        $sql = "SELECT count(petitionid) AS c,status FROM " . db_prefix("petitions") . " GROUP BY status";
        $result = db_query_cached($sql, "petition_counts");
        $petitions = array(0 => 0, 1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0, 7 => 0);
        while ($row = db_fetch_assoc($result)) {
            $petitions[(int) $row['status']] = $row['c'];
        }
        $pet = translate_inline("`0`bPetitions:`b");
        $ued = translate_inline("`0`bUser Editor`b");
        db_free_result($result);
        if ($session['user']['superuser'] & SU_EDIT_USERS) {
            $p = "<a href='user.php'>{$ued}</a>|<a href='viewpetition.php'>{$pet}</a>";
            addnav("", "user.php");
            addnav("", "viewpetition.php");
        } else {
            $p = "<a href='viewpetition.php'>{$pet}</a>";
            addnav("", "viewpetition.php");
        }
        $p .= " `\${$petitions[5]}`0|`^{$petitions[4]}`0|`b{$petitions[0]}`b|{$petitions[1]}|`!{$petitions[3]}`0|`#{$petitions[7]}`0|`%{$petitions[6]}`0|`i{$petitions[2]}`i";
        $pcount = templatereplace("petitioncount", array("petitioncount" => appoencode($p, true)));
        $footer = str_replace("{petitiondisplay}", $pcount, $footer);
        $header = str_replace("{petitiondisplay}", $pcount, $header);
    } else {
        $footer = str_replace("{petitiondisplay}", "", $footer);
        $header = str_replace("{petitiondisplay}", "", $header);
    }
    //output character stats
    $footer = str_replace("{stats}", $charstats, $footer);
    $header = str_replace("{stats}", $charstats, $header);
    //do something -- I don't know what
    $header = str_replace("{script}", $script, $header);
    //output view PHP source link
    $sourcelink = "source.php?url=" . preg_replace("/[?].*/", "", $_SERVER['REQUEST_URI']);
    $footer = str_replace("{source}", "<a href='{$sourcelink}' onclick=\"" . popup($sourcelink) . ";return false;\" target='_blank'>" . translate_inline("View PHP Source") . "</a>", $footer);
    $header = str_replace("{source}", "<a href='{$sourcelink}' onclick=\"" . popup($sourcelink) . ";return false;\" target='_blank'>" . translate_inline("View PHP Source") . "</a>", $header);
    //output version
    $footer = str_replace("{version}", "Version: {$logd_version}", $footer);
    //output page generation time
    $gentime = getmicrotime() - $pagestarttime;
    $session['user']['gentime'] += $gentime;
    $session['user']['gentimecount']++;
    $load = exec("uptime");
    $load = split("load average:", $load);
    $load = split(", ", $load[1]);
    $perfhook = array("gentime" => $gentime, "dbinfo" => $dbinfo, "cpu" => $load, "script" => $SCRIPT_NAME, "request" => $REQUEST_URI);
    $perfhook = modulehook("footer-performance", $perfhook);
    $l1 = $load[0];
    $l5 = $load[1];
    $l15 = $load[2];
    $mem = memory_get_usage(true);
    if ($mem < 1024) {
        $memdisp = $mem . " bytes";
    } else {
        if ($mem < 1048576) {
            $memdisp = round($mem / 1024, 6) . " kilobytes";
        } else {
            $memdisp = round($mem / 1048576, 6) . " megabytes";
        }
    }
    if (!isset($dbinfo['cache_fail'])) {
        $dbinfo['cache_fail'] = 0;
    }
    global $output_time;
    $footer = str_replace("{pagegen}", "Page gen: " . round($gentime, 3) . "s / " . $dbinfo['queriesthishit'] . " queries (" . round($dbinfo['querytime'], 3) . "s), cache " . $dbinfo['cache_success'] . " successful (" . round($dbinfo['cachetime'], 3) . "s) / " . $dbinfo['cache_fail'] . " failed.  Average for this account: " . round($session['user']['gentime'] / $session['user']['gentimecount'], 3) . "s - " . round($session['user']['gentime'], 3) . "/" . round($session['user']['gentimecount'], 3) . "<br />Current CPU Load: {$l1} | {$l5} | {$l15}<br />Memory usage for this page: {$memdisp}", $footer);
    tlschema();
    // global $allqueries;
    // debug($allqueries);
    // global $cachedqueries;
    // debug($cachedqueries);
    // global $module_prefs;
    // debug($module_prefs);
    // global $moduleperformance;
    // debug($moduleperformance);
    // global $allqueriesbyfile;
    // debug($allqueriesbyfile);
    //clean up spare {fields}s from header and footer (in case they're not used)
    $footer = preg_replace("/{[^} \t\n\r]*}/i", "", $footer);
    $header = preg_replace("/{[^} \t\n\r]*}/i", "", $header);
    //finalize output
    $output = $header . $output . $footer;
    $session['user']['gensize'] += strlen($output);
    $session['output'] = $output;
    if ($saveuser === true) {
        saveuser();
    }
    unset($session['output']);
    //this somehow allows some frames to load before the user's navs say it can
    //session_write_close();
    echo $output;
    $session['badnav'] = 0;
    exit;
}
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");
    }
}
function systemmail($to, $subject, $body, $from = 0, $noemail = false)
{
    global $session;
    $sql = "SELECT prefs,emailaddress FROM " . db_prefix("accounts") . " WHERE acctid='{$to}'";
    $result = db_query($sql);
    $row = db_fetch_assoc($result);
    db_free_result($result);
    $prefs = unserialize($row['prefs']);
    $serialized = 0;
    if ($from == 0) {
        if (is_array($subject)) {
            $subject = serialize($subject);
            $serialized = 1;
        }
        if (is_array($body)) {
            $body = serialize($body);
            $serialized += 2;
        }
        $subject = safeescape($subject);
        $body = safeescape($body);
    } else {
        $subject = safeescape($subject);
        $subject = str_replace("\n", "", $subject);
        $subject = str_replace("`n", "", $subject);
        $body = safeescape($body);
        if (isset($prefs['dirtyemail']) && $prefs['dirtyemail'] || $from == 0) {
        } else {
            $subject = soap($subject, false, "mail");
            $body = soap($body, false, "mail");
        }
    }
    $sql = "INSERT INTO " . db_prefix("mail") . " (msgfrom,msgto,subject,body,sent,originator) VALUES ('" . $from . "','" . (int) $to . "','{$subject}','{$body}','" . date("Y-m-d H:i:s") . "', " . $session['user']['acctid'] . ")";
    db_query($sql);
    invalidatedatacache("mail-{$to}");
    $email = false;
    if (isset($prefs['emailonmail']) && $prefs['emailonmail'] && $from > 0) {
        $email = true;
    } elseif (isset($prefs['emailonmail']) && $prefs['emailonmail'] && $from == 0 && isset($prefs['systemmail']) && $prefs['systemmail']) {
        $email = true;
    }
    $emailadd = "";
    if (isset($row['emailaddress'])) {
        $emailadd = $row['emailaddress'];
    }
    if (!is_email($emailadd)) {
        $email = false;
    }
    if ($email && !$noemail) {
        if ($serialized & 2) {
            $body = unserialize(stripslashes($body));
            $body = translate_mail($body, $to);
        }
        if ($serialized & 1) {
            $subject = unserialize(stripslashes($subject));
            $subject = translate_mail($subject, $to);
        }
        $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid='{$from}'";
        $result = db_query($sql);
        $row1 = db_fetch_assoc($result);
        db_free_result($result);
        if ($row1['name'] != "") {
            $fromline = full_sanitize($row1['name']);
        } else {
            $fromline = translate_inline("The Green Dragon", "mail");
        }
        $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid='{$to}'";
        $result = db_query($sql);
        $row1 = db_fetch_assoc($result);
        db_free_result($result);
        $toline = full_sanitize($row1['name']);
        // We've inserted it into the database, so.. strip out any formatting
        // codes from the actual email we send out... they make things
        // unreadable
        $body = preg_replace("'[`]n'", "\n", $body);
        $body = full_sanitize($body);
        $subject = htmlentities($subject, ENT_COMPAT, getsetting("charset", "ISO-8859-1"));
        $mailsubj = translate_mail(array("New LoGD Mail (%s)", $subject), $to);
        $mailbody = translate_mail(array("You have received new mail on LoGD at http://%s`n`n" . "-=-=-=-=-=-=-=-=-=-=-=-=-=-`n" . "From: %s`n" . "To: %s`n" . "Subject: %s`n" . "Body: `n%s`n" . "-=-=-=-=-=-=-=-=-=-=-=-=-=-" . "`nDo not respond directly to this email, it was sent from the game email address, and not the email address of the person who sent you the " . "message.  If you wish to respond, log into Legend of the Green Dragon at http://%s .`n`n" . "You may turn off these alerts in your preferences page, available from the village square.", $_SERVER['HTTP_HOST'] . dirname($_SERVER['SCRIPT_NAME']), $fromline, $toline, full_sanitize(stripslashes($subject)), stripslashes($body), $_SERVER['HTTP_HOST'] . dirname($_SERVER['SCRIPT_NAME'])), $to);
        mail($row['emailaddress'], $mailsubj, str_replace("`n", "\n", $mailbody), "From: " . getsetting("gameadminemail", "postmaster@localhost"));
    }
    invalidatedatacache("mail-{$to}");
}
function dag_run_private()
{
    require_once "modules/dag/misc_functions.php";
    global $session;
    if (httpget('manage') != "true") {
        page_header("Dag Durnick's Table");
        output("<span style='color: #9900FF'>", true);
        output("`c`bDag Durnick's Table`b`c");
    } else {
        dag_manage();
    }
    $op = httpget('op');
    addnav("Navigation");
    addnav("I?Return to the Inn", "inn.php");
    if ($op != '') {
        addnav("Talk to Dag Durnick", "runmodule.php?module=dag");
    }
    if ($op == "list") {
        output("Dag fishes a small leather bound book out from under his cloak, flips through it to a certain page and holds it up for you to see.");
        output("\"`7Deese ain't the most recent figgers, I ain't just had time to get th' other numbers put in.`0\"`n`n");
        // ***ADDED***
        // By Andrew Senger
        // Added for new Bounty Code
        output("`c`bThe Bounty List`b`c`n");
        $sql = "SELECT bountyid,amount,target,setter,setdate FROM " . db_prefix("bounty") . " WHERE status=0 AND setdate<='" . date("Y-m-d H:i:s") . "' ORDER BY bountyid ASC";
        $result = db_query($sql);
        rawoutput("<table border=0 cellpadding=2 cellspacing=1 bgcolor='#999999'>");
        $amount = translate_inline("Amount");
        $level = translate_inline("Level");
        $name = translate_inline("Name");
        $loc = translate_inline("Location");
        $sex = translate_inline("Sex");
        $alive = translate_inline("Alive");
        $last = translate_inline("Last On");
        rawoutput("<tr class='trhead'><td><b>{$amount}</b></td><td><b>{$level}</b></td><td><b>{$name}</b></td><td><b>{$loc}</b></td><td><b>{$sex}</b></td><td><b>{$alive}</b></td><td><b>{$last}</b></td>");
        $listing = array();
        $totlist = 0;
        for ($i = 0; $i < db_num_rows($result); $i++) {
            $row = db_fetch_assoc($result);
            $amount = (int) $row['amount'];
            $sql = "SELECT name,alive,sex,level,laston,loggedin,lastip,location FROM " . db_prefix("accounts") . " WHERE acctid={$row['target']}";
            $result2 = db_query($sql);
            if (db_num_rows($result2) == 0) {
                /* this person has been deleted, clear bounties */
                $sql = "UPDATE " . db_prefix("bounty") . " SET status=1 WHERE target={$row['target']}";
                db_query($sql);
                continue;
            }
            $row2 = db_fetch_assoc($result2);
            $yesno = 0;
            for ($j = 0; $j <= $i; $j++) {
                if (isset($listing[$j]) && $listing[$j]['Name'] == $row2['name']) {
                    $listing[$j]['Amount'] = $listing[$j]['Amount'] + $amount;
                    $yesno = 1;
                }
            }
            if ($yesno == 0) {
                $loggedin = date("U") - strtotime($row2['laston']) < getsetting("LOGINTIMEOUT", 900) && $row2['loggedin'];
                $listing[] = array('Amount' => $amount, 'Level' => $row2['level'], 'Name' => $row2['name'], 'Location' => $row2['location'], 'Sex' => $row2['sex'], 'Alive' => $row2['alive'], 'LastOn' => $row2['laston'], 'LoggedIn' => $loggedin);
                $totlist = $totlist + 1;
            }
        }
        $sort = httpget("sort");
        if ($sort == "level") {
            usort($listing, 'dag_sortbountieslevel');
        } elseif ($sort != "") {
            usort($listing, 'dag_sortbounties');
        } else {
            usort($listing, 'dag_sortbountieslevel');
        }
        for ($i = 0; $i < $totlist; $i++) {
            rawoutput("<tr class='" . ($i % 2 ? "trdark" : "trlight") . "'><td>");
            output_notl("`^%s`0", $listing[$i]['Amount']);
            rawoutput("</td><td>");
            output_notl("`^%s`0", $listing[$i]['Level']);
            rawoutput("</td><td>");
            output_notl("`^%s`0", $listing[$i]['Name']);
            rawoutput("</td><td>");
            output($listing[$i]['LoggedIn'] ? "`#Online`0" : $listing[$i]['Location']);
            rawoutput("</td><td>");
            output($listing[$i]['Sex'] ? "`!Female`0" : "`!Male`0");
            rawoutput("</td><td>");
            output($listing[$i]['Alive'] ? "`1Yes`0" : "`4No`0");
            rawoutput("</td><td>");
            $laston = relativedate($listing[$i]['LastOn']);
            output_notl("%s", $laston);
            rawoutput("</td></tr>");
        }
        rawoutput("</table>");
        // ***END ADDING***
    } else {
        if ($op == "addbounty") {
            if (get_module_pref("bounties") >= get_module_setting("maxbounties")) {
                output("Dag gives you a piercing look.");
                output("`7\"Ye be thinkin' I be an assassin or somewhat?  Ye already be placin' more than 'nuff bounties for t'day.  Now, be ye gone before I stick a bounty on yer head fer annoyin' me.\"`n`n");
            } else {
                $fee = get_module_setting("bountyfee");
                if ($fee < 0 || $fee > 100) {
                    $fee = 10;
                    set_module_setting("bountyfee", $fee);
                }
                $min = get_module_setting("bountymin");
                $max = get_module_setting("bountymax");
                output("Dag Durnick glances up at you and adjusts the pipe in his mouth with his teeth.`n");
                output("`7\"So, who ye be wantin' to place a hit on? Just so ye be knowing, they got to be legal to be killin', they got to be at least level %s, and they can't be having too much outstandin' bounty nor be getting hit too frequent like, so if they ain't be listed, they can't be contracted on!  We don't run no slaughterhouse here, we run a.....business.  Also, there be a %s%% listin' fee fer any hit ye be placin'.\"`n`n", get_module_setting("bountylevel"), get_module_setting("bountyfee"));
                rawoutput("<form action='runmodule.php?module=dag&op=finalize' method='POST'>");
                output("`2Target: ");
                rawoutput("<input name='contractname'>");
                output_notl("`n");
                output("`2Amount to Place: ");
                rawoutput("<input name='amount' id='amount' width='5'>");
                output_notl("`n`n");
                $final = translate_inline("Finalize Contract");
                rawoutput("<input type='submit' class='button' value='{$final}'>");
                rawoutput("</form>");
                addnav("", "runmodule.php?module=dag&op=finalize");
            }
        } elseif ($op == "finalize") {
            if (httpget('subfinal') == 1) {
                $sql = "SELECT acctid,name,login,level,locked,age,dragonkills,pk,experience FROM " . db_prefix("accounts") . " WHERE name='" . addslashes(rawurldecode(stripslashes(httppost('contractname')))) . "' AND locked=0";
            } else {
                $contractname = stripslashes(rawurldecode(httppost('contractname')));
                $name = "%";
                for ($x = 0; $x < strlen($contractname); $x++) {
                    $name .= substr($contractname, $x, 1) . "%";
                }
                $sql = "SELECT acctid,name,login,level,locked,age,dragonkills,pk,experience FROM " . db_prefix("accounts") . " WHERE name LIKE '" . addslashes($name) . "' AND locked=0";
            }
            $result = db_query($sql);
            if (db_num_rows($result) == 0) {
                output("Dag Durnick sneers at you, `7\"There not be anyone I be knowin' of by that name.  Maybe ye should come back when ye got a real target in mind?\"");
            } elseif (db_num_rows($result) > 100) {
                output("Dag Durnick scratches his head in puzzlement, `7\"Ye be describing near half th' town, ye fool?  Why don't ye be giving me a better name now?\"");
            } elseif (db_num_rows($result) > 1) {
                output("Dag Durnick searches through his list for a moment, `7\"There be a couple of 'em that ye could be talkin' about.  Which one ye be meaning?\"`n");
                rawoutput("<form action='runmodule.php?module=dag&op=finalize&subfinal=1' method='POST'>");
                output("`2Target: ");
                rawoutput("<select name='contractname'>");
                for ($i = 0; $i < db_num_rows($result); $i++) {
                    $row = db_fetch_assoc($result);
                    rawoutput("<option value=\"" . rawurlencode($row['name']) . "\">" . full_sanitize($row['name']) . "</option>");
                }
                rawoutput("</select>");
                output_notl("`n`n");
                $amount = httppost('amount');
                output("`2Amount to Place: ");
                rawoutput("<input name='amount' id='amount' width='5' value='{$amount}'>");
                output_notl("`n`n");
                $final = translate_inline("Finalize Contract");
                rawoutput("<input type='submit' class='button' value='{$final}'>");
                rawoutput("</form>");
                addnav("", "runmodule.php?module=dag&op=finalize&subfinal=1");
            } else {
                // Now, we have just the one, so check it.
                $row = db_fetch_assoc($result);
                if ($row['locked']) {
                    output("Dag Durnick sneers at you, `7\"There not be anyone I be knowin' of by that name.  Maybe ye should come back when ye got a real target in mind?\"");
                } elseif ($row['login'] == $session['user']['login']) {
                    output("Dag Durnick slaps his knee laughing uproariously, `7\"Ye be wanting to take out a contract on yerself?  I ain't be helping no suicider, now!\"");
                } elseif ($row['level'] < get_module_setting("bountylevel") || $row['age'] < getsetting("pvpimmunity", 5) && $row['dragonkills'] == 0 && $row['pk'] == 0 && $row['experience'] < getsetting("pvpminexp", 1500)) {
                    output("Dag Durnick stares at you angrily, `7\"I told ye that I not be an assassin.  That ain't a target worthy of a bounty.  Now get outta me sight!\"");
                } else {
                    // All good!
                    $amt = abs((int) httppost('amount'));
                    $min = get_module_setting("bountymin") * $row['level'];
                    $max = get_module_setting("bountymax") * $row['level'];
                    $fee = get_module_setting("bountyfee");
                    $cost = round($amt * ((100 + $fee) / 100), 0);
                    $curbounty = 0;
                    $sql = "SELECT sum(amount) AS total FROM " . db_prefix("bounty") . " WHERE status=0 AND target={$row['acctid']}";
                    $result = db_query($sql);
                    if (db_num_rows($result) > 0) {
                        $nrow = db_fetch_assoc($result);
                        $curbounty = $nrow['total'];
                    }
                    if ($amt < $min) {
                        output("Dag Durnick scowls, `7\"Ye think I be workin' for that pittance?  Be thinkin' again an come back when ye willing to spend some real coin.  That mark be needin' at least %s gold to be worth me time.\"", $min);
                    } elseif ($session['user']['gold'] < $cost) {
                        output("Dag Durnick scowls, `7\"Ye don't be havin enough gold to be settin' that contract.  Wastin' my time like this, I aught to be puttin' a contract on YE instead!");
                    } elseif ($amt + $curbounty > $max) {
                        if ($curbounty) {
                            output("Dag looks down at the pile of coin and just leaves them there.");
                            output("`7\"I'll just be passin' on that contract.  That's way more'n `^%s`7 be worth and ye know it.  I ain't no durned assassin. A bounty o' %s already be on their head, what with the bounties I ain't figgered in to th' book already.  I might be willin' t'up it to %s, after me %s%% listin' fee of course\"`n`n", $row['name'], $curbounty, $max, $fee);
                        } else {
                            output("Dag looks down at the pile of coin and just leaves them there.");
                            output("`7\"I'll just be passin' on that contract.  That's way more'n `^%s`7 be worth and ye know it.  I ain't no durned assassin.  I might be willin' t'let y' set one of %s, after me %s%% listin' fee of course\"`n`n", $row['name'], $max, $fee);
                        }
                    } else {
                        output("You slide the coins towards Dag Durnick, who deftly palms them from the table.");
                        output("`7\"I'll just be takin' me %s%% listin' fee offa the top.  The word be put out that ye be wantin' `^%s`7 taken care of. Be patient, and keep yer eyes on the news.\"`n`n", $fee, $row['name']);
                        set_module_pref("bounties", get_module_pref("bounties") + 1);
                        $session['user']['gold'] -= $cost;
                        // ***ADDED***
                        // By Andrew Senger
                        // Adding for new Bounty Code
                        $setdate = time();
                        // random set date up to 4 hours in the future.
                        $setdate += e_rand(0, 14400);
                        $sql = "INSERT INTO " . db_prefix("bounty") . " (amount, target, setter, setdate) VALUES ({$amt}, " . $row['acctid'] . ", " . (int) $session['user']['acctid'] . ", '" . date("Y-m-d H:i:s", $setdate) . "')";
                        db_query($sql);
                        // ***END ADD***
                        debuglog("spent {$cost} to place a {$amt} bounty on {$row['name']}");
                    }
                }
            }
        } else {
            output("You stroll over to Dag Durnick, who doesn't even bother to look up at you.");
            output("He takes a long pull on his pipe.`n");
            output("`7\"Ye probably be wantin' to know if there's a price on yer head, ain't ye.\"`n`n");
            // ***ADDED***
            // By Andrew Senger
            // Adding for new Bounty Code
            $sql = "SELECT sum(amount) as total FROM " . db_prefix("bounty") . " WHERE status=0 AND setdate<='" . date("Y-m-d H:i:s") . "' AND target=" . $session['user']['acctid'];
            $result = db_query($sql);
            $curbounty = 0;
            if (db_num_rows($result) != 0) {
                $row = db_fetch_assoc($result);
                $curbounty = $row['total'];
            }
            if ($curbounty == 0) {
                output("\"`3Ye don't have no bounty on ya.  I suggest ye be keepin' it that way.\"");
            } else {
                output("\"`3Well, it be lookin like ye have `^%s gold`3 on yer head currently. Ye might wanna be watchin yourself.\"", $curbounty);
            }
            // ***END ADD***
            addnav("Bounties");
            addnav("Check the Wanted List", "runmodule.php?module=dag&op=list");
            addnav("Set a Bounty", "runmodule.php?module=dag&op=addbounty");
        }
    }
    modulehook('dagnav');
    if ($op == "list") {
        addnav("Sort List");
        addnav("View by Bounty", "runmodule.php?module=dag&op=list&sort=bounty");
        addnav("View by Level", "runmodule.php?module=dag&op=list&sort=level");
    }
    rawoutput("</span>");
    page_footer();
}
    if ($info !== false) {
        require_once "../lib/sanitize.php";
        $o = addslashes($_SESSION['logdnet']['']);
        $o = str_replace("\n\r", "\n", $o);
        $o = str_replace("\r", "\n", $o);
        $o = str_replace("\n", "\\n", $o);
        $refer = "";
        if (isset($_SERVER['HTTP_REFERER'])) {
            $refer = $_SERVER['HTTP_REFERER'];
        }
        if (isset($_SESSION['session']['user'])) {
            echo $_SESSION['logdnet']['note'] . "\n";
            echo "// At {$_SESSION['logdnet']['when']}\n";
            //require_once("../lib/dbwrapper.php");
            //require_once("../lib/settings.php");
            echo "document.write(\"" . sprintf($o, full_sanitize($_SESSION['session']['user']['login']), htmlentities($_SESSION['session']['user']['login']) . ":" . $_SERVER['HTTP_HOST'] . $refer, ENT_COMPAT, "ISO-8859-1") . "\");";
        } else {
            $image = join("", file("paypal1.gif"));
            header("Content-Type: image/gif");
            header("Content-Length: " . strlen($image));
            echo $image;
        }
    } else {
        // We failed to connect to central, just use our local image!
        $image = join("", file("paypal1.gif"));
        header("Content-Type: image/gif");
        header("Content-Length: " . strlen($image));
        echo $image;
    }
} elseif (isset($_SESSION['logdnet'])) {
    header("Content-Type: " . $_SESSION['logdnet']['content-type']);
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();
}
<?php

page_header("Clan Hall for %s", full_sanitize($claninfo['clanname']));
addnav("Clan Options");
if ($op == "") {
    require_once "lib/clan/clan_default.php";
} elseif ($op == "motd") {
    require_once "lib/clan/clan_motd.php";
} elseif ($op == "membership") {
    require_once "lib/clan/clan_membership.php";
} elseif ($op == "withdrawconfirm") {
    output("Are you sure you want to withdraw from your clan?");
    addnav("Withdraw?");
    addnav("No", "clan.php");
    addnav("!?Yes", "clan.php?op=withdraw");
} elseif ($op == "withdraw") {
    require_once "lib/clan/clan_withdraw.php";
}