function marriage_lovedrinks()
{
    $z = 2;
    $s = get_module_setting('loveDrinksAdd');
    if (is_module_installed('drinks') && $s < $z) {
        $sql = array();
        $ladd = array();
        if ($s < 1) {
            // We use 'lessthan' so more drinks can be packaged with this
            $sql[] = "INSERT INTO " . db_prefix("drinks") . " VALUES (0, 'Love Brew', 1, 25, 5, 0, 0, 0, 20, 0, 5, 15, 0.0, 0, 0, 'Cedrik reaches under the bar, pulling out a purple cupid shaped bottle... as he pours it into a crystalline glass, the glass shines and he puts a pineapple within the liquid... \"Here, have a Love Brew..\" says Cedrik.. and as you try it, you feel uplifted!', '`%Love Brew', 12, 'You remember love..', 'Despair sets in.', '1.1', '.9', '1.5', '0', '', '', '')";
            $ladd[] = "Love Brew";
        }
        if ($s < 2) {
            // We use 'lessthan' so more drinks can be packaged with this
            $sql[] = "INSERT INTO " . db_prefix("drinks") . " VALUES (0, 'Heart Mist', 1, 25, 5, 0, 0, 0, 20, 0, 5, 15, 0.0, 0, 0, 'Cedrik grabs for a rather garish looking bottle on the shelf behind him... as he pours it into a large yellow mug, the porcelain seems to dissolve.. ooh er.. he puts a tomato within the sweet smelling gunk... \"Here, have a Heart Mist..\" says Cedrik.. and as you try it, you see symbols of love!', '`\$Heart Mist', 18, '`%Misty hearts fly around you..', '`#The sky falls...', '1.1', '.9', '1.5', '0', '', '', '')";
            $ladd[] = "Heart Misy";
        }
        foreach ($sql as $val) {
            db_query($val);
        }
        foreach ($ladd as $val) {
            $sql = "SELECT * FROM " . db_prefix("drinks") . " WHERE name='{$val}' ORDER BY costperlevel";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            set_module_objpref('drinks', $row['drinkid'], 'loveOnly', 1, 'marriage');
        }
        set_module_setting('loveDrinksAdd', $z);
        output("`n`c`b`^Marriage Module - Drinks have been added to the Loveshack`0`b`c");
    } elseif (!is_module_active('drinks')) {
        set_module_setting('loveDrinksAdd', 0);
    }
}
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 mountrarity_dohook($hookname, $args)
{
    switch ($hookname) {
        case "newday-runonce":
            $sql = "SELECT mountid FROM " . db_prefix("mounts") . " WHERE mountactive=1";
            $result = db_query($sql);
            while ($row = db_fetch_assoc($result)) {
                $id = $row['mountid'];
                $rarity = get_module_objpref("mounts", $id, "rarity");
                if (e_rand(1, 100) > $rarity) {
                    set_module_objpref("mounts", $id, "unavailable", 1);
                } else {
                    // You need to reset the availability if it's not unavailable
                    // otherwise, it never becomes available again!
                    set_module_objpref("mounts", $id, "unavailable", 0);
                }
            }
            break;
        case "mountfeatures":
            $rarity = get_module_objpref("mounts", $args['id'], "rarity");
            $args['features']['Rarity'] = $rarity;
            break;
        case "stables-desc":
            if (get_module_setting("showout")) {
                $sql = "SELECT mountid, mountname FROM " . db_prefix("mounts") . " WHERE mountactive=1";
                $result = db_query($sql);
                output("`nA sign by the door proclaims that the following mounts are out of stock for today:");
                while ($row = db_fetch_assoc($result)) {
                    $out = get_module_objpref("mounts", $row['mountid'], "unavailable");
                    if ($out) {
                        output("`n%s", $row['mountname']);
                    }
                }
            } else {
                output("`nIf you don't see something you like today, perhaps you should check again tomorrow.");
            }
            break;
        case "stables-nav":
            $sql = "SELECT mountid FROM " . db_prefix("mounts") . " WHERE mountactive=1";
            $result = db_query($sql);
            while ($row = db_fetch_assoc($result)) {
                $id = $row['mountid'];
                $out = get_module_objpref("mounts", $id, "unavailable");
                if ($out) {
                    blocknav("stables.php?op=examine&id={$id}");
                }
            }
            break;
    }
    return $args;
}
function improbablestufftrading_dohook($hookname, $args)
{
    global $session;
    switch ($hookname) {
        case "village":
            tlschema($args['schemas']['marketnav']);
            addnav($args['marketnav']);
            tlschema();
            addnav("eBoy's Trading Station", "runmodule.php?module=improbablestufftrading&op=start");
            break;
        case "newday-runonce":
            //Scramble the prices
            //Set up a loop, one to seven
            for ($i = 0; $i <= 7; $i++) {
                set_module_objpref("city", $i, "smallmedkit-current", e_rand(get_module_objpref("city", $cityid, "smallmedkit-min"), get_module_objpref("city", $cityid, "smallmedkit-max")));
                set_module_objpref("city", $i, "largemedkit-current", e_rand(get_module_objpref("city", $cityid, "largemedkit-min"), get_module_objpref("city", $cityid, "largemedkit-max")));
                set_module_objpref("city", $i, "energydrink-current", e_rand(get_module_objpref("city", $cityid, "energydrink-min"), get_module_objpref("city", $cityid, "energydrink-max")));
                set_module_objpref("city", $i, "nicotinegum-current", e_rand(get_module_objpref("city", $cityid, "nicotinegum-min"), get_module_objpref("city", $cityid, "nicotinegum-max")));
                set_module_objpref("city", $i, "powerpill-current", e_rand(get_module_objpref("city", $cityid, "powerpill-min"), get_module_objpref("city", $cityid, "powerpill-max")));
                set_module_objpref("city", $i, "teleporter-current", e_rand(get_module_objpref("city", $cityid, "teleporter-min"), get_module_objpref("city", $cityid, "teleporter-max")));
                set_module_objpref("city", $i, "banggrenade-current", e_rand(get_module_objpref("city", $cityid, "banggrenade-min"), get_module_objpref("city", $cityid, "banggrenade-max")));
                set_module_objpref("city", $i, "whoomphgrenade-current", e_rand(get_module_objpref("city", $cityid, "whoomphgrenade-min"), get_module_objpref("city", $cityid, "whoomphgrenade-max")));
                set_module_objpref("city", $i, "zapgrenade-current", e_rand(get_module_objpref("city", $cityid, "zapgrenade-min"), get_module_objpref("city", $cityid, "zapgrenade-max")));
                set_module_objpref("city", $i, "repellentspray-current", e_rand(get_module_objpref("city", $cityid, "repellentspray-min"), get_module_objpref("city", $cityid, "repellentspray-max")));
                set_module_objpref("city", $i, "rationpack-current", e_rand(get_module_objpref("city", $cityid, "rationpack-min"), get_module_objpref("city", $cityid, "rationpack-max")));
                set_module_objpref("city", $i, "improbabilitybomb-current", e_rand(get_module_objpref("city", $cityid, "improbabilitybomb-min"), get_module_objpref("city", $cityid, "improbabilitybomb-max")));
                set_module_objpref("city", $i, "kittencard-current", e_rand(get_module_objpref("city", $cityid, "kittencard-min"), get_module_objpref("city", $cityid, "kittencard-max")));
                set_module_objpref("city", $i, "bribe", e_rand(1000, 3000));
                $bribable = e_rand(0, 100);
                if ($bribable < 25) {
                    //eBoy is unbribable
                    set_module_objpref("city", $i, "acceptingbribes", 0);
                } else {
                    if ($bribable > 75) {
                        //eBoy is Bribable - else no change from yesterday
                        set_module_objpref("city", $i, "acceptingbribes", 1);
                    }
                }
            }
            break;
    }
    return $args;
}
function additionalkeys_run()
{
    global $session;
    $dwid = httpget('dwid');
    $type = httpget('type');
    $typeid = get_module_setting("typeid", $type);
    $op = httpget('op');
    $points = get_module_objpref("dwellingtypes", $typeid, "keydonationcost", "additionalkeys");
    $gem = get_module_objpref("dwellingtypes", $typeid, "keygemcost", "additionalkeys");
    $gold = get_module_objpref("dwellingtypes", $typeid, "keygoldcost", "additionalkeys");
    $pointsavailable = $session['user']['donation'] - $session['user']['donationspent'];
    addnav("Navigation");
    addnav("Return to Management", "runmodule.php?module=dwellings&op=manage&dwid={$dwid}");
    page_header("Keymaker");
    switch ($op) {
        case "buykeys":
            $type = httpget('type');
            $typeid = get_module_setting("typeid", $type);
            output("`n`0You enter the smithy and wait at the desk until a dwarf appears. \"`2Soso, you would like to buy more keys?`0\" he asks you and you nod. ");
            output("Then he tells you that this will cost you `^%s gold, %s gems `0and `^%s donationpoints`0. \"`2Still interested?`0\"", $gold, $gem, $points);
            addnav("Keymaker");
            addnav("Yes", "runmodule.php?module=additionalkeys&op=yes&dwid={$dwid}&type={$type}");
            break;
        case "yes":
            $type = httpget('type');
            $typeid = get_module_setting("typeid", $type);
            if ($session['user']['gold'] < $gold || $session['user']['gems'] < $gem || $pointsavailable < $points) {
                output("`n`n\"`2Did I not just tell you what it costs to get an extra key? So why do you waste my precious time?!`0\" the keymaker yells at you. ");
                output("Embarassed you just nod, what is apparently you can do best und leave the keymakers office.");
            } else {
                $add = get_module_objpref("dwellings", $dwid, "addkeys", "additionalkeys");
                $add++;
                set_module_objpref("dwellings", $dwid, "addkeys", $add, "additionalkeys");
                $session['user']['donationspent'] += $points;
                $session['user']['gems'] -= $gem;
                $session['user']['gold'] -= $gold;
                output("`n`n`0It takes a moment as the dwarf finally wipes away the sweat and returns to the desk, where you are still waiting for your key. He hands it over to you and says, \"`2Think about it carefully, whom you like to give it.`0\"");
            }
            break;
    }
    page_footer();
}
function creatureadmin_run()
{
    global $session;
    page_header("Spreadsheet Wotsit");
    $op = httpget("op");
    switch ($op) {
        case "start":
            output("This form accepts a tab-delimited series of fields identical to the Google Docs spreadsheet that Zolo, Sessine and I are working on.  To use it, copy a whole row out of that spreadsheet, paste it into the box below, and press the button.`n`n");
            rawoutput("<form action='runmodule.php?module=creatureadmin&op=confirm' method='POST'>");
            rawoutput("<br /><textarea name='creature' cols='40' rows='12'></textarea>");
            rawoutput("<input type='submit' class='button' value='" . translate_inline("The Button") . "'");
            rawoutput("</form>");
            addnav("", "runmodule.php?module=creatureadmin&op=confirm");
            break;
        case "confirm":
            $post = httppost("creature");
            debug($post);
            $c = explode("\t", $post);
            debug($c);
            $creatureid = $c[0];
            $creaturename = $c[1];
            $creaturelevel = $c[2];
            $creatureweapon = $c[3];
            $creaturewin = $c[4];
            $creaturelose = $c[5];
            $description = $c[6];
            $t = array();
            $t[1]['name'] = $c[7];
            $t[1]['hp'] = $c[8];
            $t[1]['targatk'] = $c[9];
            $t[1]['targdef'] = $c[10];
            $t[1]['targmsg'] = $c[11];
            $t[1]['depatk'] = $c[12];
            $t[1]['depdef'] = $c[13];
            $t[1]['dephp'] = $c[14];
            $t[1]['depmsg'] = $c[15];
            $t[2]['name'] = $c[16];
            $t[2]['hp'] = $c[17];
            $t[2]['targatk'] = $c[18];
            $t[2]['targdef'] = $c[19];
            $t[2]['targmsg'] = $c[20];
            $t[2]['depatk'] = $c[21];
            $t[2]['depdef'] = $c[22];
            $t[2]['dephp'] = $c[23];
            $t[2]['depmsg'] = $c[24];
            $t[3]['name'] = $c[25];
            $t[3]['hp'] = $c[26];
            $t[3]['targatk'] = $c[27];
            $t[3]['targdef'] = $c[28];
            $t[3]['targmsg'] = $c[29];
            $t[3]['depatk'] = $c[30];
            $t[3]['depdef'] = $c[31];
            $t[3]['dephp'] = $c[32];
            $t[3]['depmsg'] = $c[33];
            $t[4]['name'] = $c[34];
            $t[4]['hp'] = $c[35];
            $t[4]['targatk'] = $c[36];
            $t[4]['targdef'] = $c[37];
            $t[4]['targmsg'] = $c[38];
            $t[4]['depatk'] = $c[39];
            $t[4]['depdef'] = $c[40];
            $t[4]['dephp'] = $c[41];
            $t[4]['depmsg'] = $c[42];
            $t[5]['name'] = $c[43];
            $t[5]['hp'] = $c[44];
            $t[5]['targatk'] = $c[45];
            $t[5]['targdef'] = $c[46];
            $t[5]['targmsg'] = $c[47];
            $t[5]['depatk'] = $c[48];
            $t[5]['depdef'] = $c[49];
            $t[5]['dephp'] = $c[50];
            $t[5]['depmsg'] = $c[51];
            $t[6]['name'] = $c[52];
            $t[6]['hp'] = $c[53];
            $t[6]['targatk'] = $c[54];
            $t[6]['targdef'] = $c[55];
            $t[6]['targmsg'] = $c[56];
            $t[6]['depatk'] = $c[57];
            $t[6]['depdef'] = $c[58];
            $t[6]['dephp'] = $c[59];
            $t[6]['depmsg'] = $c[60];
            $coresql = "UPDATE " . db_prefix("creatures") . " SET creaturename = '{$creaturename}', creatureweapon = '{$creatureweapon}', creaturewin = '{$creaturewin}', creaturelose = '{$creaturelose}', creaturelevel = '{$creaturelevel}' WHERE creatureid = {$creatureid}";
            db_query($coresql);
            set_module_objpref("creatures", $creatureid, "description", $description, "creatureaddon");
            set_module_objpref("creatures", $creatureid, "usetargets", 1, "creaturetargets");
            for ($i = 1; $i <= 6; $i++) {
                set_module_objpref("creatures", $creatureid, "target" . $i, $t[$i]['name'], "creaturetargets");
                set_module_objpref("creatures", $creatureid, "hitpoints" . $i, $t[$i]['hp'], "creaturetargets");
                set_module_objpref("creatures", $creatureid, "hitatk" . $i, $t[$i]['targatk'], "creaturetargets");
                set_module_objpref("creatures", $creatureid, "hitdef" . $i, $t[$i]['targdef'], "creaturetargets");
                set_module_objpref("creatures", $creatureid, "hitmsg" . $i, $t[$i]['targmsg'], "creaturetargets");
                set_module_objpref("creatures", $creatureid, "killatk" . $i, $t[$i]['depatk'], "creaturetargets");
                set_module_objpref("creatures", $creatureid, "killdef" . $i, $t[$i]['depdef'], "creaturetargets");
                set_module_objpref("creatures", $creatureid, "killhp" . $i, $t[$i]['dephp'], "creaturetargets");
                set_module_objpref("creatures", $creatureid, "killmsg" . $i, $t[$i]['depmsg'], "creaturetargets");
            }
            output("Done!");
            break;
        case "finalize":
            break;
    }
    addnav("Grotto", "superuser.php");
    page_footer();
    return $args;
}
function cityprefs_run()
{
    global $session;
    page_header("City Prefs Editor");
    $op = httpget('op');
    $cityid = httpget('cityid');
    if ($cityid > 0) {
        $cityname = get_cityprefs_cityname("cityid", $cityid);
        page_header("%s Properties", $cityname);
        $modu = get_cityprefs_module("cityid", $cityid);
        if ($modu != "none") {
            addnav("Operations");
            addnav("Module settings", "configuration.php?op=modulesettings&module={$modu}");
        }
        addnav("Navigation");
        if (is_module_active("cities")) {
            addnav(array("Journey to %s", $cityname), "runmodule.php?module=cities&op=travel&city=" . urlencode($cityname) . "&su=1");
        } else {
            addnav(array("Journey to %s", $cityname), "village.php");
        }
    }
    addnav("Navigation");
    addnav("Back to the Grotto", "superuser.php");
    if (is_module_active("modloc")) {
        addnav("Module locations", "runmodule.php?module=modloc");
    }
    if ($op != "su") {
        addnav("Back to city list", "runmodule.php?module=cityprefs&op=su");
    }
    switch ($op) {
        case "su":
            addnav("Operations");
            addnav("Auto-add new cities", "runmodule.php?module=cityprefs&op=update");
            $id = translate_inline("ID");
            $name = translate_inline("City Name");
            $module = translate_inline("Module");
            $edit = translate_inline("Edit");
            $sql = "select * from " . db_prefix("cityprefs");
            $result = db_query($sql);
            rawoutput("<table border='0' cellpadding='3' cellspacing='0' align='center'><tr class='trhead'><td style=\"width:50px\">{$id}</td><td style='width:150px' align=center>{$name}</td><td align=center>{$module}</td><td align=center>{$edit}</td></tr>");
            for ($i = 0; $i < db_num_rows($result); $i++) {
                $row = db_fetch_assoc($result);
                $vloc = array();
                $vname = getsetting("villagename", LOCATION_FIELDS);
                $vloc[$vname] = "village";
                $vloc = modulehook("validlocation", $vloc);
                ksort($vloc);
                reset($vloc);
                foreach ($vloc as $loc => $val) {
                    if ($loc == $row['cityname']) {
                        $area = $val;
                    }
                }
                rawoutput("<tr class='" . ($i % 2 ? "trlight" : "trdark") . "'><td align=center>" . $row['cityid'] . "</td><td align=center>");
                output_notl("%s", $row['cityname']);
                rawoutput("</td><td align=center>");
                output_notl("%s", $row['module']);
                rawoutput("</td><td align=center>");
                rawoutput("<a href='runmodule.php?module=cityprefs&op=editmodule&area=" . htmlentities($val) . "&cityid=" . $row['cityid'] . "'>{$edit}</a></td></tr>");
                addnav("", "runmodule.php?module=cityprefs&op=editmodule&area=" . htmlentities($val) . "&cityid=" . $row['cityid'] . "");
            }
            rawoutput("</table>");
            break;
        case "update":
            $vloc = array();
            $vloc = modulehook("validlocation", $vloc);
            ksort($vloc);
            reset($vloc);
            $out = 0;
            foreach ($vloc as $loc => $val) {
                $sql = "select cityname from " . db_prefix("cityprefs") . " where cityname='" . addslashes($loc) . "'";
                $result = db_query($sql);
                if (db_num_rows($result) == 0) {
                    $sql = "select modulename from " . db_prefix("module_settings") . " where value='" . addslashes($loc) . "' and setting='villagename'";
                    $result = db_query($sql);
                    $row = db_fetch_assoc($result);
                    $sql = "INSERT INTO " . db_prefix("cityprefs") . " (module,cityname) VALUES ('" . $row['modulename'] . "','" . addslashes($loc) . "')";
                    db_query($sql);
                    $out = 1;
                    output("`n`@%s`0 was added.", $loc);
                }
            }
            if ($out == 0) {
                output("There were no new locations found.");
            }
            break;
        case "editmodule":
            //code from clan editor by CortalUX
        //code from clan editor by CortalUX
        case "editmodulesave":
            addnav("Operations");
            addnav("Edit city name and module", "runmodule.php?module=cityprefs&op=editcity&cityid={$cityid}");
            addnav("Delete this city", "runmodule.php?module=cityprefs&op=delcity&cityid={$cityid}");
            $mdule = httpget("mdule");
            if ($mdule == "") {
                output("Select a pref to edit.`n`n");
            } else {
                if ($op == "editmodulesave") {
                    // Save module prefs
                    $post = httpallpost();
                    reset($post);
                    while (list($key, $val) = each($post)) {
                        set_module_objpref("city", $cityid, $key, stripslashes($val), $mdule);
                    }
                    output("`^Saved!`0`n");
                }
                require_once "lib/showform.php";
                rawoutput("<form action='runmodule.php?module=cityprefs&op=editmodulesave&cityid={$cityid}&mdule={$mdule}' method='POST'>");
                module_objpref_edit("city", $mdule, $cityid);
                rawoutput("</form>");
                addnav("", "runmodule.php?module=cityprefs&op=editmodulesave&cityid={$cityid}&mdule={$mdule}");
                //code from clan editor by CortalUX
            }
            addnav("Module Prefs");
            module_editor_navs("prefs-city", "runmodule.php?module=cityprefs&op=editmodule&cityid={$cityid}&mdule=");
            break;
        case "editcity":
            output("Changing these values will not affect the city itself, just what city is associated with the preferences.  This is useful if you want to preserve prefs after removing a city.");
            addnav("Navigation");
            addnav("Back to city properties", "runmodule.php?module=cityprefs&op=editmodule&cityid={$cityid}");
            $sql = "select * from " . db_prefix("cityprefs") . " where cityid={$cityid}";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            $module = $row['module'];
            $city = $row['cityname'];
            $submit = translate_inline("Submit");
            rawoutput("<form action='runmodule.php?module=cityprefs&op=editcity2&cityid={$cityid}' method='POST'>");
            addnav("", "runmodule.php?module=cityprefs&op=editcity2&cityid={$cityid}");
            rawoutput("<input name='cityname' id='cityname' value='{$city}' size='40' maxlength='255'><br>");
            rawoutput("<input name='modulename' id='modulename' value='{$module}' size='40' maxlength='255'><br>");
            rawoutput("<input type='submit' class='button' value='{$submit}'></form>");
            break;
        case "editcity2":
            addnav("Navigation");
            addnav("Back to city properties", "runmodule.php?module=cityprefs&op=editmodule&cityid={$cityid}");
            $cityname = httppost('cityname');
            $modulename = httppost('modulename');
            db_query("update " . db_prefix("cityprefs") . " set cityname='" . $cityname . "',module='" . $modulename . "' where cityid={$cityid}");
            output("The city name is now %s and the module name is %s.", $cityname, $modulename);
            break;
        case "delcity":
            addnav("Navigation");
            $cityid = httpget('cityid');
            addnav("Back to city properties", "runmodule.php?module=cityprefs&op=editmodule&cityid={$cityid}");
            addnav("Options");
            addnav("Yes, delete it", "runmodule.php?module=cityprefs&op=delcity2&cityid={$cityid}");
            output("Are you sure you want to delete this city?  All city prefs will be deleted.  If you would like to retain these settings for a future city, just rename it.");
            break;
        case "delcity2":
            addnav("Navigation");
            addnav("Back to city properties", "runmodule.php?module=cityprefs&op=editmodule&cityid={$cityid}");
            $cityid = httpget('cityid');
            db_query("delete from " . db_prefix("cityprefs") . " where cityid={$cityid}");
            output("The city has been deleted.");
            break;
    }
    page_footer();
}
         output_notl("`b`n`n");
     }
 }
 $sql = "SELECT modulename FROM " . db_prefix("modules") . ";";
 $result = db_query($sql);
 $listing = array("about", "armor", "badnav", "badword", "bank", "battle", "bio", "buffs", "claneditor", "clans", "commentary", "common", "configuration", "create", "creatures", "donation", "dragon", "events", "faq", "fightnav", "forest", "gardens", "graveyard", "gypsy", "healer", "hof", "home", "inn", "installer", "lib-commentary", "lib-pageparts", "list", "lodge", "logdnet", "login", "mail", "masters", "moderate", "modulemanage", "motd", "mountname", "mounts", "nav", "newday", "paylog", "petition", "prefs", "pvp", "rawsql", "referers", "referral", "retitle", "rock", "shades", "showform", "skill", "skills", "source", "stables", "stats", "superuser", "taunt", "train", "translatortool", "untranslated", "user", "village", "weapon");
 while ($row = db_fetch_assoc($result)) {
     array_push($listing, "module-" . $row['modulename']);
 }
 asort($listing);
 if (httppost('datecheck')) {
     $listing2 = $listing;
     while (list($key, $val) = each($listing2)) {
         $file = pullurl($chosenpath . $val . ".sql");
         if (strstr($file[0], "Verified")) {
             set_module_objpref("namespaces", 2, $val, substr($file[0], 0, 10), "translationwizard");
         } else {
             output_notl("`b");
             output("For namespace '%s' the pull was `\$ not`0 successful (missing file)", $val);
             output_notl("`b`n`n");
         }
     }
 }
 output("If you want to see what files we have currently on the server, visit `\$ %s`0", $lookuppath);
 output_notl("`n");
 rawoutput("<input type='submit' name='datecheck' value='" . translate_inline("Pull all dates") . "' class='button'>");
 output("If you pull only for those in the untranslated, you don't need to check anything.");
 output_notl("`n");
 output("Moduledate refers to the date in the file you pulled. That means when it was changed last as you pulled it.");
 output_notl(" ");
 output("`bDon't`b select too much. It may cause a `\$ timeout`0...");
            db_query($sql);
            invalidatedatacache("companiondata-{$id}");
            if (db_affected_rows() > 0) {
                output("`^Companion saved!`0`n`n");
            } else {
                //				if (strlen($sql) > 400) $sql = substr($sql,0,200)." ... ".substr($sql,strlen($sql)-200);
                output("`^Companion `\$not`^ saved: `\$%s`0`n`n", $sql);
            }
        }
    } elseif ($subop == "module") {
        // Save modules settings
        $module = httpget("module");
        $post = httpallpost();
        reset($post);
        while (list($key, $val) = each($post)) {
            set_module_objpref("companions", $id, $key, $val, $module);
        }
        output("`^Saved!`0`n");
    }
    if ($id) {
        $op = "edit";
    } else {
        $op = "";
    }
    httpset("op", $op);
}
if ($op == "") {
    $sql = "SELECT * FROM " . db_prefix("companions") . " ORDER BY category, name";
    $result = db_query($sql);
    $ops = translate_inline("Ops");
    $name = translate_inline("Name");
function onslaught_shuffleoutposts()
{
    //Randomly determines new weighting patterns for each Outpost
    $sql = "select * from " . db_prefix("cityprefs");
    $result = db_query($sql);
    for ($i = 0; $i < db_num_rows($result); $i++) {
        $row = db_fetch_assoc($result);
        $cid = $row['cityid'];
        set_module_objpref("city", $cid, "spawnrate", e_rand(1, 200));
    }
}
function clanmembercap_run()
{
    global $session;
    $op = httpget('op');
    $clanid = $session['user']['clanid'];
    switch ($op) {
        case "bounce":
            page_header("Clan Full");
            $clanid = httpget("clanid");
            output("This Clan has reached full capacity at %s members.", get_module_objpref("clans", $clanid, "limit", "clanmembercap"));
            addnav("Back to Clan hall", "clan.php");
            villagenav();
            break;
        case "start":
            page_header("Increase Member Cap");
            if (!get_module_objpref("clans", $clanid, "limit", "clanmembercap")) {
                $startlimit = get_module_setting("lim", "clanmembercap");
                $costfornext = get_module_setting("cost", "clanmembercap");
                set_module_objpref("clans", $clanid, "limit", $startlimit, "clanmembercap");
                set_module_objpref("clans", $clanid, "costfornext", $costfornext, "clanmembercap");
            }
            $currentlimit = get_module_objpref("clans", $clanid, "limit", "clanmembercap");
            $costfornext = get_module_objpref("clans", $clanid, "costfornext", "clanmembercap");
            $bank = get_module_objpref("clans", $clanid, "bank", "clanmembercap");
            output("Using a preposterous amount of cigarettes, you can increase the number of members allowed in your Clan.  You can currently have up to %s members - to add another member slot, it'll cost you %s cigarettes.`n`nYou currently have %s cigarettes in your Member Cap bank.  Remember that this is different to the Clan Buffs bank, and you can't transfer cigarettes from one to the other.  Your member cap will be automatically increased once the bank has enough cigarettes in it.`n`nHow many cigarettes will you deposit?`n`n", $currentlimit, $costfornext, $bank);
            $dep = translate_inline("Deposit");
            rawoutput("<form action='runmodule.php?module=clanmembercap&op=deposit' method='POST'>");
            rawoutput("<input id='input' name='amount' width=5 > <input type='submit' class='button' value='{$dep}'>");
            output("`bEnter 0 or nothing to deposit all of your cigarettes.`b`n`n");
            rawoutput("</form>");
            rawoutput("<script language='javascript'>document.getElementById('input').focus();</script>", true);
            addnav("", "runmodule.php?module=clanmembercap&op=deposit");
            addnav("Back to Clan hall", "clan.php");
            break;
        case "deposit":
            page_header("Depositing Cigarettes");
            $amount = abs((int) httppost('amount'));
            if ($amount == 0) {
                $amount = $session['user']['gems'];
            }
            if ($amount > $session['user']['gems']) {
                output("`4That's more cigarettes than you have.`0`n`n");
                addnav("Back to Clan hall", "clan.php");
                break;
            }
            debuglog("deposited " . $amount . " cigarettes in the clan's member cap bank");
            $session['user']['gems'] -= $amount;
            increment_module_objpref("clans", $clanid, "bank", $amount, "clanmembercap");
            $currentlimit = get_module_objpref("clans", $clanid, "limit", "clanmembercap");
            $costfornext = get_module_objpref("clans", $clanid, "costfornext", "clanmembercap");
            $bank = get_module_objpref("clans", $clanid, "bank", "clanmembercap");
            if ($bank > $costfornext) {
                //level up the member cap
                $currentlimit += 1;
                set_module_objpref("clans", $clanid, "limit", $currentlimit, "clanmembercap");
                //take the cigs out of the bank
                $newbank = $bank - $costfornext;
                set_module_objpref("clans", $clanid, "bank", $newbank, "clanmembercap");
                //figure out the cost of the next member cap increase
                $inc = get_module_setting("costincrease", "clanmembercap");
                $costfornext = round($costfornext * $inc);
                set_module_objpref("clans", $clanid, "costfornext", $costfornext, "clanmembercap");
                output("`bYour clan's Member Cap has been increased!`b`n`nThere are now %s cigarettes in the bank.`n`n", $newbank);
            } else {
                output("There are now %s cigarettes in this clan's Member Cap bank, out of %s needed for the next level-up.`n`n", $bank, $costfornext);
            }
            addnav("Back to Clan hall", "clan.php");
            break;
    }
    page_footer();
}
            $sql = "INSERT INTO " . db_prefix("creatures") . " (" . join(",", $cols) . ",createdby) VALUES (\"" . join("\",\"", $vals) . "\",\"" . addslashes($session['user']['login']) . "\")";
            db_query($sql);
            $id = db_insert_id();
        }
        if (db_affected_rows()) {
            output("`^Creature saved!`0`n");
        } else {
            output("`^Creature `\$not`^ saved!`0`n");
        }
    } elseif ($subop == "module") {
        // Save module settings
        $module = httpget("module");
        $post = httpallpost();
        reset($post);
        while (list($key, $val) = each($post)) {
            set_module_objpref("creatures", $id, $key, $val, $module);
        }
        output("`^Saved!`0`n");
    }
    // Set the httpget id so that we can do the editor once we save
    httpset("creatureid", $id, true);
    // Set the httpget op so we drop back into the editor
    httpset("op", "edit");
}
$op = httpget('op');
$id = httpget('creatureid');
if ($op == "del") {
    $sql = "DELETE FROM " . db_prefix("creatures") . " WHERE creatureid = '{$id}'";
    db_query($sql);
    if (db_affected_rows() > 0) {
        output("Creature deleted`n`n");
function titans_move_titan($titan)
{
    //move a Titan one square towards its target
    if (!is_array($titan)) {
        $titan = titans_get_titan($titan);
    }
    if ($titan['creature']['location']['x'] > $titan['creature']['destination']['x']) {
        $titan['creature']['location']['x']--;
    }
    if ($titan['creature']['location']['x'] < $titan['creature']['destination']['x']) {
        $titan['creature']['location']['x']++;
    }
    if ($titan['creature']['location']['y'] > $titan['creature']['destination']['y']) {
        $titan['creature']['location']['y']--;
    }
    if ($titan['creature']['location']['y'] < $titan['creature']['destination']['y']) {
        $titan['creature']['location']['y']++;
    }
    //todo: destroy village walls once reached
    if ($titan['creature']['location']['x'] == $titan['creature']['destination']['x'] && $titan['creature']['location']['y'] == $titan['creature']['destination']['y']) {
        //destroy walls
        set_module_objpref("city", $titan['creature']['destination']['cityid'], "defences", 0, "onslaught");
        debug("Destroying walls!");
    }
    titans_set_titan($titan);
    return $titan;
}
<?php

page_header("Dwelling Listing");
$dwid = httpget("dwid");
addnav("Back to Dwelling List", "runmodule.php?module=dwellingseditor");
$mdule = httpget("mdule");
if ($mdule == "") {
    output("Select a pref to edit.");
} else {
    if (httpget('sub') == "save") {
        // Save module prefs
        $post = httpallpost();
        reset($post);
        while (list($key, $val) = each($post)) {
            set_module_objpref("dwellings", $dwid, $key, $val, $mdule);
        }
        output("`^Saved!`0`n");
    }
    $link = "runmodule.php?module=dwellingseditor&op=dweditmodule&sub=save&dwid={$dwid}&mdule={$mdule}";
    require_once "lib/showform.php";
    rawoutput("<form action='{$link}' method='POST'>");
    module_objpref_edit("dwellings", $mdule, $dwid);
    rawoutput("</form>");
    addnav("", $link);
    //code from clan editor by CortalUX
}
addnav("Module Prefs");
module_editor_navs("prefs-dwellings", "runmodule.php?module=dwellingseditor&op=dweditmodule&dwid={$dwid}&mdule=");
    rawoutput("<input id='input' name='turns' width=5><br>");
    modulehook("dwellings-build-input", array("type" => $type, "dwid" => $dwid));
    $submit = translate_inline("Submit");
    rawoutput("<input type='submit' class='button' value='{$submit}'>");
    rawoutput("</form>");
} else {
    $turns = abs((int) httppost('turns'));
    if ($turns > $session['user']['turns']) {
        output("`nYou do not have enough turns.");
    } elseif ($turnstogo < $turns) {
        output("`nAre you trying to over work yourself?");
        output("You only need to work for %s turns.", $turnstogo);
        // Needed... Otherwise the next step will throw some output, which is simply not correct.
    } elseif ($turns == 0) {
        output("`nDoing some work is quite refreshening, isn't it.");
        output("Especially if you are not doing anything.");
    } else {
        modulehook("dwellings-build-final", array("type" => $type, "dwid" => $dwid));
        $session['user']['turns'] -= $turns;
        set_module_objpref("dwellings", $dwid, "buildturns", $spentturns + $turns);
        $turnstogo = $turncost - get_module_objpref("dwellings", $dwid, "buildturns");
        if (!$turnstogo) {
            $sql = "UPDATE " . db_prefix("dwellings") . " SET status=1,gold=0,gems=0 WHERE dwid={$dwid}";
            db_query($sql);
            output("`nStanding back, you take a look at all your hard work.  Your dwelling is done!");
            addnav("Enter your Dwelling", "runmodule.php?module=dwellings&op=enter&dwid={$dwid}");
        } else {
            output("`@You are now one step closer to finishing your %s`@.", $dwname);
        }
    }
}
     $id2 = $row['acctid'];
     $name2 = $row['name'];
     output("The marriage between `^%s`0 and `^%s`0 is complete.", $name1, $name2);
     require_once "lib/systemmail.php";
     $t = array("`^Royal Decree of Marriage");
     $mail1 = array("`^By Royal Decree, you have been married to `@%s`^ by `&%s`^ during a quiet civil ceremony.", $name2, $suname);
     $mail2 = array("`^By Royal Decree, you have been married to `@%s`^ by `&%s`^ during a quiet civil ceremony.", $name1, $suname);
     systemmail($id1, $t, $mail1);
     systemmail($id2, $t, $mail2);
     $sql = "UPDATE " . db_prefix("accounts") . " SET marriedto='{$id1}' WHERE acctid='{$id2}'";
     db_query($sql);
     $sql = "UPDATE " . db_prefix("accounts") . " SET marriedto='{$id2}' WHERE acctid='{$id1}'";
     db_query($sql);
     $time = date("Y-m-d H:i:s");
     set_module_objpref("marriage", $id1, "marriagedate", $time);
     set_module_objpref("marriage", $id2, "marriagedate", $time);
     break;
 case "blockf":
     output("`c`b`^Block Flirting`b`c`n");
     $who = httpget('who');
     if ($who == "") {
         output("Blocking a player from flirting does NOT reset their flirt points. It just prevents them from engaging in any flirting activity. A YoM will be sent to the player after you block them.");
         if (get_module_setting("charmnewday") > 0) {
             output("Since the game is set to deduct flirt points with each newday, blocking a player may cause a divorce if they are already married.");
         }
         if (get_module_setting("flirttype") == 1) {
             output("``n`nYour system is currently set up to use flirting.");
         } else {
             output("`n`n`\$Your system is currently NOT set up to use flirting so changing this setting will have no effect.`^");
         }
         output("`n`nWho do you wish to block from engaging in flirtation?`n");
     break;
 case "depositfinish":
     addnav("Return to Clan Buffs", "runmodule.php?module=clanbuffs&op=enter");
     $amount = abs((int) httppost('amount'));
     if ($amount == 0) {
         $amount = $session['user']['gems'];
     }
     $notenough = translate_inline("`\$ERROR: Not enough gems on your person to deposit.");
     $depositbalance = translate_inline("`!Your deposit of `^%s `!gems was successful. There is now a total of `^%s`! gems in your clan bank and `^%s`! gems on your person.`6\"");
     if ($amount > $session['user']['gems']) {
         output($notenough);
     } else {
         debuglog("deposited " . $amount . " gems in the clan bank");
         $gems = get_module_objpref("clans", $session['user']['clanid'], "gems");
         $gems += $amount;
         set_module_objpref("clans", $session['user']['clanid'], "gems", $gems);
         $session['user']['gems'] -= $amount;
         output($depositbalance, $amount, $gems, $session['user']['gems']);
     }
     break;
     //end shameless borrowing
 //end shameless borrowing
 case "hof":
     page_header("Hall of Fame");
     $page = httpget('page');
     $pp = 25;
     $pageoffset = (int) $page;
     if ($pageoffset > 0) {
         $pageoffset--;
     }
     $pageoffset *= $pp;
function calculate_level()
{
    global $session;
    $cost = unserialize(get_module_setting("costarray"));
    $total = 0;
    if (get_module_setting("allowatk") && get_module_objpref("clans", $session['user']['clanid'], "atkactive")) {
        $total += $cost['atk']['active'];
        $total += $cost['atk'][get_module_objpref("clans", $session['user']['clanid'], "atklevel")];
    }
    if (get_module_setting("allowdef") && get_module_objpref("clans", $session['user']['clanid'], "defactive")) {
        $total += $cost['def']['active'];
        $total += $cost['def'][get_module_objpref("clans", $session['user']['clanid'], "deflevel")];
    }
    if (get_module_setting("allowdrain") && get_module_objpref("clans", $session['user']['clanid'], "drainactive")) {
        $total += $cost['drain']['active'];
        $total += $cost['drain'][get_module_objpref("clans", $session['user']['clanid'], "drainlevel")];
    }
    if (get_module_setting("allowthorn") && get_module_objpref("clans", $session['user']['clanid'], "thornactive")) {
        $total += $cost['thorn']['active'];
        $total += $cost['thorn'][get_module_objpref("clans", $session['user']['clanid'], "thornlevel")];
    }
    if (get_module_setting("allowregen") && get_module_objpref("clans", $session['user']['clanid'], "regenactive")) {
        $total += $cost['regen']['active'];
        $total += $cost['regen'][get_module_objpref("clans", $session['user']['clanid'], "regenlevel")];
    }
    $total += $cost['round'][get_module_objpref("clans", $session['user']['clanid'], "roundlevel")];
    if (get_module_setting("allowult") && get_module_objpref("clans", $session['user']['clanid'], "ultactive")) {
        $total += $cost['ult']['active'];
    }
    if ($total == $cost['ult']['allow']) {
        set_module_objpref("clans", $session['user']['clanid'], "ultready", 1);
    }
    $total = round($total / $cost['total'] * 100, 1);
    set_module_objpref("clans", $session['user']['clanid'], "totallevel", $total);
}
    $gold_cost = get_module_objpref("dwellingtypes", $typeid, "cost-gold", "dwellings_pvp");
    $gems_cost = get_module_objpref("dwellingtypes", $typeid, "cost-gems", "dwellings_pvp");
    $daysleft = get_module_objpref("dwellings", $dwid, "run-out", "dwellings_pvp");
    $isauto = get_module_objpref("dwellings", $dwid, "isauto", "dwellings_pvp");
    set_module_objpref("dwellings", $dwid, "run-out", $daysleft - 1, "dwellings_pvp");
    $subj = translate_inline("Concerning Dwellings Guard");
    if ($daysleft == 1) {
        if ($gold_coffer >= $gold_cost && $gems_coffer >= $gems_cost && (get_module_setting("whatif") && $isauto)) {
            $extra = translate_inline("However, you have enough gold and gems inside of your coffers to purchase another Guard. So, we will go ahead and place a guard order when they expire.");
        } else {
            $extra = "";
        }
        $body = sprintf("`@We are sorry to inform you, but your establishment, %s`@, in `^%s`@ will lose the usage of it's personal guard in `\$1 day`@. This is due to the rental time running out. %s`n`nDwellings Commission.", $row['name'], $row['location'], $extra);
        require_once "lib/systemmail.php";
        systemmail($row['ownerid'], $subj, $body);
    } elseif ($daysleft <= 0) {
        if ($gold_coffer >= $gold_cost && $gems_coffer >= $gems_cost && (get_module_setting("whatif") && $isauto)) {
            require_once "modules/dwellings/lib.php";
            dwellings_modify_coffers($dwid, "gold", "-" . $gold_cost);
            dwellings_modify_coffers($dwid, "gems", "-" . $gems_cost);
            $days = get_module_objpref("dwellingtypes", $typeid, "guard-length", "dwellings_pvp");
            invalidatedatacache("objpref-dwellings-{$dwid}-run-out-dwellings_pvp");
            invalidatedatacache("objpref-dwellings-{$dwid}-bought-dwellings_pvp");
            set_module_objpref("dwellings", $dwid, "run-out", $days, "dwellings_pvp");
            set_module_objpref("dwellings", $dwid, "bought", 1, "dwellings_pvp");
        } else {
            invalidatedatacache("objpref-dwellings-{$dwid}-bought-dwellings_pvp");
            set_module_objpref("dwellings", $dwid, "bought", 0, "dwellings_pvp");
        }
    }
}
            }
            db_query($sql);
            invalidatedatacache("mountdata-{$id}");
            if (db_affected_rows() > 0) {
                output("`^Mount saved!`0`n");
            } else {
                output("`^Mount `\$not`^ saved: `\$%s`0`n", $sql);
            }
        }
    } elseif ($subop == "module") {
        // Save modules settings
        $module = httpget("module");
        $post = httpallpost();
        reset($post);
        while (list($key, $val) = each($post)) {
            set_module_objpref("mounts", $id, $key, $val, $module);
        }
        output("`^Saved!`0`n");
    }
    if ($id) {
        $op = "edit";
    } else {
        $op = "";
    }
    httpset("op", $op);
}
if ($op == "") {
    $sql = "SELECT count(acctid) AS c, hashorse FROM " . db_prefix("accounts") . " GROUP BY hashorse";
    $result = db_query($sql);
    $mounts = array();
    while ($row = db_fetch_assoc($result)) {
function ratemonster_run()
{
    global $session;
    page_header("Thanks for helping!");
    $cid = httpget('monster');
    switch (httpget('op')) {
        case "start":
            //Look up monster name
            $sql = "SELECT creaturename FROM " . db_prefix("creatures") . " WHERE creatureid={$cid}";
            $result = db_query($sql);
            $creature = db_fetch_assoc($result);
            $cname = $creature['creaturename'];
            output("Your feedback is important.  Information on what monsters you think are the funniest or most interesting, as well as monsters you find boring, will help both staff and players to write better monsters in the future.  When rating a monster, take into account how interesting, amusing, exciting, or utterly crap the monster was.  Right now we're most interested in the quality of the writing - so please don't rate monsters according to their difficulty (we'll be asking about that soon, once we've weeded out the crap monsters).  Thanks!`n`nYou are now rating the monster \"%s.\"`n`n", $cname);
            addnav("Rate this monster");
            addnav("5: Awesome", "runmodule.php?module=ratemonster&op=rate&monster={$cid}&rating=5");
            addnav("4: Pretty good", "runmodule.php?module=ratemonster&op=rate&monster={$cid}&rating=4");
            addnav("3: Average", "runmodule.php?module=ratemonster&op=rate&monster={$cid}&rating=3");
            addnav("2: Poor", "runmodule.php?module=ratemonster&op=rate&monster={$cid}&rating=2");
            addnav("1: Terrible", "runmodule.php?module=ratemonster&op=rate&monster={$cid}&rating=1");
            break;
        case "rate":
            $rating = httpget('rating');
            $currentscore = get_module_objpref("creatures", $cid, "score");
            $currentcount = get_module_objpref("creatures", $cid, "ratings");
            $currentscore += $rating;
            $currentcount++;
            set_module_objpref("creatures", $cid, "score", $currentscore);
            set_module_objpref("creatures", $cid, "ratings", $currentcount);
            $avg = round($currentscore / $currentcount, 2);
            output("Thank you!  This monster has an average rating of %s over %s votes.`n`n", $avg, $currentcount);
            //Now ensure the player can't vote for this monster again
            $info = unserialize(get_module_pref("info"));
            $info['ratedmonsters'][] = $cid;
            $rated = $info['ratedmonsters'];
            //			if (count($rated)>=100 && !$info['gotdps']){
            //				$session['user']['donation']+=1000;
            //				$info['gotdps']=true;
            //				output("`c`bYou have Donator Points!`c`bThank you so much for rating all those monsters!  Here's a 1000 Donator Point bonus.  Have fun with that!`n`n");
            //			}
            set_module_pref("info", serialize($info));
            break;
        case "superuser":
            $out = array();
            //for each monster, retrieve votes and averages
            $sql = "SELECT creaturename, creatureid, creaturelevel FROM " . db_prefix("creatures") . "";
            $result = db_query($sql);
            $max = db_num_rows($result);
            for ($i = 0; $i < $max; $i++) {
                $monster = db_fetch_assoc($result);
                $votes = get_module_objpref("creatures", $monster['creatureid'], "ratings");
                $score = get_module_objpref("creatures", $monster['creatureid'], "score");
                if ($votes) {
                    $entry = array();
                    $entry['name'] = $monster['creaturename'];
                    $entry['level'] = $monster['creaturelevel'];
                    $entry['id'] = $monster['creatureid'];
                    $entry['avg'] = number_format($score / $votes, 3);
                    $entry['tot'] = $score;
                    $entry['num'] = $votes;
                    $out[] = $entry;
                }
            }
            usort($out, 'ratings_compare');
            array_reverse($out);
            rawoutput("<table border='0' cellpadding='2' cellspacing='1' align='center' width='100%'>");
            rawoutput("<tr class='trhead'><td>Creature Name</td><td>Creature Level</td><td>Creature ID</td><td>Vote Count</td><td>Score</td><td>Average Vote</td></tr>");
            $i = 0;
            foreach ($out as $key => $vals) {
                $i++;
                rawoutput("<tr class='" . ($i % 2 ? "trdark" : "trlight") . "'>");
                rawoutput("<td>" . $vals['name'] . "</td><td>" . $vals['level'] . "</td><td>" . $vals['id'] . "</td><td>" . $vals['num'] . "</td><td>" . $vals['tot'] . "</td><td>" . $vals['avg'] . "</td></tr>");
            }
            rawoutput("</table>");
            addnav("Back to the Grotto", "superuser.php");
            break;
    }
    addnav("Back to the game");
    addnav("J?Return to the Jungle", "forest.php");
    page_footer();
}
function drinks_editor()
{
    global $mostrecentmodule;
    if (!get_module_pref("canedit")) {
        check_su_access(SU_EDIT_USERS);
    }
    page_header("Drink Editor");
    require_once "lib/superusernav.php";
    superusernav();
    addnav("Drink Editor");
    addnav("Add a drink", "runmodule.php?module=drinks&act=editor&op=add&admin=true");
    $op = httpget('op');
    $drinkid = httpget('drinkid');
    $header = "";
    if ($op != "") {
        addnav("Drink Editor Main", "runmodule.php?module=drinks&act=editor&admin=true");
        if ($op == 'add') {
            $header = translate_inline("Adding a new drink");
        } else {
            if ($op == 'edit') {
                $header = translate_inline("Editing a drink");
            }
        }
    } else {
        $header = translate_inline("Current drinks");
    }
    output_notl("`&<h3>{$header}`0</h3>", true);
    $drinksarray = array("Drink,title", "drinkid" => "Drink ID,hidden", "name" => "Drink Name", "costperlevel" => "Cost per level,int", "hpchance" => "Chance of modifying HP (see below),range,0,10,1", "turnchance" => "Chance of modifying turns (see below),range,0,10,1", "alwayshp" => "Always modify hitpoints,bool", "alwaysturn" => "Always modify turns,bool", "drunkeness" => "Drunkeness,range,1,100,1", "harddrink" => "Is drink hard alchohol?,bool", "hpmin" => "Min HP to add (see below),range,-20,20,1", "hpmax" => "Max HP to add (see below),range,-20,20,1", "hppercent" => "Modify HP by some percent (see below),range,-25,25,5", "turnmin" => "Min turns to add (see below),range,-5,5,1", "turnmax" => "Max turns to add (see below),range,-5,5,1", "remarks" => "Remarks", "buffname" => "Name of the buff", "buffrounds" => "Rounds buff lasts,range,1,20,1", "buffroundmsg" => "Message each round of buff", "buffwearoff" => "Message when buff wears off", "buffatkmod" => "Attack modifier of buff", "buffdefmod" => "Defense modifier of buff", "buffdmgmod" => "Damage modifier of buff", "buffdmgshield" => "Damage shield modifier of buff", "buffeffectfailmsg" => "Effect failure message (see below)", "buffeffectnodmgmsg" => "No damage message (see below)", "buffeffectmsg" => "Effect message (see below)");
    if ($op == "del") {
        $sql = "DELETE FROM " . db_prefix("drinks") . " WHERE drinkid='{$drinkid}'";
        module_delete_objprefs('drinks', $drinkid);
        db_query($sql);
        $op = "";
        httpset('op', "");
    }
    if ($op == "save") {
        $subop = httpget("subop");
        if ($subop == "") {
            $drinkid = httppost("drinkid");
            list($sql, $keys, $vals) = postparse($drinksarray);
            if ($drinkid > 0) {
                $sql = "UPDATE " . db_prefix("drinks") . " SET {$sql} WHERE drinkid='{$drinkid}'";
            } else {
                $sql = "INSERT INTO " . db_prefix("drinks") . " ({$keys}) VALUES ({$vals})";
            }
            db_query($sql);
            if (db_affected_rows() > 0) {
                output("`^Drink saved!");
            } else {
                $str = db_error();
                if ($str == "") {
                    output("`^Drink not saved: no changes detected.");
                } else {
                    output("`^Drink not saved: `\$%s`0", $sql);
                }
            }
        } elseif ($subop == "module") {
            $drinkid = httpget("drinkid");
            // Save module settings
            $module = httpget("editmodule");
            // This should obey the same rules as the configuration editor
            // So disabling
            //$sql = "DELETE FROM " . db_prefix("module_objprefs") . " WHERE objtype='drinks' AND objid='$drinkid' AND modulename='$module'";
            //db_query($sql);
            $post = httpallpost();
            reset($post);
            while (list($key, $val) = each($post)) {
                set_module_objpref("drinks", $drinkid, $key, $val, $module);
            }
            output("`^Saved.");
        }
        if ($drinkid) {
            $op = "edit";
            httpset("drinkid", $drinkid, true);
        } else {
            $op = "";
        }
        httpset('op', $op);
    }
    if ($op == "activate") {
        $sql = "UPDATE " . db_prefix("drinks") . " SET active=1 WHERE drinkid='{$drinkid}'";
        db_query($sql);
        $op = "";
        httpset('op', "");
    }
    if ($op == "deactivate") {
        $sql = "UPDATE " . db_prefix("drinks") . " SET active=0 WHERE drinkid='{$drinkid}'";
        db_query($sql);
        $op = "";
        httpset('op', "");
    }
    if ($op == "") {
        $op = translate_inline("Ops");
        $id = translate_inline("Id");
        $nm = translate_inline("Name");
        $dkn = translate_inline("Drunkeness");
        $hard = translate_inline("Hard Alchohol?");
        $edit = translate_inline("Edit");
        $deac = translate_inline("Deactivate");
        $act = translate_inline("Activate");
        $conf = translate_inline("Are you sure you wish to delete this drink?");
        $del = translate_inline("Del");
        rawoutput("<table border=0 cellpadding=2 cellspacing=1 bgcolor='#999999'>");
        rawoutput("<tr class='trhead'>");
        rawoutput("<td>{$op}</td><td>{$id}</td><td>{$nm}</td><td>{$dkn}</td><td>{$hard}</td>");
        rawoutput("</tr>");
        $sql = "SELECT drinkid,active,name,drunkeness,harddrink FROM " . db_prefix("drinks") . " ORDER BY drinkid";
        $result = db_query($sql);
        for ($i = 0; $i < db_num_rows($result); $i++) {
            $row = db_fetch_assoc($result);
            $id = $row['drinkid'];
            rawoutput("<tr class='" . ($i % 2 ? "trlight" : "trdark") . "'>");
            rawoutput("<td nowrap>[ <a href='runmodule.php?module=drinks&act=editor&op=edit&drinkid={$id}&admin=true'>{$edit}</a>");
            addnav("", "runmodule.php?module=drinks&act=editor&op=edit&drinkid={$id}&admin=true");
            if ($row['active']) {
                rawoutput(" | <a href='runmodule.php?module=drinks&act=editor&op=deactivate&drinkid={$id}&admin=true'>{$deac}</a>");
                addnav("", "runmodule.php?module=drinks&act=editor&op=deactivate&drinkid={$id}&admin=true");
            } else {
                rawoutput(" | <a href='runmodule.php?module=drinks&act=editor&op=activate&drinkid={$id}&admin=true'>{$act}</a>");
                addnav("", "runmodule.php?module=drinks&act=editor&op=activate&drinkid={$id}&admin=true");
            }
            rawoutput(" | <a href='runmodule.php?module=drinks&act=editor&op=del&drinkid={$id}&admin=true' onClick='return confirm(\"{$conf}\");'>{$del}</a> ]</td>");
            addnav("", "runmodule.php?module=drinks&act=editor&op=del&drinkid={$id}&admin=true");
            output_notl("<td>`^%s</td>`0", $id, true);
            output_notl("<td>`&%s`0</td>", $row['name'], true);
            output_notl("<td>`^%s`0</td>", $row['drunkeness'], true);
            $hard = translate_inline("`^No");
            if ($row['harddrink']) {
                $hard = translate_inline("`\$Yes");
            }
            output_notl("<td>%s`0</td>", $hard, true);
            rawoutput("</tr>");
        }
        rawoutput("</table>");
    }
    $subop = httpget("subop");
    if ($op == "edit") {
        addnav("Drink properties", "runmodule.php?module=drinks&act=editor&op=edit&drinkid={$drinkid}&admin=true");
        module_editor_navs("prefs-drinks", "runmodule.php?module=drinks&act=editor&drinkid={$drinkid}&op=edit&subop=module&editmodule=");
        if ($subop == "module") {
            $module = httpget("editmodule");
            $oldmodule = $mostrecentmodule;
            rawoutput("<form action='runmodule.php?module=drinks&act=editor&op=save&subop=module&editmodule={$module}&drinkid={$drinkid}&admin=true' method='POST'>");
            module_objpref_edit('drinks', $module, $drinkid);
            $mostrecentmodule = $oldmodule;
            rawoutput("</form>");
            addnav("", "runmodule.php?module=drinks&act=editor&op=save&subop=module&editmodule={$module}&drinkid={$drinkid}&admin=true");
        } elseif ($subop == "") {
            $sql = "SELECT * FROM " . db_prefix("drinks") . " WHERE drinkid='" . httpget('drinkid') . "'";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
        }
    } elseif ($op == "add") {
        /* We're adding a new drink, make an empty row */
        $row = array();
        $row['drinkid'] = 0;
    }
    if (($op == "edit" || $op == "add") && $subop == "") {
        rawoutput("<form action='runmodule.php?module=drinks&act=editor&op=save&admin=true' method='POST'>");
        addnav("", "runmodule.php?module=drinks&act=editor&op=save&admin=true");
        showform($drinksarray, $row);
        rawoutput("</form>");
        output("`\$NOTE:`7 Make sure that you know what you are doing when modifying or adding drinks.`n");
        output("Just because the drinks have a lot of options, doesn't mean you have to use all of them`n`n");
        output("`2Drink ID: `7This field is used internally and should be unique.`n");
        output("`2Name: `7The name of the drink the user will see.`n");
        output("`2Cost per level: `7This value times the users level is the drink cost.`n");
        output("`2Chance of modifying HP: `7If set, this is the number of chances out of the total of this and the turn chance for HP getting modified.`n");
        output("`2Chance of modifying turns: `7If set, this is the number of chances out of the total of this and the HP chance for turns getting modified.`n");
        output("`2Always modify HP: `7If set, hitpoints will be modified.  Should not be set alongside HP chance above.`n");
        output("`2Always modify turns: `7If set, turns will be modified.  Should not be set alongside turn chance above.`n");
        output("`2Drunkeness: `7How drunk will this make the player.`n");
        output("`2Hard Drink: `7Users are only allowed a certain number of hard drinks per day regardless of drunkeness.`n");
        output("`2Min HP to add: `7If we are modifying hitpoints, and if HP percent isn't set, use this and the HP max value to pick a random amount of HP to add.  Can be negative.`n");
        output("`2Max HP to add: `7If we are modifying hitpoints and if HP percent isn't set, use this and the HP min value to pick a random amount of HP to add.  Can be negative.`n");
        output("`2HP percent: `7If we are modifying hitpoints and if this is set, the users hitpoints are modified by this percentage.  Can be negative.`n");
        output("`2Min turns to add: `7If we are modifying turns, use this and the turn max value to pick a random amount of turns to add.  Can be negative.`n");
        output("`2Max turns to add: `7If we are modifying turns, use this and the turn min value to pick a random amount of turns to add.  Can be negative.`n");
        output("`2Remarks: `7Text displayed to the user when they order the drink.`n");
        output("`2Buff name: `7What is this buff called.`n");
        output("`2Buff rounds: `7How many rounds this buff lasts.`n");
        output("`2Buff round message: `7What message should show as each round occurs.`n");
        output("`2Buff wearoff: `7What message is shown when this buff wears off.`n");
        output("`2Buff attack modifier: `7Multiplier to modify attack points by? 1.0 is no modification, 2.0 doubles their attack points.`n");
        output("`2Buff defense modifier: `7Multiplier to modify defense points by? 1.0 is no modification, 2.0 doubles their defense points.`n");
        output("`2Buff damage modifier: `7Multiplier to modify damage by? 1.0 is no modification, 2.0 doubles their damage points. This is `\$VERY POTENT`7!`n");
        output("`2Buff damage shield modifier: `7When you are hit, deals damage to your opponent based on damage done to you. 1.0 deals identical damage, 2.0 deals double damage back to the opponent.`n");
        output("`2Effect failure message: Message if this buff fails. (Only used with damage shield)`n");
        output("`2Effect no damage message: Message if no damage is done. (Only used with damage shield)`n");
        output("`2Effect message: What shows when this buff has an effect. (Only used with damage shield)`n`n");
    }
    page_footer();
}
function buildinghitpoints_set_data($info)
{
    set_module_objpref("city", $info['cid'], "buildinghitpoints", serialize($info['data']));
}
         output("`n`^%s `3says \"`&Don't look so surprised! Nothing is sacred anymore...`3\"", $vicar);
     }
     $allprefs = unserialize(get_module_pref('allprefs'));
     $allprefs['counsel'] = 0;
     $allprefs['buyring'] = 0;
     set_module_pref('allprefs', serialize($allprefs));
     $allprefsm = unserialize(get_module_pref('allprefs', 'marriage', $session['user']['marriedto']));
     $allprefsm['counsel'] = 0;
     $allprefsm['buyring'] = 0;
     set_module_pref('allprefs', serialize($allprefsm), 'marriage', $session['user']['marriedto']);
     invalidatedatacache("marriage-marriedonline");
     invalidatedatacache("marriage-marriedrealm");
     require_once "lib/datetime.php";
     $time = date("Y-m-d H:i:s");
     set_module_objpref("marriage", $session['user']['marriedto'], "marriagedate", $time);
     set_module_objpref("marriage", $session['user']['acctid'], "marriagedate", $time);
     apply_buff('marriage-start', array("name" => "`@Marriage", "rounds" => 100, "wearoff" => "`&The elation wears off.", "defmod" => 1.83, "survivenewday" => 1, "roundmsg" => "`@You are elated at your marriage"));
     debuglog("proposal accepted from {$row['name']}");
     break;
 case "reject":
     $stuff = explode(',', get_module_pref('proposals'));
     $i = "";
     foreach ($stuff as $val) {
         if ($val != "" && $val != $target && $val != $session['user']['acctid']) {
             $i .= "," . $val;
         }
     }
     set_module_pref('proposals', $i);
     $stuff = explode(',', get_module_pref('proposals', 'marriage', $target));
     $i = "";
     foreach ($stuff as $val) {
function claneditor_run()
{
    global $session;
    tlschema("claneditor");
    $dt = httpget("dt");
    $op = httpget('op');
    if ($dt != "") {
        $sql = "SELECT * FROM " . db_prefix("clans") . " WHERE clanid='{$dt}'";
        $result = db_query($sql);
        $claninfo = db_fetch_assoc($result);
        if (db_num_rows($result) == 0) {
            $op = "";
        }
    }
    addcommentary();
    $ranks = array(CLAN_APPLICANT => "`!Applicant`0", CLAN_MEMBER => "`#Member`0", CLAN_OFFICER => "`^Officer`0", CLAN_LEADER => "`&Leader`0", CLAN_FOUNDER => "`\$Founder");
    $args = modulehook("clanranks", array("ranks" => $ranks, "clanid" => $dt));
    $ranks = translate_inline($args['ranks'], "clan");
    superusernav();
    addnav("Clans");
    addnav("List Clans", "runmodule.php?module=claneditor&op=list");
    addnav("Create a New Clan", "runmodule.php?module=claneditor&op=new");
    if ($op == "" || $op == "list") {
        page_header("Clan Listing");
        rawoutput("<table border='0' padding='0'><tr><td>");
        $sql = "SELECT MAX(" . db_prefix("clans") . ".clanid) AS clanid, MAX(clanname) AS clanname,count(" . db_prefix("accounts") . ".acctid) AS c FROM " . db_prefix("clans") . " LEFT JOIN " . db_prefix("accounts") . " ON " . db_prefix("clans") . ".clanid=" . db_prefix("accounts") . ".clanid AND clanrank>" . CLAN_APPLICANT . " GROUP BY " . db_prefix("clans") . ".clanid ORDER BY c DESC";
        $result = db_query($sql);
        if (db_num_rows($result) > 0) {
            output("`%Karissa`7 steps in as if by magic, listing the clans for you.`n");
            output("`@`bList of Clans:`b`0`n`n");
            $v = 0;
            $memb_n = translate_inline("(%s members)");
            $memb_1 = translate_inline("(%s member)");
            rawoutput('<table cellspacing="0" cellpadding="2" align="left">');
            output_notl("<tr class='trhead'><td>%s</td><td>%s</td></tr>", translate_inline("`b`&Name of Clan`b"), translate_inline("`&`iNumber of Members`i"), true);
            for ($i = 0; $i < db_num_rows($result); $i++) {
                $row = db_fetch_assoc($result);
                if ($row['c'] == 0) {
                    $sql = "DELETE FROM " . db_prefix("clans") . " WHERE clanid={$row['clanid']}";
                    db_query($sql);
                } else {
                    rawoutput('<tr class="' . ($v % 2 ? "trlight" : "trdark") . '"><td>', true);
                    if ($row['c'] == 1) {
                        $memb = sprintf($memb_1, $row['c']);
                    } else {
                        $memb = sprintf($memb_n, $row['c']);
                    }
                    output_notl("&#149; <a href='runmodule.php?module=claneditor&op=mview&dt=%s'>%s</a></td><td>%s`n", $row['clanid'], full_sanitize(htmlentities($row['clanname']), ENT_COMPAT, getsetting("charset", "ISO-8859-1")), $memb, true);
                    rawoutput('</td></tr>');
                    addnav("", "runmodule.php?module=claneditor&op=mview&dt={$row['clanid']}");
                    $v++;
                }
            }
            rawoutput("</table>", true);
        } else {
            output("`7There are no clans in the database.`n`c");
        }
        rawoutput("</td></tr><tr><td>");
        output_notl("<br>[<a href='runmodule.php?module=claneditor&op=new'>%s</a>]", translate_inline("Create a New Clan"), true);
        addnav("", "runmodule.php?module=claneditor&op=new");
        rawoutput("</td></tr></table>");
        page_footer();
    } elseif ($op == "new") {
        page_header("Clan Creation");
        $apply = httpget('apply');
        if ($apply == 1) {
            $id = httpget("id");
            $ocn = httppost('clanname');
            $ocs = httppost('clanshort');
            $clanname = stripslashes($ocn);
            $clanname = full_sanitize($clanname);
            $clanname = preg_replace("'[^[:alpha:] \\'-]'", "", $clanname);
            $clanname = addslashes($clanname);
            httppostset('clanname', $clanname);
            $clanshort = full_sanitize($ocs);
            $clanshort = preg_replace("'[^[:alpha:]]'", "", $clanshort);
            httppostset('clanshort', $clanshort);
            $sql = "SELECT * FROM " . db_prefix("clans") . " WHERE clanname='{$clanname}'";
            $result = db_query($sql);
            $e = translate_inline("`%Karissa`7 hands you a form to start a clan.");
            $e1 = translate_inline("`%Karissa`7 looks over your form but informs you that your clan name must consist only of letters, spaces, apostrophes, or dashes.  Also, your short name can consist only of letters. She hands you a blank form.");
            $e2 = translate_inline("`%Karissa`7 looks over your form but informs you that you must have at least 5 and no more than 50 characters in your clan's name (and they must consist only of letters, spaces, apostrophes, or dashes), then hands you a blank form.");
            $e3 = translate_inline("`%Karissa`7 looks over your form but informs you that you must have at least 2 and no more than 5 characters in your clan's short name (and they must all be letters), then hands you a blank form.");
            $e4 = translate_inline("`%Karissa`7 looks over your form but informs you that the clan name %s is already taken, and hands you a blank form.");
            $e5 = translate_inline("`%Karissa`7 looks over your form but informs you that the short name %s is already taken, and hands you a blank form.");
            if ($ocs == "" && $ocn == "" && !httppostisset('clanname') && !httppostisset('clanshort')) {
                output_notl($e);
                clanform();
            } elseif ($clanname != $ocn || $clanshort != $ocs) {
                output_notl($e1);
                clanform();
            } elseif (strlen($clanname) < 5 || strlen($clanname) > 50) {
                output_notl($e2);
                clanform();
            } elseif (strlen($clanshort) < 2 || strlen($clanshort) > 5) {
                output_notl($e3);
                clanform();
            } elseif (db_num_rows($result) > 0) {
                output_notl($e4, stripslashes($clanname));
                clanform();
            } else {
                $sql = "SELECT * FROM " . db_prefix("clans") . " WHERE clanshort='{$clanshort}'";
                $result = db_query($sql);
                if (db_num_rows($result) > 0) {
                    output_notl($e5, stripslashes($clanshort));
                    clanform();
                } else {
                    $sql = "INSERT INTO " . db_prefix("clans") . " (clanname,clanshort) VALUES ('{$clanname}','{$clanshort}')";
                    db_query($sql);
                    $clid = db_insert_id();
                    $sql = "UPDATE " . db_prefix("accounts") . " SET clanid='{$clid}',clanrank='" . CLAN_LEADER . "' WHERE acctid='{$id}'";
                    db_query($sql);
                    $subj = "New Clan!";
                    $msg = array("%s`0`^ has made you a new clan!", $session['user']['name']);
                    systemmail($id, $subj, $msg);
                    output("`%Karissa`7 looks over your form, and finding that everything seems to be in order, she takes your fees, stamps the form \"`\$APPROVED`7\" and files it in a drawer.`n`n");
                    output("Congratulations, you've created a new clan named %s!", stripslashes($clanname));
                }
            }
        } elseif ($apply == 0) {
            clanuserform();
        } else {
            output("`7You teleport to the Clan Hall...");
            output("`7You approach `%Karissa`7 and mention that you would like to start a new clan.");
            output("She tells you that there are three requirements to starting a clan.");
            output("First, you have to decide on a full name for your clan.");
            output("Second, you have to decide on an abbreviation for your clan.");
            output("Third you have to decide on the person that should run the clan.");
            $e = translate_inline("`n`n\"`5If you're ok with these three requirements, please fill out the following form,`7\" she says, handing you a sheet of paper.");
            output_notl($e);
            clanuserform();
        }
    } else {
        if ($op != "deleteclan") {
            page_header("The Clan of %s", full_sanitize($claninfo['clanname']));
            output("`n`c`^`bThe Clan of %s`b`c`n`n", full_sanitize($claninfo['clanname']));
        } else {
            page_header("Clan Deletion");
        }
        if ($op == "mview") {
            $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid={$claninfo['motdauthor']}";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            $motdauthname = $row['name'];
            $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid={$claninfo['descauthor']}";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            $descauthname = $row['name'];
            output("`&`bCurrent MoTD:`b `#by %s`2`n", $motdauthname);
            output_notl(nltoappon($claninfo['clanmotd']) . "`n`n");
            commentdisplay("", "clan-{$claninfo['clanid']}", "Speak into their Clan", 25, "projects");
            output_notl("`n`n");
            modulehook("collapse{", array("name" => "collapsedesc"));
            output("`&`bCurrent Description:`b `#by %s`2`n", $descauthname);
            output_notl(nltoappon($claninfo['clandesc']) . "`n");
            modulehook("}collapse");
            $sql = "SELECT count(*) AS c, clanrank FROM " . db_prefix("accounts") . " WHERE clanid={$claninfo['clanid']} GROUP BY clanrank DESC";
            $result = db_query($sql);
            // begin collapse
            modulehook("collapse{", array("name" => "clanmemberdet"));
            output("`n`bMembership Details:`b`n");
            $leaders = 0;
            while ($row = db_fetch_assoc($result)) {
                output_notl($ranks[$row['clanrank']] . ": " . $row['c'] . "`n");
                if ($row['clanrank'] >= CLAN_OFFICER) {
                    $leaders += $row['c'];
                }
            }
            output("`n");
            $noleader = translate_inline("`^There is currently no leader!  Promoting %s`^ to leader as they are the highest ranking member (or oldest member in the event of a tie).`n`n");
            if ($leaders == 0) {
                //There's no leader here, probably because the leader's account
                //expired.
                $sql = "SELECT name,acctid,clanrank FROM " . db_prefix("accounts") . " WHERE clanid={$dt} ORDER BY clanrank DESC, clanjoindate";
                $result = db_query($sql);
                $row = db_fetch_assoc($result);
                $sql = "UPDATE " . db_prefix("accounts") . " SET clanrank=" . CLAN_LEADER . " WHERE acctid='" . $row['acctid'] . "'";
                db_query($sql);
                output_notl($noleader, $row['name']);
            }
            // end collapse
            modulehook("}collapse");
        } elseif ($op == "deleteclan") {
            if (httpget("sop") == "yes") {
                //notify users of the deletion of the clan
                $sql = "SELECT acctid FROM " . db_prefix("accounts") . " WHERE clanid={$dt}";
                $result = db_query($sql);
                $subj = array("Deletion of %s", $claninfo['clanname']);
                $msg = array("The clan you were in, %s, has closed its doors.\nSorry for any inconvenience.", $claninfo['clanname']);
                while ($row = db_fetch_assoc($result)) {
                    systemmail($row['acctid'], $subj, $msg);
                }
                //change the clan if a user is in this clan
                $sql = "UPDATE " . db_prefix("accounts") . " SET clanid=0,clanrank=" . CLAN_APPLICANT . ",clanjoindate='0000-00-00 00:00:00' WHERE clanid={$dt}";
                db_query($sql);
                //change the current users clan if this user was in that clan
                if ($session['user']['clanid'] == $dt) {
                    $session['user']['clanid'] = 0;
                    $session['user']['clanrank'] = CLAN_APPLICANT;
                    $session['user']['clanjoindate'] = '0000-00-00 00:00:00';
                }
                //drop the clan.
                $sql = "DELETE FROM " . db_prefix("clans") . " WHERE clanid={$dt}";
                db_query($sql);
                module_delete_objprefs('clans', $dt);
                $op = "";
                httpset("op", "");
                unset($claninfo);
                $dt = "";
                output("That clan has been wiped.`n");
                output("`@Users within the clan have been notified.");
            } else {
                output("`%`c`bAre you SURE you want to delete this clan?`b`c`n");
                $dc = translate_inline("Delete this clan? Are you sure!");
                rawoutput("[<a href='runmodule.php?module=claneditor&op=deleteclan&sop=yes&dt={$dt}' onClick='return confirm(\"{$dc}\");'>{$dc}</a>]");
                addnav("", "runmodule.php?module=claneditor&op=deleteclan&sop=yes&dt={$dt}");
            }
        } elseif ($op == "editmodule" || $op == "editmodulesave") {
            $mdule = httpget("mdule");
            if ($op == "editmodulesave") {
                // Save module prefs
                $post = httpallpost();
                reset($post);
                while (list($key, $val) = each($post)) {
                    set_module_objpref("clans", $dt, $key, $val, $mdule);
                }
                output("`^Saved!`0`n");
            }
            rawoutput("<form action='runmodule.php?module=claneditor&op=editmodulesave&dt={$dt}&mdule={$mdule}' method='POST'>");
            module_objpref_edit("clans", $mdule, $dt);
            rawoutput("</form>");
            addnav("", "runmodule.php?module=claneditor&op=editmodulesave&dt={$dt}&mdule={$mdule}");
        } elseif ($op == "updinfo") {
            page_header("Update Clan Information");
            $clanmotd = substr(httppost('clanmotd'), 0, 4096);
            if (httppostisset('clanmotd') && $clanmotd != $claninfo['clanmotd']) {
                if ($clanmotd == "") {
                    $mauthor = 0;
                } else {
                    $mauthor = $session['user']['acctid'];
                }
                $sql = "UPDATE " . db_prefix("clans") . " SET clanmotd='{$clanmotd}',motdauthor={$mauthor} WHERE clanid={$claninfo['clanid']}";
                db_query($sql);
                invalidatedatacache("clandata-{$claninfo['clanid']}");
                $claninfo['clanmotd'] = stripslashes($clanmotd);
                output("Updating MoTD`n");
                $claninfo['motdauthor'] = $mauthor;
            }
            $clandesc = httppost('clandesc');
            if (httppostisset('clandesc') && $clandesc != $claninfo['clandesc']) {
                if ($clandesc == "") {
                    $claninfo['descauthor'] = 0;
                    $dauthor = 0;
                } else {
                    $dauthor = $session['user']['acctid'];
                }
                $sql = "UPDATE " . db_prefix("clans") . " SET clandesc='" . addslashes(substr(stripslashes($clandesc), 0, 4096)) . "',descauthor={$dauthor} WHERE clanid={$claninfo['clanid']}";
                db_query($sql);
                invalidatedatacache("clandata-{$claninfo['clanid']}");
                output("Updating description`n");
                $claninfo['clandesc'] = stripslashes($clandesc);
                $claninfo['descauthor'] = $session['user']['acctid'];
            }
            $customsay = httppost('customsay');
            if (httppostisset('customsay') && $customsay != $claninfo['customsay']) {
                $sql = "UPDATE " . db_prefix("clans") . " SET customsay='{$customsay}' WHERE clanid={$claninfo['clanid']}";
                db_query($sql);
                invalidatedatacache("clandata-{$claninfo['clanid']}");
                output("Updating custom say line`n");
                $claninfo['customsay'] = stripslashes($customsay);
            }
            $clanname = httppost('clanname');
            if ($clanname) {
                $clanname = full_sanitize($clanname);
            }
            $clanshort = httppost('clanshort');
            if ($clanshort) {
                $clanshort = full_sanitize($clanshort);
            }
            if (httppostisset('clanname') && $clanname != $claninfo['clanname']) {
                $sql = "UPDATE " . db_prefix("clans") . " SET clanname='{$clanname}' WHERE clanid={$claninfo['clanid']}";
                output("Updating the clan name`n");
                db_query($sql);
                invalidatedatacache("clandata-{$detail}");
                $claninfo['clanname'] = $clanname;
            }
            if (httppostisset('clanshort') && $clanshort != $claninfo['clanshort']) {
                $sql = "UPDATE " . db_prefix("clans") . " SET clanshort='{$clanshort}' WHERE clanid={$claninfo['clanid']}";
                output("Updating the short clan name`n");
                db_query($sql);
                invalidatedatacache("clandata-{$detail}");
                $claninfo['clanshort'] = $clanshort;
            }
            $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid={$claninfo['motdauthor']}";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            $motdauthname = $row['name'];
            $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid={$claninfo['descauthor']}";
            $result = db_query($sql);
            $row = db_fetch_assoc($result);
            $descauthname = $row['name'];
            output("`&`bCurrent MoTD:`b `#by %s`2`n", $motdauthname);
            output_notl(nltoappon($claninfo['clanmotd']) . "`n");
            output("`&`bCurrent Description:`b `#by %s`2`n", $descauthname);
            output_notl(nltoappon($claninfo['clandesc']) . "`n");
            rawoutput("<form action='runmodule.php?module=claneditor&op=updinfo&dt={$dt}' method='POST'>");
            addnav("", "runmodule.php?module=claneditor&op=updinfo&dt={$dt}");
            output("`&`bMoTD:`b `7(4096 chars)`n");
            rawoutput("<textarea name='clanmotd' cols='50' rows='10'>" . htmlentities($claninfo['clanmotd'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "</textarea><br>");
            output("`bRenaming:`b`n");
            output("`iLong Name:`i ");
            rawoutput("<input name='clanname' value=\"" . htmlentities($claninfo['clanname'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "\" maxlength=50 size=50>");
            output("`n`iShort Name:`i ");
            rawoutput("<input name='clanshort' value=\"" . htmlentities($claninfo['clanshort'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "\" maxlength=5 size=5>");
            output_notl("`n");
            output("`n`&`bDescription:`b `7(4096 chars)`n");
            if (httppost('block') > "") {
                $blockdesc = translate_inline("Description blocked for inappropriate usage.");
                $sql = "UPDATE " . db_prefix("clans") . " SET descauthor=4294967295, clandesc='{$blockdesc}' where clanid='" . $claninfo['clanid'] . "'";
                output("Blocking public description`n");
                db_query($sql);
                invalidatedatacache("clandata-" . $claninfo['clanid'] . "");
                $claninfo['blockdesc'] = "";
                $claninfo['descauthor'] = 4294967295.0;
            } elseif (httppost('unblock') > "") {
                $sql = "UPDATE " . db_prefix("clans") . " SET descauthor=0, clandesc='' where clanid='" . $claninfo['clanid'] . "'";
                output("Unblocking public description`n");
                db_query($sql);
                invalidatedatacache("clandata-" . $claninfo['clanid'] . "");
                $claninfo['clandesc'] = "";
                $claninfo['descauthor'] = 0;
            }
            $blocked = translate_inline("The clan has been blocked from posting a description.`n");
            if ($claninfo['descauthor'] == 4294967295.0) {
                output_notl("`b`%" . $blocked . "`b");
            }
            rawoutput("<textarea name='clandesc' cols='50' rows='10'>" . htmlentities($claninfo['clandesc'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "</textarea><br>");
            output("`n`&`bCustom Talk Line`b `7(blank means \"says\" -- 15 chars max)`n");
            rawoutput("<input name='customsay' value=\"" . htmlentities($claninfo['customsay'], ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "\" maxlength=\"15\"><br/>");
            $save = translate_inline("Save");
            rawoutput("<input type='submit' class='button' value=\"{$save}\">");
            $snu = htmlentities(translate_inline("Save & Unblock public description"), ENT_COMPAT, getsetting("charset", "ISO-8859-1"));
            $snb = htmlentities(translate_inline("Save & Block public description"), ENT_COMPAT, getsetting("charset", "ISO-8859-1"));
            if ($claninfo['descauthor'] == "4294967295") {
                rawoutput("<input type='submit' name='unblock' value=\"{$snu}\" class='button'>");
            } else {
                rawoutput("<input type='submit' name='block' value=\"{$snb}\" class='button'>");
            }
            rawoutput("</form>");
        } elseif ($op == "membership") {
            output("This is the clans current membership:`n");
            $setrank = httpget('setrank');
            $who = httpget('who');
            if ($setrank > "") {
                $sql = "UPDATE " . db_prefix("accounts") . " SET clanrank={$setrank} WHERE login='******'";
                db_query($sql);
            }
            $remove = httpget('remove');
            if ($remove > "") {
                $sql = "UPDATE " . db_prefix("accounts") . " SET clanrank=" . CLAN_APPLICANT . ",clanid=0,clanjoindate='0000-00-00 00:00:00' WHERE login='******' AND clanrank<={$session['user']['clanrank']}";
                db_query($sql);
                //delete unread application emails from this user.
                //breaks if the applicant has had their name changed via
                //dragon kill, superuser edit, or lodge color change
                $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE login='******'";
                $row = db_fetch_assoc(db_query($sql));
                $subj = serialize(array($apply_short, $row['name']));
                $sql = "DELETE FROM " . db_prefix("mail") . " WHERE msgfrom=0 AND seen=0 AND subject='{$subj}'";
                db_query($sql);
            }
            $sql = "SELECT acctid,name,login,clanrank,laston,clanjoindate,dragonkills,level FROM " . db_prefix("accounts") . " WHERE clanid={$claninfo['clanid']} ORDER BY clanrank DESC,clanjoindate";
            $result = db_query($sql);
            rawoutput("<table border='0' cellpadding='2' cellspacing='0'>");
            $rank = translate_inline("Rank");
            $name = translate_inline("Name");
            $lev = translate_inline("Level");
            $dk = translate_inline("Dragon Kills");
            $jd = translate_inline("Join Date");
            $lo = translate_inline("Last On");
            $ops = translate_inline("Operations");
            $promote = translate_inline("Promote");
            $demote = translate_inline("Demote");
            $remove = translate_inline("Remove From The Clan");
            $confirm = translate_inline("Are you sure you wish to remove this member from the clan?");
            rawoutput("<tr class='trhead'><td>{$rank}</td><td>{$name}</td><td>{$lev}</td><td>{$dk}</td><td>{$jd}</td><td>{$lo}</td>" . ($session['user']['clanrank'] > CLAN_MEMBER ? "<td>{$ops}</td>" : "") . "</tr>", true);
            $i = 0;
            $tot = 0;
            while ($row = db_fetch_assoc($result)) {
                $i++;
                $tot += $row['dragonkills'];
                rawoutput("<tr class='" . ($i % 2 ? "trlight" : "trdark") . "'>");
                rawoutput("<td>");
                output_notl($ranks[$row['clanrank']]);
                rawoutput("</td><td>");
                $link = "bio.php?char=" . $row['acctid'] . "&ret=" . urlencode($_SERVER['REQUEST_URI']);
                rawoutput("<a href='{$link}'>", true);
                addnav("", $link);
                output_notl("`&%s`0", $row['name']);
                rawoutput("</a>");
                rawoutput("</td><td align='center'>");
                output_notl("`^%s`0", $row['level']);
                rawoutput("</td><td align='center'>");
                output_notl("`\$%s`0", $row['dragonkills']);
                rawoutput("</td><td>");
                output_notl("`3%s`0", $row['clanjoindate']);
                rawoutput("</td><td>");
                output_notl("`#%s`0", reltime(strtotime($row['laston'])));
                rawoutput("</td>");
                rawoutput("<td>");
                rawoutput("[ <a href='runmodule.php?module=claneditor&op=membership&dt={$dt}&setrank=" . ($row['clanrank'] + 1) . "&who=" . rawurlencode($row['login']) . "'>{$promote}</a> | ");
                addnav("", "runmodule.php?module=claneditor&op=membership&dt={$dt}&setrank=" . ($row['clanrank'] + 1) . "&who=" . rawurlencode($row['login']));
                rawoutput("<a href='runmodule.php?module=claneditor&op=membership&dt={$dt}&setrank=" . ($row['clanrank'] - 1) . "&who=" . rawurlencode($row['login']) . "'>{$demote}</a> | ");
                addnav("", "runmodule.php?module=claneditor&op=membership&dt={$dt}&setrank=" . ($row['clanrank'] - 1) . "&who=" . rawurlencode($row['login']));
                rawoutput("<a href='runmodule.php?module=claneditor&op=membership&dt={$dt}&remove=" . rawurlencode($row['login']) . "' onClick=\"return confirm('{$confirm}');\">{$remove}</a> ]");
                addnav("", "runmodule.php?module=claneditor&op=membership&dt={$dt}&remove=" . rawurlencode($row['login']));
                rawoutput("</td>");
                rawoutput("</tr>");
            }
            rawoutput("</table>");
            output("`n`n`^This clan has a total of `\$%s`^ dragon kills.", $tot);
        }
        if ($dt != "" && isset($claninfo)) {
            addnav("Clan Options");
            addnav("Main View", "runmodule.php?module=claneditor&op=mview&dt={$dt}");
            addnav("Update Clan Information", "runmodule.php?module=claneditor&op=updinfo&dt={$dt}");
            addnav("Delete this Clan", "runmodule.php?module=claneditor&op=deleteclan&dt={$dt}");
            addnav("Update Members", "runmodule.php?module=claneditor&op=membership&dt={$dt}");
            addnav("Module Prefs");
            module_editor_navs("prefs-clans", "runmodule.php?module=claneditor&op=editmodule&dt=" . $claninfo['clanid'] . "&mdule=");
        }
    }
    page_footer();
}
<?php

$act = httpget('act');
set_module_objpref("dwellings", $dwid, "isauto", $act, "dwellings_pvp");
redirect("runmodule.php?module=dwellings&op=manage&dwid={$dwid}");
$mdule = httpget("mdule");
if ($mdule == "") {
    output("Select a pref to edit.");
    addnav("Operations");
    $sql = "SELECT module FROM " . db_prefix("dwellingtypes") . " WHERE typeid={$typeid}";
    $res = db_query($sql);
    $row = db_fetch_assoc($res);
    $modlink = $row['module'];
    if ($session['user']['superuser'] & SU_EDIT_CONFIG) {
        addnav(array("%s Module Settings", $modlink), "configuration.php?op=modulesettings&module={$modlink}");
    }
} else {
    if (httpget('sub') == "save") {
        // Save module prefs
        $post = httpallpost();
        reset($post);
        while (list($key, $val) = each($post)) {
            set_module_objpref("dwellingtypes", $typeid, $key, $val, $mdule);
        }
        output("`^Saved!`0`n");
    }
    $link = "runmodule.php?module=dwellingseditor&op=typeeditmodule&sub=save&typeid={$typeid}&mdule={$mdule}";
    require_once "lib/showform.php";
    rawoutput("<form action='{$link}' method='POST'>");
    module_objpref_edit("dwellingtypes", $mdule, $typeid);
    rawoutput("</form>");
    addnav("", $link);
    //code from clan editor by CortalUX
}
addnav("Module Prefs");
module_editor_navs("prefs-dwellingtypes", "runmodule.php?module=dwellingseditor&op=typeeditmodule&typeid={$typeid}&mdule=");
function get_module_objpref($type, $objid, $name, $module = false)
{
    global $mostrecentmodule;
    if ($module === false) {
        $module = $mostrecentmodule;
    }
    $sql = "SELECT value FROM " . db_prefix("module_objprefs") . " WHERE modulename='{$module}' AND objtype='{$type}' AND setting='" . addslashes($name) . "' AND objid='{$objid}' ";
    $result = db_query_cached($sql, "objpref-{$type}-{$objid}-{$name}-{$module}", 86400);
    if (db_num_rows($result) > 0) {
        $row = db_fetch_assoc($result);
        return $row['value'];
    }
    //we couldn't find this elsewhere, load the default value if it exists.
    $info = get_module_info($module);
    if (isset($info['prefs-' . $type][$name])) {
        if (is_array($info['prefs-' . $type][$name])) {
            $v = $info['prefs-' . $type][$name][0];
            $x = explode("|", $v);
        } else {
            $x = explode("|", $info['prefs-' . $type][$name]);
        }
        if (isset($x[1])) {
            set_module_objpref($type, $objid, $name, $x[1], $module);
            return $x[1];
        }
    }
    return NULL;
}
function marriage_divorce()
{
    global $session;
    $who = $session['user']['marriedto'];
    if ($who == 0) {
        return;
    } else {
        if ($who == INT_MAX) {
            require_once "lib/partner.php";
            $getpartner = get_partner(false);
            $session['user']['marriedto'] = 0;
            addnews("`&%s`% and `&%s`% were divorced today...", $session['user']['name'], $getpartner);
            debuglog("got divorced from {$getpartner} today.");
            return;
        }
    }
    $session['user']['marriedto'] = 0;
    $sql = "SELECT name,sex FROM " . db_prefix("accounts") . " WHERE acctid='{$who}' AND locked=0";
    $res = db_query($sql);
    if (db_num_rows($res) < 1) {
        return;
    }
    $row = db_fetch_assoc($res);
    $sql = "UPDATE " . db_prefix("accounts") . " SET marriedto='0' WHERE acctid='{$who}'";
    db_query($sql);
    if (get_module_setting("dmoney") > 0) {
        $gold = round($session['user']['gold'] * get_module_setting("dmoney") / 100);
    }
    $mailmessage = array("`^%s`@ has divorced you.", $session['user']['name']);
    $mailmessagg = array("`^%s`@ has divorced you.`n`nYou get `^%s gold`@.", $session['user']['name'], $gold);
    $t = array("`@Divorce!");
    addnews("`&%s`0`% and `&%s`% were divorced today...", $session['user']['name'], $row['name']);
    debuglog($session['user']['login'] . " got a divorce from {$row['name']}", $who, $session['user']['acctid']);
    debuglog($session['user']['login'] . " got a divorce from {$row['name']}", $session['user']['acctid'], $who);
    require_once "lib/systemmail.php";
    if (get_module_setting('dmoney') > 0 && $gold > 0) {
        $sql = "UPDATE " . db_prefix("accounts") . " SET gold=gold + " . $gold . " WHERE acctid='{$who}'";
        $session['user']['gold'] = 0;
        db_query($sql);
        systemmail($who, $t, $mailmessagg);
        output_notl("`n`n");
        output("`@You notice also that all your gold at hand is gone... \"`&I need this to make myself a new home, thanks...`@\"`n");
    } else {
        systemmail($who, $t, $mailmessage);
    }
    output("`n`@You feel guilty about the divorce.");
    invalidatedatacache("marriage-marriedonline");
    invalidatedatacache("marriage-marriedrealm");
    set_module_objpref("marriage", $who, "marriagedate", "0000-00-00 00:00:00");
    set_module_objpref("marriage", $session['user']['acctid'], "marriagedate", "0000-00-00 00:00:00");
    //Check to make sure the divorced gets a negative buff the next day; otherwise no more marriage buff anymore
    $allprefsr = unserialize(get_module_pref('allprefs', 'marriage', $who));
    if (get_module_setting("acceptbuff") == 1) {
        $allprefsr['received'] = 2;
    } else {
        $allprefsr['received'] = 0;
    }
    set_module_pref('allprefs', serialize($allprefsr), 'marriage', $who);
    //prevent from getting the marriage buff anymore
    $allprefs = unserialize(get_module_pref('allprefs'));
    $allprefs['received'] = 0;
    set_module_pref('allprefs', serialize($allprefs));
    apply_buff('marriage-divorce', array("name" => "`4Divorce Guilt", "rounds" => 100, "wearoff" => "`\$You feel no longer guilty about your divorce.", "defmod" => 0.83, "survivenewday" => 1, "roundmsg" => "`\$Guilt haunts you."));
}