function hunterslodge_avatar_run()
{
    require_once "lib/sanitize.php";
    require_once "lib/names.php";
    global $session;
    $op = httpget("op");
    $free = httpget("free");
    $context = httpget("context");
    switch ($context) {
        case "village":
            $backlink = "village.php";
            break;
        case "forest":
            $backlink = "forest.php";
            break;
        case "worldmap":
            $backlink = "runmodule.php?module=worldmapen&op=continue";
            break;
        case "lodge":
            $backlink = "runmodule.php?module=iitems_hunterslodge&op=start";
            break;
    }
    page_header("Choose your Avatar");
    switch ($op) {
        case "change":
            output("Want to change your Avatar?  No problem.  Upload your avatar via the box below.  Please note that NSFW images, stolen artwork or otherwise dodgy avatars will be erased without refund.  Upload files in .jpg or .png format.  Your limits are 100 pixels wide, 100 pixels tall, with a maximum filesize of 100k.  100px * 100px * 100k, simple!`n`n");
            output("Upload your avatar:`n");
            rawoutput("<form method='POST' enctype='multipart/form-data' name='upload' action='runmodule.php?module=hunterslodge_avatar&op=confirm&free={$free}&context={$context}'><input type='file' name='file'><br><br><input type='submit' class='button' name='Upload' value='Upload!'></form>");
            addnav("", "runmodule.php?module=hunterslodge_avatar&op=confirm&free={$free}&context={$context}");
            addnav("Cancel");
            addnav("Don't set an Avatar, just go back to where I came from", $backlink);
            break;
        case "confirm":
            if (httppost("Upload")) {
                $allowed_types = "(jpg|png)";
                debug(httpallpost());
                debug($_FILES);
                $file = $_FILES["file"];
                debug($file);
                $errors = array(0 => "File Received!", 1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini.", 2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.", 3 => "The uploaded file was only partially uploaded.", 4 => "No file was uploaded.", 6 => "Missing a temporary folder.");
                output_notl("`\$" . $errors[$error] . "`n");
                if (is_uploaded_file($file["tmp_name"])) {
                    if (preg_match("/\\." . $allowed_types . "\$/i", $file["name"])) {
                        if ($file["size"] <= 102400) {
                            $extension = substr($file['name'], strlen($file['name']) - 4, 4);
                            $loginname = str_replace(" ", "", $session['user']['login']);
                            $filename = "images/avatars/" . date("YmdHs") . $loginname . $extension;
                            if (move_uploaded_file($file["tmp_name"], $filename)) {
                                $pic_size = @getimagesize($filename);
                                // GD2 required here - else size always is recognized as 0
                                $pic_width = $pic_size[0];
                                $pic_height = $pic_size[1];
                                if ($pic_height <= 100 && $pic_width <= 100) {
                                    output("So, this is what you want to look like?  Click \"Set Avatar\" to confirm.`n`n");
                                    addnav("Confirm");
                                    addnav("Set Avatar", "runmodule.php?module=hunterslodge_avatar&op=set&free={$free}&context={$context}&avatar=" . rawurlencode($filename));
                                    $image = "<img align='left' src='" . $filename . "'>";
                                    rawoutput("<table><tr><td valign='top'>");
                                    $terms = appoencode(translate_inline("Your Avatar"));
                                    rawoutput("</td><td valign='top'>{$image}</td></tr><td></td><td>{$terms}</td></table>");
                                } else {
                                    output("That picture's too big!  The limit is 100 pixels by 100 pixels.`n`n");
                                }
                            } else {
                                output("The file could not be uploaded.`n`n");
                            }
                        } else {
                            output("You may only have a filesize up to 100 kilobytes!`n`n");
                        }
                    } else {
                        output("That file extension is not supported!`n`n");
                    }
                } else {
                    output("You did not specify a file to upload.`n`n");
                }
            }
            output("`0To try again with a different picture, use the form below.`n`n");
            rawoutput("<form method='POST' enctype='multipart/form-data' name='upload' action='runmodule.php?module=hunterslodge_avatar&op=confirm&free={$free}&context={$context}'><input type='file' name='file'><br><br><input type='submit' class='button' name='Upload' value='Upload!'></form>");
            addnav("", "runmodule.php?module=hunterslodge_avatar&op=confirm&free={$free}&context={$context}");
            addnav("Cancel");
            addnav("Don't set an Avatar, just go back to where I came from", $backlink);
            break;
        case "set":
            $av = httpget("avatar");
            set_module_pref("avatar", $av);
            output("Your Avatar has been changed!`n`n");
            if (!$free) {
                $id = has_item("hunterslodge_avatar");
                delete_item($id);
            }
            addnav("Return");
            addnav("Go back to where I came from", $backlink);
            break;
    }
    page_footer();
}
function funddrive_dohook($hook, $args)
{
    switch ($hook) {
        case 'donation_adjustments':
            global $session;
            if ($args['amount'] > 0) {
                increment_module_setting('base', $args['amount']);
            }
            break;
        case 'everyfooter':
            $settings = get_all_module_settings();
            if (!is_array($args['paypal'])) {
                $args['paypal'] = [];
            }
            $percent = round($settings['base'] / $settings['goal'], 2) * 100;
            if ($percent > 100) {
                $percent = 100;
            }
            $fillWidth = round(1.5 * $percent, 0);
            $unfilled = 150 - $fillWidth;
            //You may want to modify the bar to fit your site's needs. - Stephen
            $bar = appoencode("{$settings['message']}`n\n                <div class='fund-drive' align='center'>\n                    <table class='fund-drive-bar' style='border: solid 1px black; background-color: black; border-collapse: collapse; width: 150px; height: 10px;'>\n                        <tr>\n                            <td class='fund-drive-filled' width='{$fillWidth}px' style='background-color: #00FF00;'>\n                            </td>\n                            <td class='fund-drive-unfilled' width='{$unfilled}px'>\n                            </td>\n                        </tr>\n                    </table>\n                </div>", true);
            array_push($args['paypal'], $bar);
            break;
    }
    return $args;
}
function switch_dohook($hook, $args)
{
    switch ($hook) {
        case 'charstats':
            global $SCRIPT_NAME, $session;
            if ($SCRIPT_NAME == 'village.php' && $session['user']['specialinc'] == '') {
                addcharstat("Vital Info");
                addcharstat(sprintf_translate("<a href='login.php?op=logout'>%s</a>", "`%Log Out"), sprintf_translate("<a href='runmodule.php?module=switch' style='font-weight: bold;'>%s</a>", appoencode('`%Switch')));
                addnav('', 'login.php?op=logout');
                addnav('', 'runmodule.php?module=switch');
            }
            break;
    }
    return $args;
}
function mementos_feelgood_run()
{
    global $session;
    page_header("Memento Attributes");
    $mould = httpget('mould');
    $itemname = get_item_pref("verbosename", $mould);
    require_once "modules/mementos_feelgood/attributes.php";
    $attributes = mementos_feelgood_getattributes();
    switch (httpget('op')) {
        case "choosestat":
            output("`bWhat are Memento Attributes for?`b`nLet someone know how you feel about them by giving them a special Memento with a stat enhancement.  Like Mementos in themselves, these stat enhancements don't do anything to your character's abilities - they're intended only as trifles to flatter and delight.`n`nSee someone engage in a particularly special bit of rhyming roleplay?  Give them a Red Music Box of +1 Musical Mastery.  If someone else gives the player another Memento with the Musical Mastery stat attached, then their Bio will show that they have two points in Musical Mastery.  You get the idea, I'm sure - it's a tool for showing your appreciation or admiration in a playful way.`n`n`bNo really, what are Memento Attributes `ifor?`i  What do they `ido?`i`b`nThey make people feel good.  That's it!`n`n`bHow much do they cost?`b`nNothing!  They're free!  You can only apply one Attribute to any given Memento type, mind - and you can't change your mind afterwards, so choose carefully.`n`n`bHow to use them`b`nFigure out what you want your Memento to mean, and look for something in the list below that's a good match.  When you click, that Attribute will be applied to all the Mementos that came out of this Mould, and all the Mementos that will ever come out of it in the future.`n`n");
            foreach ($attributes as $key => $vals) {
                rawoutput("<strong><a href='runmodule.php?module=mementos_feelgood&op=confirm&assignstat=" . $key . "&mould=" . $mould . "'></strong>" . stripslashes(appoencode($vals['name'])) . "</a>: " . stripslashes(appoencode($vals['description'])) . "<br />");
                addnav("", "runmodule.php?module=mementos_feelgood&op=confirm&assignstat=" . $key . "&mould=" . $mould);
            }
            break;
        case "confirm":
            $assignstat = httpget('assignstat');
            $statname = $attributes[$assignstat]['name'];
            output("You're about to assign the Attribute \"%s\" to the Memento mould \"%s\".  Are you sure you want to do that?", $statname, $itemname);
            addnav("Yes!");
            addnav("Do it!", "runmodule.php?module=mementos_feelgood&op=confirmfinal&assignstat=" . $assignstat . "&mould=" . $mould);
            addnav("No wait hang on");
            addnav("That's not what I want to do AT ALL.", "runmodule.php?module=mementos_feelgood&op=choosestat&mould=" . $mould);
            break;
        case "confirmfinal":
            $assignstat = httpget('assignstat');
            output("Attribute applied!");
            //get all the items like this and apply the pref to all of them
            $sql = "SELECT * FROM " . db_prefix("items_prefs") . " WHERE setting='memento_originalitem' AND value='" . $mould . "'";
            $result = db_query($sql);
            while ($row = db_fetch_assoc($result)) {
                debug("Setting pref for itemid " . $row['id']);
                set_item_pref("memento_feelgood_attribute", $assignstat, $row['id']);
            }
            set_item_pref("memento_feelgood_attribute", $assignstat, $mould);
            break;
    }
    addnav("Return");
    addnav("Memento Forge", "runmodule.php?module=mementos&op=start");
    page_footer();
    return true;
}
Пример #5
0
function addnav($text, $link = false, $priv = false, $pop = false)
{
    global $nav, $session, $accesskeys, $REQUEST_URI, $quickkeys;
    $text = translate($text);
    if (date("m-d") == "04-01") {
        $text = borkalize($text);
    }
    if ($link === false) {
        $nav .= templatereplace("navhead", array("title" => appoencode($text, $priv)));
    } elseif ($link === "") {
        $nav .= templatereplace("navhelp", array("text" => appoencode($text, $priv)));
    } else {
        if ($text != "") {
            $extra = "";
            if (1) {
                if (strpos($link, "?")) {
                    $extra = "&c={$session['counter']}";
                } else {
                    $extra = "?c={$session['counter']}";
                }
            }
            $extra .= "-" . date("His");
            //$link = str_replace(" ","%20",$link);
            //hotkey for the link.
            $key = "";
            if (substr($text, 1, 1) == "?") {
                // check to see if a key was specified up front.
                if ($accesskeys[strtolower(substr($text, 0, 1))] == 1) {
                    // output ("key ".substr($text,0,1)." already taken`n");
                    $text = substr($text, 2);
                } else {
                    $key = substr($text, 0, 1);
                    $text = substr($text, 2);
                    //output("key set to $key`n");
                    $found = false;
                    for ($i = 0; $i < strlen($text); $i++) {
                        $char = substr($text, $i, 1);
                        if ($ignoreuntil == $char) {
                            $ignoreuntil = "";
                        } else {
                            if ($ignoreuntil != "") {
                                if ($char == "<") {
                                    $ignoreuntil = ">";
                                }
                                if ($char == "&") {
                                    $ignoreuntil = ";";
                                }
                                if ($char == "`") {
                                    $ignoreuntil = substr($text, $i + 1, 1);
                                }
                            } else {
                                if ($char == $key) {
                                    $found = true;
                                    break;
                                }
                            }
                        }
                    }
                    if ($found == false) {
                        if (strpos($text, "__") !== false) {
                            $text = str_replace("__", "(" . $key . ") ", $text);
                        } else {
                            $text = "(" . strtoupper($key) . ") " . $text;
                        }
                        $i = strpos($text, $key);
                        // output("Not found`n");
                    }
                }
                //
            }
            if ($key == "") {
                for ($i = 0; $i < strlen($text); $i++) {
                    $char = substr($text, $i, 1);
                    if ($ignoreuntil == $char) {
                        $ignoreuntil = "";
                    } else {
                        if ($accesskeys[strtolower($char)] == 1 || strpos("abcdefghijklmnopqrstuvwxyz0123456789", strtolower($char)) === false || $ignoreuntil != "") {
                            if ($char == "<") {
                                $ignoreuntil = ">";
                            }
                            if ($char == "&") {
                                $ignoreuntil = ";";
                            }
                            if ($char == "`") {
                                $ignoreuntil = substr($text, $i + 1, 1);
                            }
                        } else {
                            break;
                        }
                    }
                }
            }
            if ($i < strlen($text)) {
                $key = substr($text, $i, 1);
                $accesskeys[strtolower($key)] = 1;
                $keyrep = " accesskey=\"{$key}\" ";
            } else {
                $key = "";
                $keyrep = "";
            }
            //output("Key is $key for $text`n");
            if ($key == "") {
                //$nav.="<a href=\"".HTMLEntities($link.$extra)."\" class='nav'>".appoencode($text,$priv)."<br></a>";
                //$key==""; // This is useless
            } else {
                $text = substr($text, 0, strpos($text, $key)) . "`H" . $key . "`H" . substr($text, strpos($text, $key) + 1);
                if ($pop) {
                    $quickkeys[$key] = popup($link . $extra);
                } else {
                    $quickkeys[$key] = "window.location='{$link}{$extra}';";
                }
            }
            $nav .= templatereplace("navitem", array("text" => appoencode($text, $priv), "link" => HTMLEntities($link . $extra), "accesskey" => $keyrep, "popup" => $pop == true ? "target='_blank' onClick=\"" . popup($link . $extra) . "; return false;\"" : ""));
            //$nav.="<a href=\"".HTMLEntities($link.$extra)."\" $keyrep class='nav'>".appoencode($text,$priv)."<br></a>";
        }
        $session['allowednavs'][$link . $extra] = true;
        $session['allowednavs'][str_replace(" ", "%20", $link) . $extra] = true;
        $session['allowednavs'][str_replace(" ", "+", $link) . $extra] = true;
    }
}
/**
 * Returns the current character stats or (if the character isn't logged in) the currently online players
 * Hooks provided:
 *		charstats
 *
 * @return array The current stats for this character or the list of online players
 */
