function worldmapen_editor_real()
{
    global $session;
    page_header("World Editor");
    require_once "lib/superusernav.php";
    superusernav();
    // initialize the internal static maps
    worldmapen_loadMap();
    worldmapen_loadTerrainDefs();
    $op = httpget("op");
    $act = httpget("act");
    $subop = httpget("subop");
    debug("op={$op}, act={$act}, subop={$subop}");
    switch ($subop) {
        case "regen":
            worldmapen_editor_regen($op, $subop, $act);
            break;
        case "manual":
            worldmapen_editor_manual($op, $subop, $act);
            break;
        case "terrain":
            worldmapen_editor_terrain($op, $subop, $act);
            break;
        default:
            worldmapen_viewmap(false);
            break;
    }
    addnav("Replace Cities", "runmodule.php?module=worldmapen&op=edit&subop=regen");
    addnav("Manually Place Cities", "runmodule.php?module=worldmapen&op=edit&subop=manual");
    addnav("Edit terrain type", "runmodule.php?module=worldmapen&op=edit&subop=terrain");
    page_footer();
}
function clancommentaryoverview_run()
{
    page_header("Clan Commentary Overview");
    $numcomments = get_module_setting("numcomments");
    require_once "lib/superusernav.php";
    superusernav();
    addnav("C?Commentary Overview", "moderate.php");
    addnav("Clan Halls");
    $sql = "SELECT clanid, clanname, clanshort FROM " . db_prefix("clans") . " ORDER BY clanid";
    $res = db_query($sql);
    // since these are proper names, they shouldn't be translated
    tlschema("notranslate");
    while ($row = db_fetch_assoc($res)) {
        addnav(array("<%s> %s", $row['clanshort'], $row['clanname']), "moderate.php?area=clan-{$row['clanid']}");
    }
    tlschema();
    $sql = "SELECT clanid, clanname FROM " . db_prefix("clans") . " ORDER BY clanid";
    $res = db_query($sql);
    $firstclan = 1;
    while ($clan = db_fetch_assoc($res)) {
        $cid = $clan['clanid'];
        $csql = "SELECT * FROM " . db_prefix("commentary") . " WHERE section='clan-" . $cid . "' ORDER BY postdate DESC LIMIT " . $numcomments;
        $cres = db_query($csql);
        if (db_num_rows($cres) > 0) {
            if ($firstclan == 1) {
                $firstclan = 0;
                addnav("", "runmodule.php?module=clancommentaryoverview");
                $buttonrefresh = translate_inline("Refresh");
                rawoutput("<form action='runmodule.php?module=clancommentaryoverview' method='post'>");
                rawoutput("<input type='submit' class='button' value='{$buttonrefresh}'>");
                rawoutput("</form>");
            }
            rawoutput("<hr>");
            $cname = $clan['clanname'];
            addnav("", "moderate.php?area=clan-" . $cid);
            rawoutput("<a href='moderate.php?area=clan-" . $cid . "'>");
            output_notl("`b`^%s`b`0", $cname);
            rawoutput("</a>");
            output_notl("`n");
            $carray = array();
            while ($ccomment = db_fetch_assoc($cres)) {
                array_push($carray, $ccomment);
            }
            while ($ccomment = array_pop($carray)) {
                clancommentaryoverview_displaycomment($ccomment);
            }
        }
    }
    page_footer();
}
+-----------+---------------------+------+-----+---------+----------------+
| payid     | int(11)             |      | PRI | NULL    | auto_increment |
| info      | text                |      |     |         |                |
| response  | text                |      |     |         |                |
| txnid     | varchar(32)         |      | MUL |         |                |
| amount    | float(9,2)          |      |     | 0.00    |                |
| name      | varchar(50)         |      |     |         |                |
| acctid    | int(11) unsigned    |      |     | 0       |                |
| processed | tinyint(4) unsigned |      |     | 0       |                |
| filed     | tinyint(4) unsigned |      |     | 0       |                |
| txfee     | float(9,2)          |      |     | 0.00    |                |
+-----------+---------------------+------+-----+---------+----------------+
*/
page_header("Payment Log");
require_once "lib/superusernav.php";
superusernav();
$op = httpget('op');
if ($op == "") {
    $sql = "SELECT info,txnid FROM " . db_prefix("paylog") . " WHERE processdate='0000-00-00'";
    $result = db_query($sql);
    while ($row = db_fetch_assoc($result)) {
        $info = unserialize($row['info']);
        $sql = "UPDATE " . db_prefix('paylog') . " SET processdate='" . date("Y-m-d H:i:s", strtotime($info['payment_date'])) . "' WHERE txnid='" . addslashes($row['txnid']) . "'";
        db_query($sql);
    }
    $sql = "SELECT substring(processdate,1,7) AS month, sum(amount)-sum(txfee) AS profit FROM " . db_prefix('paylog') . " GROUP BY month DESC";
    $result = db_query($sql);
    addnav("Months");
    while ($row = db_fetch_assoc($result)) {
        addnav(array("%s %s %s", date("M Y", strtotime($row['month'] . "-01")), getsetting("paypalcurrency", "USD"), $row['profit']), "paylog.php?month={$row['month']}");
    }
function findcomm_run()
{
    global $session;
    $op = httpget('op');
    page_header("Find Commentary");
    if ($op != "enter") {
        addnav("Find Another Name", "runmodule.php?module=findcomm&op=enter");
    }
    switch ($op) {
        case "enter":
            output("Type in the name of the person whose commentary you wish to find.`n`n");
            rawoutput("<form action='runmodule.php?module=findcomm&op=list' method='post'>");
            rawoutput("Name: <input type='text' name='name'>");
            rawoutput("<input type='submit' class='button' value='" . translate_inline("Find") . "'></form>");
            addnav("", "runmodule.php?module=findcomm&op=list");
            break;
        case "list":
            $del = httppost('del');
            if ($del != "") {
                $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 commentid IN ('" . join("','", array_keys($del)) . "')";
                $res = db_query($sql);
                while ($row = db_fetch_assoc($res)) {
                    $sql = "INSERT LOW_PRIORITY INTO " . db_prefix("moderatedcomments") . " (moderator,moddate,comment) \r\n\t\t\t\t\t\t\tVALUES ('{$session['user']['acctid']}','" . date("Y-m-d H:i:s") . "','" . addslashes(serialize($row)) . "')";
                    db_query($sql);
                }
                $sql = "DELETE FROM " . db_prefix("commentary") . " \r\n\t\t\t\t\t\tWHERE commentid IN ('" . join("','", array_keys($del)) . "')";
                db_query($sql);
                output("Comments Deleted.`n`n");
            }
            $id = httpget('id');
            if ($id == "") {
                $name = httppost('name');
                $search = "%";
                for ($i = 0; $i < strlen($name); $i++) {
                    $search .= substr($name, $i, 1) . "%";
                }
                debug($search);
                $sql = "SELECT name,acctid FROM " . db_prefix("accounts") . " \r\n\t\t\t\t\t\tWHERE (name LIKE '{$search}' OR login LIKE '{$search}') \r\n\t\t\t\t\t\tLIMIT 25";
                $res = db_query($sql);
                $count = db_num_rows($res);
                $n = translate_inline("Name");
                rawoutput("<table border=0 cellpadding=2 align='center' cellspacing=1 bgcolor='#999999'>", true);
                rawoutput("<tr class='trhead'><td>{$n}</td></tr>");
                $i = 0;
                while ($row = db_fetch_assoc($res)) {
                    $i++;
                    $ac = $row['acctid'];
                    rawoutput("<tr class='" . ($i % 2 ? "trlight" : "trdark") . "'><td>");
                    rawoutput("<a href='runmodule.php?module=findcomm&op=list&id=" . rawurlencode($ac) . "'>");
                    output_notl("%s", $row['name']);
                    rawoutput("</a>");
                    addnav("", "runmodule.php?module=findcomm&op=list&id=" . rawurlencode($ac));
                    rawoutput("</td></tr>");
                }
                rawoutput("</table>");
            } else {
                $sql = "SELECT DISTINCT section FROM " . db_prefix("commentary") . " \r\n\t\t\t\t\t\tWHERE author='{$id}' \r\n\t\t\t\t\t\tORDER BY section ASC";
                $res = db_query($sql);
                $section = translate_inline("Section");
                $comments = translate_inline("Comments");
                rawoutput("<form action='runmodule.php?module=findcomm&op=list&id={$id}' method='post'>");
                rawoutput("<table border=0 cellpadding=2 align='center' cellspacing=1 bgcolor='#999999'>", true);
                rawoutput("<tr class='trhead'><td>{$section}</td><td>{$comments}</td></tr>");
                $i = 0;
                while ($row = db_fetch_assoc($res)) {
                    $i++;
                    $ac = $row['acctid'];
                    rawoutput("<tr class='" . ($i % 2 ? "trlight" : "trdark") . "'><td>");
                    output_notl("`b%s`b`0", $row['section']);
                    rawoutput("</td><td>");
                    output_notl("%s", findcomm_findcomment($row['section'], $id), true);
                    rawoutput("</td></tr>");
                }
                rawoutput("</table>");
                rawoutput("<input type='submit' class='button' value='" . translate_inline("Delete") . "'></form>");
                addnav("", "runmodule.php?module=findcomm&op=list&id={$id}");
            }
            break;
    }
    require_once "lib/superusernav.php";
    superusernav();
    page_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();
}
function charrestore_run()
{
    check_su_access(SU_EDIT_USERS);
    require_once "lib/superusernav.php";
    page_header("Character Restore");
    superusernav();
    addnav("Functions");
    addnav("Search", "runmodule.php?module=charrestore&op=list");
    if (httpget("op") == "list") {
        output("Please note that only characters who have reached at least level %s in DK %s will have been saved!`n`n", get_module_setting("lvl_threshold"), get_module_setting("dk_threshold"));
        rawoutput("<form action='runmodule.php?module=charrestore&op=list' method='POST'>");
        addnav("", "runmodule.php?module=charrestore&op=list");
        output("Character Login: "******"<input name='login' value=\"" . htmlentities(stripslashes(httppost("login")), ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "\"><br>");
        output("After date: ");
        rawoutput("<input name='start' value=\"" . htmlentities(stripslashes(httppost("start")), ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "\"><br>");
        output("Before date: ");
        rawoutput("<input name='end' value=\"" . htmlentities(stripslashes(httppost("end")), ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "\"><br>");
        $submit = translate_inline("Submit");
        rawoutput("<input type='submit' value='{$submit}' class='button'>");
        rawoutput("</form>");
        //do the search.
        $login = httppost("login");
        $start = httppost("start");
        $end = httppost("end");
        if ($start > "") {
            $start = strtotime($start);
        }
        if ($end > "") {
            $end = strtotime($end);
        }
        if ($login . $start . $end > "") {
            $path = charrestore_getstorepath();
            debug($path);
            $d = dir($path);
            $count = 0;
            while (($entry = $d->read()) !== false) {
                $e = explode("|", $entry);
                if (count($e) < 2) {
                    continue;
                }
                $name = str_replace("_", " ", $e[0]);
                $date = strtotime($e[1]);
                if ($login > "") {
                    if (strpos(strtolower($name), strtolower($login)) === false) {
                        continue;
                    }
                }
                if ($start > "") {
                    if ($date < $start) {
                        continue;
                    }
                }
                if ($end > "") {
                    if ($date > $end) {
                        continue;
                    }
                }
                $count++;
                rawoutput("<a href='runmodule.php?module=charrestore&op=beginrestore&file=" . rawurlencode($entry) . "'>{$name}</a> (" . date("M d, Y", $date) . ")<br>");
                addnav("", "runmodule.php?module=charrestore&op=beginrestore&file=" . rawurlencode($entry));
            }
            if ($count == 0) {
                output("No characters matching the specified criteria were found.");
            }
        }
    } elseif (httpget("op") == "beginrestore") {
        $user = unserialize(join("", file(charrestore_getstorepath() . httpget("file"))));
        $sql = "SELECT count(*) AS c FROM " . db_prefix("accounts") . " WHERE login='******'account']['login']}'";
        $result = db_query($sql);
        $row = db_fetch_assoc($result);
        rawoutput("<form action='runmodule.php?module=charrestore&op=finishrestore&file=" . rawurlencode(stripslashes(httpget("file"))) . "' method='POST'>");
        addnav("", "runmodule.php?module=charrestore&op=finishrestore&file=" . rawurlencode(stripslashes(httpget("file"))));
        if ($row['c'] > 0) {
            output("`\$The user's login conflicts with an existing login in the system.");
            output("You will have to provide a new one, and you should probably think about giving them a new name after the restore.`n");
            output("`^New Login: "******"<input name='newlogin'><br>");
        }
        $yes = translate_inline("Do the restore");
        rawoutput("<input type='submit' value='{$yes}' class='button'>");
        output("`n`#Some user info:`0`n");
        $vars = array("login" => "Login", "name" => "Name", "laston" => "Last On", "email" => "Email", "dragonkills" => "DKs", "level" => "Level", "gentimecount" => "Total hits");
        while (list($key, $val) = each($vars)) {
            output("`^{$val}: `#%s`n", $user['account'][$key]);
        }
        rawoutput("<input type='submit' value='{$yes}' class='button'>");
        rawoutput("</form>");
    } elseif (httpget("op") == "finishrestore") {
        $user = unserialize(join("", file(charrestore_getstorepath() . httpget("file"))));
        $sql = "SELECT count(*) AS c FROM " . db_prefix("accounts") . " WHERE login='******'newlogin') > '' ? httppost('newlogin') : $user['account']['login']) . "'";
        $result = db_query($sql);
        $row = db_fetch_assoc($result);
        if ($row['c'] > 0) {
            redirect("runmodule.php?module=charrestore&op=beginrestore&file=" . rawurlencode(stripslashes(httpget("file"))));
        } else {
            if (httppost("newlogin") > "") {
                $user['account']['login'] = httppost('newlogin');
            }
            $sql = "DESCRIBE " . db_prefix("accounts");
            $result = db_query($sql);
            $known_columns = array();
            while ($row = db_fetch_assoc($result)) {
                $known_columns[$row['Field']] = true;
            }
            $keys = array();
            $vals = array();
            while (list($key, $val) = each($user['account'])) {
                if ($key == "laston") {
                    array_push($keys, $key);
                    array_push($vals, "'" . date("Y-m-d H:i:s", strtotime("-1 day")) . "'");
                } elseif (!isset($known_columns[$key])) {
                    output("`2Dropping the column `^%s`n", $key);
                } else {
                    array_push($keys, $key);
                    array_push($vals, "'" . addslashes($val) . "'");
                }
            }
            $sql = "INSERT INTO " . db_prefix("accounts") . " (\n" . join("\t,\n", $keys) . ") VALUES (\n" . join("\t,\n", $vals) . ")";
            db_query($sql);
            $id = db_insert_id();
            if ($id > 0) {
                addnav("Edit the restored user", "user.php?op=edit&userid={$id}");
                if ($id != $user['account']['acctid']) {
                    output("`^The account was restored, though the account ID was not preserved; things such as news, mail, comments, debuglog, and other items associated with this account that were not stored as part of the snapshot have lost their association.");
                    output("The original ID was `&%s`^, and the new ID is `&%s`^.", $user['account']['acctid'], $id);
                    output("The most common cause of this problem is another account already present with the same ID.");
                    output("Did you do a restore of an already existing account?  If so, the existing account was not overwritten.`n");
                } else {
                    output("`#The account was restored.`n");
                }
                output("`#Now working on module preferences.`n");
                while (list($modulename, $values) = each($user['prefs'])) {
                    output("`3Module: `2%s`3...`n", $modulename);
                    if (is_module_installed($modulename)) {
                        while (list($prefname, $value) = each($values)) {
                            set_module_pref($prefname, $value, $modulename, $id);
                        }
                    } else {
                        output("`\$Skipping prefs for module `^%s`\$ because this module is not currently installed.`n", $modulename);
                    }
                }
                output("`#The preferences were restored.`n");
            } else {
                output("`\$Something funky has happened, preventing this account from correctly being created.");
                output("I'm sorry, you may have to recreate this account by hand.");
                output("The SQL I tried was:`n");
                rawoutput("<pre>" . htmlentities($sql, ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "</pre>");
            }
        }
    }
    page_footer();
}
function drinks_editor()
{
    global $mostrecentmodule;
    if (!get_module_pref("canedit")) {
        check_su_access(SU_EDIT_USERS);
    }
    page_header("Drink Editor");
    require_once "lib/superusernav.php";
    superusernav();
    addnav("Drink Editor");
    addnav("Add a drink", "runmodule.php?module=drinks&act=editor&op=add&admin=true");
    $op = httpget('op');
    $drinkid = httpget('drinkid');
    $header = "";
    if ($op != "") {
        addnav("Drink Editor Main", "runmodule.php?module=drinks&act=editor&admin=true");
        if ($op == 'add') {
            $header = translate_inline("Adding a new drink");
        } else {
            if ($op == 'edit') {
                $header = translate_inline("Editing a drink");
            }
        }
    } else {
        $header = translate_inline("Current drinks");
    }
    output_notl("`&<h3>{$header}`0</h3>", true);
    $drinksarray = array("Drink,title", "drinkid" => "Drink ID,hidden", "name" => "Drink Name", "costperlevel" => "Cost per level,int", "hpchance" => "Chance of modifying HP (see below),range,0,10,1", "turnchance" => "Chance of modifying turns (see below),range,0,10,1", "alwayshp" => "Always modify hitpoints,bool", "alwaysturn" => "Always modify turns,bool", "drunkeness" => "Drunkeness,range,1,100,1", "harddrink" => "Is drink hard alchohol?,bool", "hpmin" => "Min HP to add (see below),range,-20,20,1", "hpmax" => "Max HP to add (see below),range,-20,20,1", "hppercent" => "Modify HP by some percent (see below),range,-25,25,5", "turnmin" => "Min turns to add (see below),range,-5,5,1", "turnmax" => "Max turns to add (see below),range,-5,5,1", "remarks" => "Remarks", "buffname" => "Name of the buff", "buffrounds" => "Rounds buff lasts,range,1,20,1", "buffroundmsg" => "Message each round of buff", "buffwearoff" => "Message when buff wears off", "buffatkmod" => "Attack modifier of buff", "buffdefmod" => "Defense modifier of buff", "buffdmgmod" => "Damage modifier of buff", "buffdmgshield" => "Damage shield modifier of buff", "buffeffectfailmsg" => "Effect failure message (see below)", "buffeffectnodmgmsg" => "No damage message (see below)", "buffeffectmsg" => "Effect message (see below)");
    if ($op == "del") {
        $sql = "DELETE FROM " . db_prefix("drinks") . " WHERE drinkid='{$drinkid}'";
        module_delete_objprefs('drinks', $drinkid);
        db_query($sql);
        $op = "";
        httpset('op', "");
    }
    if ($op == "save") {
        $subop = httpget("subop");
        if ($subop == "") {
            $drinkid = httppost("drinkid");
            list($sql, $keys, $vals) = postparse($drinksarray);
            if ($drinkid > 0) {
                $sql = "UPDATE " . db_prefix("drinks") . " SET {$sql} WHERE drinkid='{$drinkid}'";
            } else {
                $sql = "INSERT INTO " . db_prefix("drinks") . " ({$keys}) VALUES ({$vals})";
            }
            db_query($sql);
            if (db_affected_rows() > 0) {
                output("`^Drink saved!");
            } else {
                $str = db_error();
                if ($str == "") {
                    output("`^Drink not saved: no changes detected.");
                } else {
                    output("`^Drink not saved: `\$%s`0", $sql);
                }
            }
        } elseif ($subop == "module") {
            $drinkid = httpget("drinkid");
            // Save module settings
            $module = httpget("editmodule");
            // This should obey the same rules as the configuration editor
            // So disabling
            //$sql = "DELETE FROM " . db_prefix("module_objprefs") . " WHERE objtype='drinks' AND objid='$drinkid' AND modulename='$module'";
            //db_query($sql);
            $post = httpallpost();
            reset($post);
            while (list($key, $val) = each($post)) {
                set_module_objpref("drinks", $drinkid, $key, $val, $module);
            }
            output("`^Saved.");
        }
        if ($drinkid) {
            $op = "edit";
            httpset("drinkid", $drinkid, true);
        } else {
            $op = "";
        }
        httpset('op', $op);
    }
    if ($op == "activate") {
        $sql = "UPDATE " . db_prefix("drinks") . " SET active=1 WHERE drinkid='{$drinkid}'";
        db_query($sql);
        $op = "";
        httpset('op', "");
    }
    if ($op == "deactivate") {
        $sql = "UPDATE " . db_prefix("drinks") . " SET active=0 WHERE drinkid='{$drinkid}'";
        db_query($sql);
        $op = "";
        httpset('op', "");
    }
    if ($op == "") {
        $op = translate_inline("Ops");
        $id = translate_inline("Id");
        $nm = translate_inline("Name");
        $dkn = translate_inline("Drunkeness");
        $hard = translate_inline("Hard Alchohol?");
        $edit = translate_inline("Edit");
        $deac = translate_inline("Deactivate");
        $act = translate_inline("Activate");
        $conf = translate_inline("Are you sure you wish to delete this drink?");
        $del = translate_inline("Del");
        rawoutput("<table border=0 cellpadding=2 cellspacing=1 bgcolor='#999999'>");
        rawoutput("<tr class='trhead'>");
        rawoutput("<td>{$op}</td><td>{$id}</td><td>{$nm}</td><td>{$dkn}</td><td>{$hard}</td>");
        rawoutput("</tr>");
        $sql = "SELECT drinkid,active,name,drunkeness,harddrink FROM " . db_prefix("drinks") . " ORDER BY drinkid";
        $result = db_query($sql);
        for ($i = 0; $i < db_num_rows($result); $i++) {
            $row = db_fetch_assoc($result);
            $id = $row['drinkid'];
            rawoutput("<tr class='" . ($i % 2 ? "trlight" : "trdark") . "'>");
            rawoutput("<td nowrap>[ <a href='runmodule.php?module=drinks&act=editor&op=edit&drinkid={$id}&admin=true'>{$edit}</a>");
            addnav("", "runmodule.php?module=drinks&act=editor&op=edit&drinkid={$id}&admin=true");
            if ($row['active']) {
                rawoutput(" | <a href='runmodule.php?module=drinks&act=editor&op=deactivate&drinkid={$id}&admin=true'>{$deac}</a>");
                addnav("", "runmodule.php?module=drinks&act=editor&op=deactivate&drinkid={$id}&admin=true");
            } else {
                rawoutput(" | <a href='runmodule.php?module=drinks&act=editor&op=activate&drinkid={$id}&admin=true'>{$act}</a>");
                addnav("", "runmodule.php?module=drinks&act=editor&op=activate&drinkid={$id}&admin=true");
            }
            rawoutput(" | <a href='runmodule.php?module=drinks&act=editor&op=del&drinkid={$id}&admin=true' onClick='return confirm(\"{$conf}\");'>{$del}</a> ]</td>");
            addnav("", "runmodule.php?module=drinks&act=editor&op=del&drinkid={$id}&admin=true");
            output_notl("<td>`^%s</td>`0", $id, true);
            output_notl("<td>`&%s`0</td>", $row['name'], true);
            output_notl("<td>`^%s`0</td>", $row['drunkeness'], true);
            $hard = translate_inline("`^No");
            if ($row['harddrink']) {
                $hard = translate_inline("`\$Yes");
            }
            output_notl("<td>%s`0</td>", $hard, true);
            rawoutput("</tr>");
        }
        rawoutput("</table>");
    }
    $subop = httpget("subop");
    if ($op == "edit") {
        addnav("Drink properties", "runmodule.php?module=drinks&act=editor&op=edit&drinkid={$drinkid}&admin=true");
        module_editor_navs("prefs-drinks", "runmodule.php?module=drinks&act=editor&drinkid={$drinkid}&op=edit&subop=module&editmodule=");
        if ($subop == "module") {
            $module = httpget("editmodule");
            $oldmodule = $mostrecentmodule;
            rawoutput("<form action='runmodule.php?module=drinks&act=editor&op=save&subop=module&editmodule={$module}&drinkid={$drinkid}&admin=true' method='POST'>");
            module_objpref_edit('drinks', $module, $drinkid);
            $mostrecentmodule = $oldmodule;
            rawoutput("</form>");
            addnav("", "runmodule.php?module=drinks&act=editor&op=save&subop=module&editmodule={$module}&drinkid={$drinkid}&admin=true");
        } elseif ($subop == "") {
            $sql = "SELECT * FROM " . db_prefix("drinks") . " WHERE drinkid='" . httpget('drinkid') . "'";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
        }
    } elseif ($op == "add") {
        /* We're adding a new drink, make an empty row */
        $row = array();
        $row['drinkid'] = 0;
    }
    if (($op == "edit" || $op == "add") && $subop == "") {
        rawoutput("<form action='runmodule.php?module=drinks&act=editor&op=save&admin=true' method='POST'>");
        addnav("", "runmodule.php?module=drinks&act=editor&op=save&admin=true");
        showform($drinksarray, $row);
        rawoutput("</form>");
        output("`\$NOTE:`7 Make sure that you know what you are doing when modifying or adding drinks.`n");
        output("Just because the drinks have a lot of options, doesn't mean you have to use all of them`n`n");
        output("`2Drink ID: `7This field is used internally and should be unique.`n");
        output("`2Name: `7The name of the drink the user will see.`n");
        output("`2Cost per level: `7This value times the users level is the drink cost.`n");
        output("`2Chance of modifying HP: `7If set, this is the number of chances out of the total of this and the turn chance for HP getting modified.`n");
        output("`2Chance of modifying turns: `7If set, this is the number of chances out of the total of this and the HP chance for turns getting modified.`n");
        output("`2Always modify HP: `7If set, hitpoints will be modified.  Should not be set alongside HP chance above.`n");
        output("`2Always modify turns: `7If set, turns will be modified.  Should not be set alongside turn chance above.`n");
        output("`2Drunkeness: `7How drunk will this make the player.`n");
        output("`2Hard Drink: `7Users are only allowed a certain number of hard drinks per day regardless of drunkeness.`n");
        output("`2Min HP to add: `7If we are modifying hitpoints, and if HP percent isn't set, use this and the HP max value to pick a random amount of HP to add.  Can be negative.`n");
        output("`2Max HP to add: `7If we are modifying hitpoints and if HP percent isn't set, use this and the HP min value to pick a random amount of HP to add.  Can be negative.`n");
        output("`2HP percent: `7If we are modifying hitpoints and if this is set, the users hitpoints are modified by this percentage.  Can be negative.`n");
        output("`2Min turns to add: `7If we are modifying turns, use this and the turn max value to pick a random amount of turns to add.  Can be negative.`n");
        output("`2Max turns to add: `7If we are modifying turns, use this and the turn min value to pick a random amount of turns to add.  Can be negative.`n");
        output("`2Remarks: `7Text displayed to the user when they order the drink.`n");
        output("`2Buff name: `7What is this buff called.`n");
        output("`2Buff rounds: `7How many rounds this buff lasts.`n");
        output("`2Buff round message: `7What message should show as each round occurs.`n");
        output("`2Buff wearoff: `7What message is shown when this buff wears off.`n");
        output("`2Buff attack modifier: `7Multiplier to modify attack points by? 1.0 is no modification, 2.0 doubles their attack points.`n");
        output("`2Buff defense modifier: `7Multiplier to modify defense points by? 1.0 is no modification, 2.0 doubles their defense points.`n");
        output("`2Buff damage modifier: `7Multiplier to modify damage by? 1.0 is no modification, 2.0 doubles their damage points. This is `\$VERY POTENT`7!`n");
        output("`2Buff damage shield modifier: `7When you are hit, deals damage to your opponent based on damage done to you. 1.0 deals identical damage, 2.0 deals double damage back to the opponent.`n");
        output("`2Effect failure message: Message if this buff fails. (Only used with damage shield)`n");
        output("`2Effect no damage message: Message if no damage is done. (Only used with damage shield)`n");
        output("`2Effect message: What shows when this buff has an effect. (Only used with damage shield)`n`n");
    }
    page_footer();
}
function alt_char_list_run()
{
    global $session;
    page_header("Alternate Character List");
    $op = httpget('op');
    $ac = db_prefix("accounts");
    switch ($op) {
        case "":
            $nmf = translate_inline("`inone`i");
            $page = httpget('page');
            $id = rawurldecode(httpget('id'));
            $pp = get_module_setting("pp");
            $pageoffset = (int) $page;
            if ($pageoffset > 0) {
                $pageoffset--;
            }
            $pageoffset *= $pp;
            $limit = "LIMIT {$pageoffset},{$pp}";
            $sql = "SELECT count(acctid) AS c FROM {$ac}";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            $total = $row['c'];
            $count = db_num_rows($result);
            if ($pageoffset + $pp < $total) {
                $cond = $pageoffset + $pp;
            } else {
                $cond = $total;
            }
            $extra = "";
            if ($id != "") {
                $extra = "WHERE acctid = {$id}";
            }
            $sql = "SELECT acctid, name, login, lastip, uniqueid, emailaddress FROM {$ac} {$extra} ORDER BY acctid ASC {$limit}";
            $acct_name = translate_inline("Character Name (login)");
            $ip = translate_inline("Alts by IP");
            $id = translate_inline("Alts by ID");
            $email = translate_inline("Alts by Email");
            $result = db_query($sql);
            rawoutput("<table border='0' cellpadding='2' cellspacing='1' align='center' bgcolor='#999999'>");
            rawoutput("<tr class='trhead'><td>{$acct_name}</td><td>{$ip}</td><td>{$id}</td><td>{$email}</td></tr>");
            if (db_num_rows($result) > 0) {
                $i = 0;
                while ($row = db_fetch_assoc($result)) {
                    $i++;
                    rawoutput("<tr class='" . ($i % 2 ? "trdark" : "trlight") . "'><td>");
                    output_notl("`&%s (%s)`0", $row['name'], $row['login']);
                    rawoutput("</td><td style='text-align:center;'>");
                    $sql_ip = "SELECT name, login FROM {$ac} WHERE lastip = '{$row['lastip']}' AND acctid != {$row['acctid']}";
                    $res_ip = db_query($sql_ip);
                    if (db_num_rows($res_ip) > 0) {
                        while ($row_ip = db_fetch_assoc($res_ip)) {
                            output_notl("`b%s`b (%s)`n", $row_ip['name'], $row_ip['login']);
                        }
                    } else {
                        output_notl("%s", $nmf);
                    }
                    rawoutput("</td><td style='text-align:center;'>");
                    $sql_id = "SELECT name, login FROM {$ac} WHERE uniqueid = '{$row['uniqueid']}' AND acctid != {$row['acctid']}";
                    $res_id = db_query($sql_id);
                    if (db_num_rows($res_id) > 0) {
                        while ($row_id = db_fetch_assoc($res_id)) {
                            output_notl("`b%s`b (%s)`n", $row_id['name'], $row_id['login']);
                        }
                    } else {
                        output_notl("%s", $nmf);
                    }
                    rawoutput("</td><td style='text-align:center;'>");
                    $sql_email = "SELECT name, login FROM {$ac} WHERE emailaddress = '{$row['emailaddress']}' AND acctid != {$row['acctid']}";
                    $res_email = db_query($sql_email);
                    if (db_num_rows($res_email) > 0) {
                        while ($row_email = db_fetch_assoc($res_email)) {
                            output_notl("`b%s`b (%s)`n", $row_email['name'], $row_email['login']);
                        }
                    } else {
                        output_notl("%s", $nmf);
                    }
                    rawoutput("</td></tr>");
                }
            }
            rawoutput("</table>");
            if ($total > $pp) {
                addnav("Pages");
                for ($p = 0; $p < $total; $p += $pp) {
                    addnav(array("Page %s (%s-%s)", $p / $pp + 1, $p + 1, min($p + $pp, $total)), "runmodule.php?module=alt_char_list&page=" . ($p / $pp + 1));
                }
            }
            break;
        case "search":
            addnav("Main Page", "runmodule.php?module=alt_char_list");
            if (httppost('submit')) {
                $name = httppost('char_name');
                $search = "%";
                for ($i = 0; $i < strlen($name); $i++) {
                    $search .= substr($name, $i, 1) . "%";
                }
                debug($search);
                $sql = "SELECT name, acctid, lastip, uniqueid, emailaddress FROM {$ac} WHERE (name LIKE '{$search}' OR login LIKE '{$search}')";
                $res = db_query($sql);
                $count = db_num_rows($res);
                $n = translate_inline("Name");
                $ip = translate_inline("IP");
                $id = translate_inline("ID");
                $email = translate_inline("Email");
                rawoutput("<table border='0' cellpadding='2' cellspacing='1' align='center' bgcolor='#999999'>");
                rawoutput("<tr class='trhead'><td>{$n}</td><td>{$ip}</td><td>{$id}</td><td>{$email}</td></tr>");
                $i = 0;
                while ($row = db_fetch_assoc($res)) {
                    $i++;
                    $id = $row['acctid'];
                    rawoutput("<tr class='" . ($i % 2 ? "trlight" : "trdark") . "'><td>");
                    rawoutput("<a href='runmodule.php?module=alt_char_list&id=" . rawurlencode($id) . "'>");
                    output_notl("%s", $row['name']);
                    rawoutput("</a>");
                    addnav("", "runmodule.php?module=alt_char_list&id=" . rawurlencode($id));
                    rawoutput("</td><td>");
                    output_notl("%s", $row['lastip']);
                    rawoutput("</td><td>");
                    output_notl("%s", $row['uniqueid']);
                    rawoutput("</td><td>");
                    output_notl("%s", $row['emailaddress']);
                    rawoutput("</td></tr>");
                }
                rawoutput("</table>");
            } else {
                $char_name = translate_inline("Character Name");
                rawoutput("<form action='runmodule.php?module=alt_char_list&op=search' method='post'>");
                rawoutput("{$char_name}: <input type='text' name='char_name'/><br/>");
                rawoutput("<input class='button' type='submit' name='submit' value='" . translate_inline("Submit") . "'/></form>");
            }
            addnav("", "runmodule.php?module=alt_char_list&op=search");
            break;
    }
    addnav("Other Actions");
    addnav("Search", "runmodule.php?module=alt_char_list&op=search");
    $ret = urlencode(httpget("ret"));
    if ($ret != "") {
        addnav("Return to viewing character", "bio.php?char={$char}&ret={$ret}");
    }
    require_once "lib/superusernav.php";
    superusernav();
    page_footer();
}
function dag_manage()
{
    page_header("Dag's Bounty Lists");
    require_once "lib/superusernav.php";
    superusernav();
    // Add some bounty expiration for closed bounties
    $sql = "DELETE FROM " . db_prefix("bounty") . " WHERE status=1 AND windate <'" . date("Y-m-d H:i:s", strtotime("-" . getsetting("expirecontent", 180) / 10 . " days")) . "'";
    db_query($sql);
    addnav("Actions");
    addnav("A?View All Bounties", "runmodule.php?module=dag&manage=true&op=viewbounties&type=1&sort=1&dir=1&admin=true");
    addnav("O?View Open Bounties", "runmodule.php?module=dag&manage=true&op=viewbounties&type=2&sort=1&dir=1&admin=true");
    addnav("C?View Closed Bounties", "runmodule.php?module=dag&manage=true&op=viewbounties&type=3&sort=1&dir=1&admin=true");
    addnav("R?Refresh List", "runmodule.php?module=dag&manage=true&admin=true");
    rawoutput("<form action='runmodule.php?module=dag&manage=true&op=viewbounties&type=search&admin=true' method='POST'>");
    addnav("", "runmodule.php?module=dag&manage=true&op=viewbounties&type=search&admin=true");
    output("Setter: ");
    rawoutput("<input name='setter' value=\"" . htmlentities(stripslashes(httppost('setter'))) . "\">");
    output(" Winner: ");
    rawoutput("<input name='getter' value=\"" . htmlentities(stripslashes(httppost('getter'))) . "\">");
    output(" Target: ");
    rawoutput("<input name='target' value=\"" . htmlentities(stripslashes(httppost('target'))) . "\">");
    output_notl("`n");
    output("Order by: ");
    $id = translate_inline("ID");
    $amt = translate_inline("Amount");
    $targ = translate_inline("Target");
    $set = translate_inline("Setter");
    $sdate = translate_inline("Set Date");
    $stat = translate_inline("Status");
    $win = translate_inline("Winner");
    $wdate = translate_inline("Win Date");
    $desc = translate_inline("Descending");
    $asc = translate_inline("Ascending");
    $search = translate_inline("Search");
    rawoutput("<select name='s'>\r\n\t\t<option value='1'" . (httppost('s') == '1' ? " selected" : "") . ">{$id}</option>\r\n\t\t<option value='2'" . (httppost('s') == '2' ? " selected" : "") . ">{$amt}</option>\r\n\t\t<option value='3'" . (httppost('s') == '3' ? " selected" : "") . ">{$targ}</option>\r\n\t\t<option value='4'" . (httppost('s') == '4' ? " selected" : "") . ">{$set}</option>\r\n\t\t<option value='5'" . (httppost('s') == '5' ? " selected" : "") . ">{$sdate}</option>\r\n\t\t<option value='6'" . (httppost('s') == '6' ? " selected" : "") . ">{$stat}</option>\r\n\t\t<option value='7'" . (httppost('s') == '7' ? " selected" : "") . ">{$win}</option>\r\n\t\t<option value='8'" . (httppost('s') == '8' ? " selected" : "") . ">{$wdate}</option>\r\n\t\t</select>");
    rawoutput("<input type='radio' name='d' value='1'" . (httppost('d') == 1 ? " checked" : "") . "> {$desc}");
    rawoutput("<input type='radio' name='d' value='2'" . (httppost('d') == 1 ? "" : " checked") . "> {$asc}");
    output_notl("`n");
    rawoutput("<input type='submit' class='button' value='{$search}'>");
    rawoutput("</form>");
    $op = httpget('op');
    if ($op == "") {
        // ***ADDED***
        // By Andrew Senger
        // Adding for new Bounty Code
        output_notl("`n`n");
        output("`c`bThe Bounty List`b`c`n");
        $sql = "SELECT bountyid,amount,target,setter,setdate FROM " . db_prefix("bounty") . " WHERE status=0 ORDER BY bountyid ASC";
        $result = db_query($sql);
        rawoutput("<table border=0 cellpadding=2 cellspacing=1 bgcolor='#999999'>");
        $amt = translate_inline("Amount");
        $lev = 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>{$amt}</b></td><td><b>{$lev}</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,uniqueid 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 ($listing[$j]['Name'] == $row2['name']) {
                    $listing[$j]['Amount'] = $listing[$j]['Amount'] + $amount;
                    $yesno = 1;
                }
            }
            if ($yesno == 0) {
                $listing[] = array('Amount' => $amount, 'Level' => $row2['level'], 'Name' => $row2['name'], 'Location' => $row2['location'], 'Sex' => $row2['sex'], 'Alive' => $row2['alive'], 'LastOn' => $row2['laston']);
                $totlist = $totlist + 1;
            }
        }
        usort($listing, 'dag_sortbounties');
        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($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']);
            if ($loggedin) {
                $laston = translate_inline("Now");
            }
            output_notl("%s", $laston);
            rawoutput("</td></tr>");
        }
        rawoutput("</table>");
        output("`n`n`c`bAdd Bounty`b`c`n");
        rawoutput("<form action='runmodule.php?module=dag&manage=true&op=addbounty&admin=true' 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&manage=true&op=addbounty&admin=true");
    } else {
        if ($op == "addbounty") {
            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("No one by that name!");
            } elseif (db_num_rows($result) > 100) {
                output("Too many names!");
            } elseif (db_num_rows($result) > 1) {
                output("Select the correct name:`n");
                rawoutput("<form action='runmodule.php?module=dag&manage=true&op=addbounty&subfinal=1&admin=true' 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&manage=true&op=addbounty&subfinal=1");
            } else {
                // Now, we have just the one, so check it.
                $row = db_fetch_assoc($result);
                if ($row['locked']) {
                    output("Target is a locked user.");
                }
                $amt = (int) httppost('amount');
                if ($amt <= 0) {
                    output("That bounty value make no sense.");
                } else {
                    // All good!
                    $sql = "INSERT INTO " . db_prefix("bounty") . " (amount, target, setter, setdate) VALUES ({$amt}, " . $row['acctid'] . ", 0, '" . date("Y-m-d H:i:s") . "')";
                    db_query($sql);
                    output("Bounty added!");
                }
            }
        } else {
            if ($op == "viewbounties") {
                $type = httpget('type');
                $sort = httpget('sort');
                $dir = httpget('dir');
                output("`c`bThe Bounty List`b`c`n");
                if ($type == 1) {
                    output("`c`bViewing: `3All Bounties`b`c");
                } elseif ($type == 2) {
                    output("`c`bViewing: `3Open Bounties`b`c");
                } elseif ($type == 3) {
                    output("`c`bViewing: `3Closed Bounties`b`c");
                }
                addnav("Sorting");
                if ($sort == 1 && $dir == 1) {
                    addnav("1?By BountyID - Asc", "runmodule.php?module=dag&manage=true&op=viewbounties&type=" . $type . "&sort=1&dir=2&admin=true");
                    output("`c`bSorting By: `3BountyID - Desc`b`c`n`n");
                } elseif ($sort == 1 && $dir == 2) {
                    addnav("1?By BountyID - Desc", "runmodule.php?module=dag&manage=true&op=viewbounties&type=" . $type . "&sort=1&dir=1&admin=true");
                    output("`c`bSorting By: `3BountyID - Asc`b`c`n`n");
                } else {
                    addnav("1?By BountyID - Desc", "runmodule.php?module=dag&manage=true&op=viewbounties&type=" . $type . "&sort=1&dir=1&admin=true");
                }
                if ($sort == 2 && $dir == 1) {
                    addnav("2?By Amount - Asc", "runmodule.php?module=dag&manage=true&op=viewbounties&type=" . $type . "&sort=2&dir=2&admin=true");
                    output("`c`bSorting By: `3Amount - Desc`b`c`n`n");
                } elseif ($sort == 2 && $dir == 2) {
                    addnav("2?By Amount - Desc", "runmodule.php?module=dag&manage=true&op=viewbounties&type=" . $type . "&sort=2&dir=1&admin=true");
                    output("`c`bSorting By: `3Amount - Asc`b`c`n`n");
                } else {
                    addnav("2?By Amount - Desc", "runmodule.php?module=dag&manage=true&op=viewbounties&type=" . $type . "&sort=2&dir=1&admin=true");
                }
                if ($sort == 3 && $dir == 1) {
                    addnav("3?By Target - Asc", "runmodule.php?module=dag&manage=true&op=viewbounties&type=" . $type . "&sort=3&dir=2&admin=true");
                    output("`c`bSorting By: `3Target - Desc`b`c`n`n");
                } elseif ($sort == 3 && $dir == 2) {
                    addnav("3?By Target - Desc", "runmodule.php?module=dag&manage=true&op=viewbounties&type=" . $type . "&sort=3&dir=1&admin=true");
                    output("`c`bSorting By: `3Target - Asc`b`c`n`n");
                } else {
                    addnav("3?By Target - Desc", "runmodule.php?module=dag&manage=true&op=viewbounties&type=" . $type . "&sort=3&dir=1&admin=true");
                }
                if ($sort == 4 && $dir == 1) {
                    addnav("4?By Setter - Asc", "runmodule.php?module=dag&manage=true&op=viewbounties&type=" . $type . "&sort=4&dir=2&admin=true");
                    output("`c`bSorting By: `3Setter - Desc`b`c`n`n");
                } elseif ($sort == 4 && $dir == 2) {
                    addnav("4?By Setter - Desc", "runmodule.php?module=dag&manage=true&op=viewbounties&type=" . $type . "&sort=4&dir=1&admin=true");
                    output("`c`bSorting By: `3Setter - Asc`b`c`n`n");
                } else {
                    addnav("4?By Setter - Desc", "runmodule.php?module=dag&manage=true&op=viewbounties&type=" . $type . "&sort=4&dir=1&admin=true");
                }
                if ($sort == 5 && $dir == 1) {
                    addnav("5?By Set Date - Asc", "runmodule.php?module=dag&manage=true&op=viewbounties&type=" . $type . "&sort=5&dir=2&admin=true");
                    output("`c`bSorting By: `3Set Date - Desc`b`c`n`n");
                } elseif ($sort == 5 && $dir == 2) {
                    addnav("5?By Set Date - Desc", "runmodule.php?module=dag&manage=true&op=viewbounties&type=" . $type . "&sort=5&dir=1&admin=true");
                    output("`c`bSorting By: `3Set Date - Asc`b`c`n`n");
                } else {
                    addnav("5?By Set Date - Desc", "runmodule.php?module=dag&manage=true&op=viewbounties&type=" . $type . "&sort=5&dir=1&admin=true");
                }
                if ($type == 1) {
                    if ($sort == 6 && $dir == 1) {
                        addnav("6?By Status - Asc", "runmodule.php?module=dag&manage=true&op=viewbounties&type=" . $type . "&sort=6&dir=2&admin=true");
                        output("`c`bSorting By: `3Status - Desc`b`c`n`n");
                    } elseif ($sort == 6 && $dir == 2) {
                        addnav("6?By Status - Desc", "runmodule.php?module=dag&manage=true&op=viewbounties&type=" . $type . "&sort=6&dir=1&admin=true");
                        output("`c`bSorting By: `3Status - Asc`b`c`n`n");
                    } else {
                        addnav("6?By Status - Desc", "runmodule.php?module=dag&manage=true&op=viewbounties&type=" . $type . "&sort=6&dir=1&admin=true");
                    }
                }
                if ($type == 1 || $type == 3) {
                    if ($sort == 7 && $dir == 1) {
                        addnav("7?By Winner - Asc", "runmodule.php?module=dag&manage=true&op=viewbounties&type=" . $type . "&sort=7&dir=2&admin=true");
                        output("`c`bSorting By: `3Winner - Desc`b`c`n`n");
                    } elseif ($sort == 7 && $dir == 2) {
                        addnav("7?By Winner - Desc", "runmodule.php?module=dag&manage=true&op=viewbounties&type=" . $type . "&sort=7&dir=1&admin=true");
                        output("`c`bSorting By: `3Winner - Asc`b`c`n`n");
                    } else {
                        addnav("7?By Winner - Desc", "runmodule.php?module=dag&manage=true&op=viewbounties&type=" . $type . "&sort=7&dir=1&admin=true");
                    }
                    if ($sort == 8 && $dir == 1) {
                        addnav("8?By Win Date - Asc", "runmodule.php?module=dag&manage=true&op=viewbounties&type=" . $type . "&sort=8&dir=2&admin=true");
                        output("`c`bSorting By: `3Win Date - Desc`b`c`n`n");
                    } elseif ($sort == 8 && $dir == 2) {
                        addnav("8?By Win Date - Desc", "runmodule.php?module=dag&manage=true&op=viewbounties&type=" . $type . "&sort=8&dir=1&admin=true");
                        output("`c`bSorting By: `3Win Date - Asc`b`c`n`n");
                    } else {
                        addnav("8?By Win Date - Desc", "runmodule.php?module=dag&manage=true&op=viewbounties&type=" . $type . "&sort=8&dir=1&admin=true");
                    }
                }
                addnav("Return to Bounty Home", "runmodule.php?module=dag&manage=true&op=bounties&admin=true");
                switch ($type) {
                    case 1:
                        $t = "";
                        break;
                    case 2:
                        $t = " WHERE status=0";
                        break;
                    case 3:
                        $t = " WHERE status=1";
                        break;
                }
                switch ($sort) {
                    case 1:
                        $s = " ORDER BY bountyid";
                        break;
                    case 2:
                        $s = " ORDER BY amount";
                        break;
                    case 3:
                        $s = " ORDER BY target";
                        break;
                    case 4:
                        $s = " ORDER BY setter";
                        break;
                    case 5:
                        $s = " ORDER BY setdate";
                        break;
                    case 6:
                        $s = " ORDER BY status";
                        break;
                    case 7:
                        $s = " ORDER BY winner";
                        break;
                    case 8:
                        $s = " ORDER BY windate";
                        break;
                }
                switch ($dir) {
                    case 1:
                        $d = " DESC";
                        break;
                    case 2:
                        $d = " ASC";
                        break;
                }
                //override those options in favor of the search form if it exists
                if ($type == 'search') {
                    switch (httppost('s')) {
                        case 1:
                            $s = " ORDER BY bountyid";
                            break;
                        case 2:
                            $s = " ORDER BY amount";
                            break;
                        case 3:
                            $s = " ORDER BY target";
                            break;
                        case 4:
                            $s = " ORDER BY setter";
                            break;
                        case 5:
                            $s = " ORDER BY setdate";
                            break;
                        case 6:
                            $s = " ORDER BY status";
                            break;
                        case 7:
                            $s = " ORDER BY winner";
                            break;
                        case 8:
                            $s = " ORDER BY windate";
                            break;
                    }
                    switch (httppost('d')) {
                        case 1:
                            $d = " DESC";
                            break;
                        case 2:
                            $d = " ASC";
                            break;
                    }
                    $t = "";
                    if (httppost('setter') > '') {
                        if ($t > "") {
                            $t .= " AND";
                        }
                        $a = httppost('setter');
                        $setter = "%";
                        for ($i = 0; $i < strlen($a); $i++) {
                            $setter .= $a[$i] . "%";
                        }
                        $sql = "SELECT acctid FROM " . db_prefix("accounts") . " WHERE name LIKE '{$setter}'";
                        $result = db_query($sql);
                        $ids = array();
                        while ($row = db_fetch_assoc($result)) {
                            array_push($ids, $row['acctid']);
                        }
                        if (count($ids) == 0) {
                            $ids[0] = 0;
                        }
                        $t .= " setter IN (" . join(",", $ids) . ")";
                    }
                    if (httppost('getter') > '') {
                        if ($t > "") {
                            $t .= " AND";
                        }
                        $a = httppost('getter');
                        $getter = "%";
                        for ($i = 0; $i < strlen($a); $i++) {
                            $getter .= $a[$i] . "%";
                        }
                        $sql = "SELECT acctid FROM " . db_prefix("accounts") . " WHERE name LIKE '{$getter}'";
                        $result = db_query($sql);
                        $ids = array();
                        while ($row = db_fetch_assoc($result)) {
                            array_push($ids, $row['acctid']);
                        }
                        if (count($ids) == 0) {
                            $ids[0] = 0;
                        }
                        $t .= " winner IN (" . join(",", $ids) . ")";
                    }
                    if (httppost('target') > '') {
                        if ($t > "") {
                            $t .= " AND";
                        }
                        $a = httppost('target');
                        $target = "%";
                        for ($i = 0; $i < strlen($a); $i++) {
                            $target .= $a[$i] . "%";
                        }
                        $sql = "SELECT acctid FROM " . db_prefix("accounts") . " WHERE name LIKE '{$target}'";
                        $result = db_query($sql);
                        $ids = array();
                        while ($row = db_fetch_assoc($result)) {
                            array_push($ids, $row['acctid']);
                        }
                        if (count($ids) == 0) {
                            $ids[0] = 0;
                        }
                        $t .= " target IN (" . join(",", $ids) . ")";
                    }
                    if ($t > "") {
                        $t = " WHERE" . $t;
                    }
                }
                $sql = "SELECT bountyid,amount,target,setter,setdate,status,winner,windate FROM " . db_prefix("bounty") . $t . $s . $d;
                $result = db_query($sql);
                rawoutput("<table border=0 cellpadding=2 cellspacing=1 bgcolor='#999999'>");
                $id = translate_inline("ID");
                $amt = translate_inline("Amt");
                $targ = translate_inline("Target");
                $set = translate_inline("Setter");
                $sdate = translate_inline("Set Date/Time");
                $stat = translate_inline("Status");
                $win = translate_inline("Winner");
                $wdate = translate_inline("Win Date/Time");
                $ops = translate_inline("Ops");
                rawoutput("<tr class='trhead'><td><b>{$id}</b></td><td><b>{$amt}</b></td><td><b>{$targ}</b></td><td><b>{$set}</b></td><td><b>{$sdate}</b></td><td><b>{$stat}</b></td><td><b>{$win}</b></td><td><b>{$wdate}</b></td><td>{$ops}</td></tr>");
                for ($i = 0; $i < db_num_rows($result); $i++) {
                    $row = db_fetch_assoc($result);
                    if ($row['target'] == 0) {
                        $target['name'] = translate_inline("`2Green Dragon");
                    } else {
                        $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid=" . (int) $row['target'];
                        $result2 = db_query($sql);
                        if (db_num_rows($result2) == 0) {
                            $target['name'] = translate_inline("`4Deleted Character");
                        } else {
                            $target = db_fetch_assoc($result2);
                        }
                    }
                    if ($row['setter'] == 0) {
                        $setter['name'] = translate_inline("`2Green Dragon");
                    } else {
                        $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid=" . (int) $row['setter'];
                        $result3 = db_query($sql);
                        if (db_num_rows($result3) == 0) {
                            $setter['name'] = translate_inline("`4Deleted Character");
                        } else {
                            $setter = db_fetch_assoc($result3);
                        }
                    }
                    $winner['name'] = "";
                    if ($row['winner'] == 0 && $row['status'] == 1) {
                        $winner['name'] = translate_inline("`2Green Dragon");
                    } elseif ($row['status'] == 1) {
                        $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid=" . (int) $row['winner'];
                        $result4 = db_query($sql);
                        if (db_num_rows($result4) == 0) {
                            $winner['name'] = translate_inline("`2Deleted Character");
                        } else {
                            $winner = db_fetch_assoc($result4);
                        }
                    }
                    rawoutput("<tr class='" . ($i % 2 ? "trdark" : "trlight") . "'><td>");
                    output_notl("`^%s`0", $row['bountyid']);
                    rawoutput("</td><td>");
                    output_notl("`^%s`0", $row['amount']);
                    rawoutput("</td><td>");
                    output_notl("`&%s`0", $target['name']);
                    rawoutput("</td><td>");
                    output_notl("`^%s`0", $setter['name']);
                    rawoutput("</td><td>");
                    output_notl("`^%s`0", $row['setdate']);
                    rawoutput("</td><td>");
                    output($row['status'] == 0 ? "`^Open`0" : "`^Closed`0");
                    rawoutput("</td><td>");
                    output_notl("`^%s`0", $winner['name']);
                    rawoutput("</td><td>");
                    output_notl("`^%s`0", $row['status'] ? $row['windate'] : "");
                    rawoutput("</td><td>");
                    if ($row['status'] == 0) {
                        $link = "runmodule.php?module=dag&manage=true&op=closebounty&id={$row['bountyid']}&admin=true";
                        $close = translate_inline("Close");
                        rawoutput("<a href=\"{$link}\">{$close}</a>");
                        addnav("", $link);
                    } else {
                        rawoutput("&nbsp;");
                    }
                    rawoutput("</td></tr>");
                }
                rawoutput("</table>");
            } else {
                if ($op == "closebounty") {
                    $windate = date("Y-m-d H:i:s");
                    $bountyid = (int) httpget('id');
                    $sql = "UPDATE " . db_prefix("bounty") . " SET status=1,winner=0,windate=\"{$windate}\" WHERE bountyid={$bountyid}";
                    db_query($sql);
                    output("Bounty closed.");
                    // ***END ADD***
                }
            }
        }
    }
    page_footer();
}
function riddles_editor()
{
    global $session;
    require_once "lib/nltoappon.php";
    if (!get_module_pref("canedit")) {
        check_su_access(SU_EDIT_RIDDLES);
    }
    $op = httpget('op');
    $id = httpget('id');
    page_header("Riddle Editor");
    require_once "lib/superusernav.php";
    superusernav();
    addnav("Riddle Editor");
    addnav("Riddle Editor Home", "runmodule.php?module=riddles&act=editor&admin=true");
    addnav("Add a riddle", "runmodule.php?module=riddles&act=editor&op=edit&admin=true");
    if ($op == "save") {
        $id = httppost('id');
        $riddle = trim(httppost('riddle'));
        $answer = trim(httppost('answer'));
        if ($id > "") {
            $sql = "UPDATE " . db_prefix("riddles") . " SET riddle='" . nltoappon($riddle) . "', answer='{$answer}' WHERE id='{$id}'";
        } else {
            $sql = "INSERT INTO " . db_prefix("riddles") . " (riddle,answer,author) VALUES('" . nltoappon($riddle) . "','{$answer}','{$session['user']['login']}')";
        }
        db_query($sql);
        if (db_affected_rows() > 0) {
            $op = "";
            httpset("op", "");
            output("Riddle saved.");
        } else {
            output("The query was not executed for some reason I can't fathom.");
            output("Perhaps you didn't actually make any changes to the riddle.");
        }
    } elseif ($op == "del") {
        $sql = "DELETE FROM " . db_prefix("riddles") . " WHERE id='{$id}'";
        db_query($sql);
        $op = "";
        httpset("op", "");
        output("Riddle deleted.");
    }
    if ($op == "") {
        $sql = "SELECT * FROM " . db_prefix("riddles");
        $result = db_query($sql);
        $i = translate_inline("Id");
        $ops = translate_inline("Ops");
        $rid = translate_inline("Riddle");
        $ans = translate_inline("Answer");
        $auth = translate_inline("Author");
        rawoutput("<table border=0 cellpadding=2 cellspacing=1 bgcolor='#999999'><tr class='trhead'><td>{$i}</td><td>{$ops}</td><td>{$rid}</td><td>{$ans}</td><td>{$auth}</td></tr>");
        for ($i = 0; $i < db_num_rows($result); $i++) {
            $row = db_fetch_assoc($result);
            rawoutput("<tr class='" . ($i % 2 ? "trlight" : "trdark") . "'>");
            rawoutput("<td valign='top'>");
            output_notl("%s", $row['id']);
            rawoutput("</td><td valign='top'>");
            $conf = translate_inline("Are you sure you wish to delete this riddle?");
            $edit = translate_inline("Edit");
            $del = translate_inline("Delete");
            $elink = "runmodule.php?module=riddles&act=editor&op=edit&id=" . $row['id'] . "&admin=true";
            $dlink = "runmodule.php?module=riddles&act=editor&op=del&id=" . $row['id'] . "&admin=true";
            output_notl("[");
            rawoutput("<a href='{$elink}'>{$edit}</a>");
            output_notl("|");
            rawoutput("<a href='{$dlink}' onClick='return confirm(\"{$conf}\");'>{$del}</a>");
            output_notl("]");
            addnav("", $elink);
            addnav("", $dlink);
            rawoutput("</td><td valign='top'>");
            output_notl("`&%s`0", $row['riddle']);
            rawoutput("</td><td valign='top'>");
            output_notl("`#%s`0", $row['answer']);
            rawoutput("</td><td valign='top'>");
            output_notl("`^%s`0", $row['author']);
            rawoutput("</td></tr>");
        }
        rawoutput("</table>");
    } elseif ($op == "edit") {
        $sql = "SELECT * FROM " . db_prefix("riddles") . " WHERE id='{$id}'";
        $result = db_query($sql);
        rawoutput("<form action='runmodule.php?module=riddles&act=editor&op=save&admin=true' method='POST'>", true);
        addnav("", "runmodule.php?module=riddles&act=editor&op=save&admin=true");
        if ($row = db_fetch_assoc($result)) {
            output("`bEdit a riddle`b`n");
            $title = "Edit a riddle";
            $i = $row['id'];
            rawoutput("<input type='hidden' name='id' value='{$i}'>");
        } else {
            output("`bAdd a riddle`b`n");
            $title = "Add a riddle";
            $row = array("riddle" => "", "answer" => "", "author" => $session['user']['login']);
        }
        $form = array("Riddle,title", "riddle" => "Riddle text,textarea", "answer" => "Answer", "author" => "Author,viewonly");
        require_once "lib/showform.php";
        showform($form, $row);
        rawoutput("</form>");
        output("`^NOTE:`& Separate multiple correct answers with semicolons (;)`n`n");
        output("`7The following are ignored at the start of answers: `&a, an, and, the, my, your, someones, someone's, someone, his, hers`n");
        output("`7The following are ignored at the end of answers: `&s, ing, ed`0`n`n");
        output("`\$NOTE:  Riddles are displayed in the language they are stored in the database.");
        output("Similarly, answers are expected in the language stored in the database.");
    }
    page_footer();
}
function translationwizard_run()
{
    global $session, $logd_version, $coding;
    check_su_access(SU_IS_TRANSLATOR);
    //check again Superuser Access
    $op = httpget('op');
    page_header("Translation Wizard");
    //get some standards
    $languageschema = get_module_pref("language", "translationwizard");
    //these lines grabbed the local scheme, in 1.1.0 there is a setting for it
    $coding = getsetting("charset", "ISO-8859-1");
    $viewsimple = get_module_pref("view", "translationwizard");
    $mode = httpget('mode');
    $namespace = httppost('ns');
    $from = httpget('from');
    $page = get_module_setting(page);
    if (httpget('ns') != "" && $namespace == "") {
        $namespace = httpget('ns');
    }
    //if there is no post then there is maybe something to get
    $trans = httppost("transtext");
    if (is_array($trans)) {
        $transintext = $trans;
    } else {
        if ($trans) {
            $transintext = array($trans);
        } else {
            $transintext = array();
        }
    }
    $trans = httppost("transtextout");
    if (is_array($trans)) {
        $transouttext = $trans;
    } else {
        if ($trans) {
            $transouttext = array($trans);
        } else {
            $transouttext = array();
        }
    }
    //end of the header
    if ($op == "") {
        $op = "default";
    }
    require "./modules/translationwizard/errorhandler.php";
    require "./modules/translationwizard/{$op}.php";
    require_once "lib/superusernav.php";
    superusernav();
    require "./modules/translationwizard/build_nav.php";
    page_footer();
}