function friendlist_search()
{
    global $session;
    $n = httppost("n");
    rawoutput("<form action='runmodule.php?module=friendlist&op=search' method='POST'>");
    addnav("", "runmodule.php?module=friendlist&op=search");
    if ($n != "") {
        $string = "%";
        for ($x = 0; $x < strlen($n); $x++) {
            $string .= substr($n, $x, 1) . "%";
        }
        $sql = "SELECT name,dragonkills,acctid FROM " . db_prefix("accounts") . " WHERE name LIKE '%{$string}%' AND acctid<>" . $session['user']['acctid'] . " AND locked=0 ORDER BY level,dragonkills";
        $result = db_query($sql);
        if (db_num_rows($result) > 0) {
            $ignored = rexplode(get_module_pref('ignored'));
            $friends = rexplode(get_module_pref('friends'));
            $request = rexplode(get_module_pref('request'));
            $iveignored = rexplode(get_module_pref('iveignored'));
            output("`@These users were found:`n");
            rawoutput("<table style='width:60%;text-align:center;' cellpadding='3' cellspacing='0' border='0'>");
            rawoutput("<tr class='trhead'><td>" . translate_inline("Name") . "</td><td>" . translate_inline("Operations") . "</td></tr>");
            for ($i = 0; $i < db_num_rows($result); $i++) {
                $row = db_fetch_assoc($result);
                rawoutput("<tr class='" . ($i % 2 ? "trlight" : "trdark") . "'><td>");
                output_notl($row['name']);
                rawoutput("</td><td>");
                if (in_array($row['acctid'], $ignored)) {
                    $info = translate_inline("This user has ignored you.");
                    $info .= " [<a href='runmodule.php?module=friendlist&op=ignore&ac=" . $row['acctid'] . "' class='colDkGreen'>" . translate_inline("Ignore") . "</a>]";
                    addnav("", "runmodule.php?module=friendlist&op=ignore&ac=" . $row['acctid']);
                } elseif (in_array($row['acctid'], $friends)) {
                    $info = translate_inline("This user is already in your list.");
                } elseif (in_array($row['acctid'], $request)) {
                    $info = translate_inline("This user has already requested to you.");
                } else {
                    if (in_array($row['acctid'], $iveignored)) {
                        $info = "[<a href='runmodule.php?module=friendlist&op=unignore&ac=" . $row['acctid'] . "' class='colLtRed'>" . translate_inline("Unignore") . "</a>]";
                        addnav("", "runmodule.php?module=friendlist&op=unignore&ac=" . $row['acctid']);
                    } else {
                        $info = "[<a href='runmodule.php?module=friendlist&op=ignore&ac=" . $row['acctid'] . "' class='colDkGreen'>" . translate_inline("Ignore") . "</a>]";
                        addnav("", "runmodule.php?module=friendlist&op=ignore&ac=" . $row['acctid']);
                        $info .= " - [<a href='runmodule.php?module=friendlist&op=request&ac=" . $row['acctid'] . "' class='colDkGreen'>" . translate_inline("Request") . "</a>]";
                        addnav("", "runmodule.php?module=friendlist&op=request&ac=" . $row['acctid']);
                    }
                }
                rawoutput("{$info}</td></tr>");
            }
            rawoutput("</table>");
        } else {
            output("`c`@`bA user was not found with that name.`b`c");
        }
        output_notl("`n");
    }
    output("`^`b`cFriend Search...`c`b");
    output("`n`nWho do you want to search for?");
    output("`n`nName of user: "******"<input name='n' maxlength='50' value=\"" . htmlentities(stripslashes(httppost('n'))) . "\">");
    $apply = translate_inline("Search");
    rawoutput("<input type='submit' class='button' value='{$apply}'></form>");
}
function hunterslodge_customarmour_run()
{
    require_once "lib/sanitize.php";
    require_once "lib/names.php";
    global $session;
    $op = httpget("op");
    $free = httpget("free");
    page_header("Choose your Custom Armour");
    switch ($op) {
        case "change":
            output("Want to change your Custom Armour?  No problem.  Enter your desired armour in the box below.  You've got 25 characters to play around with.`n(leave this blank to disable custom armour naming and return to default, game-supplied armour names)`n`n");
            rawoutput("<form action='runmodule.php?module=hunterslodge_customarmour&op=confirm&free=" . $free . "' method='POST'>");
            $armour = get_module_pref("customarmour");
            rawoutput("<input id='input' name='newarmour' width='25' maxlength='25' value='" . htmlentities($armour, ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "'>");
            rawoutput("<input type='submit' class='button' value='Preview'>");
            rawoutput("</form>");
            addnav("", "runmodule.php?module=hunterslodge_customarmour&op=confirm&free=" . $free);
            addnav("Cancel");
            addnav("Don't set custom armour, just go back to the Lodge", "runmodule.php?module=iitems_hunterslodge&op=start");
            break;
        case "confirm":
            $newarmour = httppost("newarmour");
            $sub = httpget("sub");
            $newarmour = str_replace("`", "", $newarmour);
            $newarmour = comment_sanitize($newarmour);
            $newarmour = substr($newarmour, 0, 25);
            if ($newarmour) {
                output("Your new custom armour is:`n%s`nWould you like to set your new armour now?`n`n", $newarmour);
            } else {
                output("You've chosen to go back to the default, game-supplied armours.  Are you sure that's what you want?`n`n");
            }
            addnav("Confirm");
            addnav("Set custom armour", "runmodule.php?module=hunterslodge_customarmour&op=set&free={$free}&newarmour=" . rawurlencode($newarmour));
            addnav("Cancel");
            addnav("Don't set custom armour, just go back to the Lodge", "runmodule.php?module=iitems_hunterslodge&op=start");
            break;
        case "set":
            $newarmour = rawurldecode(httpget("newarmour"));
            if ($newarmour == "") {
                output("Your custom armour name has been removed.  The next time you change your armour, you'll return to game-supplied armour names.`n`n");
            } else {
                output("Your custom armour has been set to %s!`n`n", $newarmour);
                $session['user']['armor'] = $newarmour;
            }
            set_module_pref("customarmour", $newarmour);
            if (!$free) {
                require_once "modules/iitems/lib/lib.php";
                $id = has_item("hunterslodge_customarmour");
                delete_item($id);
            }
            addnav("Return");
            addnav("Return to the Lodge", "runmodule.php?module=iitems_hunterslodge&op=start");
            break;
    }
    page_footer();
}
function dwellingscostsp_dohook($hookname, $args)
{
    global $session;
    switch ($hookname) {
        case "dwellings-buy-valuecheck":
            $typeid = get_module_setting("typeid", $args['type']);
            $paidsp = abs((int) httppost('paidsp'));
            if ($paidsp < 0) {
                $paidsp = 0;
            }
            $pointsavailable = $session['user']['donation'] - $session['user']['donationspent'];
            if ($pointsavailable < $paidsp) {
                $args['allowpay'] = 0;
                blocknav("runmodule.php?module=dwellings&op=build&type=" . $args['type'] . "&dwid=" . $args['dwid'] . "");
                output("`nYou do not have that many site points.");
            } elseif ($paidsp > get_module_objpref("dwellingtypes", $typeid, "spcost") - get_module_objpref("dwellings", $args['dwid'], "spspent")) {
                $args['allowpay'] = 0;
                blocknav("runmodule.php?module=dwellings&op=build&type=" . $args['type'] . "&dwid=" . $args['dwid'] . "");
                output("`nYou have tried to spend more site points than you need to.");
            }
            break;
        case "dwellings-buy-setup":
            $typeid = get_module_setting("typeid", $args['type']);
            $paidsp = abs((int) httppost('paidsp'));
            if ($paidsp < 0) {
                $paidsp = 0;
            }
            $spent = get_module_objpref("dwellings", $args['dwid'], "spspent") + $paidsp;
            set_module_objpref("dwellings", $args['dwid'], "spspent", $spent);
            $session['user']['donationspent'] += $paidsp;
            if ($spent != get_module_objpref("dwellingtypes", $typeid, "spcost")) {
                $args['finished'] = 0;
            }
            break;
        case "dwellings-pay-costs":
            $typeid = get_module_setting("typeid", $args['type']);
            $costsp = get_module_objpref("dwellingtypes", $typeid, "spcost") - get_module_objpref("dwellings", $args['dwid'], "spspent");
            if ($costsp) {
                output("`#%s Site Points`0`n", $costsp);
            }
            break;
        case "dwellings-pay-input":
            $typeid = get_module_setting("typeid", $args['type']);
            $costsp = get_module_objpref("dwellingtypes", $typeid, "spcost") - get_module_objpref("dwellings", $args['dwid'], "spspent");
            $sp = translate_inline("Site Points");
            if ($costsp) {
                rawoutput("{$sp}: <input id='input' name='paidsp' width=5><br>");
            }
            break;
    }
    return $args;
}
function hunterslodge_customtitle_run()
{
    require_once "lib/sanitize.php";
    require_once "lib/names.php";
    global $session;
    $op = httpget("op");
    $free = httpget("free");
    page_header("Choose your Custom Title");
    switch ($op) {
        case "change":
            output("Ready to change your Title?  No problem.  Enter your desired Title in the box below.  You've got 25 characters to play with, including colour codes.`n`n");
            titlechange_form();
            addnav("Cancel");
            addnav("Don't change colours, just go back to the Lodge", "runmodule.php?module=iitems_hunterslodge&op=start");
            break;
        case "confirm":
            $ntitle = rawurldecode(httppost('newname'));
            $ntitle = newline_sanitize($ntitle);
            if ($ntitle == "") {
                $ntitle = "`0";
            }
            $ntitle = preg_replace("/[`][cHw]/", "", $ntitle);
            $ntitle = sanitize_html($ntitle);
            $nname = get_player_basename();
            output("`0Your new title will look like this: %s`0`n", $ntitle);
            output("`0Your entire name will look like: %s %s`0`n`n", $ntitle, $nname);
            output("Do you want to set the new title now?`n`n");
            output("`0Try a different title below, if you like.`n`n");
            titlechange_form();
            addnav("Confirm");
            addnav("Set the new Title", "runmodule.php?module=hunterslodge_customtitle&op=set&free={$free}&newname=" . rawurlencode($ntitle));
            addnav("Cancel");
            addnav("Don't change your Title, just go back to the Lodge", "runmodule.php?module=iitems_hunterslodge&op=start");
            break;
        case "set":
            $ntitle = rawurldecode(httpget('newname'));
            $fromname = $session['user']['name'];
            $newname = change_player_ctitle($ntitle);
            $session['user']['ctitle'] = $ntitle;
            $session['user']['name'] = $newname;
            output("You are now known as %s!`0`n`n", $session['user']['name']);
            if (!$free) {
                $id = has_item("hunterslodge_customtitle");
                delete_item($id);
            }
            addnav("Return");
            addnav("Return to the Lodge", "runmodule.php?module=iitems_hunterslodge&op=start");
            break;
    }
    page_footer();
}
function addcommentary()
{
    global $session, $emptypost;
    $info = httpallpost();
    unset($info['section']);
    unset($info['talkline']);
    unset($info['schema']);
    unset($info['insertcommentary']);
    unset($info['counter']);
    unset($info['removecomment']);
    $section = httppost('section');
    $talkline = httppost('talkline');
    $schema = httppost('schema');
    $comment = trim(httppost('insertcommentary'));
    $counter = httppost('counter');
    $remove = URLDecode(httpget('removecomment'));
    if ($remove > 0) {
        $return = '/' . httpget('returnpath');
        $section = httpget('section');
        $sql = "SELECT " . db_prefix("commentary") . ".*," . db_prefix("accounts") . ".name," . db_prefix("accounts") . ".acctid, " . db_prefix("accounts") . ".clanrank," . db_prefix("clans") . ".clanshort FROM " . db_prefix("commentary") . " INNER JOIN " . db_prefix("accounts") . " ON " . db_prefix("accounts") . ".acctid = " . db_prefix("commentary") . ".author LEFT JOIN " . db_prefix("clans") . " ON " . db_prefix("clans") . ".clanid=" . db_prefix("accounts") . ".clanid WHERE commentid={$remove}";
        $row = db_fetch_assoc(db_query($sql));
        $sql = "INSERT LOW_PRIORITY INTO " . db_prefix("moderatedcomments") . " (moderator,moddate,comment) VALUES ('{$session['user']['acctid']}','" . date("Y-m-d H:i:s") . "','" . addslashes(serialize($row)) . "')";
        db_query($sql);
        $sql = "DELETE FROM " . db_prefix("commentary") . " WHERE commentid='{$remove}';";
        db_query($sql);
        invalidatedatacache("comments-{$section}");
        // *** DRAGONBG.COM CORE PATCH START ***
        invalidatedatacache("comments-");
        // *** DRAGONBG.COM CORE PATCH END ***
        $session['user']['specialinc'] == '';
        //just to make sure he was not in a special
        $return = cmd_sanitize($return);
        $return = substr($return, strrpos($return, "/") + 1);
        if (strpos($return, "?") === false && strpos($return, "&") !== false) {
            $x = strpos($return, "&");
            $return = substr($return, 0, $x - 1) . "?" . substr($return, $x + 1);
        }
        debug($return);
        redirect($return);
    }
    if (array_key_exists('commentcounter', $session) && $session['commentcounter'] == $counter) {
        if ($section || $talkline || $comment) {
            $tcom = color_sanitize($comment);
            if ($tcom == "" || $tcom == ":" || $tcom == "::" || $tcom == "/me") {
                $emptypost = 1;
            } else {
                injectcommentary($section, $talkline, $comment, $schema);
            }
        }
    }
}
function settings_dohook($hook, $args)
{
    switch ($hook) {
        case 'footer-news':
        case 'village':
            if ($hook == 'village') {
                addnav($args['othernav']);
            } else {
                addnav('News');
            }
            addnav('*?Settings*', 'runmodule.php?module=settings');
            blocknav('prefs.php');
            break;
        case 'footer-modules':
            if (httpget('cat') != '' && httpget('module') != '' || is_array(httppost('module'))) {
                $userprefs = db_prefix('module_userprefs');
                $modules = db_prefix('modules');
                $sql = db_query("SELECT DISTINCT m.modulename AS fallback,\n                    mu.modulename, mu.setting, m.formalname\n                    FROM {$modules} AS m\n                    LEFT JOIN {$userprefs} AS mu ON m.modulename = mu.modulename\n                    WHERE (setting LIKE 'user_%' OR m.infokeys LIKE '%|prefs|%')");
                $fill = [];
                $rewrite = json_decode(get_module_setting('rewrite'), true);
                while ($row = db_fetch_assoc($sql)) {
                    if ($row['setting'] != '' && strpos($row['setting'], 'user_') !== false) {
                        $structuredKey = "{$row['modulename']}__{$row['setting']}";
                        if ($rewrite[$structuredKey] != $row['formalname']) {
                            $fill[$structuredKey] = $rewrite[$structuredKey];
                        } else {
                            $fill[$structuredKey] = $row['formalname'];
                        }
                    } else {
                        $possibleKeys = get_module_info($row['fallback'])['prefs'];
                        foreach ($possibleKeys as $key => $val) {
                            if (strpos($key, 'user_') !== false) {
                                $structuredKey = "{$row['fallback']}__{$key}";
                                if ($rewrite[$structuredKey] != $row['formalname'] && $rewrite[$structuredKey] != '') {
                                    $fill[$structuredKey] = $rewrite[$structuredKey];
                                } else {
                                    $fill[$structuredKey] = $row['formalname'];
                                }
                            }
                        }
                    }
                }
                if ($fill != $rewrite) {
                    set_module_setting('rewrite', json_encode($fill));
                    output("`QUpdating the 'Settings' module rewrite conditions...");
                }
            }
            break;
    }
    return $args;
}
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();
}
function clanform()
{
    rawoutput("<form action='clan.php?op=new&apply=1' method='POST'>");
    addnav("", "clan.php?op=new&apply=1");
    output("`b`cNew Clan Application Form`c`b");
    output("Clan Name: ");
    rawoutput("<input name='clanname' maxlength='50' value=\"" . htmlentities(stripslashes(httppost('clanname')), ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "\">");
    output("`nShort Name: ");
    rawoutput("<input name='clanshort' maxlength='5' size='5' value=\"" . htmlentities(stripslashes(httppost('clanshort')), ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "\">");
    output("`nNote, color codes are permitted in neither clan names nor short names.");
    output("The clan name is shown on player bios and on clan overview pages while the short name is displayed next to players' names in comment areas and such.`n");
    $apply = translate_inline("Apply");
    rawoutput("<input type='submit' class='button' value='{$apply}'></form>");
}
function hunterslodge_namedmount_run()
{
    require_once "lib/sanitize.php";
    require_once "lib/names.php";
    global $session;
    global $playermount;
    $op = httpget("op");
    $free = httpget("free");
    page_header("Name your Mount");
    switch ($op) {
        case "change":
            output("Want to change your Mount's name?  No problem.  Enter your desired name in the box below.  You've got 25 characters to play around with.`n(leave this blank to disable mount naming)`n`n");
            rawoutput("<form action='runmodule.php?module=hunterslodge_namedmount&op=confirm&free=" . $free . "' method='POST'>");
            rawoutput("<input id='input' name='newname' width='25' maxlength='25' value='" . htmlentities($race, ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "'>");
            rawoutput("<input type='submit' class='button' value='Preview'>");
            rawoutput("</form>");
            addnav("", "runmodule.php?module=hunterslodge_namedmount&op=confirm&free=" . $free);
            addnav("Cancel");
            addnav("Don't set a mount name, just go back to the Lodge", "runmodule.php?module=iitems_hunterslodge&op=start");
            break;
        case "confirm":
            $newname = httppost("newname");
            $sub = httpget("sub");
            $newname = comment_sanitize($newname);
            $newname = substr($newname, 0, 25);
            if ($newname) {
                output("Your Mount's name is now:`n%s`0 the %s`nWould you like to set your mount's name now?`n`n", $newname, $playermount['mountname']);
            } else {
                output("You've chosen to go back to having an unnamed Mount.  Are you sure that's what you want?`n`n");
            }
            addnav("Confirm");
            addnav("Set mount name", "runmodule.php?module=hunterslodge_namedmount&op=set&free={$free}&newname=" . rawurlencode($newname));
            addnav("Cancel");
            addnav("Don't set a custom mount name, just go back to the Lodge", "runmodule.php?module=iitems_hunterslodge&op=start");
            break;
        case "set":
            $newname = rawurldecode(httpget("newname"));
            output("You now ride %s`0 the %s!`n`n", $newname, $playermount['mountname']);
            set_module_pref("mountname", $newname);
            if (!$free) {
                $id = has_item("hunterslodge_namedmount");
                delete_item($id);
            }
            addnav("Return");
            addnav("Return to the Lodge", "runmodule.php?module=iitems_hunterslodge&op=start");
            break;
    }
    page_footer();
}
function changelog_dohook($hook, $args)
{
    switch ($hook) {
        case 'header-modules':
            $module = httppost('module') ?: httpget('module');
            $op = httpget('op');
            if ($module != '') {
                if (substr($op, -1) == 'e') {
                    $op = substr($op, 0, -1);
                } else {
                    if ($op == 'mass') {
                        $method = array_keys(httpallpost())[1];
                        if (substr($method, -1) == 'e') {
                            $method = substr($method, 0, -1);
                        }
                        $op = "mass {$method}";
                        $plural = 's';
                    }
                }
                require_once 'lib/gamelog.php';
                if (is_array($module)) {
                    $lastModule = array_pop($module);
                    $module = implode(', ', $module);
                    $module .= ",`@ and `^{$lastModule}";
                }
                gamelog(sprintf_translate('`Q%sed`@ the `^%s`@ module%s.', $op, $module, $plural), get_module_setting('category'));
            }
            break;
        case 'village':
            if (get_module_setting('infonav')) {
                addnav($args['infonav']);
                addnav('View Changelog', 'runmodule.php?module=changelog&ret=village');
            }
            break;
        case 'header-about':
            addnav('About LoGD');
            addnav('View Changelog', 'runmodule.php?module=changelog&ret=about');
            break;
        case 'newday-runonce':
            $gamelog = db_prefix('gamelog');
            $date = date('Y-m-d H:i:s', strtotime('now'));
            $category = get_module_setting('category');
            db_query("UPDATE {$gamelog} SET date = '{$date}' WHERE category = '{$category}'");
            break;
    }
    return $args;
}
function marriage_pform($backoperation)
{
    global $session;
    $whom = httppost("whom");
    rawoutput("<form action='runmodule.php?module=marriage&op=" . $backoperation . "&op2=propose&stage=0' method='POST'>");
    addnav("", "runmodule.php?module=marriage&op=" . $backoperation . "&op2=propose&stage=0");
    if ($whom != "") {
        $string = "%";
        for ($x = 0; $x < strlen($whom); $x++) {
            $string .= substr($whom, $x, 1) . "%";
        }
        if (get_module_setting('sg') == 1) {
            $sql = "SELECT login,name,acctid FROM " . db_prefix("accounts") . " WHERE login LIKE '%{$whom}%' AND acctid<>" . $session['user']['acctid'] . " AND marriedto=0 ORDER BY level,login";
        } else {
            $sql = "SELECT login,name,acctid FROM " . db_prefix("accounts") . " WHERE name LIKE '%{$string}%' AND acctid<>" . $session['user']['acctid'] . " AND sex<>" . $session['user']['sex'] . " AND marriedto=0 ORDER BY level,login";
        }
        $result = db_query($sql);
        if (db_num_rows($result) != 0) {
            output("`@Please choose from the following people:`n`n`c");
            rawoutput("<table cellpadding='3' cellspacing='0' border='0'>");
            rawoutput("<tr class='trhead'><td><center>Name</center></td></tr>");
            for ($i = 0; $i < db_num_rows($result); $i++) {
                $n++;
                $row = db_fetch_assoc($result);
                rawoutput("<tr class='" . ($i % 2 ? "trlight" : "trdark") . "'><td><a href='runmodule.php?module=marriage&op2=propose&op=" . $backoperation . "&stage=1&target=" . $row['acctid'] . "'>");
                output_notl("`0[`^%s`0]", $row['name']);
                rawoutput("</td></tr>");
                addnav("", "runmodule.php?module=marriage&op2=propose&op=" . $backoperation . "&stage=1&target=" . $row['acctid']);
            }
            rawoutput("</table>");
            output_notl("`c");
        } else {
            output("`c`@`bA user was not found with that name.`b`c");
        }
        output_notl("`n");
    }
    if ($n == 0) {
        output("Who do you want to propose to?`n`n");
    } else {
        output("Would you like to look for someone else?`n`n");
    }
    rawoutput("<input name='whom' maxlength='50' value=\"" . htmlentities(stripslashes($whom)) . "\">");
    $apply = translate_inline("Search");
    rawoutput("<input type='submit' class='button' value='{$apply}'></form>");
    output("`c`@(Remember: They can't be married already!)`c");
}
function worldmapen_editor_manual($op, $subop, $act)
{
    $vloc = array();
    $vname = getsetting("villagename", LOCATION_FIELDS);
    $vloc[$vname] = "village";
    $vloc = modulehook("validlocation", $vloc);
    ksort($vloc);
    if ($act == "save") {
        foreach ($vloc as $loc => $val) {
            $space_valx = preg_replace('/\\s/', '_', $loc . 'X');
            $space_valy = preg_replace('/\\s/', '_', $loc . 'Y');
            set_module_setting($loc . 'X', httppost($space_valx));
            set_module_setting($loc . 'Y', httppost($space_valy));
            set_module_setting($loc . 'Z', 1);
            // Eventually we'll do the Z coord too
            // set_module_setting($loc.'Z',
            //        httppost($loc."Z"));
        }
        output("`^`bSettings saved successfully.`b`n");
        reset($vloc);
    }
    output("`^Maximum X value is `b%s`b`n", get_module_setting("worldmapsizeX"));
    output("`^Maximum Y value is `b%s`b`n", get_module_setting("worldmapsizeY"));
    $worldarray = array("World Locations,title");
    foreach ($vloc as $loc => $val) {
        $mapx = get_module_setting("worldmapsizeX");
        $mapy = get_module_setting("worldmapsizeY");
        //Added to allow setting cities outside of the map. - Making cities inaccessible via normal travel.
        $myx = $mapx + 1;
        $worldarray[] = array("Locations for %s,title", $loc);
        $worldarray[$loc . 'X'] = array("X Coordinate,range,1,{$myx},1");
        $worldarray[$loc . 'Y'] = array("Y coordinate,range,1,{$mapy},1");
    }
    rawoutput("<form method='post' action='runmodule.php?module=worldmapen&op=edit&subop=manual&act=save&admin=true'>");
    require_once "lib/showform.php";
    global $module_settings;
    showform($worldarray, $module_settings['worldmapen']);
    rawoutput("</form>");
    addnav("", "runmodule.php?module=worldmapen&op=edit&subop=manual&act=save&admin=true");
    addnav("E?Return to World Map Editor", "runmodule.php?module=worldmapen&op=edit&admin=true");
}
        break;
    case "delbuff":
        $id = httpget('id');
        $sql = "DELETE FROM " . db_prefix("magicitembuffs") . " WHERE buffid = {$id} LIMIT 1";
        $result = db_query($sql);
        invalidatedatacache("magicitem-buff-{$id}");
        if (db_affected_rows($result)) {
            output("`^Buff has been succesfully deleted.`n`n");
        } else {
            output("`3While deleting this buff, an error occured. Probably someone else already deleted this buff.`n`n");
        }
        $sql = "UPDATE " . db_prefix("magicitems") . " SET buffid = 0 WHERE buffid = '{$id}'";
        db_query($sql);
        break;
    case "newitem":
        require_once "modules/mysticalshop_buffs/newitem.php";
        break;
    case "newitem2":
        $id = httppost('id');
        $buffid = httppost('buffid');
        if ($buffid == 0 or $buffid == "") {
            $buffid = 0;
        } else {
            $buffid = httppost('buffid');
        }
        $name = httppost('name');
        $sql = "UPDATE " . db_prefix("magicitems") . " SET buffid = {$buffid} WHERE id = '{$id}'";
        db_query($sql);
        output("`^Done!");
        break;
}
<?php

$apply = httpget('apply');
if ($apply == 1) {
    $ocn = httppost('clanname');
    $ocs = httppost('clanshort');
    $clanname = stripslashes($ocn);
    $clanname = full_sanitize($clanname);
    $clanname = preg_replace("'[^[:alpha:] \\'-]'", "", $clanname);
    $clanname = addslashes($clanname);
    httppostset('clanname', $clanname);
    $clanshort = full_sanitize($ocs);
    $clanshort = preg_replace("'[^[:alpha:]]'", "", $clanshort);
    httppostset('clanshort', $clanshort);
    $sql = "SELECT * FROM " . db_prefix("clans") . " WHERE clanname='{$clanname}'";
    $result = db_query($sql);
    $e = array(translate_inline("%s`7 looks over your form but informs you that your clan name must consist only of letters, spaces, apostrophes, or dashes.  Also, your short name can consist only of letters. She hands you a blank form."), translate_inline("%s`7 looks over your form but informs you that you must have at least 5 and no more than 50 characters in your clan's name (and they must consist only of letters, spaces, apostrophes, or dashes), then hands you a blank form."), translate_inline("%s`7 looks over your form but informs you that you must have at least 2 and no more than 5 characters in your clan's short name (and they must all be letters), then hands you a blank form."), translate_inline("%s`7 looks over your form but informs you that the clan name %s is already taken, and hands you a blank form."), translate_inline("%s`7 looks over your form but informs you that the short name %s is already taken, and hands you a blank form."), translate_inline("%s`7 asks for the %s gold to start the clan, but you seem to be unable to produce the fees."), translate_inline("%s`7 asks for the %s gold and %s gems to start the clan, but you seem to be unable to produce the fees."), translate_inline("%s`7 asks for the %s gems to start the clan, but you seem to be unable to produce the fees."), translate_inline("She takes your application, and stamps it \"`\$DENIED`7\"."));
    if ($clanname != $ocn || $clanshort != $ocs) {
        output_notl($e[0], $registrar);
        clanform();
        addnav("Return to the Lobby", "clan.php");
    } elseif (strlen($clanname) < 5 || strlen($clanname) > 50) {
        output_notl($e[1], $registrar);
        clanform();
        addnav("Return to the Lobby", "clan.php");
    } elseif (strlen($clanshort) < 2 || strlen($clanshort) > 5) {
        output_notl($e[2], $registrar);
        clanform();
        addnav("Return to the Lobby", "clan.php");
    } elseif (db_num_rows($result) > 0) {
        output_notl($e[3], $registrar, stripslashes($clanname));
function massmail_run()
{
    global $session;
    $op = httpget('op');
    popup_header("Ye Olde Poste Office");
    rawoutput("<table width='50%' border='0' cellpadding='0' cellspacing='2'>");
    rawoutput("<tr><td>");
    $t = translate_inline("Back to the Ye Olde Poste Office");
    rawoutput("<a href='mail.php'>{$t}</a></td><td>");
    rawoutput("</td></tr></table>");
    output_notl("`n`n");
    $clanid = $session['user']['clanid'];
    $body = httppost('body');
    $subject = "`^Clan Mail";
    $time = date("Y-m-d H:i:s", strtotime("-" . getsetting("LOGINTIMEOUT", 900) . " sec"));
    $name = $session['user']['name'];
    require_once "lib/systemmail.php";
    switch ($op) {
        case "clanmail":
            //copied and modified from Chris Vorndrans Bulletin
            if ($body == "") {
                rawoutput("<form action='runmodule.php?module=massmail&op=clanmail' method='POST'>");
                output("`n`^Clan Mail:`n`n");
                rawoutput("<textarea name=\"body\" rows=\"10\" cols=\"60\" class=\"input\"></textarea>");
                rawoutput("<input type='submit' class='button' value='" . translate_inline("Send") . "'></form>");
                rawoutput("</form>");
            } else {
                $sql = "SELECT * FROM " . db_prefix("accounts") . " WHERE clanid = '{$clanid}'";
                $res = db_query($sql);
                for ($i = 0; $i < db_num_rows($res); $i++) {
                    $row = db_fetch_assoc($res);
                    systemmail($row['acctid'], $subject, $body);
                }
                output("`^Message has been sent.`0");
            }
            addnav("", "runmodule.php?module=massmail&op=clanmail");
            break;
        case "adminall":
            if ($body == "") {
                rawoutput("<form action='runmodule.php?module=massmail&op=adminall' method='POST'>");
                output("`n`^Send to All Players:`n`n");
                rawoutput("<textarea name=\"body\" rows=\"10\" cols=\"60\" class=\"input\"></textarea>");
                rawoutput("<input type='submit' class='button' value='" . translate_inline("Send") . "'></form>");
                rawoutput("</form>");
            } else {
                $sql = "SELECT * FROM " . db_prefix("accounts");
                $res = db_query($sql);
                for ($i = 0; $i < db_num_rows($res); $i++) {
                    $row = db_fetch_assoc($res);
                    systemmail($row['acctid'], "`^Server News from " . $name, $body);
                }
                output("Your mail was sent to all players");
            }
            addnav("", "runmodule.php?module=massmail&op=adminall");
            break;
        case "adminonline":
            if ($body == "") {
                rawoutput("<form action='runmodule.php?module=massmail&op=adminonline' method='POST'>");
                output("`n`^Send to all online:`n`n");
                rawoutput("<textarea name=\"body\" rows=\"10\" cols=\"60\" class=\"input\"></textarea>");
                rawoutput("<input type='submit' class='button' value='" . translate_inline("Send") . "'></form>");
                rawoutput("</form>");
            } else {
                $sql = "SELECT * FROM " . db_prefix("accounts") . " WHERE loggedin = 1 AND laston > '{$time}'";
                $res = db_query($sql);
                for ($i = 0; $i < db_num_rows($res); $i++) {
                    $row = db_fetch_assoc($res);
                    systemmail($row['acctid'], "`^Server News from " . $name, $body);
                }
                output("Your Mail was sent to all online");
            }
            addnav("", "runmodule.php?module=massmail&op=adminonline");
            break;
            //end of copied code
    }
    popup_footer();
}
     db_query($sql);
     invalidatedatacache("clandata-{$claninfo['clanid']}");
     $claninfo['clanmotd'] = stripslashes($clanmotd);
     output("Updating MoTD`n");
     $claninfo['motdauthor'] = $session['user']['acctid'];
 }
 $clandesc = httppost('clandesc');
 if (httppostisset('clandesc') && stripslashes($clandesc) != $claninfo['clandesc'] && $claninfo['descauthor'] != 4294967295) {
     $sql = "UPDATE " . db_prefix("clans") . " SET clandesc='" . addslashes(substr(stripslashes($clandesc), 0, 4096)) . "',descauthor={$session['user']['acctid']} WHERE clanid={$claninfo['clanid']}";
     db_query($sql);
     invalidatedatacache("clandata-{$claninfo['clanid']}");
     output("Updating description`n");
     $claninfo['clandesc'] = stripslashes($clandesc);
     $claninfo['descauthor'] = $session['user']['acctid'];
 }
 $customsay = httppost('customsay');
 if (httppostisset('customsay') && $customsay != $claninfo['customsay'] && $session['user']['clanrank'] >= CLAN_LEADER) {
     $sql = "UPDATE " . db_prefix("clans") . " SET customsay='{$customsay}' WHERE clanid={$claninfo['clanid']}";
     db_query($sql);
     invalidatedatacache("clandata-{$claninfo['clanid']}");
     output("Updating custom say line`n");
     $claninfo['customsay'] = stripslashes($customsay);
 }
 $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid={$claninfo['motdauthor']}";
 $result = db_query($sql);
 $row = db_fetch_assoc($result);
 $motdauthname = $row['name'];
 $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid={$claninfo['descauthor']}";
 $result = db_query($sql);
 $row = db_fetch_assoc($result);
 $descauthname = $row['name'];
translator_setup();
$op = httpget('op');
$name = httppost('name');
$iname = getsetting("innname", LOCATION_INN);
$vname = getsetting("villagename", LOCATION_FIELDS);
if ($name != "") {
    if ($session['loggedin']) {
        redirect("badnav.php");
    } else {
        $password = httppost('password');
        $password = stripslashes($password);
        if (substr($password, 0, 5) == "!md5!") {
            $password = md5(substr($password, 5));
        } elseif (substr($password, 0, 6) == "!md52!") {
            // && strlen($password) == 38) {
            $force = httppost('force');
            if ($force) {
                $password = addslashes(substr($password, 6));
            } else {
                $password = '******';
            }
        } else {
            $password = md5(md5($password));
        }
        $sql = "SELECT * FROM " . db_prefix("accounts") . " WHERE login = '******' AND password='******' AND locked=0";
        $result = db_query($sql);
        if (db_num_rows($result) == 1) {
            $session['user'] = db_fetch_assoc($result);
            $companions = @unserialize($session['user']['companions']);
            if (!is_array($companions)) {
                $companions = array();
<?php

page_header("Actions Management");
$op2 = httpget('op2');
if ($op2 == "del") {
    $act = actions_list();
    $key = httpget('key');
    $value = $act[$key];
    output("All values of the action \"" . $value . "\" were deleted.");
    $stamina = db_prefix("stamina");
    db_query("DELETE FROM {$stamina} WHERE action='{$key}'");
    unset($act[$key]);
    set_module_setting("actionsarray", serialize($act), "staminasystem");
    actions_list();
    $actiondebug = get_module_setting("actionsarray", "staminasystem");
    debug($actiondebug);
    addnav("Continue");
    addnav("Continue", "runmodule.php?module=staminasystem&op=superuser");
}
if ($op2 == "new") {
    $new = httppost('action');
    output("The action \"{$new}\" has been added.");
    $act = actions_list();
    $act[] = $new;
    set_module_setting("actionsarray", serialize($act), "staminasystem");
    $act = actions_list();
    addnav("Continue");
    addnav("Continue", "runmodule.php?module=staminasystem&op=superuser");
}
page_footer();
    $balance = translate_inline("`@Elessa`6 scans through her ledger, \"`@You have a balance of `^%s`@ gold in the bank.`6\"`n");
    $debt = translate_inline("`@Elessa`6 scans through her ledger, \"`@You have a `\$debt`@ of `^%s`@ gold in the bank.`6\"`n");
    rawoutput("<form action='bank.php?op=withdrawfinish' method='POST'>");
    output_notl($session['user']['goldinbank'] >= 0 ? $balance : $debt, abs($session['user']['goldinbank']));
    output("`6\"`@How much would you like to withdraw `&%s`@?`6\"`n`n", $session['user']['name']);
    rawoutput("<input id='input' name='amount' width=5 > <input type='submit' class='button' value='{$withdraw}'>");
    output("`n`iEnter 0 or nothing to withdraw it all`i");
    rawoutput("</form>");
    rawoutput("<script language='javascript'>document.getElementById('input').focus();</script>");
    addnav("", "bank.php?op=withdrawfinish");
} elseif ($op == "withdrawfinish") {
    $amount = abs((int) httppost('amount'));
    if ($amount == 0) {
        $amount = abs($session['user']['goldinbank']);
    }
    if ($amount > $session['user']['goldinbank'] && httppost('borrow') == "") {
        output("`\$ERROR: Not enough gold in the bank to withdraw.`^`n`n");
        output("`6Having been informed that you have `^%s`6 gold in your account, you declare that you would like to withdraw all `^%s`6 of it.`n`n", $session['user']['goldinbank'], $amount);
        output("`@Elessa`6 looks at you for a few moments without blinking, then advises you to take basic arithmetic.  You realize your folly and think you should try again.");
    } else {
        if ($amount > $session['user']['goldinbank']) {
            $lefttoborrow = $amount;
            $didwithdraw = 0;
            $maxborrow = $session['user']['level'] * getsetting("borrowperlevel", 20);
            if ($lefttoborrow <= $session['user']['goldinbank'] + $maxborrow) {
                if ($session['user']['goldinbank'] > 0) {
                    output("`6You withdraw your remaining `^%s`6 gold.", $session['user']['goldinbank']);
                    $lefttoborrow -= $session['user']['goldinbank'];
                    $session['user']['gold'] += $session['user']['goldinbank'];
                    $session['user']['goldinbank'] = 0;
                    debuglog("withdrew {$amount} gold from the bank");
// translator ready
// mail ready
require_once "common.php";
require_once "lib/commentary.php";
require_once "lib/villagenav.php";
require_once "lib/events.php";
require_once "lib/http.php";
tlschema("gardens");
page_header("The Gardens");
addcommentary();
$skipgardendesc = handle_event("gardens");
$op = httpget('op');
$com = httpget('comscroll');
$refresh = httpget("refresh");
$commenting = httpget("commenting");
$comment = httppost('insertcommentary');
// Don't give people a chance at a special event if they are just browsing
// the commentary (or talking) or dealing with any of the hooks in the village.
if (!$op && $com == "" && !$comment && !$refresh && !$commenting) {
    if (module_events("gardens", getsetting("gardenchance", 0)) != 0) {
        if (checknavs()) {
            page_footer();
        } else {
            // Reset the special for good.
            $session['user']['specialinc'] = "";
            $session['user']['specialmisc'] = "";
            $skipgardendesc = true;
            $op = "";
            httpset("op", "");
        }
    }
function namecolour_form()
{
    $context = httpget("context");
    $regname = get_player_basename();
    rawoutput("Your current name is: " . $regname);
    output("`0`nWhich renders as: %s`0`n`n", $regname);
    if (httppost("newname")) {
        $val = httppost("newname");
    } else {
        $val = htmlentities($regname, ENT_COMPAT, getsetting("charset", "ISO-8859-1"));
    }
    rawoutput("<form action='runmodule.php?module=hunterslodge_customcolours&op=confirm&context={$context}&free={$free}' method='POST'>");
    rawoutput("<input id='input' name='newname' width='30' maxlength='30' value='" . $val . "'>");
    rawoutput("<input type='submit' class='button' value='Preview'>");
    rawoutput("</form>");
    addnav("", "runmodule.php?module=hunterslodge_customcolours&op=confirm&context={$context}&free={$free}");
}
function mementos_run()
{
    global $session;
    page_header("Memento Forge");
    $op = httpget('op');
    $pointsavailable = $session['user']['donation'] - $session['user']['donationspent'];
    require_once "modules/wcgpoints.php";
    $cstones = wcgpoints_getpoints();
    switch (httpget('op')) {
        case "start":
            $moulds = load_inventory("mementomoulds_" . $session['user']['acctid'], true);
            if (count($moulds)) {
                output("Here are the original prototypes of Mementos you have made.`n`n");
                rawoutput("<table width=100% style='border: dotted 1px #000000;'>");
                $classcount = 1;
                $moulds = modulehook("mementos", $moulds);
                foreach ($moulds as $id => $prefs) {
                    $classcount++;
                    $class = $classcount % 2 ? "trdark" : "trlight";
                    rawoutput("<tr class='{$class}'><td>");
                    output("`b%s`b`0`n", stripslashes($prefs['verbosename']));
                    output("%s`0`n`n", stripslashes($prefs['description']));
                    output("`bUse Text`b:%s`0`n`n", stripslashes($prefs['usetext']));
                    if ($prefs['mouldusesleft']) {
                        output("You can make another %s of these, at `6`b250`b CobbleStones`0 and `5`b1`b Supporter Point`0 each.`n", $prefs['mouldusesleft']);
                        rawoutput("<a href='runmodule.php?module=mementos&op=makecopy&itemid=" . $id . "'>Make a copy</a><br />");
                    } else {
                        if (!isset($prefs['mouldusesleft'])) {
                            output("You can make a mould for this Memento, enabling you to make copies using `6CobbleStones`0.  It'll cost you `5500 Supporter Points`0.`n");
                            rawoutput("<a href='runmodule.php?module=mementos&op=makecopy&itemid=" . $id . "'>Make a mould</a><br />");
                        } else {
                            output("This mould is too old and knackered to make any more Mementos, but you can re-forge it for `5500 Supporter Points`0.`n");
                            rawoutput("<a href='runmodule.php?module=mementos&op=makecopy&itemid=" . $id . "'>Make a mould</a><br />");
                        }
                    }
                    addnav("", "runmodule.php?module=mementos&op=makecopy&itemid=" . $id);
                    if (is_array($prefs['memento_forge_actions']) && count($prefs['memento_forge_actions'])) {
                        foreach ($prefs['memento_forge_actions'] as $action) {
                            rawoutput($action);
                        }
                    }
                    rawoutput("</td></tr>");
                }
                rawoutput("</table>");
            } else {
                //if there are no moulds
                output("You're about to ask the grinning Joker proprietor about these Memento things you've been hearing about, when suddenly the knowledge rushes into your head unbidden.`n`nMementos are player-created objects that can be given to other players.  They grant no in-game advantages, but are fun for roleplaying.  Players often roleplay giving items to each other, but with Mementos, those items can appear in Inventories and act like 'real' in-game items.`n`n`n`bWhat you need to know about Mementos`b`nMementos are weightless, and occupy the 'Shoebox' portion of the player's Inventory.  Mementos survive Drive Kills, and don't go away when 'used.'  They can only be destroyed by being discarded by the player.  They can also be put down and picked up on map squares, and gifted to other players for free (anonymously if desired) via Common Ground's Gifting Station.`n`nYou can specify the Name (shown in the Inventory) of the Memento, the Plural form of the name, the Description (shown in the Inventory), and the Use Text (shown when the player 'uses' the Memento).`n`n`n`bCosts`b`nYou can create a single Memento at a flat cost of `550 Supporter Points`0.  You can also create Memento Moulds, at a cost of `5500 Supporter Points`0 for the mould and the first Memento, plus `5one Supporter Point`0 and `6250 CobbleStones`0 for each of up to fifty copies of that Memento.  Single Mementos can be upgraded to Memento Moulds later on if you like.`n`n`n`bExample Memento`b`n`bName:`b Red Music Box`n`bPlural:`b Red Music Boxes`n`bDescription:`b An ornate red wooden music box, decorated with cut garnets and shiny stainless-steel edging.`n`bUse Text`b: You open up the music box.  Inside is a tiny demon, smoking a cigarette.  Noticing that his house is open, he hurriedly stamps out his smoke and launches into a stirring rendition of 'NewHome is Full of Noobs.'  You close the lid quickly.`n`nEach Memento can have 100 characters for the Name, 100 characters for the Plural name, 255 characters for the Description, and 1,000 characters for the Use Text.`n`n");
            }
            addnav("Memento Stuff");
            if ($pointsavailable >= 50) {
                addnav("Create new single Memento", "runmodule.php?module=mementos&op=new&type=single");
            } else {
                addnav("You need 50 Supporter Points for a single Memento", "");
            }
            if ($pointsavailable >= 500) {
                addnav("Create new Memento Mould", "runmodule.php?module=mementos&op=new&type=mould");
            } else {
                addnav("You need 500 Supporter Points for a Memento Mould", "");
            }
            break;
        case "makecopy":
            $giveitem = false;
            $itemid = httpget("itemid");
            $name = get_item_pref("verbosename", $itemid);
            $plural = get_item_pref("plural", $itemid);
            $desc = get_item_pref("description", $itemid);
            $usetext = get_item_pref("usetext", $itemid);
            $moulduses = get_item_pref("mouldusesleft", $itemid);
            if ($moulduses > 0) {
                if ($cstones >= $cscost) {
                    output("You've bought a new %s`0 using `6CobbleStones`0!  Would you like to buy another, or head back to the Memento Forge menu?`n`n", $name);
                    $giveitem = true;
                    increment_module_pref("spent", 250, "wcgpoints");
                    $cstones = wcgpoints_getpoints();
                    $session['user']['donationspent'] += 1;
                    //log purchase
                    $logsql = "INSERT INTO " . db_prefix("purchaselog") . " (acctid,purchased,amount,data,giftwrap,timestamp) VALUES ('" . $session['user']['acctid'] . "','memento_copy_cobblestone','1','none','0','" . date("Y-m-d H:i:s") . "')";
                    db_query($logsql);
                } else {
                    output("`4You don't have enough `6CobbleStones`0 to make another copy of that Memento, I'm afraid.`n`n");
                }
            }
            $pointsavailable = $session['user']['donation'] - $session['user']['donationspent'];
            if ($giveitem) {
                $prefs = get_item_prefs($itemid);
                unset($prefs["mouldusesleft"]);
                $prefs['memento_originalitem'] = $itemid;
                give_item("memento", $prefs);
                $moulduses--;
                set_item_pref("mouldusesleft", $moulduses, $itemid);
            }
            if ($moulduses > 0) {
                output("You're about a make a new copy of the Memento called `b%s`b`0.  This will cost `6250 CobbleStones`0 and `5one Supporter Point`0.  You now have `5%s Supporter Points`0 and `6%s CobbleStones`0, and this mould will make `b%s`0 more Mementos.`n`n", $name, number_format($pointsavailable), number_format($cstones), $moulduses);
                addnav("Buy");
                if ($cstones >= $cscost && $pointsavailable) {
                    addnav("Buy a copy", "runmodule.php?module=mementos&op=makecopy&itemid=" . $itemid);
                } else {
                    addnav("Not enough `6CobbleStones`0 (or you don't have a `5Supporter Point`0 left)", "");
                }
            } else {
                output("Either this mould is knackered, or this is a unique Memento.  You can't make any more copies.  However, you can make a new mould if you like, for `5500 Supporter Points`0.  This will enable you to make further copies of the Memento for `5one Supporter Point`0 plus `6250 CobbleStones`0 each.`n`n", $originalcost);
                addnav("Buy");
                if ($pointsavailable >= 500) {
                    addnav("Make a new mould", "runmodule.php?module=mementos&op=reforge&itemid=" . $itemid);
                } else {
                    addnav("Not enough `5Supporter Points`0 to make a new mould", "");
                }
            }
            addnav("Return");
            addnav("Memento Forge", "runmodule.php?module=mementos&op=start");
            break;
        case "reforge":
            $itemid = httpget("itemid");
            output("You've successfully recreated the mould for your Memento.`n`n");
            set_item_pref("mouldusesleft", 50, $itemid);
            addnav("Return");
            addnav("Memento Forge", "runmodule.php?module=mementos&op=start");
            $session['user']['donationspent'] += 500;
            $logsql = "INSERT INTO " . db_prefix("purchaselog") . " (acctid,purchased,amount,data,giftwrap,timestamp) VALUES ('" . $session['user']['acctid'] . "','memento_mould','500','none','0','" . date("Y-m-d H:i:s") . "')";
            db_query($logsql);
            break;
        case "new":
            $type = httpget('type');
            if ($type == 'single') {
                output("You're making a new unique Memento now.  Create your desired item and hit Submit.  You can use colour codes and italics just like in commentary, and you can use bold too, using the ``b switch (remember to close your bolds and italics with another ``b or ``i!).`n`nRemember to use ``n for a new line rather than pressing Enter.  Use ``n``n for a line break between paragraphs.`n`n");
                rawoutput("<form action='runmodule.php?module=mementos&op=check&type=single' method='POST'>Memento Name (maximum 100 characters): <input name='name' id='name'><br /><br />Plural (maximum 100 characters): <input name='plural' id='plural'><br /><br />Memento Description (maximum 255 characters):<br />");
                addnav("", "runmodule.php?module=mementos&op=check&type=single");
            } else {
                if ($type == 'mould') {
                    output("You're making a new Memento Mould now.  Create your desired item and hit Submit.  You can use colour codes and italics just like in commentary, and you can use bold too, using the ``b switch (remember to close your bolds and italics with another ``b or ``i!).`n`nRemember to use ``n for a new line rather than pressing Enter.  Use ``n``n for a line break between paragraphs.`n`n");
                    rawoutput("<form action='runmodule.php?module=mementos&op=check&type=mould' method='POST'>Memento Name (maximum 100 characters): <input name='name' id='name'><br /><br />Plural (maximum 100 characters): <input name='plural' id='plural'><br /><br />Memento Description (maximum 255 characters):<br />");
                    addnav("", "runmodule.php?module=mementos&op=check&type=mould");
                }
            }
            require_once "lib/forms.php";
            previewfield_countup("description");
            rawoutput("<br /><br />Text shown when using the Memento (maximum 1,000 characters):<br />");
            previewfield_countup("usetext");
            rawoutput("<br /><input type=submit>");
            addnav("Start Again");
            addnav("Memento Forge", "runmodule.php?module=mementos&op=start");
            break;
        case "check":
            output("Here's a preview of your Memento:`n`n");
            $rname = httppost("name");
            $rplural = httppost("plural");
            $rdesc = httppost("description");
            $rusetext = httppost("usetext");
            $type = httpget("type");
            $dname = stripslashes($rname);
            $dplural = stripslashes($rplural);
            $ddesc = stripslashes($rdesc);
            $dusetext = stripslashes($rusetext);
            output("`bName:`b %s`0 (%s`0)`n`bDescription:`b %s`0`n`bUse Text:`b %s`0`n`n", $dname, $dplural, $ddesc, $dusetext);
            if (strlen($dname) <= 100 && strlen($dplural) <= 100 && strlen($ddesc) <= 255 && strlen($dusetext) <= 1000) {
                addnav("Confirm");
                if ($type == "single") {
                    addnav("Buy it! (`550 Supporter Points`0)", "runmodule.php?module=mementos&op=confirm&name=" . urlencode($rname) . "&plural=" . urlencode($rplural) . "&desc=" . urlencode($rdesc) . "&usetext=" . urlencode($rusetext) . "&type=single");
                } else {
                    if ($type == "mould") {
                        addnav("Buy it! (`5500 Supporter Points`0)", "runmodule.php?module=mementos&op=confirm&name=" . urlencode($rname) . "&plural=" . urlencode($rplural) . "&desc=" . urlencode($rdesc) . "&usetext=" . urlencode($rusetext) . "&type=mould");
                    }
                }
            } else {
                output("`4`bError: Something is too long.  Titles can be up to 100 characters, descriptions up to 255 characters, and usage texts up to 1,000 characters.`b`0`n`n");
                rawoutput("<form action='runmodule.php?module=mementos&op=check&type=" . $type . "' method='POST'>Memento Name (maximum 100 characters): <input name='name' id='name' value={$rname}><br /><br />Plural (maximum 100 characters): <input name='plural' id='plural' value={$rplural}><br /><br />Memento Description (maximum 255 characters):<br />");
                require_once "lib/forms.php";
                previewfield_countup("description", 255, $rdesc);
                rawoutput("<br /><br />Text shown when using the Memento (maximum 1,000 characters):<br />");
                previewfield_countup("usetext", 1000, $rusetext);
                rawoutput("<br /><input type=submit>");
                addnav("", "runmodule.php?module=mementos&op=check&type=" . $type);
            }
            addnav("Start Again");
            addnav("Memento Forge", "runmodule.php?module=mementos&op=start");
            break;
        case "confirm":
            $type = httpget("type");
            $name = urldecode(httpget("name"));
            $plural = urldecode(httpget("plural"));
            $desc = urldecode(httpget("desc"));
            $usetext = urldecode(httpget("usetext"));
            $prefs = array("verbosename" => $name, "plural" => $plural, "description" => $desc, "usetext" => $usetext, "memento_author" => $session['user']['acctid']);
            if ($type == "single") {
                $cost = 50;
                output("You've made a new Memento.  You can find it in your Inventory!");
            } else {
                if ($type == "mould") {
                    $cost = 500;
                    output("You've made a mould for your new Memento, and the first Memento from that mould is now in your Inventory!");
                    $prefs['mouldusesleft'] = 50;
                }
            }
            $session['user']['donationspent'] += $cost;
            //log purchase
            $logsql = "INSERT INTO " . db_prefix("purchaselog") . " (acctid,purchased,amount,data,giftwrap,timestamp) VALUES ('" . $session['user']['acctid'] . "','memento_" . $type . "','" . $cost . "','none','0','" . date("Y-m-d H:i:s") . "')";
            db_query($logsql);
            //create the mould, track its id
            $id = give_item("memento", $prefs, "mementomoulds_" . $session['user']['acctid'], true);
            //debug($id);
            $prefs['memento_originalitem'] = $id;
            set_item_pref("memento_originalitem", $id, $id);
            //give the player the initial memento
            give_item("memento", $prefs);
            addnav("Return");
            addnav("Memento Forge", "runmodule.php?module=mementos&op=start");
            break;
    }
    addnav("Return");
    addnav("Back to the Hunter's Lodge", "runmodule.php?module=iitems_hunterslodge&op=start");
    page_footer();
}
     }
     if (isset($row['body']) && $row['body'] != "") {
         $body = "\n\n---" . translate_inline("Original Message") . "---\n" . $row['body'];
     }
 }
 rawoutput("<input type='hidden' name='returnto' value=\"" . htmlentities(stripslashes(httpget("replyto"))) . "\">");
 $superusers = array();
 if (isset($row['login']) && $row['login'] != "") {
     output_notl("<input type='hidden' name='to' id='to' value=\"" . htmlentities($row['login']) . "\">", true);
     output("`2To: `^%s`n", $row['name']);
     if ($row['superuser'] & SU_GIVES_YOM_WARNING && !($row['superuser'] & SU_OVERRIDE_YOM_WARNING)) {
         array_push($superusers, $row['login']);
     }
 } else {
     output("`2To: ");
     $to = httppost('to');
     $string = "%";
     for ($x = 0; $x < strlen($to); $x++) {
         $string .= substr($to, $x, 1) . "%";
     }
     $sql = "SELECT login,name, superuser FROM " . db_prefix("accounts") . " WHERE name LIKE '" . addslashes($string) . "' AND locked=0 ORDER by login='******' DESC, name='{$to}' DESC, login";
     $result = db_query($sql);
     if (db_num_rows($result) == 1) {
         $row = db_fetch_assoc($result);
         output_notl("<input type='hidden' id='to' name='to' value=\"" . htmlentities($row['login']) . "\">", true);
         output_notl("`^{$row['name']}`n");
         if ($row['superuser'] & SU_GIVES_YOM_WARNING && !($row['superuser'] & SU_OVERRIDE_YOM_WARNING)) {
             array_push($superusers, $row['login']);
         }
     } elseif (db_num_rows($result) == 0) {
         output("`@No one was found who matches \"%s\".  ", stripslashes($to));
    }
    rawoutput("<form action='weaponeditor.php?op=save&level={$weaponlevel}' method='POST'>");
    addnav("", "weaponeditor.php?op=save&level={$weaponlevel}");
    showform($weaponarray, $row);
    rawoutput("</form>");
} else {
    if ($op == "del") {
        $sql = "DELETE FROM " . db_prefix("weapons") . " WHERE weaponid='{$id}'";
        db_query($sql);
        $op = "";
        httpset("op", $op);
    } else {
        if ($op == "save") {
            $weaponid = (int) httppost("weaponid");
            $damage = httppost("damage");
            $weaponname = httppost("weaponname");
            if ($weaponid > 0) {
                $sql = "UPDATE " . db_prefix("weapons") . " SET weaponname=\"{$weaponname}\",damage=\"{$damage}\",value=" . $values[$damage] . " WHERE weaponid='{$weaponid}'";
            } else {
                $sql = "INSERT INTO " . db_prefix("weapons") . " (level,damage,weaponname,value) VALUES ({$weaponlevel},\"{$damage}\",\"{$weaponname}\"," . $values[$damage] . ")";
            }
            db_query($sql);
            //output($sql);
            $op = "";
            httpset("op", $op);
        }
    }
}
if ($op == "") {
    $sql = "SELECT max(level+1) as level FROM " . db_prefix("weapons");
    $res = db_query($sql);
function dag_run_private()
{
    require_once "modules/dag/misc_functions.php";
    global $session;
    if (httpget('manage') != "true") {
        page_header("Dag Durnick's Table");
        output("<span style='color: #9900FF'>", true);
        output("`c`bDag Durnick's Table`b`c");
    } else {
        dag_manage();
    }
    $op = httpget('op');
    addnav("Navigation");
    addnav("I?Return to the Inn", "inn.php");
    if ($op != '') {
        addnav("Talk to Dag Durnick", "runmodule.php?module=dag");
    }
    if ($op == "list") {
        output("Dag fishes a small leather bound book out from under his cloak, flips through it to a certain page and holds it up for you to see.");
        output("\"`7Deese ain't the most recent figgers, I ain't just had time to get th' other numbers put in.`0\"`n`n");
        // ***ADDED***
        // By Andrew Senger
        // Added for new Bounty Code
        output("`c`bThe Bounty List`b`c`n");
        $sql = "SELECT bountyid,amount,target,setter,setdate FROM " . db_prefix("bounty") . " WHERE status=0 AND setdate<='" . date("Y-m-d H:i:s") . "' ORDER BY bountyid ASC";
        $result = db_query($sql);
        rawoutput("<table border=0 cellpadding=2 cellspacing=1 bgcolor='#999999'>");
        $amount = translate_inline("Amount");
        $level = translate_inline("Level");
        $name = translate_inline("Name");
        $loc = translate_inline("Location");
        $sex = translate_inline("Sex");
        $alive = translate_inline("Alive");
        $last = translate_inline("Last On");
        rawoutput("<tr class='trhead'><td><b>{$amount}</b></td><td><b>{$level}</b></td><td><b>{$name}</b></td><td><b>{$loc}</b></td><td><b>{$sex}</b></td><td><b>{$alive}</b></td><td><b>{$last}</b></td>");
        $listing = array();
        $totlist = 0;
        for ($i = 0; $i < db_num_rows($result); $i++) {
            $row = db_fetch_assoc($result);
            $amount = (int) $row['amount'];
            $sql = "SELECT name,alive,sex,level,laston,loggedin,lastip,location FROM " . db_prefix("accounts") . " WHERE acctid={$row['target']}";
            $result2 = db_query($sql);
            if (db_num_rows($result2) == 0) {
                /* this person has been deleted, clear bounties */
                $sql = "UPDATE " . db_prefix("bounty") . " SET status=1 WHERE target={$row['target']}";
                db_query($sql);
                continue;
            }
            $row2 = db_fetch_assoc($result2);
            $yesno = 0;
            for ($j = 0; $j <= $i; $j++) {
                if (isset($listing[$j]) && $listing[$j]['Name'] == $row2['name']) {
                    $listing[$j]['Amount'] = $listing[$j]['Amount'] + $amount;
                    $yesno = 1;
                }
            }
            if ($yesno == 0) {
                $loggedin = date("U") - strtotime($row2['laston']) < getsetting("LOGINTIMEOUT", 900) && $row2['loggedin'];
                $listing[] = array('Amount' => $amount, 'Level' => $row2['level'], 'Name' => $row2['name'], 'Location' => $row2['location'], 'Sex' => $row2['sex'], 'Alive' => $row2['alive'], 'LastOn' => $row2['laston'], 'LoggedIn' => $loggedin);
                $totlist = $totlist + 1;
            }
        }
        $sort = httpget("sort");
        if ($sort == "level") {
            usort($listing, 'dag_sortbountieslevel');
        } elseif ($sort != "") {
            usort($listing, 'dag_sortbounties');
        } else {
            usort($listing, 'dag_sortbountieslevel');
        }
        for ($i = 0; $i < $totlist; $i++) {
            rawoutput("<tr class='" . ($i % 2 ? "trdark" : "trlight") . "'><td>");
            output_notl("`^%s`0", $listing[$i]['Amount']);
            rawoutput("</td><td>");
            output_notl("`^%s`0", $listing[$i]['Level']);
            rawoutput("</td><td>");
            output_notl("`^%s`0", $listing[$i]['Name']);
            rawoutput("</td><td>");
            output($listing[$i]['LoggedIn'] ? "`#Online`0" : $listing[$i]['Location']);
            rawoutput("</td><td>");
            output($listing[$i]['Sex'] ? "`!Female`0" : "`!Male`0");
            rawoutput("</td><td>");
            output($listing[$i]['Alive'] ? "`1Yes`0" : "`4No`0");
            rawoutput("</td><td>");
            $laston = relativedate($listing[$i]['LastOn']);
            output_notl("%s", $laston);
            rawoutput("</td></tr>");
        }
        rawoutput("</table>");
        // ***END ADDING***
    } else {
        if ($op == "addbounty") {
            if (get_module_pref("bounties") >= get_module_setting("maxbounties")) {
                output("Dag gives you a piercing look.");
                output("`7\"Ye be thinkin' I be an assassin or somewhat?  Ye already be placin' more than 'nuff bounties for t'day.  Now, be ye gone before I stick a bounty on yer head fer annoyin' me.\"`n`n");
            } else {
                $fee = get_module_setting("bountyfee");
                if ($fee < 0 || $fee > 100) {
                    $fee = 10;
                    set_module_setting("bountyfee", $fee);
                }
                $min = get_module_setting("bountymin");
                $max = get_module_setting("bountymax");
                output("Dag Durnick glances up at you and adjusts the pipe in his mouth with his teeth.`n");
                output("`7\"So, who ye be wantin' to place a hit on? Just so ye be knowing, they got to be legal to be killin', they got to be at least level %s, and they can't be having too much outstandin' bounty nor be getting hit too frequent like, so if they ain't be listed, they can't be contracted on!  We don't run no slaughterhouse here, we run a.....business.  Also, there be a %s%% listin' fee fer any hit ye be placin'.\"`n`n", get_module_setting("bountylevel"), get_module_setting("bountyfee"));
                rawoutput("<form action='runmodule.php?module=dag&op=finalize' method='POST'>");
                output("`2Target: ");
                rawoutput("<input name='contractname'>");
                output_notl("`n");
                output("`2Amount to Place: ");
                rawoutput("<input name='amount' id='amount' width='5'>");
                output_notl("`n`n");
                $final = translate_inline("Finalize Contract");
                rawoutput("<input type='submit' class='button' value='{$final}'>");
                rawoutput("</form>");
                addnav("", "runmodule.php?module=dag&op=finalize");
            }
        } elseif ($op == "finalize") {
            if (httpget('subfinal') == 1) {
                $sql = "SELECT acctid,name,login,level,locked,age,dragonkills,pk,experience FROM " . db_prefix("accounts") . " WHERE name='" . addslashes(rawurldecode(stripslashes(httppost('contractname')))) . "' AND locked=0";
            } else {
                $contractname = stripslashes(rawurldecode(httppost('contractname')));
                $name = "%";
                for ($x = 0; $x < strlen($contractname); $x++) {
                    $name .= substr($contractname, $x, 1) . "%";
                }
                $sql = "SELECT acctid,name,login,level,locked,age,dragonkills,pk,experience FROM " . db_prefix("accounts") . " WHERE name LIKE '" . addslashes($name) . "' AND locked=0";
            }
            $result = db_query($sql);
            if (db_num_rows($result) == 0) {
                output("Dag Durnick sneers at you, `7\"There not be anyone I be knowin' of by that name.  Maybe ye should come back when ye got a real target in mind?\"");
            } elseif (db_num_rows($result) > 100) {
                output("Dag Durnick scratches his head in puzzlement, `7\"Ye be describing near half th' town, ye fool?  Why don't ye be giving me a better name now?\"");
            } elseif (db_num_rows($result) > 1) {
                output("Dag Durnick searches through his list for a moment, `7\"There be a couple of 'em that ye could be talkin' about.  Which one ye be meaning?\"`n");
                rawoutput("<form action='runmodule.php?module=dag&op=finalize&subfinal=1' method='POST'>");
                output("`2Target: ");
                rawoutput("<select name='contractname'>");
                for ($i = 0; $i < db_num_rows($result); $i++) {
                    $row = db_fetch_assoc($result);
                    rawoutput("<option value=\"" . rawurlencode($row['name']) . "\">" . full_sanitize($row['name']) . "</option>");
                }
                rawoutput("</select>");
                output_notl("`n`n");
                $amount = httppost('amount');
                output("`2Amount to Place: ");
                rawoutput("<input name='amount' id='amount' width='5' value='{$amount}'>");
                output_notl("`n`n");
                $final = translate_inline("Finalize Contract");
                rawoutput("<input type='submit' class='button' value='{$final}'>");
                rawoutput("</form>");
                addnav("", "runmodule.php?module=dag&op=finalize&subfinal=1");
            } else {
                // Now, we have just the one, so check it.
                $row = db_fetch_assoc($result);
                if ($row['locked']) {
                    output("Dag Durnick sneers at you, `7\"There not be anyone I be knowin' of by that name.  Maybe ye should come back when ye got a real target in mind?\"");
                } elseif ($row['login'] == $session['user']['login']) {
                    output("Dag Durnick slaps his knee laughing uproariously, `7\"Ye be wanting to take out a contract on yerself?  I ain't be helping no suicider, now!\"");
                } elseif ($row['level'] < get_module_setting("bountylevel") || $row['age'] < getsetting("pvpimmunity", 5) && $row['dragonkills'] == 0 && $row['pk'] == 0 && $row['experience'] < getsetting("pvpminexp", 1500)) {
                    output("Dag Durnick stares at you angrily, `7\"I told ye that I not be an assassin.  That ain't a target worthy of a bounty.  Now get outta me sight!\"");
                } else {
                    // All good!
                    $amt = abs((int) httppost('amount'));
                    $min = get_module_setting("bountymin") * $row['level'];
                    $max = get_module_setting("bountymax") * $row['level'];
                    $fee = get_module_setting("bountyfee");
                    $cost = round($amt * ((100 + $fee) / 100), 0);
                    $curbounty = 0;
                    $sql = "SELECT sum(amount) AS total FROM " . db_prefix("bounty") . " WHERE status=0 AND target={$row['acctid']}";
                    $result = db_query($sql);
                    if (db_num_rows($result) > 0) {
                        $nrow = db_fetch_assoc($result);
                        $curbounty = $nrow['total'];
                    }
                    if ($amt < $min) {
                        output("Dag Durnick scowls, `7\"Ye think I be workin' for that pittance?  Be thinkin' again an come back when ye willing to spend some real coin.  That mark be needin' at least %s gold to be worth me time.\"", $min);
                    } elseif ($session['user']['gold'] < $cost) {
                        output("Dag Durnick scowls, `7\"Ye don't be havin enough gold to be settin' that contract.  Wastin' my time like this, I aught to be puttin' a contract on YE instead!");
                    } elseif ($amt + $curbounty > $max) {
                        if ($curbounty) {
                            output("Dag looks down at the pile of coin and just leaves them there.");
                            output("`7\"I'll just be passin' on that contract.  That's way more'n `^%s`7 be worth and ye know it.  I ain't no durned assassin. A bounty o' %s already be on their head, what with the bounties I ain't figgered in to th' book already.  I might be willin' t'up it to %s, after me %s%% listin' fee of course\"`n`n", $row['name'], $curbounty, $max, $fee);
                        } else {
                            output("Dag looks down at the pile of coin and just leaves them there.");
                            output("`7\"I'll just be passin' on that contract.  That's way more'n `^%s`7 be worth and ye know it.  I ain't no durned assassin.  I might be willin' t'let y' set one of %s, after me %s%% listin' fee of course\"`n`n", $row['name'], $max, $fee);
                        }
                    } else {
                        output("You slide the coins towards Dag Durnick, who deftly palms them from the table.");
                        output("`7\"I'll just be takin' me %s%% listin' fee offa the top.  The word be put out that ye be wantin' `^%s`7 taken care of. Be patient, and keep yer eyes on the news.\"`n`n", $fee, $row['name']);
                        set_module_pref("bounties", get_module_pref("bounties") + 1);
                        $session['user']['gold'] -= $cost;
                        // ***ADDED***
                        // By Andrew Senger
                        // Adding for new Bounty Code
                        $setdate = time();
                        // random set date up to 4 hours in the future.
                        $setdate += e_rand(0, 14400);
                        $sql = "INSERT INTO " . db_prefix("bounty") . " (amount, target, setter, setdate) VALUES ({$amt}, " . $row['acctid'] . ", " . (int) $session['user']['acctid'] . ", '" . date("Y-m-d H:i:s", $setdate) . "')";
                        db_query($sql);
                        // ***END ADD***
                        debuglog("spent {$cost} to place a {$amt} bounty on {$row['name']}");
                    }
                }
            }
        } else {
            output("You stroll over to Dag Durnick, who doesn't even bother to look up at you.");
            output("He takes a long pull on his pipe.`n");
            output("`7\"Ye probably be wantin' to know if there's a price on yer head, ain't ye.\"`n`n");
            // ***ADDED***
            // By Andrew Senger
            // Adding for new Bounty Code
            $sql = "SELECT sum(amount) as total FROM " . db_prefix("bounty") . " WHERE status=0 AND setdate<='" . date("Y-m-d H:i:s") . "' AND target=" . $session['user']['acctid'];
            $result = db_query($sql);
            $curbounty = 0;
            if (db_num_rows($result) != 0) {
                $row = db_fetch_assoc($result);
                $curbounty = $row['total'];
            }
            if ($curbounty == 0) {
                output("\"`3Ye don't have no bounty on ya.  I suggest ye be keepin' it that way.\"");
            } else {
                output("\"`3Well, it be lookin like ye have `^%s gold`3 on yer head currently. Ye might wanna be watchin yourself.\"", $curbounty);
            }
            // ***END ADD***
            addnav("Bounties");
            addnav("Check the Wanted List", "runmodule.php?module=dag&op=list");
            addnav("Set a Bounty", "runmodule.php?module=dag&op=addbounty");
        }
    }
    modulehook('dagnav');
    if ($op == "list") {
        addnav("Sort List");
        addnav("View by Bounty", "runmodule.php?module=dag&op=list&sort=bounty");
        addnav("View by Level", "runmodule.php?module=dag&op=list&sort=level");
    }
    rawoutput("</span>");
    page_footer();
}
function motd_poll_form()
{
    global $session;
    $subject = httppost('subject');
    $body = httppost('body');
    if ($subject == "" || $body == "") {
        output("`\$NOTE:`^ Polls cannot be edited after they are begun in order to ensure fairness and accuracy of results.`0`n`n");
        rawoutput("<form action='motd.php?op=addpoll' method='POST'>");
        addnav("", "motd.php?op=add");
        output("Subject: ");
        rawoutput("<input type='text' size='50' name='subject' value=\"" . HTMLEntities(stripslashes($subject), ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "\"><br/>");
        output("Body:`n");
        rawoutput("<textarea class='input' name='body' cols='37' rows='5'>" . HTMLEntities(stripslashes($body), ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "</textarea><br/>");
        $option = translate_inline("Option");
        output("Choices:`n");
        $pollitem = "{$option} <input name='opt[]'><br/>";
        rawoutput($pollitem);
        rawoutput($pollitem);
        rawoutput($pollitem);
        rawoutput($pollitem);
        rawoutput($pollitem);
        rawoutput("<div id='hidepolls'>");
        rawoutput("</div>");
        rawoutput("<script language='JavaScript'>document.getElementById('hidepolls').innerHTML = '';</script>", true);
        $addi = translate_inline("Add Poll Item");
        $add = translate_inline("Add");
        rawoutput("<a href=\"#\" onClick=\"javascript:document.getElementById('hidepolls').innerHTML += '" . addslashes($pollitem) . "'; return false;\">{$addi}</a><br>");
        rawoutput("<input type='submit' class='button' value='{$add}'></form>");
    } else {
        $opt = httppost("opt");
        $body = array("body" => $body, "opt" => $opt);
        $sql = "INSERT INTO " . db_prefix("motd") . " (motdtitle,motdbody,motddate,motdtype,motdauthor) VALUES (\"{$subject}\",\"" . addslashes(serialize($body)) . "\",'" . date("Y-m-d H:i:s") . "',1,'{$session['user']['acctid']}')";
        db_query($sql);
        invalidatedatacache("motd");
        invalidatedatacache("lastmotd");
        invalidatedatacache("motddate");
        header("Location: motd.php");
        exit;
    }
}
function letteropener_run()
{
    global $session;
    page_header("Letter opener");
    require_once "common.php";
    require_once "lib/systemmail.php";
    require_once "lib/sanitize.php";
    require_once "lib/http.php";
    $maildb = "mail";
    if (get_module_setting("outbox")) {
        $maildb = "mailoutbox";
    }
    $op = httpget('op');
    $order = "acctid";
    if ($sort != "") {
        $order = "{$sort}";
    }
    $display = 0;
    $query = httppost('q');
    if ($query === false) {
        $query = httpget('q');
    }
    addnav("Back to the grotto", "superuser.php");
    addnav(array("Show last %s YOMs", get_module_setting("num")), "runmodule.php?module=letteropener&op=lastfew");
    if ($op == "read") {
        $id = httpget('id');
        $sql = "SELECT msgfrom,msgto from " . db_prefix($maildb) . " where messageid=\"" . $id . "\"";
        $result = db_query($sql);
        $row = db_fetch_assoc($result);
        $acctid = $row['msgto'];
        $sqlz = "SELECT login from " . db_prefix("accounts") . " where acctid=\"" . $acctid . "\"";
        $result = db_query($sqlz);
        $rowz = db_fetch_assoc($result);
        $login = $rowz['login'];
        addnav("Read Someone else's mail", "runmodule.php?module=letteropener");
        //addnav("~");
        addnav(array("All YOMs to %s", $login), "runmodule.php?module=letteropener&op=to&to={$login}");
        addnav(array("All YOMs from %s", $login), "runmodule.php?module=letteropener&op=from&from={$login}");
        $sql = "SELECT " . db_prefix($maildb) . ".*," . db_prefix("accounts") . ".name,login FROM " . db_prefix($maildb) . " LEFT JOIN " . db_prefix("accounts") . " ON " . db_prefix("accounts") . ".acctid=" . db_prefix($maildb) . ".msgfrom WHERE msgto=\"" . $acctid . "\" AND messageid=\"" . $id . "\"";
        $result = db_query($sql);
        if (db_num_rows($result) > 0) {
            $row = db_fetch_assoc($result);
            tlschema("mail");
            if ((int) $row['msgfrom'] == 0) {
                $row['name'] = translate_inline("`i`^System`0`i");
                if (is_array(unserialize($row['subject']))) {
                    $row['subject'] = unserialize($row['subject']);
                    $row['subject'] = call_user_func_array("sprintf_translate", $row['subject']);
                }
                if (is_array(unserialize($row['body']))) {
                    $row['body'] = unserialize($row['body']);
                    $row['body'] = call_user_func_array("sprintf_translate", $row['body']);
                }
            }
            tlschema();
            if (!$row['seen']) {
                output("`b`#NEW`b`n");
            } else {
                output("`n");
            }
            if ((int) $row['msgfrom'] != 0) {
                addnav("Or");
                //$othername=$row['msgfrom'];
                //$sql="select login from ".db_prefix("accounts")." where acctid=$othername";
                //$result = db_query($sql);
                $othername = $row['login'];
                addnav(array("All YOMs to %s", $othername), "runmodule.php?module=letteropener&op=to&to={$othername}");
                addnav(array("All YOMs from %s", $othername), "runmodule.php?module=letteropener&op=from&from={$othername}");
            }
            output("`b`2From:`b `^%s`n", $row['name']);
            output("`b`2Subject:`b `^%s`n", $row['subject']);
            output("`b`2Sent:`b `^%s`n", $row['sent']);
            output_notl("<hr>`n", true);
            output_notl(str_replace("\n", "`n", $row['body']));
            output_notl("`n<hr>`n", true);
            rawoutput("<table width='50%' border='0' cellpadding='0' cellspacing='5'><tr>");
            rawoutput("<td align='right'>&nbsp;</td>");
            rawoutput("</tr><tr>");
            $sql = "SELECT messageid FROM " . db_prefix($maildb) . " WHERE msgto='{$acctid}' AND messageid < '{$id}' ORDER BY messageid DESC LIMIT 1";
            $result = db_query($sql);
            if (db_num_rows($result) > 0) {
                $row = db_fetch_assoc($result);
                $pid = $row['messageid'];
            } else {
                $pid = 0;
            }
            $sql = "SELECT messageid FROM " . db_prefix($maildb) . " WHERE msgto='{$acctid}' AND messageid > '{$id}' ORDER BY messageid  LIMIT 1";
            $result = db_query($sql);
            if (db_num_rows($result) > 0) {
                $row = db_fetch_assoc($result);
                $nid = $row['messageid'];
            } else {
                $nid = 0;
            }
            $prev = translate_inline("< Previous");
            $next = translate_inline("Next >");
            rawoutput("<td nowrap='true'>");
            if ($pid > 0) {
                rawoutput("<a href='runmodule.php?module=letteropener&op=read&id={$pid}' class='motd'>" . htmlentities($prev) . "</a>");
                addnav("", "runmodule.php?module=letteropener&op=read&id={$pid}");
            } else {
                rawoutput(htmlentities($prev));
            }
            rawoutput("</td><td nowrap='true'>");
            if ($nid > 0) {
                rawoutput("<a href='runmodule.php?module=letteropener&op=read&id={$nid}' class='motd'>" . htmlentities($next) . "</a>");
                addnav("", "runmodule.php?module=letteropener&op=read&id={$nid}");
            } else {
                rawoutput(htmlentities($next));
            }
            rawoutput("</td>");
            rawoutput("</tr></table>");
        }
    } elseif ($op == "lastfew") {
        output("Here are the last %s non-system YOMs", get_module_setting("num"));
        $sql = "select * from " . db_prefix($maildb) . " where msgfrom>0 ORDER BY messageid DESC limit " . get_module_setting("num") . "";
        $res = db_query($sql);
        $to = translate_inline("To");
        $from = translate_inline("From");
        require_once "lib/sanitize.php";
        for ($i = 0; $i < db_num_rows($res); $i++) {
            $row = db_fetch_assoc($res);
            $sql2 = "select name from " . db_prefix("accounts") . " where acctid=" . $row['msgto'] . "";
            $res2 = db_query($sql2);
            $row2 = db_fetch_assoc($res2);
            $toname = color_sanitize($row2['name']);
            $sql3 = "select name from " . db_prefix("accounts") . " where acctid=" . $row['msgfrom'] . "";
            $res3 = db_query($sql3);
            $row3 = db_fetch_assoc($res3);
            $fromname = color_sanitize($row3['name']);
            rawoutput("<table border=1 width=100%><tr><td>{$from} :{$fromname} - " . date("M d, h:i a", strtotime($row['sent'])) . " - {$to} : {$toname}</td></tr><tr><td>" . $row['body'] . "</td></tr></table><br>");
        }
    } elseif ($op == "") {
        output("Whose mail would you like to read?`n");
        rawoutput("<form action='runmodule.php?module=letteropener' method='POST'>");
        rawoutput("<input name='q' id='q'>");
        $se = translate_inline("Search");
        rawoutput("<input type='submit' class='button' value='{$se}'>");
        rawoutput("</form>");
        rawoutput("<script language='JavaScript'>document.getElementById('q').focus();</script>");
        addnav("", "runmodule.php?module=letteropener");
        $searchresult = false;
        $where = "";
        $op = "";
        $sql = "SELECT acctid,login,name FROM " . db_prefix("accounts");
        if ($query != "") {
            $where = "WHERE login='******' OR name='{$query}'";
            $searchresult = db_query($sql . " {$where}  ORDER BY '{$order}' LIMIT 2");
        }
        if ($query !== false || $searchresult) {
            if (db_num_rows($searchresult) != 1) {
                $where = "WHERE login LIKE '%{$query}%' OR acctid LIKE '%{$query}%' OR name LIKE '%{$query}%' OR emailaddress LIKE '%{$query}%' OR lastip LIKE '%{$query}%' OR uniqueid LIKE '%{$query}%' OR gentimecount LIKE '%{$query}%' OR level LIKE '%{$query}%'";
                $searchresult = db_query($sql . " {$where}  ORDER BY '{$order}' LIMIT 101");
            }
            if (db_num_rows($searchresult) <= 0) {
                output("`\$No results found`0");
                $where = "";
            } elseif (db_num_rows($searchresult) > 100) {
                output("`\$Too many results found, narrow your search please.`0");
                $op = "";
                $where = "";
            } else {
                $op = "";
                $display = 1;
            }
        }
        if ($display == 1) {
            $q = "";
            if ($query) {
                $q = "&q={$query}";
            }
            $acid = translate_inline("AcctID");
            $login = translate_inline("Login");
            $nm = translate_inline("Name");
            $rn = 0;
            $oorder = "";
            while ($row = db_fetch_assoc($searchresult)) {
                $laston = relativedate($row['laston']);
                $loggedin = date("U") - strtotime($row['laston']) < getsetting("LOGINTIMEOUT", 900) && $row['loggedin'];
                if ($loggedin) {
                    $laston = translate_inline("`#Online`0");
                }
                $row['laston'] = $laston;
                if ($row[$order] != $oorder) {
                    $rn++;
                }
                $oorder = $row[$order];
                rawoutput("<table align=center border=1 width=350>");
                rawoutput("<tr class='trhead'><td>{$acid}: ");
                output_notl("`&%s`0", $row['acctid'], true);
                rawoutput("</td><td>{$login}: ");
                output_notl("`&%s`0", $row['login'], true);
                rawoutput("</td>");
                rawoutput("<td rowspan=2 align=left nowrap>");
                addnav("", "runmodule.php?module=letteropener&op=to&to={$row['login']}");
                addnav("", "runmodule.php?module=letteropener&op=from&from={$row['login']}");
                $to = translate_inline("All messages `#to`& this person");
                $from = translate_inline("All messages `#from`& this person");
                output_notl("<a href='runmodule.php?module=letteropener&op=to&to={$row['login']}'>`&&#149;%s`7</a>", $to, true);
                rawoutput("<br>");
                output_notl("<a href='runmodule.php?module=letteropener&op=from&from={$row['login']}'>`&&#149;%s`7</a>", $from, true);
                rawoutput("</td></tr><tr><td colspan=2>");
                output_notl("`&%s`7", $row['name'], true);
                rawoutput("</td></tr></table><Br>");
            }
        }
    } elseif ($op == "to") {
        $subject = "";
        $body = "";
        $row = "";
        addnav("Read someone else's mail", "runmodule.php?module=letteropener");
        $to = httpget('to');
        $from = httpget('from');
        if ($to != "") {
            $sql = "SELECT acctid,login,name superuser FROM " . db_prefix("accounts") . " WHERE login=\"{$to}\"";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            $sql = "SELECT acctid FROM " . db_prefix("accounts") . " WHERE login='******'login'] . "'";
            $result = db_query($sql);
            $row2 = db_fetch_assoc($result);
            $acctid = $row2['acctid'];
            rawoutput("<table>");
            $session['message'] = "";
            $sql = "SELECT subject,messageid," . db_prefix("accounts") . ".name,msgfrom,seen,sent FROM " . db_prefix($maildb) . " LEFT JOIN " . db_prefix("accounts") . " ON " . db_prefix("accounts") . ".acctid=" . db_prefix($maildb) . ".msgfrom WHERE msgto=\"" . $acctid . "\" ORDER BY sent DESC";
            $result = db_query($sql);
            if (db_num_rows($result) > 0) {
                while ($row = db_fetch_assoc($result)) {
                    tlschema("mail");
                    if ((int) $row['msgfrom'] == 0) {
                        $row['name'] = translate_inline("`i`^System`0`i");
                        if (is_array(unserialize($row['subject']))) {
                            $row['subject'] = unserialize($row['subject']);
                            $row['subject'] = call_user_func_array("sprintf_translate", $row['subject']);
                        }
                    }
                    tlschema();
                    $id = $row['messageid'];
                    output_notl("<tr>", true);
                    output_notl("<td nowrap><img src='images/" . ($row['seen'] ? "old" : "new") . "scroll.GIF' width='16' height='16' alt='" . ($row['seen'] ? "Old" : "New") . "'></td>", true);
                    output_notl("<td><a href='runmodule.php?module=letteropener&op=read&id={$id}&login={$to}'>", true);
                    addnav("", "runmodule.php?module=letteropener&op=read&id={$id}&login={$to}");
                    if (trim($row['subject']) == "") {
                        output("`i(No Subject)`i");
                    } else {
                        output_notl($row['subject']);
                    }
                    output_notl("</a></td><td><a href='runmodule.php?module=letteropener&op=read&id={$id}&login={$to}'>", true);
                    addnav("", "runmodule.php?module=letteropener&op=read&id={$id}&login={$to}");
                    output("- from %s", $row['name']);
                    output_notl("</a></td><td><a href='runmodule.php?module=letteropener&op=read&id={$id}&login={$to}'>" . date("M d, h:i a", strtotime($row['sent'])) . "</a></td>", true);
                    addnav("", "runmodule.php?module=letteropener&op=read&id={$id}&login={$to}");
                    output_notl("</tr>", true);
                }
                //}
            } else {
                output("`iThey have no mail.`i");
            }
        } elseif (db_num_rows($result) == 0) {
            output("`@No one was found who matches \"%s\".  ", stripslashes($to));
            $try = translate_inline("Please try again");
            output_notl("<a href='runmodule.php?module=letteropener'>{$try}</a>.", true);
            popup_footer();
            exit;
        } else {
            output_notl("<select name='to' id='to' onChange='check_su_warning();'>", true);
            $superusers = array();
            for ($i = 0; $i < db_num_rows($result); $i++) {
                $row = db_fetch_assoc($result);
                output_notl("<option value=\"" . HTMLEntities($row['login']) . "\">", true);
                output_notl("%s", full_sanitize($row['name']));
                if ($row['superuser'] & SU_GIVES_YOM_WARNING && !($row['superuser'] & SU_OVERRIDE_YOM_WARNING)) {
                    array_push($superusers, $row['login']);
                }
            }
            output_notl("</select>`n", true);
        }
        output_notl("</table>", true);
    } elseif ($op == "from") {
        $subject = "";
        $body = "";
        $row = "";
        addnav("Read someone else's mail", "runmodule.php?module=letteropener");
        $from = httpget('from');
        if ($from != "") {
            $sql = "SELECT acctid,login,name superuser FROM " . db_prefix("accounts") . " WHERE login=\"{$from}\"";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            $sql = "SELECT acctid FROM " . db_prefix("accounts") . " WHERE login='******'login'] . "'";
            $result = db_query($sql);
            $row2 = db_fetch_assoc($result);
            $acctid = $row2['acctid'];
            output_notl("<table>", true);
            $session['message'] = "";
            $sql = "SELECT subject,messageid," . db_prefix("accounts") . ".name,msgto,seen,sent FROM " . db_prefix($maildb) . " LEFT JOIN " . db_prefix("accounts") . " ON " . db_prefix("accounts") . ".acctid=" . db_prefix($maildb) . ".msgto WHERE msgfrom=\"" . $acctid . "\" ORDER BY sent DESC";
            $result = db_query($sql);
            if (db_num_rows($result) > 0) {
                for ($i = 0; $i < db_num_rows($result); $i++) {
                    $row = db_fetch_assoc($result);
                    $sql2 = "Select name from " . db_prefix("accounts") . " where acctid=" . $row['msgto'] . "";
                    $result2 = db_query($sql2);
                    $row2 = db_fetch_assoc($result2);
                    $toname = $row2['name'];
                    $id = $row['messageid'];
                    output_notl("<tr>", true);
                    output_notl("<td nowrap><img src='images/" . ($row['seen'] ? "old" : "new") . "scroll.GIF' width='16' height='16' alt='" . ($row['seen'] ? "Old" : "New") . "'></td>", true);
                    output_notl("<td><a href='runmodule.php?module=letteropener&op=read&id={$id}&login={$from}'>", true);
                    if (trim($row['subject']) == "") {
                        output("`i(No Subject)`i");
                    } else {
                        output_notl($row['subject']);
                    }
                    output_notl("</a></td><td><a href='runmodule.php?module=letteropener&op=read&id={$id}&login={$from}'>", true);
                    addnav("", "runmodule.php?module=letteropener&op=read&id={$id}&login={$from}");
                    output("- to %s", $toname);
                    output_notl("</a></td><td><a href='runmodule.php?module=letteropener&op=read&id={$id}&login={$from}'>" . date("M d, h:i a", strtotime($row['sent'])) . "</a></td>", true);
                    output_notl("</tr>", true);
                }
                //}
            } else {
                output("`iThey have not sent any mail.`i");
            }
        } elseif (db_num_rows($result) == 0) {
            output("`@No one was found who matches \"%s\".  ", stripslashes($from));
            $try = translate_inline("Please try again");
            output_notl("<a href='runmodule.php?module=letteropener'>{$try}</a>.", true);
            popup_footer();
            exit;
        } else {
            output_notl("<select name='to' id='to' onChange='check_su_warning();'>", true);
            $superusers = array();
            for ($i = 0; $i < db_num_rows($result); $i++) {
                $row = db_fetch_assoc($result);
                output_notl("<option value=\"" . HTMLEntities($row['login']) . "\">", true);
                output_notl("%s", full_sanitize($row['name']));
                if ($row['superuser'] & SU_GIVES_YOM_WARNING && !($row['superuser'] & SU_OVERRIDE_YOM_WARNING)) {
                    array_push($superusers, $row['login']);
                }
            }
            output_notl("</select>`n", true);
        }
        output_notl("</table>", true);
    }
    page_footer();
}
// translator ready
// addnews ready
// mail ready
require_once "common.php";
require_once "lib/commentary.php";
require_once "lib/http.php";
tlschema("petition");
check_su_access(SU_EDIT_PETITIONS);
addcommentary();
//WHEN 0 THEN 2 WHEN 1 THEN 3 WHEN 2 THEN 7 WHEN 3 THEN 5 WHEN 4 THEN 1 WHEN 5 THEN 0 WHEN 6 THEN 4 WHEN 7 THEN 6
$statuses = array(5 => "`\$Top Level`0", 4 => "`^Escalated`0", 0 => "`bUnhandled`b", 1 => "In-Progress", 6 => "`%Bug`0", 7 => "`#Awaiting Points`0", 3 => "`!Informational`0", 2 => "`iClosed`i");
//$statuses = modulehook("petition-status", $status);
$statuses = translate_inline($statuses);
$op = httpget("op");
$id = httpget("id");
if (trim(httppost('insertcommentary')) != "") {
    /* Update the bug if someone adds comments as well */
    $sql = "UPDATE " . db_prefix("petitions") . " SET closeuserid='{$session['user']['acctid']}',closedate='" . date("Y-m-d H:i:s") . "' WHERE petitionid='{$id}'";
    db_query($sql);
}
// Eric decide he didn't want petitions to be manually deleted
//
//if ($op=="del"){
//  $sql = "DELETE FROM " . db_prefix("petitions") . " WHERE petitionid='$id'";
//  db_query($sql);
//  $sql = "DELETE FROM " . db_prefix("commentary") . " WHERE section='pet-$id'";
//  db_query($sql);
//  invalidatedatacache("petition_counts");
//  $op="";
//}
page_header("Petition Viewer");
            $session['user']['attack']++;
            break;
        case "de":
            $session['user']['defense']++;
            break;
    }
}
$labels = array("hp" => "Max Hitpoints + 5", "ff" => "Forest Fights + 1", "at" => "Attack + 1", "de" => "Defense + 1", "unknown" => "Unknown Spends (contact an admin to investigate!)");
$canbuy = array("hp" => 1, "ff" => 1, "at" => 1, "de" => 1, "unknown" => 0);
$retargs = modulehook("dkpointlabels", array('desc' => $labels, 'buy' => $canbuy));
$labels = $retargs['desc'];
$canbuy = $retargs['buy'];
$pdks = array();
reset($labels);
foreach ($labels as $type => $label) {
    $pdks[$type] = (int) httppost($type);
}
$pdk = httpget("pdk");
$dp = count($session['user']['dragonpoints']);
$dkills = $session['user']['dragonkills'];
if ($pdk == 1) {
    reset($labels);
    $pdktotal = 0;
    $pdkneg = false;
    modulehook("pdkpointrecalc");
    foreach ($labels as $type => $label) {
        $pdktotal += (int) $pdks[$type];
        if ((int) $pdks[$type] < 0) {
            $pdkneg = true;
        }
    }
                $sql1 = "DELETE FROM " . db_prefix("untranslated") . " WHERE intext='{$text}' AND language='" . LANGUAGE . "' AND namespace='{$url}'";
                db_query($sql1);
            }
        } elseif (db_num_rows($result) > 1) {
            $rows = array();
            while ($row = db_fetch_assoc($result)) {
                // MySQL is case insensitive so we need to do it here.
                if ($row['intext'] == $text) {
                    $rows['tid'] = $row['tid'];
                }
            }
            $sql = "UPDATE " . db_prefix("translations") . " SET author='{$session['user']['login']}', version='{$logd_version}', uri='{$page}', outtext='{$trans}' WHERE tid IN (" . join(",", $rows) . ")";
        }
    }
    db_query($sql);
    if (httppost("savenotclose") > "") {
        header("Location: translatortool.php?op=list&u={$page}");
        exit;
    } else {
        popup_header("Updated");
        rawoutput("<script language='javascript'>window.close();</script>");
        popup_footer();
    }
} elseif ($op == "list") {
    popup_header("Translation List");
    $sql = "SELECT uri,count(*) AS c FROM " . db_prefix("translations") . " WHERE language='" . LANGUAGE . "' GROUP BY uri ORDER BY uri ASC";
    $result = db_query($sql);
    rawoutput("<form action='translatortool.php' method='GET'>");
    rawoutput("<input type='hidden' name='op' value='list'>");
    output("Known Namespaces:");
    rawoutput("<select name='u'>");