function charstats()
{
    global $session, $playermount, $companions;
    wipe_charstats();
    $u =& $session['user'];
    if ($session['loggedin']) {
        $u['hitpoints'] = round($u['hitpoints'], 0);
        $u['experience'] = round($u['experience'], 0);
        $u['maxhitpoints'] = round($u['maxhitpoints'], 0);
        // $spirits=array(-6=>"Resurrected",-2=>"Very Low",-1=>"Low","0"=>"Normal",1=>"High",2=>"Very High");
        // if ($u['alive']){ }else{ $spirits[(int)$u['spirits']] = "DEAD"; }
        //calculate_buff_fields();
        reset($session['bufflist']);
        $atk = $u['attack'];
        $def = $u['defense'];
        $buffcount = 0;
        $buffs = "";
        while (list($key, $val) = each($session['bufflist'])) {
            if (isset($val['suspended']) && $val['suspended']) {
                continue;
            }
            if (isset($val['atkmod'])) {
                $atk *= $val['atkmod'];
            }
            if (isset($val['defmod'])) {
                $def *= $val['defmod'];
            }
            // Short circuit if the name is blank
            if ($val['name'] > "" || $session['user']['superuser'] & SU_DEBUG_OUTPUT) {
                tlschema($val['schema']);
                if ($val['name'] == "") {
                    $val['name'] = "DEBUG: {$key}";
                }
                if (is_array($val['name'])) {
                    $val['name'][0] = str_replace("`%", "`%%", $val['name'][0]);
                    $val['name'] = call_user_func_array("sprintf_translate", $val['name']);
                } else {
                    //in case it's a string
                    $val['name'] = translate_inline($val['name']);
                }
                if ($val['rounds'] >= 0) {
                    // We're about to sprintf, so, let's makes sure that
                    // `% is handled.
                    //$n = translate_inline(str_replace("`%","`%%",$val['name']));
                    $b = translate_inline("`#%s `7(%s rounds left)`n", "buffs");
                    $b = sprintf($b, $val['name'], $val['rounds']);
                    $buffs .= appoencode($b, true);
                } else {
                    $buffs .= appoencode("`#{$val['name']}`n", true);
                }
                tlschema();
                $buffcount++;
            }
        }
        if ($buffcount == 0) {
            $buffs .= appoencode(translate_inline("`^None`0"), true);
        }
        $atk = round($atk, 2);
        $def = round($def, 2);
        if ($atk < $u['attack']) {
            $atk = round($u['attack'], 1) . "`\$" . round($atk - $u['attack'], 1);
        } else {
            if ($atk > $u['attack']) {
                $atk = round($u['attack'], 1) . "`@+" . round($atk - $u['attack'], 1);
            } else {
                // They are equal, display in the 1 signifigant digit format.
                $atk = round($atk, 1);
            }
        }
        if ($def < $u['defense']) {
            $def = round($u['defense'], 1) . "`\$" . round($def - $u['defense'], 1);
        } else {
            if ($def > $u['defense']) {
                $def = round($u['defense'], 1) . "`@+" . round($def - $u['defense'], 1);
            } else {
                // They are equal, display in the 1 signifigant digit format.
                $def = round($def, 1);
            }
        }
        addcharstat("Vital Info");
        //health bar
        if ($u['alive']) {
            $cur = $u['hitpoints'];
            $realmax = $u['maxhitpoints'];
            $cur_adjustment = check_temp_stat("hitpoints", 1);
            $max_adjustment = check_temp_stat("maxhitpoints", 1);
        } else {
            $cur = $u['soulpoints'];
            $realmax = $u['level'] * 5 + 50;
            $cur_adjustment = check_temp_stat("soulpoints", 1);
            $max_adjustment = "";
        }
        if ($pct > 60) {
            $ccode = "`@";
        } elseif ($pct > 25) {
            $ccode = "`^";
        } else {
            $ccode = "`\$";
        }
        $hicode = "`&";
        if (!$u['alive']) {
            $ccode = "`7";
        }
        require_once "lib/bars.php";
        $hpbar = fadebar($cur, $realmax);
        $stat = "{$ccode} {$cur} {$cur_adjustment} `0/ {$realmax} {$max_adjustment}<br />" . $hpbar;
        if ($u['alive']) {
            addcharstat("Hitpoints", $stat);
            addcharstat("Attack", $atk . check_temp_stat("attack", 1));
            addcharstat("Defence", $def . check_temp_stat("defense", 1));
        } else {
            addcharstat("Adrenaline", $stat);
            addcharstat("Attack", 10 + round(($u['level'] - 1) * 1.5));
            addcharstat("Defence", 10 + round(($u['level'] - 1) * 1.5));
        }
        // addcharstat("Turns", $u['turns'].check_temp_stat("turns",1));
        // addcharstat("Attack", $atk.check_temp_stat("attack",1));
        // addcharstat("Defence", $def.check_temp_stat("defense",1));
        if (count($companions) > 0) {
            addcharstat("Companions");
            foreach ($companions as $name => $companion) {
                if ($companion['hitpoints'] > 0 || isset($companion['cannotdie']) && $companion['cannotdie'] == true) {
                    if ($companion['hitpoints'] < 0) {
                        $companion['hitpoints'] = 0;
                    }
                    if ($companion['hitpoints'] < $companion['maxhitpoints']) {
                        $color = "`\$";
                    } else {
                        $color = "`@";
                    }
                    if (isset($companion['suspended']) && $companion['suspended'] == true) {
                        $suspcode = "`7 *";
                    } else {
                        $suspcode = "";
                    }
                    addcharstat($companion['name'], $color . $companion['hitpoints'] . "`7/`&" . $companion['maxhitpoints'] . "{$suspcode}`0");
                }
            }
        }
        addcharstat("Personal Info");
        if ($u['alive']) {
            addcharstat("Requisition", number_format($u['gold'] . check_temp_stat("gold", 1)));
            addcharstat("Cigarettes", number_format($u['gems'] . check_temp_stat("gems", 1)));
        } else {
            addcharstat("Cage Fights", $u['gravefights'] . check_temp_stat("gravefights", 1));
            addcharstat("Favour", number_format($u['deathpower'] . check_temp_stat("deathpower", 1)));
        }
        if ($u['alive']) {
            addcharstat("Level", "`b" . $u['level'] . check_temp_stat("level", 1) . "`b");
            //exp bar
            require_once "lib/experience.php";
            $min = exp_for_next_level($u['level'] - 1, $u['dragonkills']);
            $req = exp_for_next_level($u['level'], $u['dragonkills']);
            $exp = round($session['user']['experience'], 0) . check_temp_stat("experience", 1);
            if ($exp < $min) {
                $min = $exp;
            }
            if ($req - $min > 0) {
                $nonpct = floor(($req - $exp) / ($req - $min) * 100);
            } else {
                $nonpct = 0;
            }
            $pct = 100 - $nonpct;
            if ($pct > 100) {
                $pct = 100;
                $nonpct = 0;
            }
            if ($pct < 0) {
                $pct = 0;
                $nonpct = 100;
            }
            if ($exp >= $req) {
                $color = "blue";
                if ($session['user']['level'] == 1 && $session['user']['dragonkills'] == 0) {
                    $expmsg = "<br />You have enough experience to level up!  Challenge your master in the Dojo!";
                }
            } else {
                $color = "white";
            }
            addcharstat("Experience", number_format($u['experience'] . check_temp_stat("experience", 1)) . "/{$req}<br /><table style='border: solid 1px #000000;' bgcolor='red'  cellpadding='0' cellspacing='0' width='70' height='5'><tr><td width='{$pct}%' bgcolor='{$color}'></td><td width='{$nonpct}%'></td></tr></table>{$expmsg}");
            addcharstat("Equipment Info");
            addcharstat("Weapon", $u['weapon']);
            addcharstat("Armor", $u['armor']);
            if ($u['hashorse']) {
                addcharstat("Creature", $playermount['mountname'] . "`0");
            }
        }
        require_once "lib/datetime.php";
        $gt = gametimedetails();
        addcharstat("Game State");
        addcharstat("Game Time", gmdate("g:i a", $gt['gametime']));
        addcharstat("New day in:", date("H:i:s", secondstonextgameday()));
        modulehook("charstats");
        $charstat = getcharstats($buffs);
        if (!is_array($session['bufflist'])) {
            $session['bufflist'] = array();
        }
        return $charstat;
    } else {
        $ret = "";
        if ($ret = datacache("charlisthomepage")) {
        } else {
            $onlinecount = 0;
            // If a module wants to do it's own display of the online chars,
            // let it.
            $list = modulehook("onlinecharlist", array());
            if (isset($list['handled']) && $list['handled']) {
                $onlinecount = $list['count'];
                $ret = $list['list'];
            } else {
                $sql = "SELECT name,alive,location,sex,level,laston,loggedin,lastip,uniqueid FROM " . db_prefix("accounts") . " WHERE locked=0 AND loggedin=1 AND laston>'" . date("Y-m-d H:i:s", strtotime("-" . getsetting("LOGINTIMEOUT", 900) . " seconds")) . "' ORDER BY level DESC";
                $result = db_query($sql);
                $ret .= appoencode(sprintf(translate_inline("`bOnline Characters (%s players):`b`n"), db_num_rows($result)));
                while ($row = db_fetch_assoc($result)) {
                    $ret .= appoencode("`^{$row['name']}`n");
                    $onlinecount++;
                }
                db_free_result($result);
                if ($onlinecount == 0) {
                    $ret .= appoencode(translate_inline("`iNone`i"));
                }
            }
            savesetting("OnlineCount", $onlinecount);
            savesetting("OnlineCountLast", strtotime("now"));
            updatedatacache("charlisthomepage", $ret);
        }
        return $ret;
    }
}
    }
    rawoutput("<script language='JavaScript'>\r\n\tvar superusers = new Array();");
    while (list($key, $val) = each($superusers)) {
        rawoutput("\tsuperusers['" . addslashes($val) . "'] = true;");
    }
    rawoutput("</script>");
    output("`2Subject:");
    rawoutput("<input name='subject' value=\"" . HTMLEntities($subject) . HTMLEntities(stripslashes(httpget('subject'))) . "\"><br>");
    rawoutput("<div id='warning' style='visibility: hidden; display: none;'>");
    output("`2Notice: `^{$superusermessage}`n");
    rawoutput("</div>");
    output("`2Body:`n");
    rawoutput("<textarea name='body' id='textarea' class='input' cols='60' rows='9' onKeyUp='sizeCount(this);'>" . HTMLEntities($body) . HTMLEntities(stripslashes(httpget('body'))) . "</textarea><br>");
    $send = translate_inline("Send");
    rawoutput("<table border='0' cellpadding='0' cellspacing='0' width='100%'><tr><td><input type='submit' class='button' value='{$send}'></td><td align='right'><div id='sizemsg'></div></td></tr></table>");
    output_notl("</form>", true);
    $sizemsg = "`3Max message size is `@%s`3, you have `^XX`3 characters left.";
    $sizemsg = translate_inline($sizemsg);
    $sizemsg = sprintf($sizemsg, getsetting("mailsizelimit", 1024));
    $sizemsgover = "`\$Max message size is `@%s`\$, you are over by `^XX`\$ characters!";
    $sizemsgover = translate_inline($sizemsgover);
    $sizemsgover = sprintf($sizemsgover, getsetting("mailsizelimit", 1024));
    $sizemsg = explode("XX", $sizemsg);
    $sizemsgover = explode("XX", $sizemsgover);
    $usize1 = addslashes("<span>" . appoencode($sizemsg[0]) . "</span>");
    $usize2 = addslashes("<span>" . appoencode($sizemsg[1]) . "</span>");
    $osize1 = addslashes("<span>" . appoencode($sizemsgover[0]) . "</span>");
    $osize2 = addslashes("<span>" . appoencode($sizemsgover[1]) . "</span>");
    rawoutput("\r\n\t<script language='JavaScript'>\r\n\t\tvar maxlen = " . getsetting("mailsizelimit", 1024) . ";\r\n\t\tfunction sizeCount(box){\r\n\t\t\tvar len = box.value.length;\r\n\t\t\tvar msg = '';\r\n\t\t\tif (len <= maxlen){\r\n\t\t\t\tmsg = '{$usize1}'+(maxlen-len)+'{$usize2}';\r\n\t\t\t}else{\r\n\t\t\t\tmsg = '{$osize1}'+(len-maxlen)+'{$osize2}';\r\n\t\t\t}\r\n\t\t\tdocument.getElementById('sizemsg').innerHTML = msg;\r\n\t\t}\r\n\t\tsizeCount(document.getElementById('textarea'));\r\n\r\n\t\tfunction check_su_warning(){\r\n\t\t\tvar to = document.getElementById('to');\r\n\t\t\tvar warning = document.getElementById('warning');\r\n\t\t\tif (superusers[to.value]){\r\n\t\t\t\twarning.style.visibility = 'visible';\r\n\t\t\t\twarning.style.display = 'inline';\r\n\t\t\t}else{\r\n\t\t\t\twarning.style.visibility = 'hidden';\r\n\t\t\t\twarning.style.display = 'none';\r\n\t\t\t}\r\n\t\t}\r\n\t\tcheck_su_warning();\r\n\r\n\t</script>");
}
popup_footer();
 }
 $sql = "SELECT * FROM " . db_prefix("accounts") . " WHERE login = '******' AND password='******' AND locked=0";
 $result = db_query($sql);
 if (db_num_rows($result) == 1) {
     $session['user'] = db_fetch_assoc($result);
     $companions = @unserialize($session['user']['companions']);
     if (!is_array($companions)) {
         $companions = array();
     }
     $baseaccount = $session['user'];
     checkban($session['user']['login'], true);
     modulehook("check-login");
     if ($session['user']['emailvalidation'] != "" && substr($session['user']['emailvalidation'], 0, 1) != "x") {
         $session['user'] = array();
         $session['message'] = translate_inline("`4Error, you must validate your email address before you can log in.");
         echo appoencode($session['message']);
         exit;
     } else {
         $session['loggedin'] = true;
         $session['laston'] = date("Y-m-d H:i:s");
         $session['sentnotice'] = 0;
         $session['user']['dragonpoints'] = unserialize($session['user']['dragonpoints']);
         $session['user']['prefs'] = unserialize($session['user']['prefs']);
         $session['bufflist'] = unserialize($session['user']['bufflist']);
         if (!is_array($session['bufflist'])) {
             $session['bufflist'] = array();
         }
         if (!is_array($session['user']['dragonpoints'])) {
             $session['user']['dragonpoints'] = array();
         }
         invalidatedatacache("charlisthomepage");
/**
 * Private functions (Undocumented)
 *
 * @param string $text
 * @param string $link
 * @param bool $priv
 * @param bool $pop
 * @param bool $popsize
 * @return mixed
 */
function private_addnav($text, $link = false, $priv = false, $pop = false, $popsize = "500x300")
{
    //don't call this directly please.  I'll break your thumbs if you do.
    global $nav, $session, $accesskeys, $REQUEST_URI, $quickkeys, $navschema, $notranslate;
    if (is_blocked($link)) {
        return false;
    }
    $thisnav = "";
    $unschema = 0;
    $translate = true;
    if (isset($notranslate)) {
        if (in_array(array($text, $link), $notranslate)) {
            $translate = false;
        }
    }
    if (is_array($text)) {
        if ($text[0] && $session['loggedin']) {
            if ($link === false) {
                $schema = "!array!" . serialize($text);
            } else {
                $schema = $text[0];
            }
            if ($translate) {
                tlschema($navschema[$schema]);
                $unschema = 1;
            }
        }
        if ($link != "!!!addraw!!!") {
            if ($translate) {
                $text[0] = translate($text[0]);
            }
            $text = call_user_func_array("sprintf", $text);
        } else {
            $text = call_user_func_array("sprintf", $text);
        }
    } else {
        if ($text && $session['loggedin'] && $translate) {
            tlschema($navschema[$text]);
            $unschema = 1;
        }
        if ($link != "!!!addraw!!!" && $text > "" && $translate) {
            $text = translate($text);
        }
        //leave the hack in here for now, use addnav_notl please
    }
    $extra = "";
    $ignoreuntil = "";
    if ($link === false) {
        //$text = holidayize($text,'nav');
        $thisnav .= tlbutton_pop() . templatereplace("navhead", array("title" => appoencode($text, $priv)));
    } elseif ($link === "") {
        //$text = holidayize($text,'nav');
        $thisnav .= tlbutton_pop() . templatereplace("navhelp", array("text" => appoencode($text, $priv)));
    } elseif ($link == "!!!addraw!!!") {
        $thisnav .= $text;
    } else {
        if ($text != "") {
            $extra = "";
            if (strpos($link, "?")) {
                $extra = "&c={$session['counter']}";
            } else {
                $extra = "?c={$session['counter']}";
            }
            $extra .= "-" . date("His");
            //hotkey for the link.
            $key = "";
            if ($text[1] == "?") {
                // check to see if a key was specified up front.
                $hchar = strtolower($text[0]);
                if ($hchar == ' ' || array_key_exists($hchar, $accesskeys) && $accesskeys[$hchar] == 1) {
                    $text = substr($text, 2);
                    //$text = holidayize($text,'nav');
                    if ($hchar == ' ') {
                        $key = " ";
                    }
                } else {
                    $key = $text[0];
                    $text = substr($text, 2);
                    //$text = holidayize($text,'nav');
                    $found = false;
                    $text_len = strlen($text);
                    for ($i = 0; $i < $text_len; ++$i) {
                        $char = $text[$i];
                        if ($ignoreuntil == $char) {
                            $ignoreuntil = "";
                        } else {
                            if ($ignoreuntil != "") {
                                if ($char == "<") {
                                    $ignoreuntil = ">";
                                }
                                if ($char == "&") {
                                    $ignoreuntil = ";";
                                }
                                if ($char == "`") {
                                    $ignoreuntil = $text[$i + 1];
                                }
                            } else {
                                if ($char == $key) {
                                    $found = true;
                                    break;
                                }
                            }
                        }
                    }
                    if ($found == false) {
                        //the hotkey for this link wasn't actually in the
                        //text, prepend it in parens.
                        if (strpos($text, "__") !== false) {
                            $text = str_replace("__", "(" . $key . ") ", $text);
                        } else {
                            $text = "(" . strtoupper($key) . ") " . $text;
                        }
                        $i = strpos($text, $key);
                    }
                }
            } else {
                //$text = holidayize($text,'nav');
            }
            if ($key == "") {
                //we have no previously defined key.  Look for a new one.
                $tlength = strlen($text);
                for ($i = 0; $i < $tlength; $i++) {
                    $char = substr($text, $i, 1);
                    if ($ignoreuntil == $char) {
                        $ignoreuntil = "";
                    } else {
                        if (isset($accesskeys[strtolower($char)]) && $accesskeys[strtolower($char)] == 1 || strpos("abcdefghijklmnopqrstuvwxyz0123456789", strtolower($char)) === false || $ignoreuntil != "") {
                            if ($char == "<") {
                                $ignoreuntil = ">";
                            }
                            if ($char == "&") {
                                $ignoreuntil = ";";
                            }
                            if ($char == "`") {
                                $ignoreuntil = substr($text, $i + 1, 1);
                            }
                        } else {
                            break;
                        }
                    }
                }
            }
            if (!isset($i)) {
                $i = 0;
            }
            if ($i < strlen($text) && $key != ' ') {
                $key = substr($text, $i, 1);
                $accesskeys[strtolower($key)] = 1;
                $keyrep = " accesskey=\"{$key}\" ";
            } else {
                $key = "";
                $keyrep = "";
            }
            if ($key == "" || $key == " ") {
            } else {
                $pattern1 = "/^" . preg_quote($key, "/") . "/";
                $pattern2 = "/([^`])" . preg_quote($key, "/") . "/";
                $rep1 = "`H{$key}`H";
                $rep2 = "\$1`H{$key}`H";
                $text = preg_replace($pattern1, $rep1, $text, 1);
                if (strpos($text, "`H") === false) {
                    $text = preg_replace($pattern2, $rep2, $text, 1);
                }
                if ($pop) {
                    if ($popsize == "") {
                        $quickkeys[$key] = "window.open('{$link}')";
                    } else {
                        $quickkeys[$key] = popup($link, $popsize);
                    }
                } else {
                    $quickkeys[$key] = "window.location='{$link}{$extra}'";
                }
            }
            $n = templatereplace("navitem", array("text" => appoencode($text, $priv), "link" => HTMLEntities($link . ($pop != true ? $extra : ""), ENT_COMPAT, getsetting("charset", "ISO-8859-1")), "accesskey" => $keyrep, "popup" => $pop == true ? "target='_blank'" . ($popsize > "" ? " onClick=\"" . popup($link, $popsize) . "; return false;\"" : "") : ""));
            $n = str_replace("<a ", tlbutton_pop() . "<a ", $n);
            $thisnav .= $n;
        }
        $session['allowednavs'][$link . $extra] = true;
        $session['allowednavs'][str_replace(" ", "%20", $link) . $extra] = true;
        $session['allowednavs'][str_replace(" ", "+", $link) . $extra] = true;
        if (($pos = strpos($link, "#")) !== false) {
            $sublink = substr($link, 0, $pos);
            $session['allowednavs'][$sublink . $extra] = true;
        }
    }
    if ($unschema) {
        tlschema();
    }
    $nav .= $thisnav;
    return $thisnav;
}
    //erase old entries once per ten seconds
    $lastdigit = substr($now, -1);
    if ($lastdigit == "0") {
        $delsql = "DELETE FROM " . db_prefix("whostyping") . " WHERE time < {$old}";
        db_query($delsql);
    }
    invalidatedatacache("whostyping/whostyping_" . $section);
}
//retrieve, deleting as appropriate
$sql = "SELECT * FROM " . db_prefix("whostyping") . " WHERE section='{$section}'";
$result = db_query_cached($sql, "whostyping/whostyping_" . $section, 60);
$disp = array();
while ($row = db_fetch_assoc($result)) {
    if ($row['time'] > $old) {
        $disp[] = $row['name'];
    }
}
//db_free_result($result);
//display
foreach ($disp as $name) {
    $encodedname = appoencode($name . "`0 takes a breath...`n");
    echo $encodedname;
}
unset($disp);
// $end = getmicrotime(true);
// $total = $end - $start;
//echo("CavemanJoe is debugging in the middle of the night, and this cycle of whostyping.php took this long: ");
//echo($total);
//echo("test!");
//echo($session['iterations']);
exit;
            case 2:
                $type = "`%Gem";
                break;
            case 3:
                $type = "`4HP";
                break;
            case 4:
                $type = "`\$maxHP";
                break;
            case 5:
                $type = "`qFavor";
                break;
            case 6:
                $type = "`@Turns";
                break;
            case 7:
                $type = "`TScript";
        }
        $type = appoencode(translate_inline($type));
        $edit = "<a href='runmodule.php?module=dwitems&op=edit-item&id={$itemid}'>{$tedit}</a>";
        $delete = "<a href='runmodule.php?module=dwitems&op=delete-items&id={$itemid}'>{$tdelete}</a>";
        rawoutput("<tr class='" . ($i % 2 ? "trlight" : "trdark") . "'><td align=center>{$itemid}</td><td>{$name}</td><td>{$type}</td><td align=center>[ {$edit} ]</td><td align=center>[ {$delete} ]</td></tr>");
        addnav("", "runmodule.php?module=dwitems&op=delete-items&id={$itemid}");
        addnav("", "runmodule.php?module=dwitems&op=edit-item&id={$itemid}");
    }
    rawoutput("</table>");
} else {
    output("No Items were found in your database.");
}
addnav("Return to the Grotto", "superuser.php");
addnav("Back to the Editor", "runmodule.php?module=dwitems&op=editor");
/**
 * Returns the current character stats or (if the character isn't logged in) the currently online players
 * Hooks provided:
 *		charstats
 *
 * @return array The current stats for this character or the list of online players
 */
function charstats()
{
    global $session, $playermount, $companions;
    wipe_charstats();
    $u =& $session['user'];
    if ($session['loggedin']) {
        $u['hitpoints'] = round($u['hitpoints'], 0);
        $u['experience'] = round($u['experience'], 0);
        $u['maxhitpoints'] = round($u['maxhitpoints'], 0);
        $spirits = array(-6 => "Resurrected", -2 => "Very Low", -1 => "Low", "0" => "Normal", 1 => "High", 2 => "Very High");
        if ($u['alive']) {
        } else {
            $spirits[(int) $u['spirits']] = "DEAD";
        }
        //calculate_buff_fields();
        reset($session['bufflist']);
        $atk = $u['attack'];
        $def = $u['defense'];
        $buffcount = 0;
        $buffs = "";
        while (list($key, $val) = each($session['bufflist'])) {
            if (isset($val['suspended']) && $val['suspended']) {
                continue;
            }
            if (isset($val['atkmod'])) {
                $atk *= $val['atkmod'];
            }
            if (isset($val['defmod'])) {
                $def *= $val['defmod'];
            }
            // Short circuit if the name is blank
            if ($val['name'] > "" || $session['user']['superuser'] & SU_DEBUG_OUTPUT) {
                tlschema($val['schema']);
                if ($val['name'] == "") {
                    $val['name'] = "DEBUG: {$key}";
                }
                if (is_array($val['name'])) {
                    $val['name'][0] = str_replace("`%", "`%%", $val['name'][0]);
                    $val['name'] = call_user_func_array("sprintf_translate", $val['name']);
                } else {
                    //in case it's a string
                    $val['name'] = translate_inline($val['name']);
                }
                if ($val['rounds'] >= 0) {
                    // We're about to sprintf, so, let's makes sure that
                    // `% is handled.
                    //$n = translate_inline(str_replace("`%","`%%",$val['name']));
                    $b = translate_inline("`#%s `7(%s rounds left)`n", "buffs");
                    $b = sprintf($b, $val['name'], $val['rounds']);
                    $buffs .= appoencode($b, true);
                } else {
                    $buffs .= appoencode("`#{$val['name']}`n", true);
                }
                tlschema();
                $buffcount++;
            }
        }
        if ($buffcount == 0) {
            $buffs .= appoencode(translate_inline("`^None`0"), true);
        }
        $atk = round($atk, 2);
        $def = round($def, 2);
        if ($atk < $u['attack']) {
            $atk = round($u['attack'], 1) . "`\$" . round($atk - $u['attack'], 1);
        } else {
            if ($atk > $u['attack']) {
                $atk = round($u['attack'], 1) . "`@+" . round($atk - $u['attack'], 1);
            } else {
                // They are equal, display in the 1 signifigant digit format.
                $atk = round($atk, 1);
            }
        }
        if ($def < $u['defense']) {
            $def = round($u['defense'], 1) . "`\$" . round($def - $u['defense'], 1);
        } else {
            if ($def > $u['defense']) {
                $def = round($u['defense'], 1) . "`@+" . round($def - $u['defense'], 1);
            } else {
                // They are equal, display in the 1 signifigant digit format.
                $def = round($def, 1);
            }
        }
        addcharstat("Vital Info");
        addcharstat("Name", $u['name']);
        addcharstat("Level", "`b" . $u['level'] . check_temp_stat("level", 1) . "`b");
        if ($u['alive']) {
            addcharstat("Hitpoints", $u['hitpoints'] . check_temp_stat("hitpoints", 1) . "`0/" . $u['maxhitpoints'] . check_temp_stat("maxhitpoints", 1));
            addcharstat("Turns", $u['turns'] . check_temp_stat("turns", 1));
            addcharstat("Attack", $atk . check_temp_stat("attack", 1));
            addcharstat("Defense", $def . check_temp_stat("defense", 1));
        } else {
            $maxsoul = $u['level'] * 5 + 50;
            addcharstat("Soulpoints", $u['soulpoints'] . check_temp_stat("soulpoints", 1) . "`0/" . $maxsoul);
            addcharstat("Torments", $u['gravefights'] . check_temp_stat("gravefights", 1));
            addcharstat("Psyche", 10 + round(($u['level'] - 1) * 1.5));
            addcharstat("Spirit", 10 + round(($u['level'] - 1) * 1.5));
        }
        addcharstat("Spirits", translate_inline("`b" . $spirits[(int) $u['spirits']] . "`b"));
        if ($u['race'] != RACE_UNKNOWN) {
            addcharstat("Race", translate_inline($u['race'], "race"));
        } else {
            addcharstat("Race", translate_inline(RACE_UNKNOWN, "race"));
        }
        if (count($companions) > 0) {
            addcharstat("Companions");
            foreach ($companions as $name => $companion) {
                if ($companion['hitpoints'] > 0 || isset($companion['cannotdie']) && $companion['cannotdie'] == true) {
                    if ($companion['hitpoints'] < 0) {
                        $companion['hitpoints'] = 0;
                    }
                    if ($companion['hitpoints'] < $companion['maxhitpoints']) {
                        $color = "`\$";
                    } else {
                        $color = "`@";
                    }
                    if (isset($companion['suspended']) && $companion['suspended'] == true) {
                        $suspcode = "`7 *";
                    } else {
                        $suspcode = "";
                    }
                    addcharstat($companion['name'], $color . $companion['hitpoints'] . "`7/`&" . $companion['maxhitpoints'] . "{$suspcode}`0");
                }
            }
        }
        addcharstat("Personal Info");
        if ($u['alive']) {
            addcharstat("Gold", $u['gold'] . check_temp_stat("gold", 1));
        } else {
            addcharstat("Favor", $u['deathpower'] . check_temp_stat("deathpower", 1));
        }
        addcharstat("Gems", $u['gems'] . check_temp_stat("gems", 1));
        addcharstat("Experience", $u['experience'] . check_temp_stat("experience", 1));
        addcharstat("Equipment Info");
        addcharstat("Weapon", $u['weapon']);
        addcharstat("Armor", $u['armor']);
        if ($u['hashorse']) {
            addcharstat("Creature", $playermount['mountname'] . "`0");
        }
        modulehook("charstats");
        $charstat = getcharstats($buffs);
        if (!is_array($session['bufflist'])) {
            $session['bufflist'] = array();
        }
        return $charstat;
    } else {
        $ret = "";
        if ($ret = datacache("charlisthomepage")) {
        } else {
            $onlinecount = 0;
            // If a module wants to do it's own display of the online chars,
            // let it.
            $list = modulehook("onlinecharlist", array());
            if (isset($list['handled']) && $list['handled']) {
                $onlinecount = $list['count'];
                $ret = $list['list'];
            } else {
                $sql = "SELECT name,alive,location,sex,level,laston,loggedin,lastip,uniqueid FROM " . db_prefix("accounts") . " WHERE locked=0 AND loggedin=1 AND laston>'" . date("Y-m-d H:i:s", strtotime("-" . getsetting("LOGINTIMEOUT", 900) . " seconds")) . "' ORDER BY level DESC";
                $result = db_query($sql);
                $ret .= appoencode(sprintf(translate_inline("`bOnline Characters (%s players):`b`n"), db_num_rows($result)));
                while ($row = db_fetch_assoc($result)) {
                    $ret .= appoencode("`^{$row['name']}`n");
                    $onlinecount++;
                }
                db_free_result($result);
                if ($onlinecount == 0) {
                    $ret .= appoencode(translate_inline("`iNone`i"));
                }
            }
            savesetting("OnlineCount", $onlinecount);
            savesetting("OnlineCountLast", strtotime("now"));
            updatedatacache("charlisthomepage", $ret);
        }
        return $ret;
    }
}
function previewfield($name, $startdiv = false, $talkline = "says", $showcharsleft = true, $info = false, $default = false)
{
    global $schema, $session;
    $talkline = translate_inline($talkline, $schema);
    $youhave = translate_inline("You have ");
    $charsleft = translate_inline(" characters left.");
    if ($startdiv === false) {
        $startdiv = "";
    }
    rawoutput("<script language='JavaScript'>\n\t\t\t\tfunction previewtext{$name}(t,l){\n\t\t\t\t\tvar out = \"<span class=\\'colLtWhite\\'>" . addslashes(appoencode($startdiv)) . " \";\n\t\t\t\t\tvar end = '</span>';\n\t\t\t\t\tvar x=0;\n\t\t\t\t\tvar y='';\n\t\t\t\t\tvar z='';\n\t\t\t\t\tvar max=document.getElementById('input{$name}');\n\t\t\t\t\tvar charsleft='';");
    if ($talkline !== false) {
        rawoutput("\tif (t.substr(0,2)=='::'){\n\t\t\t\t\t\tx=2;\n\t\t\t\t\t\tout += '</span><span class=\\'colLtWhite\\'>';\n\t\t\t\t\t}else if (t.substr(0,1)==':'){\n\t\t\t\t\t\tx=1;\n\t\t\t\t\t\tout += '</span><span class=\\'colLtWhite\\'>';\n\t\t\t\t\t}else if (t.substr(0,3)=='/me'){\n\t\t\t\t\t\tx=3;\n\t\t\t\t\t\tout += '</span><span class=\\'colLtWhite\\'>';");
        if ($session['user']['superuser'] & SU_IS_GAMEMASTER) {
            rawoutput("\n\t\t\t\t\t}else if (t.substr(0,5)=='/game'){\n\t\t\t\t\t\tx=5;\n\t\t\t\t\t\tout = '<span class=\\'colLtWhite\\'>';");
        }
        rawoutput("\t}else{\n\t\t\t\t\t\tout += '</span><span class=\\'colDkCyan\\'>" . addslashes(appoencode($talkline)) . ", \"</span><span class=\\'colLtCyan\\'>';\n\t\t\t\t\t\tend += '</span><span class=\\'colDkCyan\\'>\"';\n\t\t\t\t\t}");
    }
    if ($showcharsleft == true) {
        /*		if (translate_inline($talkline,$schema)!="says")
        		$tll = strlen(translate_inline($talkline,$schema))+11;
        		else $tll=0;  // Don't know why needed
        		rawoutput("	if (x!=0) {
        						if (max.maxlength!=200-$tll) max.maxlength=200-$tll;
        						l=200-$tll; */
        // Don't know why needed
        rawoutput("\tif (x!=0) {\n\t\t\t\t\t\tif (max.maxLength!=200) max.maxLength=200;\n\t\t\t\t\t\tl=200;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmax.maxLength=l;\n\t\t\t\t\t}\n\t\t\t\t\tif (l-t.length<0) charsleft +='<span class=\\'colLtRed\\'>';\n\t\t\t\t\tcharsleft += '" . $youhave . "'+(l-t.length)+'" . $charsleft . "<br>';\n\t\t\t\t\tif (l-t.length<0) charsleft +='</span>';\n\t\t\t\t\tdocument.getElementById('charsleft{$name}').innerHTML=charsleft+'<br/>';");
    }
    rawoutput("\t\tfor (; x < t.length; x++){\n\t\t\t\t\t\ty = t.substr(x,1);\n\t\t\t\t\t\tif (y=='<'){\n\t\t\t\t\t\t\tout += '&lt;';\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}else if(y=='>'){\n\t\t\t\t\t\t\tout += '&gt;';\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}else if(y=='\\n'){\n\t\t\t\t\t\t\tout += '<br />';\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}else if (y=='`'){\n\t\t\t\t\t\t\tif (x < t.length-1){\n\t\t\t\t\t\t\t\tz = t.substr(x+1,1);\n\t\t\t\t\t\t\t\tif (z=='0'){\n\t\t\t\t\t\t\t\t\tout += '</span>';\n\t\t\t\t\t\t\t\t}else if (z=='1'){\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colDkBlue\\'>';\n\t\t\t\t\t\t\t\t}else if (z=='2'){\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colDkGreen\\'>';\n\t\t\t\t\t\t\t\t}else if (z=='3'){\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colDkCyan\\'>';\n\t\t\t\t\t\t\t\t}else if (z=='4'){\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colDkRed\\'>';\n\t\t\t\t\t\t\t\t}else if (z=='5'){\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colDkMagenta\\'>';\n\t\t\t\t\t\t\t\t}else if (z=='6'){\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colDkYellow\\'>';\n\t\t\t\t\t\t\t\t}else if (z=='7'){\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colDkWhite\\'>';\n\t\t\t\t\t\t\t\t}else if (z=='q'){\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colDkOrange\\'>';\n\t\t\t\t\t\t\t\t}else if (z=='!'){\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colLtBlue\\'>';\n\t\t\t\t\t\t\t\t}else if (z=='@'){\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colLtGreen\\'>';\n\t\t\t\t\t\t\t\t}else if (z=='#'){\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colLtCyan\\'>';\n\t\t\t\t\t\t\t\t}else if (z=='\$'){\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colLtRed\\'>';\n\t\t\t\t\t\t\t\t}else if (z=='%'){\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colLtMagenta\\'>';\n\t\t\t\t\t\t\t\t}else if (z=='^'){\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colLtYellow\\'>';\n\t\t\t\t\t\t\t\t}else if (z=='&'){\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colLtWhite\\'>';\n\t\t\t\t\t\t\t\t}else if (z=='Q'){\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colLtOrange\\'>';\n\t\t\t\t\t\t\t\t}else if (z==')'){\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colLtBlack\\'>';\n\t\t\t\t\t\t\t\t}else if (z=='r'){\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colRose\\'>';\n\t\t\t\t\t\t\t\t}else if (z=='R'){\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colRose\\'>';\n\t\t\t\t\t\t\t\t}else if (z=='v'){\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'coliceviolet\\'>';\n\t\t\t\t\t\t\t\t}else if (z=='V'){\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colBlueViolet\\'>';\n\t\t\t\t\t\t\t\t}else if (z=='g'){\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colXLtGreen\\'>';\n\t\t\t\t\t\t\t\t}else if (z=='G'){\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colXLtGreen\\'>';\n\t\t\t\t\t\t\t\t}else if (z=='T'){\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colDkBrown\\'>';\n\t\t\t\t\t\t\t\t}else if (z=='t'){\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colLtBrown\\'>';\n\t\t\t\t\t\t\t\t}else if (z=='~'){\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colBlack\\'>';\n\t\t\t\t\t\t\t\t}else if (z=='j'){\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colMdGrey\\'>';\n\t\t\t\t\t\t\t\t}else if (z=='J'){\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colMdBlue\\'>';\n\t\t\t\t\t\t\t\t}else if (z=='e'){\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colDkRust\\'>';\n\t\t\t\t\t\t\t\t}else if (z=='E'){\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colLtRust\\'>';\n\t\t\t\t\t\t\t\t}else if (z=='l'){\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colDkLinkBlue\\'>';\n\t\t\t\t\t\t\t\t}else if (z=='L'){\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colLtLinkBlue\\'>';\n\t\t\t\t\t\t\t\t}else if (z=='x'){\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colburlywood\\'>';\n\t\t\t\t\t\t\t\t}else if (z=='X'){\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colbeige\\'>';\n\t\t\t\t\t\t\t\t}else if (z=='y'){\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colkhaki\\'>';\n\t\t\t\t\t\t\t\t}else if (z=='Y'){\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'coldarkkhaki\\'>';\n\t\t\t\t\t\t\t\t}else if (z=='k'){\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colaquamarine\\'>';\n\t\t\t\t\t\t\t\t}else if (z=='K'){\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'coldarkseagreen\\'>';\n\t\t\t\t\t\t\t\t}else if (z=='p'){\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'collightsalmon\\'>';\n\t\t\t\t\t\t\t\t}else if (z=='P'){\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colsalmon\\'>';\n\t\t\t\t\t\t\t\t}else if (z=='m'){\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colwheat\\'>';\n\t\t\t\t\t\t\t\t}else if (z=='M'){\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'coltan\\'>';\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tx++;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\tout += y;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tdocument.getElementById(\"previewtext{$name}\").innerHTML=out+end+'<br/>';\n\t\t\t\t}\n\t\t\t\t</script>\n\t\t\t\t");
    if ($charsleft == true) {
        rawoutput("<span id='charsleft{$name}'></span>");
    }
    if (!is_array($info)) {
        if ($default) {
            rawoutput("<input name='{$name}' id='input{$name}' maxlength='255' onKeyUp='previewtext{$name}(document.getElementById(\"input{$name}\").value,200);' value='{$default}'>");
        } else {
            rawoutput("<input name='{$name}' id='input{$name}' maxlength='255' onKeyUp='previewtext{$name}(document.getElementById(\"input{$name}\").value,200);'>");
        }
    } else {
        if (isset($info['maxlength'])) {
            $l = $info['maxlength'];
        } else {
            $l = 200;
        }
        if (isset($info['type']) && $info['type'] == 'textarea') {
            rawoutput("<textarea name='{$name}' id='input{$name}' onKeyUp='previewtext{$name}(document.getElementById(\"input{$name}\").value,{$l});' ");
        } else {
            rawoutput("<input name='{$name}' id='input{$name}' onKeyUp='previewtext{$name}(document.getElementById(\"input{$name}\").value,{$l});' ");
        }
        foreach ($info as $key => $val) {
            rawoutput("{$key}='{$val}'");
        }
        if (isset($info['type']) && $info['type'] == 'textarea') {
            rawoutput(">");
            if ($default) {
                rawoutput($default);
            }
            rawoutput("</textarea>");
        } else {
            if ($default) {
                rawoutput(" value='{$default}'>");
            } else {
                rawoutput(">");
            }
        }
    }
    rawoutput("<div id='previewtext{$name}'></div>");
}
function donationextend_dohook($hookname, $args)
{
    global $session;
    switch ($hookname) {
        case "donation":
            require_once "lib/gamelog.php";
            gamelog("Donation registered by donationextend");
            $amt = $args['amt'];
            $id = $args['id'];
            $kitty = get_module_setting("kitty");
            $newkitty = $kitty + $amt;
            set_module_setting("kitty", $newkitty);
            //set last player
            if (!get_module_pref("user_shy", "donationextend", $id)) {
                $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE acctid='{$id}'";
                $result = db_query_cached($sql, "donationextend_lastdonator", 300);
                $row = db_fetch_assoc($result);
                $name = $row['name'] . "`0";
                set_module_setting("lastdonator", $name);
            } else {
                set_module_setting("lastdonator", "Anonymous");
            }
            break;
        case "everyfooter":
            //debug($args,true);
            // Set up and decrement the kitty
            require_once "lib/bars.php";
            $last = get_module_setting("lasttick");
            $ext1 = get_module_setting("extend1cost");
            $player = get_module_setting("lastdonator");
            $player = appoencode(stripslashes($player));
            $elapsed = time() - $last;
            $dropped = 0;
            $droppertenseconds = get_module_setting("extend1cost") / 8640;
            if ($elapsed > 10) {
                $dropped = $droppertenseconds;
            }
            $oldkitty = get_module_setting("kitty");
            $newkitty = $oldkitty - $dropped;
            if ($newkitty < 0) {
                $newkitty = 0;
            }
            //set up display output
            $out = "";
            $sql = "SELECT count(acctid) AS c FROM " . db_prefix("accounts") . " WHERE locked=0";
            $result = db_query_cached($sql, "donationextend_totalplayers", 1800);
            $row = db_fetch_assoc($result);
            $totalplayers = $row['c'];
            if ($newkitty > $ext1) {
                $ext2 = get_module_setting("extend2cost");
                if ($newkitty > $ext2) {
                    $over = $newkitty - $ext2;
                    $bar = simplebar($over, $ext2, 70, 5, "AA00AA", "FFFFFF");
                    $overdisp = number_format($over / 100, 2);
                    //represent as time left to end of Special Extend period
                    $droppersec = get_module_setting("extend1cost") / 86400;
                    $secsleft = round($over / $droppersec);
                    $expirationtime = time() + $secsleft;
                    require_once "lib/datetime.php";
                    $expirein = reltime($expirationtime, false);
                    $out .= "<span style='font-size:smaller'><strong>Special Extend active!</strong><br />" . $bar . "Thank you for your support!  Special Extend expires in " . $expirein . "<br /><a href='runmodule.php?module=donationextend' target='_blank' onclick=\"" . popup("runmodule.php?module=donationextend") . ";return false;\">(what's a Special Extend?)</span></a>";
                } else {
                    $moreneeded = $ext2 - $newkitty;
                    $bar = simplebar($newkitty - $ext1, $ext2 - $ext1, 70, 5, "00FF00", "AA00AA");
                    $moredisp = number_format($moreneeded / 100, 2);
                    $out .= "<span style='font-size:smaller'><strong>Extended Play active!</strong><br />" . $bar . "\$" . $moredisp . " more for <a href='runmodule.php?module=donationextend' target='_blank' onclick=\"" . popup("runmodule.php?module=donationextend") . ";return false;\">Special Extend</a>!</span>";
                }
            } else {
                $moreneeded = $ext1 - $newkitty;
                $moredisp = number_format($moreneeded / 100, 2);
                $bar = fadebar($newkitty, $ext1, 57);
                $perplayer = $moreneeded / 100 / $totalplayers;
                if ($perplayer > 1) {
                    $perplayerdisp = "about " . round($moreneeded / $totalplayers, 4) . " cents per player";
                } else {
                    $perplayerdisp = "about \$" . number_format($moreneeded / 100 / $totalplayers, 2) . " per player";
                }
                $out .= $bar;
                if ($newkitty > 0) {
                    $out .= "<span style='font-size:smaller'>\$" . $moredisp . " more (" . $perplayerdisp . ") for <a href='runmodule.php?module=donationextend' target='_blank' onclick=\"" . popup("runmodule.php?module=donationextend") . ";return false;\">Extended Play</a>!</span>";
                } else {
                    if ($session['user']['loggedin']) {
                        $out .= "<span class='colDkRed'><strong>The kitty is empty!</strong></span>  Improbable Island is entirely dependant on your donations to survive.  When the meter is empty, the Island and its creators are in trouble!  Someone please chuck a couple of bucks in the hat!";
                    }
                }
            }
            global $template;
            //debug($template);
            if (strpos($template['footer'], "{paypal_extras}")) {
                //if (isset($template['{paypal_extras}'])){
                //debug("Yes!");
                $rep = "paypal_extras";
            } else {
                //debug("No!");
                $rep = "paypal";
            }
            //$rep = "paypal_extras";
            //insert display output into page
            if (!array_key_exists($rep, $args) || !is_array($args[$rep])) {
                $args[$rep] = array();
            }
            array_push($args[$rep], $out);
            //write values back to database
            if ($elapsed > 10) {
                set_module_setting("lasttick", time());
                set_module_setting("kitty", $newkitty);
            }
            //debug($args,true);
            addcharstat("Misc");
            addcharstat("Misc", "testing testing woohoo!");
            break;
        case "stamina-newday":
            $kitty = get_module_setting("kitty");
            if ($kitty >= get_module_setting("extend1cost")) {
                require_once "modules/staminasystem/lib/lib.php";
                $bonus = get_module_setting("extend1amt");
                if ($kitty > get_module_setting("extend2cost")) {
                    $bonus += get_module_setting("extend2amt");
                    output("`0Because Improbable Island's players have been especially generous, today is a `b`5Special Extended Play`0`b day - you `2gain`0 some Stamina!`n`n");
                } else {
                    output("`0Because Improbable Island's server costs and advertising budget have been covered quite nicely by donations, today is an `b`2Extended Play`0`b day - you `2gain`0 some Stamina!`n`n");
                }
                if ($session['user']['donation'] > 0) {
                    $bonus = $bonus * 2;
                }
                addstamina($bonus);
            }
            break;
    }
    return $args;
}
function jquerycommentary_run()
{
    global $_SERVER, $output, $session;
    require_once 'lib/commentary.php';
    $section = httpget('section');
    $commentary = db_prefix('commentary');
    $accounts = db_prefix('accounts');
    if (($commid = httpget('rmvcmmnt')) != "") {
        $prefix = db_prefix('commentary');
        check_su_access(SU_EDIT_COMMENTS);
        if ($session['user']['superuser'] & SU_EDIT_COMMENTS) {
            db_query("DELETE FROM {$prefix} WHERE commentid = '{$commid}'");
        }
        db_query("INSERT INTO {$commentary} (section, author, comment, postdate) VALUES ('blackhole', '{$session['user']['acctid']}', 'I f****d up', '" . date('Y-m-d H:i:s') . "')");
        invalidatedatacache("comments-{$section}");
        invalidatedatacache("comments-blackhole");
    }
    if (httpget('section') == get_module_pref('current_section') && httpget('section') != '') {
        //echo 'x';
        //var_dump(get_all_module_settings());
        $output = "";
        $_SERVER['REQUEST_URI'] = httpget('r');
        $session['counter'] = httpget('c');
        viewcommentary(get_module_pref('current_section'), get_module_setting('message'), get_module_setting('limit'), get_module_setting('talkline'));
        $output = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $output);
        $output = substr($output, 0, strpos($output, "<jquerycommentaryend>"));
        db_query("UPDATE accounts SET laston = '" . date('Y-m-d H:i:s') . "' WHERE acctid = '{$session['user']['acctid']}'");
        echo trim("{$output}");
        invalidatedatacache("comments-{$section}");
        /*$sql = db_query(
              "SELECT a.name, a.acctid
              FROM accounts AS a
              LEFT JOIN module_userprefs AS m
              ON m.userid = a.acctid
              LEFT JOIN module_userprefs AS u
              ON u.userid = m.userid
              WHERE m.modulename = 'jquerycommentary'
              AND m.setting = 'is_typing'
              AND m.value = '1'
              AND u.modulename = 'jquerycommentary'
              AND u.setting = 'current_section'
              and u.value = '" . get_module_pref('current_section') ."'"
          );
          $typing = [];
          while ($row = db_fetch_assoc($sql)) {
              array_push($typing, [$row['acctid'], $row['name']]);
          }
          $isTyping = appoencode('`@');
          $i = 0;
          echo appoencode('`@Who\'s typing: `n');
          if (count($typing) != 0) {
              foreach ($typing as $key => $val) {
                  $i++;
                  if ($i == 1) {
                      $isTyping .= appoencode($val[1]);
                  }
                  else if ($i > 1 && count($typing) > $i) {
                      $isTyping .= appoencode("`@, {$val[1]}");
                  }
                  else if ($i == count($typing)) {
                      $isTyping .= appoencode("`@ and {$val[1]}");
                  }
              }
              echo $isTyping;
          }
          else {
              echo appoencode('`@No one');
          }*/
    }
    switch (httpget('op')) {
        case 'get_json':
            $sql = db_query("SELECT commentid, author, comment FROM commentary WHERE section = '{$session['current_commentary_area']}' AND deleted = '0' ORDER BY commentid+0 DESC LIMIT 0, 25");
            $json = [];
            while ($row = db_fetch_assoc($sql)) {
                array_push($json, $row);
            }
            echo "<pre>";
            echo json_encode($json, JSON_PRETTY_PRINT);
            echo "</pre>";
            break;
        case 'post':
            $post = httpallpost();
            $post = modulehook('jquery-post-commentary', $post);
            $commentary = db_prefix('commentary');
            if ($post['method'] == 'insertcommentary') {
                require_once 'lib/commentary.php';
                injectcommentary(get_module_pref('current_section'), get_module_setting('talkline'), $post['comment']);
            } else {
                $commentid = explode('_', $post['method']);
                require_once 'lib/systemmail.php';
                require_once 'lib/sanitize.php';
                $post['comment'] = htmlent($post['comment']);
                db_query("UPDATE {$commentary} SET comment = '{$post['comment']}' WHERE commentid = '{$commentid[1]}'");
                db_query("INSERT INTO {$commentary} (section, author, comment, postdate) VALUES ('blackhole', '{$session['user']['acctid']}', 'I f****d up', '" . date('Y-m-d H:i:s') . "')");
                invalidatedatacache("comments-{$session['current_commentary_section']}");
                invalidatedatacache("comments-blackhole");
            }
            break;
        case 'last_comment':
            require_once 'lib/sanitize.php';
            db_query("UPDATE accounts SET laston = '" . date('Y-m-d H:i:s') . "' WHERE acctid = '{$session['user']['acctid']}'");
            //$sql = db_query("SELECT comment, commentid FROM ".db_prefix('commentary')." WHERE author = '{$session['user']['acctid']}' AND section = '{$session['current_commentary_area']}' ORDER BY commentid DESC LIMIT 0,1");
            $sql = db_query("SELECT comment, commentid FROM {$commentary}\n                WHERE author = '{$session['user']['acctid']}'\n                AND (section = 'globalooc'\n                    OR section = '{$session['current_commentary_area']}')\n                ORDER BY commentid DESC\n                LIMIT 0,1");
            $row = db_fetch_assoc($sql);
            $data = $row;
            $sql = db_query("SELECT commentid, section, comment FROM {$commentary}\n                WHERE (section = 'globalooc'\n                OR section = '{$session['current_commentary_area']}'\n                OR section = 'blackhole'\n                )\n                ORDER BY commentid+0 DESC\n                LIMIT 0,1");
            $row = db_fetch_assoc($sql);
            $data['last_section'] = $row['section'];
            $data['last_comment'] = $row['commentid'];
            $data['last_message'] = $row['comment'];
            echo json_encode($data);
            break;
        case 'is_typing':
            $post = httpallpost();
            if ($post['typing'] == 'yes') {
                set_module_pref('is_typing', 1);
            } else {
                set_module_pref('is_typing', 0);
            }
            $sql = db_query("SELECT a.name, a.acctid\n                FROM accounts AS a\n                LEFT JOIN module_userprefs AS m\n                ON m.userid = a.acctid\n                LEFT JOIN module_userprefs AS u\n                ON u.userid = m.userid\n                WHERE m.modulename = 'jquerycommentary'\n                AND m.setting = 'is_typing'\n                AND m.value = '1'\n                AND u.modulename = 'jquerycommentary'\n                AND u.setting = 'current_section'\n                and u.value = '" . get_module_pref('current_section') . "'");
            $typing = [];
            while ($row = db_fetch_assoc($sql)) {
                array_push($typing, [$row['acctid'], $row['name']]);
            }
            $isTyping = appoencode('`@');
            $i = 0;
            if (count($typing) != 0) {
                foreach ($typing as $key => $val) {
                    $i++;
                    if ($i == 1) {
                        $isTyping .= appoencode($val[1]);
                    } else {
                        if ($i > 1 && count($typing) > $i) {
                            $isTyping .= appoencode("`@, {$val[1]}");
                        } else {
                            if ($i == count($typing)) {
                                $isTyping .= appoencode("`@ and {$val[1]}");
                            }
                        }
                    }
                    if ($i == count($typing)) {
                        $isTyping .= appoencode("`@...");
                    }
                }
                echo "✏ {$isTyping}";
            } else {
                echo "<br />";
            }
            break;
        case 'api':
            header('Content-Type: application/json');
            /*$sql = db_query(
                  "SELECT c.*, a.name FROM $commentary AS c
                  LEFT JOIN $accounts AS a
                  ON a.acctid = c.author
                  WHERE (section = '{$session['current_commentary_area']}'
                  OR section = 'global-ooc')
                  AND deleted = 0
                  ORDER BY commentid+0 DESC
                  GROUP BY section
                  LIMIT 0, 25"
              );*/
            $sql = db_query("SELECT comm.*, acc.name FROM\n                (\n                    (SELECT * FROM\n                        (SELECT * FROM commentary\n                        WHERE section = 'globalooc'\n                        AND deleted = '0'\n                        ORDER BY commentid+0 DESC\n                        LIMIT 0, 10)\n                    AS c\n                    ORDER BY c.commentid+0 ASC\n                    LIMIT 0, 10)\n                    UNION (\n                        SELECT * FROM\n                        (SELECT * FROM commentary\n                        WHERE section = 'superuser'\n                        AND deleted = '0'\n                        ORDER BY commentid+0 DESC\n                        LIMIT 0, 25)\n                        AS c\n                        ORDER BY c.commentid+0 ASC\n                        LIMIT 0, 25\n                    )\n                ) AS comm\n                LEFT JOIN accounts AS acc\n                ON acc.acctid = comm.author");
            $json = [];
            while ($row = db_fetch_assoc($sql)) {
                $row['name'] = appoencode($row['name']);
                $row['comment'] = appoencode($row['comment']);
                array_push($json, $row);
            }
            echo json_encode($json, JSON_PRETTY_PRINT);
            break;
    }
}
function iitems_hunterslodge_run()
{
    global $session;
    page_header("Hunter's Lodge");
    $op = httpget('op');
    $pointsleft = $session['user']['donation'] - $session['user']['donationspent'];
    $pointstotal = $session['user']['donation'];
    $pointsspent = $session['user']['donationspent'];
    switch ($op) {
        case "superuser":
            $sql = "SELECT * FROM " . db_prefix("purchaselog");
            $result = db_query($sql);
            $peritem = array();
            $now = time();
            while ($row = db_fetch_assoc($result)) {
                $item = $row['purchased'];
                $peritem[$item]['sold'] += 1;
                $peritem[$item]['income'] += $row['amount'];
                $time = strtotime($row['timestamp']);
                if (isset($peritem[$item]['firstpurchase']) && $peritem[$item]['firstpurchase'] > $time) {
                    $peritem[$item]['firstpurchase'] = $time;
                } else {
                    if (!isset($peritem[$item]['firstpurchase'])) {
                        $peritem[$item]['firstpurchase'] = $time;
                    }
                }
            }
            foreach ($peritem as $item => $data) {
                $timesincefirst = $now - $data['firstpurchase'];
                $incomeperday = round($data['income'] / ($timesincefirst / 86400) / 100, 2);
                $peritem[$item]['incomeperday'] = $incomeperday;
                $peritem[$item]['item'] = $item;
            }
            function sortbysold($a, $b)
            {
                if ($b['sold'] > $a['sold']) {
                    return true;
                } else {
                    return false;
                }
            }
            function sortbyincome($a, $b)
            {
                if ($b['income'] > $a['income']) {
                    return true;
                } else {
                    return false;
                }
            }
            function sortbydailyincome($a, $b)
            {
                if ($b['incomeperday'] > $a['incomeperday']) {
                    return true;
                } else {
                    return false;
                }
            }
            rawoutput("<table width=100% border=0 cellpadding=0 cellspacing=0><tr class='trhead'><td>Item</td><td>Item Verbose Name</td><td><a href='runmodule.php?module=iitems_hunterslodge&op=superuser&sort=sortbysold'>Units sold</a></td><td><a href='runmodule.php?module=iitems_hunterslodge&op=superuser&sort=sortbyincome'>Profit total</a></td><td><a href='runmodule.php?module=iitems_hunterslodge&op=superuser&sort=sortbydailyincome'>Profit per day</a></td></tr>");
            $classcount = 1;
            addnav("", "runmodule.php?module=iitems_hunterslodge&op=superuser&sort=sortbysold");
            addnav("", "runmodule.php?module=iitems_hunterslodge&op=superuser&sort=sortbyincome");
            addnav("", "runmodule.php?module=iitems_hunterslodge&op=superuser&sort=sortbydailyincome");
            if (httpget('sort')) {
                usort($peritem, httpget('sort'));
            }
            foreach ($peritem as $item => $data) {
                $classcount++;
                $class = $classcount % 2 ? "trdark" : "trlight";
                $vname = get_item_setting("verbosename", $data['item']);
                if (!$vname) {
                    $vname = $data['item'];
                }
                rawoutput("<tr class='{$class}'><td>" . $data['item'] . "</td><td>" . $vname . "</td><td>" . number_format($data['sold']) . "</td><td>\$" . number_format($data['income'] / 100, 2) . "</td><td>\$" . number_format($data['incomeperday'], 2) . "</td></tr>");
            }
            rawoutput("</table>");
            addnav("Return");
            addnav("Back to the Grotto", "superuser.php");
            break;
        case "explain":
            output("You give a friendly nod to the proprietor, and open your mouth to ask him a question.`n`nHe grins back at you.`n`nThere's a small `ipop`iping sensation in the centre of your skull, like a muscle abruptly shifting - and you suddenly realise what this place is all about.`n`n`bAbout Supporter Points`b`nImprobable Island is entirely funded by donations from its players.  When you donate, you get Supporter Points, which you can use on items in the Hunter's Lodge.  You get one hundred Supporter Points per US Dollar, and donations are accepted through PayPal.  To donate, click the coin slot to the lower right of your screen.  Always use the \"Site Admin\" PayPal button when donating if you wish to receive Supporter Points (donations made through the \"Author\" button go to Eric Stevens, the author of the game engine on which Improbable Island was originally based - you don't get any Supporter Points for donating through this button).  You can also get Supporter Points by referring new players to the site (click the Referrals link to the left) or sometimes in `4Other Ways`0 which will be announced from time to time.`n`n`bTo give presents`b`nAll Hunter's Lodge items (and most other in-game items) can be given as gifts to other players.  Visit the Gifting Station in Common Ground to do so.  Some items can be gifted for free - others cost one Supporter Point each to gift.  Hunter's Lodge items that bestow permanent benefits (IE unlimited title change documents) can only be gifted if they're unused.  In all cases, you'll get to choose your gift-wrap and whether to give anonymously or not.`n`n`bHey, it's my birthday soon.  Can I ask my non-Island-playing mates to buy me points on the Island?`b`nYes!  Just send them to this link:`nhttp://www.improbableisland.com/runmodule.php?module=giftpoints&acctid=%s`n`n", $session['user']['acctid']);
            addnav("Okay");
            addnav("Back to the Hunter's Lodge", "runmodule.php?module=iitems_hunterslodge&op=start");
            addnav("Referrals", "runmodule.php?module=iitems_hunterslodge&op=referrals");
            break;
        case "referrals":
            output("If you help bring new players to Improbable Island, you'll earn one Supporter Point every time those players hit a new Game Day.  To refer players, use this address:`n`n");
            $url = getsetting("serverurl", "http://" . $_SERVER['SERVER_NAME'] . ($_SERVER['SERVER_PORT'] == 80 ? "" : ":" . $_SERVER['SERVER_PORT']) . dirname($_SERVER['REQUEST_URI']));
            if (!preg_match("/\\/\$/", $url)) {
                $url = $url . "/";
                savesetting("serverurl", $url);
            }
            output_notl("%shome.php?r=%s`n`n", $url, rawurlencode($session['user']['login']));
            $sql = "SELECT name FROM " . db_prefix("accounts") . " WHERE referer={$session['user']['acctid']} ORDER BY dragonkills,level";
            $result = db_query($sql);
            $number = db_num_rows($result);
            if ($number) {
                output("Accounts you've referred:`n");
                for ($i = 0; $i < $number; $i++) {
                    $row = db_fetch_assoc($result);
                    output_notl("%s`0`n", $row['name']);
                }
            }
            addnav("Okay");
            addnav("Back to the Hunter's Lodge", "runmodule.php?module=iitems_hunterslodge&op=start");
            break;
        case "start":
            output("You head into the Hunter's Lodge.  It's a bright, shiny place, with many expensive-looking items arranged inside glass cabinets.  The proprietor, a snappily-dressed male Joker, grins at you from behind the counter.`n`n");
            if (!has_item("lodgebag")) {
                output("The joker silently hands you a small bag, with a look that suggests you put your purchases inside.`n`n");
                give_item("lodgebag");
            }
            output("`0You have `b`5%s`0`b Supporter Points left, out of `5%s`0 accumulated in total.`n`n", number_format($pointsleft), number_format($pointstotal));
            addnav("What's all this about, then?");
            addnav("How do I get supporter points, or give presents to people?", "runmodule.php?module=iitems_hunterslodge&op=explain");
            $lodgeitems = get_items_with_settings("lodge");
            //debug($lodgeitems);
            rawoutput("<table width=100% style='border: dotted 1px #000000;'>");
            $boughtitems = array();
            $sql = "SELECT * FROM " . db_prefix("purchaselog") . " WHERE acctid = '" . $session['user']['acctid'] . "'";
            $result = db_query($sql);
            while ($row = db_fetch_assoc($result)) {
                $boughtitems[$row['purchased']] = 1;
            }
            foreach ($lodgeitems as $key => $vals) {
                if (!$vals['lodge']) {
                    continue;
                }
                $classcount += 1;
                $class = $classcount % 2 ? "trdark" : "trlight";
                rawoutput("<tr class='{$class}'><td>");
                if ($vals['image']) {
                    rawoutput("<table width=100% cellpadding=0 cellspacing=0><tr><td width=100px align=center><img src=\"images/items/" . $vals['image'] . "\"></td><td>");
                }
                output("`b%s`b`n", stripslashes($vals['verbosename']));
                output("%s`0`n", stripslashes($vals['description']));
                if ($vals['weight']) {
                    output("Weight: %s kg`n`0", $vals['weight']);
                }
                rawoutput("<table width=100%><tr><td width=50%>");
                if ($vals['tradable']) {
                    output("`5Giftable Item`0`n");
                }
                if ($vals['lodge_cost']) {
                    $disp = "`b`5" . number_format($vals['lodge_cost']) . "`0`b Supporter Points";
                    $sdisp = $vals['lodge_cost'] . " Points";
                    output("Price: %s`n", $disp);
                    if ($vals['lodge_limited']) {
                        output("`4Limited Item`0: %s available`n", $vals['lodge_stock']);
                    }
                }
                if ($vals['lodge_limited'] && $vals['lodge_stock'] > 0 || !$vals['lodge_limited']) {
                    if ($vals['lodge_singlebuy'] && $boughtitems[$key]) {
                        output("`7You've already obtained and used this item.  No need to get it again!`n");
                    } else {
                        if ($pointstotal >= $vals['lodge_freebie_threshold'] && $vals['lodge_freebie_threshold']) {
                            output("`2This item is now `bfree`b!`0`n");
                            addnav("", "runmodule.php?module=iitems_hunterslodge&op=buy&item=" . $key . "&freebie=true");
                            rawoutput("<a href=\"runmodule.php?module=iitems_hunterslodge&op=buy&item=" . $key . "&freebie=true\">Get it!</a><br />");
                        } else {
                            if ($vals['lodge_freebie_threshold']) {
                                output("`2This item becomes free once you have accumulated more than %s Supporter Points, spent or unspent.`0`n", $vals['lodge_freebie_threshold']);
                            }
                            if ($pointsleft >= $vals['lodge_cost']) {
                                addnav("Buy Items");
                                addnav(array("%s (%s)", stripslashes($vals['verbosename']), $sdisp), "runmodule.php?module=iitems_hunterslodge&op=buy&item=" . $key, true);
                                addnav("", "runmodule.php?module=iitems_hunterslodge&op=buy&item=" . $key);
                                rawoutput("<a href=\"runmodule.php?module=iitems_hunterslodge&op=buy&item=" . $key . "\">More Details / Buy for " . appoencode($disp) . "</a><br />");
                            } else {
                                output("`&You need another %s Supporter Points for this item.`0`n", number_format($vals['lodge_cost'] - $pointsleft));
                                addnav("", "runmodule.php?module=iitems_hunterslodge&op=buy&item=" . $key . "&cannotafford=1");
                                rawoutput("<a href=\"runmodule.php?module=iitems_hunterslodge&op=buy&item=" . $key . "&cannotafford=1\">More Details</a><br />");
                            }
                        }
                    }
                } else {
                    output("`&Sold out!`0`n");
                }
                rawoutput("</td></tr></table>");
                if ($vals['image']) {
                    rawoutput("</td></tr></table>");
                }
                rawoutput("</td></tr>");
            }
            rawoutput("</td></tr></table>");
            modulehook("hunterslodge");
            break;
        case "buy":
            $itemid = httpget("item");
            $item = get_item_settings($itemid);
            $free = httpget("freebie");
            $cannotafford = httpget("cannotafford");
            //debug($item);
            if ($item['lodge_longdesc']) {
                output_notl("`0%s`0`n`n", stripslashes($item['lodge_longdesc']));
            }
            if (!$cannotafford) {
                if (!$free) {
                    output("You're about to buy a %s for %s Supporter Points, leaving you with %s points available to spend afterwards.`n`n", $item['verbosename'], number_format($item['lodge_cost']), number_format($pointsleft - $item['lodge_cost']));
                    addnav("Confirm");
                    addnav(array("Buy %s for %s Points", stripslashes($item['verbosename']), $item['lodge_cost']), "runmodule.php?module=iitems_hunterslodge&op=buyconfirm&item={$itemid}");
                    addnav("No, I don't want to do that!");
                    addnav("Back to the Lodge", "runmodule.php?module=iitems_hunterslodge&op=start");
                } else {
                    redirect("runmodule.php?module=iitems_hunterslodge&op=buyconfirm&item={$itemid}&freebie=true");
                }
            } else {
                output("`0You need another %s Supporter Points to get this item.`0`n`n", number_format($item['lodge_cost'] - $pointsleft));
                addnav("Okay");
                addnav("Back to the Lodge", "runmodule.php?module=iitems_hunterslodge&op=start");
                addnav("How do I get supporter points?", "runmodule.php?module=iitems_hunterslodge&op=explain");
            }
            break;
        case "buyconfirm":
            $itemid = httpget("item");
            $iteminside = httpget("item_inside");
            $item = get_item_settings($itemid);
            $free = httpget("freebie");
            if (!$free) {
                $cost = $item['lodge_cost'];
                output("You have purchased a %s for %s Supporter Points.  You can find the item in your Inventory.  Thank you for your support!`n`n", $item['verbosename'], $item['lodge_cost']);
                give_item($itemid);
                $session['user']['donationspent'] += $item['lodge_cost'];
            } else {
                //handle freebie items
                give_item($itemid);
                output("`0You now have a %s`0!  Thank you for your support!`n`n", $item['verbosename']);
                $cost = 0;
            }
            if ($item['lodge_limited']) {
                increment_item_setting("lodge_stock", -1, $itemid);
            }
            //log purchase
            $sql = "INSERT INTO " . db_prefix("purchaselog") . " (acctid,purchased,amount,data,giftwrap,timestamp) VALUES ('" . $session['user']['acctid'] . "','" . $itemid . "','" . $cost . "','" . addslashes(serialize($item)) . "','" . $wrap . "','" . date("Y-m-d H:i:s") . "')";
            //debug($sql);
            db_query($sql);
            addnav("Yay!");
            addnav("Back to the Hunter's Lodge", "runmodule.php?module=iitems_hunterslodge&op=start");
            break;
    }
    addnav("Leave");
    addnav("Return to the Outpost", "village.php");
    addnav("Inventory");
    addnav("View your Inventory", "inventory.php?items_context=lodge");
    page_footer();
    return true;
}
function stamina_minihof($action, $userid = false)
{
    global $session;
    if ($userid === false) {
        $userid = $session['user']['acctid'];
    }
    $st = microtime(true);
    $boardfilename = str_replace(" ", "", $action);
    $boardinfo = datacache("staminaboardinfo_" . $boardfilename, 120);
    $en = microtime(true);
    $to = $en - $st;
    //debug("Cache: ".$to);
    if (!is_array($boardinfo)) {
        $board = array();
        $staminasql = "SELECT setting,value,userid FROM " . db_prefix("module_userprefs") . " WHERE modulename='staminasystem' AND setting='actions'";
        $staminaresult = db_query($staminasql);
        $scount = db_num_rows($staminaresult);
        for ($i = 0; $i < $scount; $i++) {
            $row = db_fetch_assoc($staminaresult);
            $actions_array = @unserialize($row['value']);
            $actiondetails = $actions_array[$action];
            $board[$row['userid']] = $actiondetails['exp'];
        }
        $boardinfo = stamina_minihof_assignranks($board);
        updatedatacache("staminaboardinfo_" . $boardfilename, $boardinfo);
    }
    //set the player's entry in the board with brand-new data
    $player_action = get_player_action($action);
    $boardinfo['board'][$userid] = $player_action['exp'];
    $smallboard = stamina_minihof_makesmallboard($boardinfo, $userid);
    if (!$smallboard) {
        $boardinfo = stamina_minihof_assignranks($boardinfo['board']);
        $smallboard = stamina_minihof_makesmallboard($boardinfo, $userid);
    }
    //display the board!
    output("`n`n");
    rawoutput("<div align=center>");
    rawoutput("<table cellspacing='0' cellpadding='5'>");
    rawoutput("<tr class='trhead'><td colspan=3><strong>{$action}</strong></td></tr>");
    rawoutput("<tr class='trhead'><td><strong>Rank</strong></td><td><strong>Name</strong></td><td><strong>Experience</strong></td></tr>");
    $count = count($smallboard);
    for ($i = 0; $i < $count; $i++) {
        rawoutput("<tr class='" . ($i % 2 ? "trlight" : "trdark") . "'>");
        if ($smallboard[$i]['acctid'] == $userid) {
            rawoutput("<td><strong>" . number_format($smallboard[$i]['rank']) . "</strong></td><td><strong>" . appoencode($smallboard[$i]['name']) . "</strong></td><td><strong>" . number_format($smallboard[$i]['xp']) . "</strong></td></tr>");
        } else {
            rawoutput("<td>" . number_format($smallboard[$i]['rank']) . "</td><td>" . appoencode($smallboard[$i]['name']) . "</td><td>" . number_format($smallboard[$i]['xp']) . "</td></tr>");
        }
    }
    rawoutput("</table></div>");
}
function combatbars_showhiddenbar($name)
{
    $pixeloffset = 0;
    $numdisp = "???";
    rawoutput("<script style=\"text/javascript\" language=\"javascript\">document.getElementById(\"combatbars\").innerHTML += '<table cellpadding=0 cellspacing=0><tr><td width=\"220px\"><div style=\"width:200; height:25; background:url(/modules/combatbars/lifebar-bottom.png); border:1px solid #000000;\"><div style=\"width: 195; height: 25; padding-left:5px; background: url(/modules/combatbars/lifebar-top.png); background-repeat: no-repeat; line-height: 25px; background-position: -" . $pixeloffset . "px\"><font color=#ffffff><b>" . $numdisp . "</b></font></div></div></td><td><b>" . addslashes(appoencode($name)) . "</b></font></td></tr></table>';</script>");
}
<?php

global $session;
define("ALLOW_ANONYMOUS", true);
define("OVERRIDE_FORCED_NAV", true);
require_once "common.php";
require_once "lib/commentary.php";
$section = $_REQUEST['section'];
//$section = "village";
sleep(5);
//todo: get return link properly, check the player's chatloc matches up with the commentary area
$commentary = preparecommentaryblock($section);
echo $section;
$commentary = appoencode($commentary, true);
echo $commentary;
saveuser();
		$result2 = db_query($sql2);
		$row2 = db_fetch_assoc($result2);
		$stars=$row2['stars'];
		$closed=$row2['closed'];
		switch($stars){
			case 0: $stars = appoencode("`)-"); break;
			case 1: $stars = appoencode("`)*"); break;
			case 2: $stars = appoencode("`)**"); break;
			case 3: $stars = appoencode("`)***"); break;
			case 4: $stars = appoencode("`Q****"); break;
			case 5: $stars = appoencode("`Q*****"); break;
			case 6:	$stars = appoencode("`Q******"); break;
			case 7: $stars = appoencode("`7*******"); break;
			case 8: $stars = appoencode("`7********"); break;
			case 9: $stars = appoencode("`^*********"); break;
			case 10: $stars = appoencode("`^**********"); break;
		}
	 	rawoutput("<tr class='".($i%2?"trlight":"trdark")."'><td>");
	 	rawoutput("$name</td><td>".appoencode($row['windowpeer'])."</td><td>$stars</td>");
		 if($closed==0)
		 	rawoutput("<td>[ <a href=runmodule.php?module=dwellings&op=enter&dwid=$rdwid>$enter</a> ]</td></tr>");
		 else{
		 	$tclosed = translate_inline("Closed");
		 	rawoutput("<td align=center> - $tclosed - </td></tr>");
		 }
	 	addnav("","runmodule.php?module=dwellings&op=enter&dwid=$rdwid");
	 }
  	 rawoutput("</table>");
	}
?>
function previewfield($name, $startdiv = false, $talkline = "says", $showcharsleft = true, $info = false, $default = false, $jsec = false, $ucol = false, $focus = false)
{
    global $schema, $session, $chatsonpage;
    $talkline = translate_inline($talkline, $schema);
    $youhave = translate_inline("You have ");
    $charsleft = translate_inline(" characters left.");
    $chatsonpage += 1;
    //figure out whether to handle absolute or relative time
    if (!array_key_exists('commentary_autocomplete', $session['user']['prefs'])) {
        $session['user']['prefs']['commentary_autocomplete'] = 0;
    }
    if ($session['user']['prefs']['commentary_autocomplete']) {
        $autocomplete = "";
    } else {
        $autocomplete = "autocomplete='off'";
    }
    if (!$jsec) {
        $nid = $name . $chatsonpage;
    } else {
        $nid = $jsec;
    }
    //debug($nid);
    if ($ucol !== false) {
        $exclude = array("J");
        $colors = getcolors($exclude);
        $usercol = $colors[$ucol];
    } else {
        $usercol = "colLtCyan";
    }
    if ($startdiv === false) {
        $startdiv = "";
    }
    rawoutput("<script language='JavaScript'>\r\n\t\t\t\tfunction previewtext{$nid}(t,l){\r\n\t\t\t\t\tvar out = \"<span class=\\'colLtWhite\\'>" . addslashes(appoencode($startdiv)) . "\";\r\n\t\t\t\t\tvar end = '</span>';\r\n\t\t\t\t\tvar x=0;\r\n\t\t\t\t\tvar y='';\r\n\t\t\t\t\tvar z='';\r\n\t\t\t\t\tvar max=document.getElementById('input{$nid}');\r\n\t\t\t\t\tvar charsleft='';");
    if ($talkline !== false) {
        rawoutput("\tif (t.substr(0,2)=='::'){\r\n\t\t\t\t\t\tx=2;\r\n\t\t\t\t\t}else if (t.substr(0,1)==':'){\r\n\t\t\t\t\t\tx=1;\r\n\t\t\t\t\t}else if (t.substr(0,3)=='/me'){\r\n\t\t\t\t\t\tx=3;");
        if ($session['user']['superuser'] & SU_IS_GAMEMASTER) {
            rawoutput("\r\n\t\t\t\t\t}else if (t.substr(0,5)=='/game'){\r\n\t\t\t\t\t\tx=5;");
        }
        rawoutput("\t}else{\r\n\t\t\t\t\t\tout += '</span><span class=\\'colDkCyan\\'> " . addslashes(appoencode($talkline)) . " \"</span><span class=\\'{$usercol}\\'>';\r\n\t\t\t\t\t\tend += '</span><span class=\\'colDkCyan\\'>\"';\r\n\t\t\t\t\t}");
    }
    if ($showcharsleft == true) {
        rawoutput("\tif (x!=0) {\r\n\t\t\t\t\t\tif (max.maxLength!=255) max.maxLength=255;\r\n\t\t\t\t\t\tl=255;\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tmax.maxLength=l;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (l-t.length<0) charsleft +='<span class=\\'colLtRed\\'>';\r\n\t\t\t\t\tcharsleft += '" . $youhave . "'+(l-t.length)+'" . $charsleft . "<br>';\r\n\t\t\t\t\tif (l-t.length<0) charsleft +='</span>';\r\n\t\t\t\t\titalics=0;\r\n\t\t\t\t\tdocument.getElementById('charsleft{$nid}').innerHTML=charsleft+'<br/>';");
    }
    rawoutput("\t\tfor (; x < t.length; x++){\r\n\t\t\t\t\t\ty = t.substr(x,1);\r\n\t\t\t\t\t\tif (y=='<'){\r\n\t\t\t\t\t\t\tout += '&lt;';\r\n\t\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\t\t}else if(y=='>'){\r\n\t\t\t\t\t\t\tout += '&gt;';\r\n\t\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\t\t}else if(y=='\\n'){\r\n\t\t\t\t\t\t\tout += '<br />';\r\n\t\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\t\t}else if (y=='`'){\r\n\t\t\t\t\t\t\tif (x < t.length-1){\r\n\t\t\t\t\t\t\t\tz = t.substr(x+1,1);\r\n\t\t\t\t\t\t\t\tif (z=='0'){\r\n\t\t\t\t\t\t\t\t\tout += '</span>';\r\n\t\t\t\t\t\t\t\t}else if (z=='1'){\r\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colDkBlue\\'>';\r\n\t\t\t\t\t\t\t\t}else if (z=='2'){\r\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colDkGreen\\'>';\r\n\t\t\t\t\t\t\t\t}else if (z=='3'){\r\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colDkCyan\\'>';\r\n\t\t\t\t\t\t\t\t}else if (z=='4'){\r\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colDkRed\\'>';\r\n\t\t\t\t\t\t\t\t}else if (z=='5'){\r\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colDkMagenta\\'>';\r\n\t\t\t\t\t\t\t\t}else if (z=='6'){\r\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colDkYellow\\'>';\r\n\t\t\t\t\t\t\t\t}else if (z=='7'){\r\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colDkWhite\\'>';\r\n\t\t\t\t\t\t\t\t}else if (z=='q'){\r\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colDkOrange\\'>';\r\n\t\t\t\t\t\t\t\t}else if (z=='!'){\r\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colLtBlue\\'>';\r\n\t\t\t\t\t\t\t\t}else if (z=='@'){\r\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colLtGreen\\'>';\r\n\t\t\t\t\t\t\t\t}else if (z=='#'){\r\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colLtCyan\\'>';\r\n\t\t\t\t\t\t\t\t}else if (z=='\$'){\r\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colLtRed\\'>';\r\n\t\t\t\t\t\t\t\t}else if (z=='%'){\r\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colLtMagenta\\'>';\r\n\t\t\t\t\t\t\t\t}else if (z=='^'){\r\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colLtYellow\\'>';\r\n\t\t\t\t\t\t\t\t}else if (z=='&'){\r\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colLtWhite\\'>';\r\n\t\t\t\t\t\t\t\t}else if (z=='Q'){\r\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colLtOrange\\'>';\r\n\t\t\t\t\t\t\t\t}else if (z==')'){\r\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colLtBlack\\'>';\r\n\t\t\t\t\t\t\t\t}else if (z=='r'){\r\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colRose\\'>';\r\n\t\t\t\t\t\t\t\t}else if (z=='R'){\r\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colRose\\'>';\r\n\t\t\t\t\t\t\t\t}else if (z=='v'){\r\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'coliceviolet\\'>';\r\n\t\t\t\t\t\t\t\t}else if (z=='V'){\r\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colBlueViolet\\'>';\r\n\t\t\t\t\t\t\t\t}else if (z=='g'){\r\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colXLtGreen\\'>';\r\n\t\t\t\t\t\t\t\t}else if (z=='G'){\r\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colXLtGreen\\'>';\r\n\t\t\t\t\t\t\t\t}else if (z=='T'){\r\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colDkBrown\\'>';\r\n\t\t\t\t\t\t\t\t}else if (z=='t'){\r\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colLtBrown\\'>';\r\n\t\t\t\t\t\t\t\t}else if (z=='~'){\r\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colBlack\\'>';\r\n\t\t\t\t\t\t\t\t}else if (z=='j'){\r\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colMdGrey\\'>';\r\n\t\t\t\t\t\t\t\t}else if (z=='e'){\r\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colDkRust\\'>';\r\n\t\t\t\t\t\t\t\t}else if (z=='E'){\r\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colLtRust\\'>';\r\n\t\t\t\t\t\t\t\t}else if (z=='l'){\r\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colDkLinkBlue\\'>';\r\n\t\t\t\t\t\t\t\t}else if (z=='L'){\r\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colLtLinkBlue\\'>';\r\n\t\t\t\t\t\t\t\t}else if (z=='x'){\r\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colburlywood\\'>';\r\n\t\t\t\t\t\t\t\t}else if (z=='X'){\r\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colbeige\\'>';\r\n\t\t\t\t\t\t\t\t}else if (z=='y'){\r\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colkhaki\\'>';\r\n\t\t\t\t\t\t\t\t}else if (z=='Y'){\r\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'coldarkkhaki\\'>';\r\n\t\t\t\t\t\t\t\t}else if (z=='k'){\r\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colaquamarine\\'>';\r\n\t\t\t\t\t\t\t\t}else if (z=='K'){\r\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'coldarkseagreen\\'>';\r\n\t\t\t\t\t\t\t\t}else if (z=='p'){\r\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'collightsalmon\\'>';\r\n\t\t\t\t\t\t\t\t}else if (z=='P'){\r\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colsalmon\\'>';\r\n\t\t\t\t\t\t\t\t}else if (z=='m'){\r\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'colwheat\\'>';\r\n\t\t\t\t\t\t\t\t}else if (z=='M'){\r\n\t\t\t\t\t\t\t\t\tout += '</span><span class=\\'coltan\\'>';\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\telse if (z=='i'){\r\n\t\t\t\t\t\t\t\t\titalics += 1;\r\n\t\t\t\t\t\t\t\t\tinum = italics;\r\n\t\t\t\t\t\t\t\t\tif (inum%2){\r\n\t\t\t\t\t\t\t\t\t\tout += '<i>';\r\n\t\t\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\t\t\tout += '</i>';\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\tx++;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}else{\r\n\t\t\t\t\t\t\tout += y;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tdocument.getElementById(\"previewtext{$nid}\").innerHTML=out+end+'<br/>';\r\n\t\t\t\t}</script>\r\n\t\t\t\t");
    if ($charsleft == true) {
        rawoutput("<span id='charsleft{$nid}'></span>");
    }
    if (!is_array($info)) {
        if ($default) {
            rawoutput("<input name='{$name}' id='input{$nid}' " . $autocomplete . " maxlength='255' onKeyUp='previewtext{$nid}(document.getElementById(\"input{$nid}\").value,255);' value='{$default}'>");
        } else {
            rawoutput("<input name='{$name}' id='input{$nid}' " . $autocomplete . " maxlength='255' onKeyUp='previewtext{$nid}(document.getElementById(\"input{$nid}\").value,255);'>");
        }
    } else {
        if (isset($info['maxlength'])) {
            $l = $info['maxlength'];
        } else {
            $l = 255;
        }
        if (isset($info['type']) && $info['type'] == 'textarea') {
            rawoutput("<textarea name='{$name}' id='input{$nid}' onKeyUp='previewtext{$nid}(document.getElementById(\"input{$nid}\").value,{$l});' ");
        } else {
            rawoutput("<input name='{$name}' id='input{$nid}' " . $autocomplete . " onKeyUp='previewtext{$nid}(document.getElementById(\"input{$nid}\").value,{$l});' ");
        }
        foreach ($info as $key => $val) {
            rawoutput("{$key}='{$val}'");
        }
        if (isset($info['type']) && $info['type'] == 'textarea') {
            rawoutput(">");
            if ($default) {
                rawoutput($default);
            }
            rawoutput("</textarea>");
        } else {
            if ($default) {
                rawoutput(" value='{$default}'>");
            } else {
                rawoutput(">");
            }
        }
    }
    rawoutput("<div id='previewtext{$nid}'></div>");
    if ($focus) {
        rawoutput("<script language='javascript'>document.getElementById('input" . $nid . "').focus();</script>");
    }
}
                 //aspect ratio. We are scaling for height/width ratio
                 $resizedwidth = $pic_width;
                 $resizedheight = $pic_height;
                 if ($pic_height > $maxheight) {
                     $resizedheight = $maxheight;
                     $resizedwidth = round($pic_width * ($maxheight / $pic_height));
                 }
                 if ($resizedwidth > $maxwidth) {
                     $resizedheight = round($resizedheight * ($maxwidth / $resizedwidth));
                     $resizedwidth = $maxwidth;
                 }
                 $image .= " height=\"{$resizedheight}\"  width=\"{$resizedwidth}\" ";
             }
             $image .= ">";
             rawoutput("<table><tr><td valign='top'>");
             $terms = appoencode(translate_inline("Your Avatar"));
             rawoutput("</td><td valign='top'>{$image}</td></tr><td></td><td>{$terms}</td></table>");
             debug("File successfully transferred!");
             debug("Name: " . $file["name"] . "");
             debug("Size: " . $file["size"] . " Bytes");
             debug("MIME-Type: " . $file["type"] . "");
             debug("Link: <a href=\"" . $filename . "\">" . $file["name"] . "</a>");
         } else {
             output("The file could not be uploaded.");
         }
     } else {
         output("You may only have a filesize up to %s bytes!", $max_byte_size);
     }
 } else {
     output("The file extension is not supported.");
 }
function friendlist_list()
{
    global $session;
    $friends = rexplode(get_module_pref('friends'));
    $request = rexplode(get_module_pref('request'));
    $ignored = rexplode(get_module_pref('ignored'));
    $iveignored = rexplode(get_module_pref('iveignored'));
    output("`b`@Friends:`b`n");
    rawoutput("<table style='width:60%;text-align:center;' cellpadding='3' cellspacing='0' border='0'>");
    rawoutput("<tr class='trhead'><td>" . translate_inline("Name") . "</td><td>" . translate_inline("Logged In") . "</td><td>" . translate_inline("Location") . "</td><td>" . translate_inline("Alive") . "</td><td>" . translate_inline("Operations") . "</td></tr>");
    $last = date("Y-m-d H:i:s", strtotime("-" . getsetting("LOGINTIMEOUT", 900) . " sec"));
    $x = 0;
    if (implode(",", $friends) != '') {
        $sql = "SELECT name,acctid,login,laston,alive,loggedin,location FROM " . db_prefix("accounts") . " WHERE acctid IN (" . implode(',', $friends) . ") AND locked=0 ORDER BY login";
        $result = db_query($sql);
        while ($row = db_fetch_assoc($result)) {
            $ac = $row['acctid'];
            $x++;
            rawoutput("<tr class='" . ($x % 2 ? "trlight" : "trdark") . "'>");
            rawoutput("<td><a href='mail.php?op=write&to=" . rawurlencode($row['login']) . "'>" . appoencode("`&" . $row['name'], false) . "</a></td>");
            addnav("", "mail.php?op=write&to=" . rawurlencode($row['login']));
            $loggedin = $row['loggedin'];
            if ($row['laston'] < $last) {
                $loggedin = false;
            }
            $loggedin = translate_inline($loggedin ? "`^Yes`0" : "`%No`0");
            rawoutput("<td>" . appoencode($loggedin, false) . "</td>");
            rawoutput("<td><span class='colLtYellow'>" . htmlentities($row['location']) . "</span></td>");
            $alive = translate_inline($row['alive'] ? "`@Yes`0" : "`\$No`0");
            rawoutput("<td>" . appoencode($alive, false) . "</td>");
            $ops = "[<a href='runmodule.php?module=friendlist&op=deny&ac={$ac}' class='colDkGreen'>" . translate_inline("Remove") . "</a>] - [<a href='runmodule.php?module=friendlist&op=ignore&ac={$ac}' class='colDkGreen'>" . translate_inline("Ignore") . "</a>]";
            addnav("", "runmodule.php?module=friendlist&op=deny&ac={$ac}");
            addnav("", "runmodule.php?module=friendlist&op=ignore&ac={$ac}");
            rawoutput("<td>{$ops}</td></tr>");
        }
    }
    if ($x == 0) {
        rawoutput("<tr class='trlight'><td colspan='5'>");
        output("`^You have no friends");
        rawoutput("</td></tr>");
    }
    rawoutput("</table>");
    $friends = rimplode($friends);
    set_module_pref('friends', $friends);
    output("`n`b`@Friend Requests:`b`n");
    rawoutput("<table style='width:60%;text-align:center;' cellpadding='3' cellspacing='0' border='0'>");
    rawoutput("<tr class='trhead'><td>" . translate_inline("Name") . "</td><td>" . translate_inline("Operations") . "</td></tr>");
    $x = 0;
    $request = array_unique($request);
    if (implode(",", $request) != '') {
        $sql = "SELECT name,acctid,login,laston,alive,loggedin,location FROM " . db_prefix("accounts") . " WHERE acctid IN (" . implode(',', $request) . ") AND locked=0 ORDER BY login";
        $result = db_query($sql);
        while ($row = db_fetch_assoc($result)) {
            $ac = $row['acctid'];
            $x++;
            rawoutput("<tr class='" . ($x % 2 ? "trlight" : "trdark") . "'>");
            rawoutput("<td>" . appoencode($row['name'], false) . "</td>");
            $ops = "[<a href='runmodule.php?module=friendlist&op=accept&ac={$ac}' class='colDkGreen'>" . translate_inline("Accept") . "</a>] - [<a href='runmodule.php?module=friendlist&op=deny&ac={$ac}' class='colDkGreen'>" . translate_inline("Deny") . "</a>] - [<a href='runmodule.php?module=friendlist&op=ignore&ac={$ac}' class='colDkGreen'>" . translate_inline("Ignore") . "</a>]";
            addnav("", "runmodule.php?module=friendlist&op=accept&ac={$ac}");
            addnav("", "runmodule.php?module=friendlist&op=deny&ac={$ac}");
            addnav("", "runmodule.php?module=friendlist&op=ignore&ac={$ac}");
            rawoutput("<td>{$ops}</td></tr>");
        }
    }
    if ($x == 0) {
        rawoutput("<tr class='trlight'><td colspan='2'>");
        output("`^You have no requests");
        rawoutput("</td></tr>");
    }
    rawoutput("</table>");
    $request = rimplode($request);
    set_module_pref('request', $request);
    output("`n`b`@Ignored You:`b`n");
    rawoutput("<table style='width:60%;text-align:center;' cellpadding='3' cellspacing='0' border='0'>");
    rawoutput("<tr class='trhead'><td>" . translate_inline("Name") . "</td><td>" . translate_inline("Operations") . "</td></tr>");
    $x = 0;
    $ignored = array_unique($ignored);
    if (implode(",", $ignored) != '') {
        $sql = "SELECT name,acctid,login,laston,alive,loggedin,location FROM " . db_prefix("accounts") . " WHERE acctid IN (" . implode(',', $ignored) . ") AND locked=0 ORDER BY login";
        $result = db_query($sql);
        while ($row = db_fetch_assoc($result)) {
            $x++;
            $ac = $row['acctid'];
            rawoutput("<tr class='" . ($x % 2 ? "trlight" : "trdark") . "'>");
            rawoutput("<td>" . appoencode($row['name'], false) . "</td>");
            if (!in_array($ac, $iveignored)) {
                $ops = "[<a href='runmodule.php?module=friendlist&op=ignore&ac={$ac}' class='colDkGreen'>" . translate_inline("Ignore") . "</a>]";
                addnav("", "runmodule.php?module=friendlist&op=ignore&ac={$ac}");
            } else {
                $ops = appoencode("`i[" . translate_inline("Nothing") . "]`i", false);
            }
            rawoutput("<td>{$ops}</td></tr>");
        }
    }
    if ($x == 0) {
        rawoutput("<tr class='trlight'><td colspan='2'>");
        output("`^No one has ignored you");
        rawoutput("</td></tr>");
    }
    rawoutput("</table>");
    $ignored = rimplode($ignored);
    set_module_pref('ignored', $ignored);
    output("`n`b`@You've Ignored:`b`n");
    rawoutput("<table style='width:60%;text-align:center;' cellpadding='3' cellspacing='0' border='0'>");
    rawoutput("<tr class='trhead'><td>" . translate_inline("Name") . "</td><td>" . translate_inline("Operations") . "</td></tr>");
    $x = 0;
    $iveignored = array_unique($iveignored);
    if (implode(",", $iveignored) != '') {
        $sql = "SELECT name,acctid,login,laston,alive,loggedin,location FROM " . db_prefix("accounts") . " WHERE acctid IN (" . implode(',', $iveignored) . ") AND locked=0 ORDER BY login";
        $result = db_query($sql);
        while ($row = db_fetch_assoc($result)) {
            $x++;
            $ac = $row['acctid'];
            rawoutput("<tr class='" . ($x % 2 ? "trlight" : "trdark") . "'>");
            rawoutput("<td>" . appoencode($row['name'], false) . "</td>");
            $ops = "[<a href='runmodule.php?module=friendlist&op=unignore&ac={$ac}' class='colLtRed'>" . translate_inline("Unignore") . "</a>]";
            addnav("", "runmodule.php?module=friendlist&op=unignore&ac={$ac}");
            rawoutput("<td>{$ops}</td></tr>");
        }
    }
    if ($x == 0) {
        rawoutput("<tr class='trlight'><td colspan='2'>");
        output("`^You've haven't ignored anyone");
        rawoutput("</td></tr>");
    }
    rawoutput("</table>");
    $iveignored = rimplode($iveignored);
    set_module_pref('iveignored', $iveignored);
}
function improbablehousing_furnitureshop_run()
{
    global $session;
    page_header("Cadfael's Furniture");
    //have the beds and such allowed to be carried in backpack (insert suitable hundred-kilo-bed-in-backpack-lols) or carried by a secondary character in a new Inventory space (we'll call it Delivery Boy - will need a suitably silly photo).
    switch (httpget('op')) {
        case "start":
            output("Cadfael greets you with a preposterously strong Welsh accent.  \"`3Well hey there!  Take a look around, all one 'undred per cent natural and me own work!`0\"`n`n");
            //find items that are furniture!
            $furniture = get_items_with_settings("furniture");
            //debug($furniture);
            usort($furniture, 'sortbyprice');
            rawoutput("<table width=100% style='border: dotted 1px #000000;'>");
            foreach ($furniture as $sort => $vals) {
                $key = $vals['item'];
                $classcount += 1;
                $class = $classcount % 2 ? "trdark" : "trlight";
                rawoutput("<tr class='{$class}'><td>");
                if ($vals['image']) {
                    rawoutput("<table width=100% cellpadding=0 cellspacing=0><tr><td width=100px align=center><img src=\"images/items/" . $vals['image'] . "\"></td><td>");
                }
                output("`b%s`b`n", stripslashes($vals['verbosename']));
                output("%s`0`n", stripslashes($vals['description']));
                if ($vals['weight']) {
                    output("Weight: %s kg`n`0", $vals['weight']);
                }
                rawoutput("<table width=100%><tr><td width=50%>");
                if ($vals['goldcost'] && $vals['gemcost']) {
                    $disp = "`b" . number_format($vals['goldcost']) . "`b Requisition and `b" . number_format($vals['gemcost']) . "`b Cigarettes";
                    $sdisp = $vals['goldcost'] . " Req, " . $vals['gemcost'] . " Cigs";
                } else {
                    if ($vals['goldcost']) {
                        $disp = "`b" . number_format($vals['goldcost']) . "`b Requisition";
                        $sdisp = $vals['goldcost'] . " Req";
                    } else {
                        $disp = "`b" . number_format($vals['goldcost']) . "`b Cigarettes";
                        $sdisp = $vals['goldcost'] . " Cigs";
                    }
                }
                if ($session['user']['gold'] >= $vals['goldcost'] && $session['user']['gems'] >= $vals['gemcost']) {
                    addnav("Buy Items");
                    addnav(array("%s (%s)", $vals['verbosename'], $sdisp), "runmodule.php?module=improbablehousing_furnitureshop&op=buy&item=" . $key, true);
                    addnav("", "runmodule.php?module=improbablehousing_furnitureshop&op=buy&item=" . $key);
                    rawoutput("<a href=\"runmodule.php?module=improbablehousing_furnitureshop&op=buy&item=" . $key . "\">Buy for " . appoencode($disp) . "</a><br />");
                } else {
                    output("Price: %s`n", $disp);
                    output("`&You can't afford this item right now.`0`n");
                }
                rawoutput("</td></tr></table>");
                if ($vals['image']) {
                    rawoutput("</td></tr></table>");
                }
                rawoutput("</td></tr>");
            }
            rawoutput("</td></tr></table>");
            break;
        case "buy":
            $item = httpget("item");
            $goldcost = get_item_setting("goldcost", $item);
            $gemcost = get_item_setting("gemcost", $item);
            $name = get_item_setting("verbosename", $item);
            if ($goldcost && $gemcost) {
                $disp = "`b" . number_format($goldcost) . "`b Requisition and `b" . number_format($gemcost) . "`b Cigarettes";
            } else {
                if ($goldcost) {
                    $disp = "`b" . number_format($goldcost) . "`b Requisition";
                } else {
                    $disp = "`b" . number_format($goldcost) . "`b Cigarettes";
                }
            }
            output("Cadfael nods.  \"`3So, you're after a %s then, are ye?  That'll be %s, please.`0\"`n`n", $name, $disp);
            addnav("Confirmation");
            addnav("Confirm sale", "runmodule.php?module=improbablehousing_furnitureshop&op=confirmbuy&item=" . $item);
            addnav("Wait, I've changed my mind!", "runmodule.php?module=improbablehousing_furnitureshop&op=start");
            break;
        case "confirmbuy":
            $item = httpget("item");
            $goldcost = get_item_setting("goldcost", $item);
            $gemcost = get_item_setting("gemcost", $item);
            $name = get_item_setting("verbosename", $item);
            $session['user']['gold'] -= $goldcost;
            $session['user']['gems'] -= $gemcost;
            give_item($item);
            output("You hand over your hard-won currency to Cadfael, who grins and says \"`3Ah, much obliged!  Pleasure doin' business... with...`0\" he stops, bemused.  \"`3Are... are you trying to fit that into a `ibackpack?`i`0\"`n`nAfter several minutes of grunting and sweating, your backpack now resembles a... well, a barely-held-together layer of canvas stretched drum-tight into the shape of a %s.  With a very small %s bent double underneath.  Cadfael shakes his head and mutters something about it taking all sorts.`n`n", $name, $session['user']['race']);
            break;
        case "drop":
            page_header("");
            $itemid = httpget('item');
            debug($itemid);
            $hid = httpget('hid');
            require_once "modules/improbablehousing/lib/lib.php";
            $house = improbablehousing_gethousedata($hid);
            $rid = httpget('rid');
            $slot = httpget('slot');
            $house['data']['rooms'][$rid]['sleepslots'][$slot]['stamina'] = get_item_pref("sleepslot_stamina", $itemid);
            $house['data']['rooms'][$rid]['sleepslots'][$slot]['name'] = get_item_pref("sleepslot_name", $itemid);
            $house['data']['rooms'][$rid]['sleepslots'][$slot]['desc'] = get_item_pref("sleepslot_desc", $itemid);
            use_item($itemid);
            improbablehousing_sethousedata($house);
            addnav("Continue");
            addnav(array("Return to %s", $house['data']['rooms'][$rid]['name']), "runmodule.php?module=improbablehousing&op=interior&hid=" . $hid . "&rid=" . $rid);
            break;
    }
    if (httpget('op') != "drop") {
        addnav("Exit");
        addnav("Back to the Outpost", "village.php");
    }
    page_footer();
    return true;
}
function mementos_dohook($hookname, $args)
{
    global $session;
    switch ($hookname) {
        case "hunterslodge":
            addnav("Custom Items");
            addnav("Memento Forge", "runmodule.php?module=mementos&op=start");
            break;
        case "inventory":
            $inv = $args['inventory'];
            $sort = $args['sort'];
            foreach ($inv as $itemid => $prefs) {
                if ($prefs['item'] == "memento") {
                    //debug($prefs);
                    addnav("", "inventory.php?items_context=" . $args['context'] . "&memento_togglebioshow=" . $prefs['itemid'] . "&items_sort={$sort}");
                    // if (!isset($prefs['memento_showinbio'])){
                    // $prefs['memento_showinbio'] = 0;
                    // }
                    if (!$prefs['memento_showinbio']) {
                        $args['inventory'][$itemid]['inventoryactions'] .= appoencode("`4Hidden from Bio`0 (<a href=\"inventory.php?items_context=" . $args['context'] . "&memento_togglebioshow=" . $prefs['itemid'] . "&items_sort={$sort}\">show</a>) | ", true);
                    } else {
                        $args['inventory'][$itemid]['inventoryactions'] .= appoencode("`2Visible in Bio`0 (<a href=\"inventory.php?items_context=" . $args['context'] . "&memento_togglebioshow=" . $prefs['itemid'] . "&items_sort={$sort}\">hide</a>) | ", true);
                    }
                }
            }
            break;
        case "inventory-predisplay":
            $id = httpget("memento_togglebioshow");
            if ($id) {
                if (get_item_pref("memento_showinbio", $id)) {
                    output("`\$You have chosen to hide this Memento from your Bio.`0`n");
                    set_item_pref("memento_showinbio", "", $id);
                } else {
                    output("`@You have chosen to show this Memento in your Bio.`0`n");
                    set_item_pref("memento_showinbio", "1", $id);
                }
                output("Multiple Mementos of the same type are only shown once on your Bio page.`n`n");
            }
            break;
        case "bioinfo":
            $inv = load_inventory($args['acctid'], true);
            $gr = group_items($inv, false);
            $mem = array();
            foreach ($gr as $id => $prefs) {
                if ($prefs['memento_showinbio']) {
                    $mem[$id] = $prefs;
                }
            }
            if (count($mem)) {
                output("`bMementos`b`n");
                rawoutput("<table width=100% style='border: dotted 1px #000000;'>");
                foreach ($mem as $id => $prefs) {
                    $classcount += 1;
                    $class = $classcount % 2 ? "trdark" : "trlight";
                    rawoutput("<tr class='{$class}'><td>");
                    output("`b%s`b`0`n", stripslashes($prefs['verbosename']));
                    output("%s`0`n`n", stripslashes($prefs['description']));
                    rawoutput("</td></tr>");
                }
                rawoutput("</table>");
                output("`n`n");
            }
            break;
    }
    return $args;
}
            $sql = "DELETE FROM " . db_prefix("commentary") . " \r\n\t\t\t\t\tWHERE section = 'dwellings-{$dwid}' \r\n\t\t\t\t\tOR section='coffers-{$dwid}'";
            db_query($sql);
            redirect("runmodule.php?module=dwellings");
        } else {
            output("`\$ Are you really sure about selling your dwelling? ");
            $clickhere = translate_inline("Click here to confirm!");
            rawoutput("<a href='runmodule.php?module=dwellings&op=manage&subop=sell&sellgold={$sellgold}&sellgems={$sellgems}&dwid={$dwid}&confirm=1'>{$clickhere}</a>");
            addnav("", "runmodule.php?module=dwellings&op=manage&subop=sell&sellgold={$sellgold}&sellgems={$sellgems}&dwid={$dwid}&confirm=1");
        }
        break;
}
if ($subop != "") {
    output("`n`n");
}
output("`2Here you can find an overview of what's happening in your dwelling.`n`n");
$name = appoencode($row['name']);
if ($name == "") {
    $name = translate_inline("- None -");
}
$location = $row['location'];
$goldvalue = $row['goldvalue'];
$gemvalue = $row['gemvalue'];
$coffersgold = $row['gold'];
$coffersgems = $row['gems'];
$dwgold = translate_inline("gold");
$dwgems = translate_inline("gems");
$givegold = $goldvalue;
$givegems = $gemvalue;
if (get_module_setting("addcof")) {
    $givegold += $coffersgold;
    $givegems += $coffersgems;
         $row['installed'] = true;
         $all_modules[$row['category']][$row['modulename']] = $row;
     }
 }
 $install_status = get_module_install_status();
 $uninstalled = $install_status['uninstalledmodules'];
 reset($uninstalled);
 $invalidmodule = array("version" => "", "author" => "", "category" => "Invalid Modules", "download" => "", "description" => "", "invalid" => true);
 while (list($key, $modulename) = each($uninstalled)) {
     $row = array();
     //test if the file is a valid module or a lib file/whatever that got in, maybe even malcode that does not have module form
     $modulenamelower = strtolower($modulename);
     $file = strtolower(file_get_contents("modules/{$modulename}.php"));
     if (strpos($file, $modulenamelower . "_getmoduleinfo") === false || strpos($file, $modulenamelower . "_install") === false || strpos($file, $modulenamelower . "_uninstall") === false) {
         //here the files has neither do_hook nor getinfo, which means it won't execute as a module here --> block it + notify the admin who is the manage modules section
         $moduleinfo = array_merge($invalidmodule, array("name" => $modulename . ".php " . appoencode(translate_inline("(`\$Invalid Module! Contact Author or check file!`0)"))));
     } else {
         $moduleinfo = get_module_info($modulename);
     }
     //end of testing
     $row['installed'] = false;
     $row['active'] = false;
     $row['category'] = $moduleinfo['category'];
     $row['modulename'] = $modulename;
     $row['formalname'] = $moduleinfo['name'];
     $row['description'] = $moduleinfo['description'];
     $row['moduleauthor'] = $moduleinfo['author'];
     $row['invalid'] = isset($moduleinfo['invalid']) ? $moduleinfo['invalid'] : false;
     if (!array_key_exists($row['category'], $all_modules)) {
         $all_modules[$row['category']] = array();
     }
function tutor_talk()
{
    rawoutput("<style type='text/css'>\r\n\t\t.tutor {\r\n\t\t\tbackground-color: #444444;\r\n\t\t\tborder-color: #0099ff;\r\n\t\t\tborder-style: double;\r\n\t\t\tborder-width: medium;\r\n\t\t\tcolor: #CCCCCC;\r\n\t\t}\r\n\t\t.tutor .colDkBlue\t{ color: #0000B0; }\r\n\t\t.tutor .colDkGreen   { color: #00B000; }\r\n\t\t.tutor .colDkCyan\t{ color: #00B0B0; }\r\n\t\t.tutor .colDkRed\t { color: #B00000; }\r\n\t\t.tutor .colDkMagenta { color: #B000CC; }\r\n\t\t.tutor .colDkYellow  { color: #B0B000; }\r\n\t\t.tutor .colDkWhite   { color: #B0B0B0; }\r\n\t\t.tutor .colLtBlue\t{ color: #0000FF; }\r\n\t\t.tutor .colLtGreen   { color: #00FF00; }\r\n\t\t.tutor .colLtCyan\t{ color: #00FFFF; }\r\n\t\t.tutor .colLtRed\t { color: #FF0000; }\r\n\t\t.tutor .colLtMagenta { color: #FF00FF; }\r\n\t\t.tutor .colLtYellow  { color: #FFFF00; }\r\n\t\t.tutor .colLtWhite   { color: #FFFFFF; }\r\n\t\t.tutor .colLtBlack   { color: #999999; }\r\n\t\t.tutor .colDkOrange  { color: #994400; }\r\n\t\t.tutor .colLtOrange  { color: #FF9900; }\r\n\t\t</style>");
    $args = func_get_args();
    $args[0] = translate($args[0]);
    $text = call_user_func_array("sprintf", $args);
    rawoutput("<div class='tutor'>");
    rawoutput(tlbutton_clear() . appoencode($text));
    rawoutput("</div>");
}
<?php

$subop = httpget("subop");
$none = translate_inline('NONE');
if ($subop == "xml") {
    header("Content-Type: text/xml");
    $sql = "SELECT DISTINCT " . db_prefix("accounts") . ".name FROM " . db_prefix("bans") . ", " . db_prefix("accounts") . " WHERE (ipfilter='" . addslashes(httpget("ip")) . "' AND " . db_prefix("bans") . ".uniqueid='" . addslashes(httpget("id")) . "') AND ((substring(" . db_prefix("accounts") . ".lastip,1,length(ipfilter))=ipfilter " . "AND ipfilter<>'') OR (" . db_prefix("bans") . ".uniqueid=" . db_prefix("accounts") . ".uniqueid AND " . db_prefix("bans") . ".uniqueid<>''))";
    $r = db_query($sql);
    echo "<xml>";
    $number = db_num_rows($r);
    for ($x = 0; $x < $number; $x++) {
        $ro = db_fetch_assoc($r);
        echo "<name name=\"";
        echo urlencode(appoencode("`0{$ro['name']}"));
        echo "\"/>";
    }
    if (db_num_rows($r) == 0) {
        echo "<name name=\"{$none}\"/>";
    }
    echo "</xml>";
    exit;
}
db_query("DELETE FROM " . db_prefix("bans") . " WHERE banexpire < \"" . date("Y-m-d") . "\" AND banexpire>'0000-00-00'");
$duration = httpget("duration");
if ($duration == "") {
    $since = " WHERE banexpire <= '" . date("Y-m-d H:i:s", strtotime("+2 weeks")) . "' AND banexpire > '0000-00-00'";
    output("`bShowing bans that will expire within 2 weeks.`b`n`n");
} else {
    if ($duration == "forever") {
        $since = "";
        output("`bShowing all bans`b`n`n");
function rss_run()
{
    if (httpget("op") == "describe") {
        global $session;
        page_header("RSS Feed Information");
        output("This site offers RSS news feeds for periodically updated information about various aspects of the game.");
        output("Click %shere%s for more information about the RSS format.`n`n", "<a href='http://www.google.com/search?q=rss+information' target='_blank'>", "</a>", true);
        output("Feeds offered on this site:`n");
        $format = "`#&#149;`7 %s`n";
        addnav("Get RSS News Feeds");
        if (get_module_setting("do_news")) {
            addnav("Daily News", "runmodule.php?module=rss&feed=news", false, true);
            output($format, "Daily News", true);
        }
        if (get_module_setting("do_online")) {
            addnav("Who's Online", "runmodule.php?module=rss&feed=online", false, true);
            output($format, "Who's Online", true);
        }
        if (get_module_setting("do_motd")) {
            addnav("MoTD", "runmodule.php?module=rss&feed=motd", false, true);
            output($format, "Message of the Day (MoTD)", true);
        }
        addnav("Other");
        addnav("About LoGD", "about.php");
        if ($session['user']['loggedin']) {
            addnav("Return to the news", "news.php");
        } else {
            addnav("Login Page", "index.php");
        }
        page_footer();
        return;
    }
    $items = array();
    $feedtitle = "";
    $pubtime = date("Y-m-d H:i:s");
    $link = getsetting("serverurl", "http://" . $_SERVER['SERVER_NAME'] . ($_SERVER['SERVER_PORT'] == 80 ? "" : ":" . $_SERVER['SERVER_PORT']) . dirname($_SERVER['SCRIPT_NAME']));
    if (!preg_match("/\\/\$/", $link)) {
        $link = $link . "/";
        savesetting("serverurl", $link);
    }
    $feed = httpget("feed");
    //filter out turned-off feeds
    if ($feed == "news" && !get_module_setting("do_news")) {
        $feed = "";
    }
    if ($feed == "motd" && !get_module_setting("do_motd")) {
        $feed = "";
    }
    if ($feed == "online" && !get_module_setting("do_online")) {
        $feed = "";
    }
    switch ($feed) {
        case "news":
            $feedtitle = "LoGD News";
            $sql = "SELECT newstext,arguments,newsdate,now() AS currenttime,tlschema FROM " . db_prefix("news") . " ORDER BY newsid DESC LIMIT 10";
            $result = db_query_cached($sql, "mod_rss_news", get_module_setting("cache_timeout"));
            while ($row = db_fetch_assoc($result)) {
                $pubtime = $row['currenttime'];
                $arguments = array();
                $base_arguments = @unserialize($row['arguments']);
                array_push($arguments, $row['newstext']);
                while ($base_arguments && (list($key, $val) = each($base_arguments))) {
                    array_push($arguments, $val);
                }
                tlschema($row['tlschema']);
                $title = call_user_func_array("sprintf_translate", $arguments);
                tlschema();
                array_push($items, array("title" => $title, "description" => $title, "pubDate" => $row['newsdate'], "link" => $link . "news.php"));
            }
            if (count($items) == 0) {
                $items = array(array("title" => sprintf_translate("There are no news items", array()), "description" => "", "pubDate" => date("Y-m-d H:i:s"), "link" => $link . "news.php"));
            }
            break;
        case "online":
            $feedtitle = "LoGD Who's Online";
            $sql = "SELECT name,alive,location,sex,level,race,now() AS currenttime FROM " . db_prefix("accounts") . " WHERE locked=0 AND loggedin=1 AND laston>'" . date("Y-m-d H:i:s", strtotime("-" . getsetting("LOGINTIMEOUT", 900) . " seconds")) . "' ORDER BY level DESC";
            $result = db_query_cached($sql, "mod_rss_online", get_module_setting("cache_timeout"));
            while ($row = db_fetch_assoc($result)) {
                $pubtime = $row['currenttime'];
                array_push($items, array("title" => $row['name'], "description" => sprintf_translate("Level %s " . ($row['sex'] ? "female" : "male") . " %s in %s", $row['level'], strtolower($row['race']), $row['location']), "pubDate" => $row['currenttime'], "link" => $link));
            }
            if (count($items) == 0) {
                $items = array(array("title" => sprintf_translate("There are no characters online at this time.", array()), "description" => "", "pubDate" => date("Y-m-d H:i:s"), "link" => $link));
            }
            db_free_result($result);
            if ($onlinecount == 0) {
                $ret .= appoencode("`iNone`i");
            }
            break;
        case "motd":
            $sql = "SELECT motddate,motdbody,motdtitle,name AS motdauthorname,now() AS currenttime FROM " . db_prefix("motd") . " LEFT JOIN " . db_prefix("accounts") . " ON " . db_prefix("accounts") . ".acctid = " . db_prefix("motd") . ".motdauthor ORDER BY motddate DESC limit 10";
            $result = db_query_cached($sql, "mod_rss_motd", get_module_setting("cache_timeout"));
            $feedtitle = "Message of the Day";
            while ($row = db_fetch_assoc($result)) {
                $pubdate = $row['currenttime'];
                array_push($items, array("title" => $row['motdtitle'], "description" => "By {$row['motdauthorname']}\n{$row['motdbody']}", "pubDate" => $row['motddate'], "link" => $link . "motd.php#motd" . date("YmdHis", strtotime($row['motddate']))));
            }
            break;
        default:
            $feedtitle = "No such feed exists";
            $items = array(array("title" => "You have requested a news feed that does not exist.", "desription" => "The news feed you requested does not exist.  This could be because you are using an outdated feed.  Please visit the site at {$link} to try again."), "pubDate" => date("Y-m-d H:i:s"), "link" => $link);
    }
    //build the RSS feed.
    header("Content-Type: text/xml", true);
    echo "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>";
    echo "<rss version=\"2.0\">";
    echo "<channel>";
    echo "<title>" . rss_xmlencode($feedtitle) . "</title>";
    echo "<link>" . rss_xmlencode($link) . "</link>";
    echo "<description>Legend of the Green Dragon -- a browser based text roleplaying game based loosely on the old BBS game Legend of the Red Dragon (LoRD)</description>";
    echo "<language>en-us</language>";
    echo "<copyright>Copyright 2002-" . date("Y") . ", Eric Stevens &amp; JT Traub</copyright>";
    echo "<pubDate>" . date("r", strtotime($pubdate)) . "</pubDate>";
    echo "<lastBuildDate>" . date("r", strtotime($pubdate)) . "</lastBuildDate>";
    echo "<category>LotGD: " . rss_xmlencode($feedtitle) . "</category>";
    echo "<ttl>" . get_module_setting("ttl") . "</ttl>";
    echo "<image>";
    echo "<title>Legend of the Green Dragon</title>";
    echo "<url>" . rss_xmlencode($link) . "images/title.gif</url>";
    echo "<link>" . rss_xmlencode($link) . "</link>";
    echo "</image>";
    reset($items);
    while (list($key, $val) = each($items)) {
        echo "<item>";
        echo "<title>" . rss_xmlencode($val['title']) . "</title>";
        echo "<link>" . rss_xmlencode($val['link']) . "</link>";
        echo "<guid isPermaLink=\"false\">" . rss_xmlencode($val['link']) . "</guid>";
        echo "<description>" . rss_xmlencode($val['description']) . "</description>";
        echo "<pubDate>" . date("r", strtotime($val['pubDate'])) . "</pubDate>";
        echo "</item>";
    }
    echo "</channel>";
    echo "</rss>";
    exit;
}