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 rem_sc_from_book($spell, $book, $login)
{
    // v has_item proveritsja
    //$spell = preg_replace ('/[^a-z0-9_\.]/i', '', $spell);
    //$book = preg_replace ('/[^a-z0-9_\.]/i', '', $book);
    //$login = preg_replace ('/[^a-z0-9_]/i', '', $login);
    include_once 'modules/f_has_item.php';
    if (!has_item($book, $login)) {
        put_g_error('у вас нету книги');
    }
    // zapros na magiju chto v knige:
    $q = do_mysql("SELECT on_take FROM items WHERE fullname = '" . $book . "' AND type = 'b';");
    if (!mysql_num_rows($q)) {
        return 0;
    }
    $magic = mysql_result($q, 0);
    if (strpos($magic, $spell) === false) {
        put_g_error('в этой книге нету этого заклинания!');
    }
    // esli prodolzhaetsja skript, znachit magija estq, izvlekem ee (snachala udalim, togda bagov skryvatq nebvudut:)
    $magic = string_drop($magic, $spell);
    // terq sozdadim:
    //include_once ('modules/f_create_item.php');
    $q = do_mysql("SELECT type FROM magic WHERE fullname = '" . $spell . "';");
    if (!mysql_num_rows($q)) {
        put_error('netu takogo zaklinanija');
    }
    $tp = mysql_result($q, 0);
    //#####$scroll = create_item ('i.s.'.$tp.'.'.$spell);
    include_once 'modules/f_gain_item.php';
    gain_item('i.s.' . $tp . '.' . $spell, 1, $login);
    // obnovim knigu i vse:
    do_mysql("UPDATE items SET on_take = '" . $magic . "' WHERE fullname = '" . $book . "';");
    return 1;
}
function teach_magic_from_sc($scroll, $npc, $login)
{
    //$scroll = preg_replace ('/[^a-z0-9_\.]/i', '', $scroll);
    //$npc = preg_replace ('/[^a-z0-9_\.]/i', '', $npc);
    //$login = preg_replace ('/[^a-z0-9_]/i', '', $login);
    $nid = is_npc($npc);
    $id = is_player($login);
    // v odnoj li lokacii
    $q = do_mysql("SELECT location FROM npc WHERE id_npc = '" . $nid . "';");
    if (!mysql_num_rows($q)) {
        return 0;
    }
    $loc1 = mysql_result($q, 0);
    $q = do_mysql("SELECT location FROM players WHERE id_player = '" . $id . "';");
    if (!mysql_num_rows($q)) {
        return 0;
    }
    $loc2 = mysql_result($q, 0);
    if ($loc1 != $loc2) {
        return 0;
    }
    include_once 'modules/f_has_item.php';
    if (!has_item($scroll, $login)) {
        put_g_error('у вас нету свитка!');
    }
    $q = do_mysql("SELECT on_take, price FROM items WHERE fullname = '" . $scroll . "' AND type = 's';");
    if (!mysql_num_rows($q)) {
        return 0;
    }
    $spell = mysql_fetch_assoc($q);
    // neumeet li on uzhe
    include_once 'modules/f_has_magic.php';
    if (has_magic($spell['on_take'], $login)) {
        put_g_error('вы уже умеете это заклинание!');
    }
    // cenu vyschitaem:
    $q = do_mysql("SELECT money FROM players WHERE id_player = '" . $id . "';");
    $money = mysql_result($q, 0);
    $cost = $spell['price'] * 10;
    if ($money < $cost) {
        put_g_error('нехватает серебра, нужно ' . $cost . ' серебреных!');
    }
    $money -= $cost;
    // dobavljaem zakl:
    $q = do_mysql("SELECT magic FROM players WHERE id_player = '" . $id . "';");
    $magic = mysql_result($q, 0);
    if (!$magic) {
        $magic = $spell['on_take'];
    } else {
        $magic .= '|' . $spell['on_take'];
    }
    // obnovim dannye:
    do_mysql("UPDATE players SET magic = '" . $magic . "', money = '" . $money . "' WHERE id_player = '" . $id . "';");
    // udaljaem svitok
    include_once 'modules/f_delete_item.php';
    delete_item($scroll);
    $q = do_mysql("SELECT name FROM magic WHERE fullname = '" . $spell['on_take'] . "';");
    $name = mysql_result($q, 0);
    exit_msg('магия', 'вы выучили заклинание ' . $name . ' за ' . $cost . ' серебреных!');
}
function hunterslodge_customtitle_run()
{
    require_once "lib/sanitize.php";
    require_once "lib/names.php";
    global $session;
    $op = httpget("op");
    $free = httpget("free");
    page_header("Choose your Custom Title");
    switch ($op) {
        case "change":
            output("Ready to change your Title?  No problem.  Enter your desired Title in the box below.  You've got 25 characters to play with, including colour codes.`n`n");
            titlechange_form();
            addnav("Cancel");
            addnav("Don't change colours, just go back to the Lodge", "runmodule.php?module=iitems_hunterslodge&op=start");
            break;
        case "confirm":
            $ntitle = rawurldecode(httppost('newname'));
            $ntitle = newline_sanitize($ntitle);
            if ($ntitle == "") {
                $ntitle = "`0";
            }
            $ntitle = preg_replace("/[`][cHw]/", "", $ntitle);
            $ntitle = sanitize_html($ntitle);
            $nname = get_player_basename();
            output("`0Your new title will look like this: %s`0`n", $ntitle);
            output("`0Your entire name will look like: %s %s`0`n`n", $ntitle, $nname);
            output("Do you want to set the new title now?`n`n");
            output("`0Try a different title below, if you like.`n`n");
            titlechange_form();
            addnav("Confirm");
            addnav("Set the new Title", "runmodule.php?module=hunterslodge_customtitle&op=set&free={$free}&newname=" . rawurlencode($ntitle));
            addnav("Cancel");
            addnav("Don't change your Title, just go back to the Lodge", "runmodule.php?module=iitems_hunterslodge&op=start");
            break;
        case "set":
            $ntitle = rawurldecode(httpget('newname'));
            $fromname = $session['user']['name'];
            $newname = change_player_ctitle($ntitle);
            $session['user']['ctitle'] = $ntitle;
            $session['user']['name'] = $newname;
            output("You are now known as %s!`0`n`n", $session['user']['name']);
            if (!$free) {
                $id = has_item("hunterslodge_customtitle");
                delete_item($id);
            }
            addnav("Return");
            addnav("Return to the Lodge", "runmodule.php?module=iitems_hunterslodge&op=start");
            break;
    }
    page_footer();
}
function hunterslodge_customrace_run()
{
    require_once "lib/sanitize.php";
    require_once "lib/names.php";
    global $session;
    $op = httpget("op");
    $free = httpget("free");
    page_header("Choose your Custom Race");
    switch ($op) {
        case "change":
            output("Want to change your Custom Race?  No problem.  Enter your desired race in the box below.  You've got 25 characters to play around with.`n(leave this blank to disable custom race naming and return to default, game-supplied race names)`n`n");
            rawoutput("<form action='runmodule.php?module=hunterslodge_customrace&op=confirm&free=" . $free . "' method='POST'>");
            $race = get_module_pref("customrace");
            rawoutput("<input id='input' name='newrace' width='25' maxlength='25' value='" . htmlentities($race, ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "'>");
            rawoutput("<input type='submit' class='button' value='Preview'>");
            rawoutput("</form>");
            addnav("", "runmodule.php?module=hunterslodge_customrace&op=confirm&free=" . $free);
            addnav("Cancel");
            addnav("Don't set a custom race, just go back to the Lodge", "runmodule.php?module=iitems_hunterslodge&op=start");
            break;
        case "confirm":
            $newrace = httppost("newrace");
            $sub = httpget("sub");
            $newrace = str_replace("`", "", $newrace);
            $newrace = comment_sanitize($newrace);
            $newrace = substr($newrace, 0, 25);
            if ($newrace) {
                output("Your new custom race is:`n%s`nWould you like to set your new Race now?`n`n", $newrace);
            } else {
                output("You've chosen to go back to the default, game-supplied races.  Are you sure that's what you want?`n`n");
            }
            addnav("Confirm");
            addnav("Set custom race", "runmodule.php?module=hunterslodge_customrace&op=set&free={$free}&newrace=" . rawurlencode($newrace));
            addnav("Cancel");
            addnav("Don't set a custom race, just go back to the Lodge", "runmodule.php?module=iitems_hunterslodge&op=start");
            break;
        case "set":
            $newrace = rawurldecode(httpget("newrace"));
            output("Your custom race has been set to %s!`n`n", $newrace);
            set_module_pref("customrace", $newrace);
            if (!$free) {
                $id = has_item("hunterslodge_customrace");
                delete_item($id);
            }
            addnav("Return");
            addnav("Return to the Lodge", "runmodule.php?module=iitems_hunterslodge&op=start");
            break;
    }
    page_footer();
}
function hunterslodge_healthinsurance_dohook($hookname, $args)
{
    global $session;
    switch ($hookname) {
        case "healmultiply":
            if ($session['user']['race'] != "Robot") {
                if (has_item("hunterslodge_healthinsurance")) {
                    redirect("runmodule.php?module=hunterslodge_healthinsurance");
                }
            }
            break;
    }
    return $args;
}
function giftbox_use($args)
{
    global $session;
    debug($args);
    $cname = get_item_pref("verbosename", $args['giftbox_contains']);
    output("`0You open up the box to find a %s!`0`n`n", $cname);
    if (get_item_pref("inventorylocation", $args['giftbox_contains']) == "lodgebag") {
        if (!has_item("lodgebag")) {
            give_item("lodgebag");
        }
    } else {
        clear_item_pref("inventorylocation", $args['giftbox_contains']);
    }
    change_item_owner($args['giftbox_contains'], $session['user']['acctid']);
    return $args;
}
function add_sc_to_book($scroll, $book, $login)
{
    // v has_item proveritsja
    //$scroll = preg_replace ('/[^a-z0-9_\.]/i', '', $scroll);
    //$book = preg_replace ('/[^a-z0-9_\.]/i', '', $book);
    //$login = preg_replace ('/[^a-z0-9_]/i', '', $login);
    include_once 'modules/f_has_item.php';
    if (!has_item($scroll, $login)) {
        put_g_error('у вас нету свитка');
    }
    if (!has_item($book, $login)) {
        put_g_error('у вас нету книги');
    }
    // tolqko esli estq navyk:
    $q = do_mysql("SELECT skills FROM players WHERE login = '******';");
    $skills = mysql_result($q, 0);
    $skills = explode('|', $skills);
    if (!$skills[30]) {
        put_g_error('у вас нету навыка');
    }
    // dobavim:
    $q = do_mysql("SELECT on_take FROM items WHERE fullname = '" . $book . "' AND type = 'b';");
    if (!mysql_num_rows($q)) {
        return 0;
    }
    $mlist = mysql_result($q, 0);
    $q = do_mysql("SELECT on_take FROM items WHERE type = 's' AND fullname = '" . $scroll . "';");
    if (!mysql_num_rows($q)) {
        return 0;
    }
    $spell = mysql_result($q, 0);
    if (strpos($mlist, $spell) !== false) {
        put_g_error('в этой книге уже есть это заклинание!');
    }
    if ($mlist) {
        $mlist .= '~' . $spell;
    } else {
        $mlist = $spell;
    }
    do_mysql("UPDATE items SET on_take = '" . $mlist . "' WHERE fullname = '" . $book . "';");
    // udalim svitok:
    include_once 'modules/f_delete_item.php';
    delete_item($scroll);
    return 1;
}
function staminafood_run()
{
    global $session;
    $pmeat1 = has_item_quantity("meat_low");
    $pmeat2 = has_item_quantity("meat_medium");
    $pmeat3 = has_item_quantity("meat_high");
    addnav("Eat");
    switch (httpget("op")) {
        case "sellmeat":
            switch ($session['user']['location']) {
                case "NewHome":
                    page_header("Joe's Diner");
                    if (httpget('q') == 1) {
                        delete_item(has_item("meat_medium"));
                        $session['user']['gold'] += 5;
                        output("With a surly grunt, Joe grabs your meat and slaps down five Requisition tokens.`n`n");
                    } else {
                        for ($i = 1; $i <= $pmeat2; $i++) {
                            delete_item(has_item("meat_medium"));
                            $session['user']['gold'] += 5;
                        }
                        output("With a surly grunt, Joe grabs your meat and slaps down %s Requisition tokens.`n`n", $pmeat2 * 5);
                    }
                    break;
                case "New Pittsburgh":
                    page_header("BRAAAAAINS");
                    if (httpget('q') == 1) {
                        delete_item(has_item("meat_medium"));
                        $session['user']['gold'] += 6;
                        output("With a nod, the waiter takes your meat and hands back six Requisition tokens.`n`n");
                    } else {
                        for ($i = 1; $i <= $pmeat2; $i++) {
                            delete_item(has_item("meat_medium"));
                            $session['user']['gold'] += 6;
                        }
                        output("With a nod, the waiter takes your meat and hands back %s Requisition tokens.`n`n", $pmeat2 * 6);
                    }
                    break;
                case "Kittania":
                    page_header("Cool Springs Cafe");
                    if (httpget('q') == 1) {
                        delete_item(has_item("meat_high"));
                        $session['user']['gold'] += 12;
                        output("With a warm smile, the waitress takes your meat and hands back twelve Requisition tokens.`n`n");
                    } else {
                        for ($i = 1; $i <= $pmeat3; $i++) {
                            delete_item(has_item("meat_high"));
                            $session['user']['gold'] += 12;
                        }
                        output("With a warm smile, the waitress takes your meat and hands back %s Requisition tokens.`n`n", $pmeat3 * 12);
                    }
                    break;
                case "Squat Hole":
                    page_header("Kebabs 'N' S***e");
                    if (httpget('q') == 1) {
                        delete_item(has_item("meat_low"));
                        $session['user']['gold'] += 2;
                        output("With a squeaky \"Ta mate,\" the Midget behind the counter relieves you of the stinking yellow meat and hands back two Requisition tokens.`n`n");
                    } else {
                        for ($i = 1; $i <= $pmeat1; $i++) {
                            delete_item(has_item("meat_low"));
                            $session['user']['gold'] += 2;
                        }
                        output("With a squeaky \"Ta mate,\" the Midget behind the counter relieves you of the stinking yellow meat and hands back %s Requisition tokens.`n`n", $pmeat1 * 2);
                    }
                    break;
            }
            break;
        case "start":
            switch (httpget("location")) {
                case "nh":
                    page_header("Joe's Diner");
                    output("`0You head into what presents itself as a 1950's-style diner.  Plastic red and white gingham patterns cover every available surface.  Tomato-shaped ketchup bottles are dotted on tables here and there, dried gunge crusting their nozzles.  Behind the bar can be seen Joe, the owner, who is keeping himself busy wiping down the counter tops with a rag, redistributing the half-inch-thick layer of grease into a more uniform level.  A sign above the counter reads \"`2WE BUY MEAT.  WE PAY 5 REQ PER 120 GRAM'S.`0\"`n`n");
                    if ($session['user']['race'] != "Robot") {
                        output("The smell of fried onions does its wicked work, and you glance up at the menu.`n`n");
                        if (get_module_pref("fullness") <= 100) {
                            if ($session['user']['gold'] >= 10) {
                                addnav("Crisps (10 Req)", "runmodule.php?module=staminafood&op=buy&bought=1");
                            } else {
                                output("After a careful read of the menu, you realise that you can't afford a single thing on it.  Bah.");
                            }
                            if ($session['user']['gold'] >= 40) {
                                addnav("Garden Salad (40 Req)", "runmodule.php?module=staminafood&op=buy&bought=2");
                            }
                            if ($session['user']['gold'] >= 50) {
                                addnav("Plate of Chips (50 Req)", "runmodule.php?module=staminafood&op=buy&bought=3");
                                addnav("Coffee (50 Req)", "runmodule.php?module=staminafood&op=buy&bought=4");
                            }
                            if ($session['user']['gold'] >= 150) {
                                addnav("Bangers & Mash (150 Req)", "runmodule.php?module=staminafood&op=buy&bought=5");
                            }
                            if ($session['user']['gold'] >= 300) {
                                addnav("Cheeseburger (300 Req)", "runmodule.php?module=staminafood&op=buy&bought=6");
                            }
                        } else {
                            output("You are far too full to eat any more today.`n`n");
                        }
                    }
                    if ($pmeat2) {
                        output("You remember that Maiko told you that the NewHome diner will only buy middling-quality meat.  You have %s pieces of average-quality meat to sell.  All of them, quite conveniently - perhaps a little TOO conveniently - weigh exactly a hundred and twenty grams each.`n`n", $pmeat2);
                        addnav("Sell Meat");
                        addnav("Sell one piece", "runmodule.php?module=staminafood&op=sellmeat&q=1");
                        if ($pmeat2 > 1) {
                            addnav("Sell all Meat", "runmodule.php?module=staminafood&op=sellmeat&q=all");
                        }
                    }
                    break;
                case "ki":
                    page_header("Cool Springs Cafe");
                    output("You head into what at first appears to be a little hut.  As you work down the stairs into the rock underneath Kittania, you realise that this place is so much more.`n`nStrings of fairy lights illuminate the cavern, and soft trickling sounds can be heard against the laughter and conversation of KittyMorphs around you.`n`nYou take a seat and a white-furred KittyMorph approaches, a menu in her hand.  \"Welcome to the Cool Springs Cafe,\" she says with a smile.  \"We try to tread on Mother Earth as lightly as we can, in here; all of our produce is locally-grown, you'll find a wonderful selection of vegetarian and vegan meals, and the various waters come from the three springs that run through this very cavern.  Now, what can I get you?\"`n`nYou peruse the menu, your eyes lingering on the last entry, detailing a rare, dripping, bloody steak.  The KittyMorph follows your gaze, and laughs sheepishly.  \"Like I said, we `itry`i,\" she giggles, elongated canines peeking out.  \"We `iare`i carnivores, you know.  Oh, on that note, I should mention that we also buy meat, if you've got any of the good stuff to sell.  We pay twelve Requisition per slice.\"`n`n");
                    if ($session['user']['race'] != "Robot") {
                        if (get_module_pref("fullness") <= 100) {
                            if ($session['user']['gold'] >= 50) {
                                addnav("Hot Chocolate (50 Req)", "runmodule.php?module=staminafood&op=buy&bought=7");
                                addnav("White Spring Water (50 Req)", "runmodule.php?module=staminafood&op=buy&bought=8");
                            } else {
                                output("After a careful read of the menu, you realise that you can't afford a single thing on it.  Bah.");
                            }
                            if ($session['user']['gold'] >= 100) {
                                addnav("Nut and Berry Salad (100 Req)", "runmodule.php?module=staminafood&op=buy&bought=9");
                            }
                            if ($session['user']['gold'] >= 175) {
                                addnav("Turquoise Spring Water (175 Req)", "runmodule.php?module=staminafood&op=buy&bought=10");
                            }
                            if ($session['user']['gold'] >= 250) {
                                addnav("Red Spring Water (250 Req)", "runmodule.php?module=staminafood&op=buy&bought=11");
                            }
                            if ($session['user']['gold'] >= 500) {
                                addnav("Still-Twitching Steak (500 Req)", "runmodule.php?module=staminafood&op=buy&bought=12");
                            }
                        } else {
                            output("You are far too full to eat any more today.`n`n");
                        }
                    }
                    if ($pmeat3) {
                        output("You remember that Maiko told you that the Kittania cafe will only buy the best-quality meat.  You have %s pieces of high-quality meat to sell.`n`n", $pmeat3);
                        addnav("Sell Meat");
                        addnav("Sell one piece", "runmodule.php?module=staminafood&op=sellmeat&q=1");
                        if ($pmeat3 > 1) {
                            addnav("Sell all Meat", "runmodule.php?module=staminafood&op=sellmeat&q=all");
                        }
                    }
                    break;
                case "np":
                    page_header("BRAAAAAINS");
                    output("You head into the local cafe, imaginatively titled \"BRAAAAAINS\".  A waiter comes shuffling over to you, green skin peeling from his face.  \"BRAAAAAINS?\" he asks, holding out a menu.`n`nA sign above the counter says \"We are only too happy to buy your surplus meat.  We pay 6 Requisition tokens per 120 grams.\"`n`n");
                    if ($session['user']['race'] != "Robot") {
                        if (get_module_pref("fullness") <= 100) {
                            if ($session['user']['gold'] >= 50) {
                                addnav("Egg and Brains (50 Req)", "runmodule.php?module=staminafood&op=buy&bought=13");
                            } else {
                                output("After a careful read of the menu, you realise that you can't afford a single thing on it.  Bah.");
                            }
                            if ($session['user']['gold'] >= 100) {
                                addnav("Sausage and Brains (100 Req)", "runmodule.php?module=staminafood&op=buy&bought=14");
                            }
                            if ($session['user']['gold'] >= 150) {
                                addnav("Spam and Brains (150 Req)", "runmodule.php?module=staminafood&op=buy&bought=15");
                            }
                            if ($session['user']['gold'] >= 200) {
                                addnav("Egg, Brains, Sausage and Brains (200 Req)", "runmodule.php?module=staminafood&op=buy&bought=16");
                            }
                            if ($session['user']['gold'] >= 250) {
                                addnav("Brains, Spam, Brains, Sausage and Brains (250 Req)", "runmodule.php?module=staminafood&op=buy&bought=17");
                            }
                            if ($session['user']['gold'] >= 300) {
                                addnav("Brains, Brains, Brains, Brains and Spam (300 Req)", "runmodule.php?module=staminafood&op=buy&bought=18");
                            }
                        } else {
                            output("You are far too full to eat any more today.`n`n");
                        }
                    }
                    if ($pmeat2) {
                        output("You remember that Maiko told you that the New Pittsburgh diner will only buy middling-quality meat.  You have %s pieces of average-quality meat to sell.  All of them, quite conveniently - perhaps a little TOO conveniently - weigh a hundred and twenty grams each.`n`n", $pmeat2);
                        addnav("Sell Meat");
                        addnav("Sell one piece", "runmodule.php?module=staminafood&op=sellmeat&q=1");
                        if ($pmeat2 > 1) {
                            addnav("Sell all Meat", "runmodule.php?module=staminafood&op=sellmeat&q=all");
                        }
                    }
                    break;
                case "sq":
                    page_header("Kebabs 'N' S***e");
                    output("You head into the local kebab house.  As you're studying the menu, a Midget brushes past you, dragging a six-foot blue plastic bag with the words \"INCINERATE ONLY\" stencilled on the side.  He stops, glares up at you, and mutters \"Yer din't see `inuffink.`i\"  Then he resumes his journey, dragging the bag into the back of the shop.  You're sure you saw a bit of steering wheel poking out.`n`nA sign above the counter reads \"WE BY MEET 2 REK PER BIT\"`n`n");
                    if ($session['user']['race'] != "Robot") {
                        if (get_module_pref("fullness") <= 100) {
                            if ($session['user']['gold'] >= 20) {
                                addnav("Crisps (20 Req)", "runmodule.php?module=staminafood&op=buy&bought=25");
                            } else {
                                output("After a careful read of the menu, you realise that you can't afford a single thing on it.  Bah.");
                            }
                            if ($session['user']['gold'] >= 50) {
                                addnav("Skinheads on a Raft (50 Req)", "runmodule.php?module=staminafood&op=buy&bought=26");
                            }
                            if ($session['user']['gold'] >= 75) {
                                addnav("Doner Kebab (75 Req)", "runmodule.php?module=staminafood&op=buy&bought=27");
                                addnav("Crimson Pitbull (75 Req)", "runmodule.php?module=staminafood&op=buy&bought=28");
                            }
                            if ($session['user']['gold'] >= 150) {
                                addnav("C**k Nuggets (150 Req)", "runmodule.php?module=staminafood&op=buy&bought=29");
                            }
                            if ($session['user']['gold'] >= 200) {
                                addnav("Sausage Feast Pizza (200 Req)", "runmodule.php?module=staminafood&op=buy&bought=30");
                            }
                        } else {
                            output("You are far too full to eat any more today.`n`n");
                        }
                    }
                    if ($pmeat1) {
                        output("You remember that Maiko told you that the Squat Hole kebab shop only buys the sort of meat that the dog food factory would throw away.  You have %s wobbling chunks of Crap Meat to sell.`n`n", $pmeat1);
                        addnav("Sell Meat");
                        addnav("Sell one piece", "runmodule.php?module=staminafood&op=sellmeat&q=1");
                        if ($pmeat1 > 1) {
                            addnav("Sell all Meat", "runmodule.php?module=staminafood&op=sellmeat&q=all");
                        }
                    }
                    break;
                case "pl":
                    page_header("Mutated Munchies");
                    if ($session['user']['race'] != "Robot") {
                        output("You head into the local cafe.  The stench of vomit and disinfectant hangs in the air.  Bravely, you sit down at a table and peruse the menu.`n`n");
                        if (get_module_pref("fullness") <= 100) {
                            if ($session['user']['gold'] >= 100) {
                                addnav("Wriggly Biscuits (100 Req)", "runmodule.php?module=staminafood&op=buy&bought=19");
                            } else {
                                output("After a careful read of the menu, you realise that you can't afford a single thing on it.  Bah.");
                            }
                            if ($session['user']['gold'] >= 200) {
                                addnav("Phallic Nuts (200 Req)", "runmodule.php?module=staminafood&op=buy&bought=20");
                            }
                            if ($session['user']['gold'] >= 300) {
                                addnav("Noodly Noodles (300 Req)", "runmodule.php?module=staminafood&op=buy&bought=21");
                            }
                            if ($session['user']['gold'] >= 400) {
                                addnav("Three-Eyed Fish (400 Req)", "runmodule.php?module=staminafood&op=buy&bought=22");
                            }
                            if ($session['user']['gold'] >= 500) {
                                addnav("Magical Mystery Meatloaf (500 Req)", "runmodule.php?module=staminafood&op=buy&bought=23");
                            }
                            if ($session['user']['gold'] >= 750) {
                                addnav("Mutant Steak (750 Req)", "runmodule.php?module=staminafood&op=buy&bought=24");
                            }
                        } else {
                            output("You are far too full to eat any more today.`n`n");
                        }
                    } else {
                        output("You are a robot, and this place doesn't buy meat.  You have no business here.  Out with you!`n`n");
                    }
                    break;
            }
            break;
        case "buy":
            page_header("Om nom nom");
            require_once "modules/staminasystem/lib/lib.php";
            switch (httpget("bought")) {
                case 1:
                    output("You munch happily on your crisps, reflecting that they're probably not too good for you - but hell, at least they're cheap.`n`nYou gain some Stamina!");
                    $st = 5000;
                    $nu = 5;
                    $fa = 10;
                    $fu = 5;
                    $co = 10;
                    break;
                case 2:
                    output("You pick the snails out of your Garden Salad, and tuck in.`n`nYou gain some Stamina!");
                    $st = 18000;
                    $nu = 15;
                    $fa = 0;
                    $fu = 10;
                    $co = 40;
                    break;
                case 3:
                    output("You wolf down your plate of chips.  They're like little brown paper bags filled with pus, but damn it, you paid good money for these and you're going to eat them come Hell or high water.`n`nYou gain some Stamina!");
                    $st = 25000;
                    $nu = 20;
                    $fa = 30;
                    $fu = 25;
                    $co = 50;
                    break;
                case 4:
                    output("The coffee swirls grittily down your throat.  You feel like you have more energy!");
                    apply_stamina_buff('newhomedinercoffee', array("name" => "Caffeine Rush", "action" => "Global", "costmod" => 0.8, "expmod" => 1, "rounds" => 20, "roundmsg" => "Your Caffeine Rush makes everything a little bit easier!", "wearoffmsg" => "The effects of the caffeine seem to have worn off."));
                    $co = 50;
                    break;
                case 5:
                    output("It's not so much Bangers and Mash as Mingers and Mush, but you get stuck in anyway.`n`nYou gain some Stamina!");
                    $st = 105000;
                    $nu = 40;
                    $fa = 30;
                    $fu = 40;
                    $co = 150;
                    break;
                case 6:
                    output("You can has cheeseburger!  Well, it's not so much \"cheese\" as \"unidentifiable bright orange goo\", but I'm sure you'll live.`n`nYou gain some Stamina!");
                    $st = 225000;
                    $nu = 60;
                    $fa = 40;
                    $fu = 25;
                    $co = 300;
                    break;
                case 7:
                    output("You sip your hot chocolate, listening to the babbling brooks.  Life ain't so bad.`n`nYou gain some Stamina!");
                    $st = 25000;
                    $nu = 10;
                    $fa = 10;
                    $fu = 15;
                    $co = 50;
                    break;
                case 8:
                    output("There's something very odd about the water from the White Spring.  You feel light on your feet.  It seems to make everything easier, somehow.");
                    apply_stamina_buff('whitespringwater', array("name" => "White Spring Lightness", "action" => "Global", "costmod" => 0.8, "expmod" => 1, "rounds" => 20, "roundmsg" => "The waters of the White Spring seem to be making everything a little easier.", "wearoffmsg" => "The White Spring effects seem to have worn off."));
                    $co = 50;
                    break;
                case 9:
                    output("You scarf down your salad of nuts and berries, secretly wishing for a nice juicy steak.`n`nYou gain some Stamina!");
                    $st = 65000;
                    $nu = 25;
                    $fa = 5;
                    $fu = 10;
                    $co = 100;
                    break;
                case 10:
                    output("The water from the Turquoise Spring is served at room temperature, but somehow tastes very cold.  After a few moments, your eyesight improves; you can make out individual facets of a crystal buried in the far wall of the cavern.  This should make it a bit easier to hunt down monsters!");
                    apply_stamina_buff('turquoisespringwater', array("name" => "Turquoise Sight", "class" => "Hunting", "costmod" => 0.5, "expmod" => 1, "rounds" => 3, "roundmsg" => "Thanks to your heightened senses granted by the waters of the Turquoise Spring, hunting for monsters seems a lot easier now.", "wearoffmsg" => "The effects of the Turquoise Spring water have worn off, and your senses return to their usual state."));
                    $co = 175;
                    break;
                case 11:
                    output("You down the water from the Red Spring.  There's a distinct taste of iron in there.  After a few moments, you become anxious - surely there must be something around here that you can engage in combat...");
                    apply_stamina_buff('redspringwater', array("name" => "Red Haze", "class" => "Combat", "costmod" => 0.5, "expmod" => 1, "rounds" => 20, "roundmsg" => "The waters of the Red Spring make fighting seem more natural and fluid.  You're not expending nearly as much Stamina as usual.", "wearoffmsg" => "The effects of the Red Spring water have worn off, and your senses return to their natural state."));
                    $co = 250;
                    break;
                case 12:
                    output("The menu described a still-twitching steak, and boy, it delivered.  Steam rises from the plate of raw muscle in front of you.  The meat jerks and spasms as it reacts to the sudden flood of oxygen, slapping gently against the plate.  Your mouth waters, and you can see some nearby KittyMorphs glancing jealously in your direction.  You wolf it down before they get any ideas.`n`nYou gain some Stamina!");
                    $st = 385000;
                    $nu = 100;
                    $fa = 10;
                    $fu = 80;
                    $co = 500;
                    break;
                case 13:
                    output("You scarf down your braaaaainy meal, hoping that there will be no complications from the frankly ridiculous amounts of braaaaains that you're eating.`n`nYou gain some Stamina!");
                    $st = 25000;
                    $nu = 10;
                    $fa = 10;
                    $fu = 10;
                    $co = 50;
                    break;
                case 14:
                    output("You scarf down your braaaaainy meal, hoping that there will be no complications from the frankly ridiculous amounts of braaaaains that you're eating.`n`nYou gain some Stamina!");
                    $st = 65000;
                    $nu = 20;
                    $fa = 20;
                    $fu = 20;
                    $co = 100;
                    break;
                case 15:
                    output("You scarf down your braaaaainy meal, hoping that there will be no complications from the frankly ridiculous amounts of braaaaains that you're eating.`n`nYou gain some Stamina!");
                    $st = 105000;
                    $nu = 30;
                    $fa = 30;
                    $fu = 30;
                    $co = 150;
                    break;
                case 16:
                    output("You scarf down your braaaaainy meal, hoping that there will be no complications from the frankly ridiculous amounts of braaaaains that you're eating.`n`nYou gain some Stamina!");
                    $st = 145000;
                    $nu = 40;
                    $fa = 40;
                    $fu = 40;
                    $co = 200;
                    break;
                case 17:
                    output("You scarf down your braaaaainy meal, hoping that there will be no complications from the frankly ridiculous amounts of braaaaains that you're eating.`n`nYou gain some Stamina!");
                    $st = 185000;
                    $nu = 50;
                    $fa = 50;
                    $fu = 50;
                    $co = 250;
                    break;
                case 18:
                    output("You scarf down your braaaaainy meal, hoping that there will be no complications from the frankly ridiculous amounts of braaaaains that you're eating.`n`nYou gain some Stamina!");
                    $st = 225000;
                    $nu = 60;
                    $fa = 60;
                    $fu = 60;
                    $co = 300;
                    break;
                case 19:
                    output("You chew thoughtfully on your Wriggly Biscuits.  They live up to their name quite adequately.`n`nYou gain some Stamina!");
                    $st = 65000;
                    $nu = 20;
                    $fa = 10;
                    $fu = 10;
                    $co = 100;
                    break;
                case 20:
                    output("You run your tongue lovingly up, down and around the extremely phallic nuts, savouring their delightfully salty flavour.`n`nYou gain some Stamina!");
                    $st = 145000;
                    $nu = 40;
                    $fa = 10;
                    $fu = 20;
                    $co = 200;
                    break;
                case 21:
                    output("The Noodly Noodles jerk and spasm, each bite releasing a sticky yellow goo.  Tasty!`n`nYou gain some Stamina!");
                    $st = 225000;
                    $nu = 40;
                    $fa = 10;
                    $fu = 20;
                    $co = 300;
                    break;
                case 22:
                    output("You stare down at your three-eyed fish.  It stares back up at you, in ways that you can only imagine.  After a few moments of depressed contemplation, you tuck in - and hey, it's actually not that bad.`n`nYou gain some Stamina!");
                    $st = 305000;
                    $nu = 50;
                    $fa = 25;
                    $fu = 40;
                    $co = 400;
                    break;
                case 23:
                    output("As your fork sinks into your Magical Mystery Meatloaf, a hundred pairs of eyes open on its crispy skin.  They close again almost instantly, and you try your hardest to persuade yourself that you were hallucinating from the disinfectant fumes - it beats reality, that's for damn sure.`n`nYou gain some Stamina!");
                    $st = 385000;
                    $nu = 50;
                    $fa = 25;
                    $fu = 50;
                    $co = 500;
                    break;
                case 24:
                    output("The Mutant Steak is lean, delicious, nutritious and as big as your head!  What a pleasant surprise!`n`nYou gain some Stamina!");
                    $st = 585000;
                    $nu = 150;
                    $fa = 10;
                    $fu = 80;
                    $co = 750;
                    break;
                case 25:
                    output("You grimace, and call over to the midget behind the counter.  \"These taste like someone tried to make bacon flavour crisps and failed, badly.\"`n`n\"Read the fookin' packet, dick'ead!\"`n`nYou do as he says.  Ah.  Tumour flavour.  Nice.`n`nYou gain some Stamina!");
                    $st = 10000;
                    $nu = 5;
                    $fa = 10;
                    $fu = 5;
                    $co = 20;
                    break;
                case 26:
                    output("Skinheads on a Raft turned out to be beans on toast.  You're not sure whether to be relieved.`n`nYou gain some Stamina!");
                    $st = 25000;
                    $nu = 20;
                    $fa = 20;
                    $fu = 15;
                    $co = 50;
                    break;
                case 27:
                    //Potential for expansion: have the kebab taste better if the player's drunk, have the player find a wedding ring that he can sell for Req, etc.
                    output("You scarf down your doner kebab, stopping occasionally to pick out the occasional toenail or piece of car dashboard.  It's pretty fatty, and would taste a lot better if you were drunk, but you make do.`n`nYou gain some Stamina!");
                    $st = 65000;
                    $nu = 20;
                    $fa = 40;
                    $fu = 20;
                    $co = 75;
                    break;
                case 28:
                    output("You knock back your Crimson Pitbull, which turned out to be some sort of energy drink.`n`nYou feel aggressive!");
                    apply_stamina_buff('crimsonpitbull', array("name" => "Bark of the Crimson Pitbull", "class" => "Combat", "costmod" => 0.5, "expmod" => 1, "rounds" => 20, "roundmsg" => "The harsh, chemically-sweet taste of the Crimson Pitbull lurks in the back of your throat.  You're not expending nearly as much Stamina as usual.", "wearoffmsg" => "The effects of the Crimson Pitbull have worn off, and your senses return to their natural state."));
                    $co = 75;
                    break;
                case 29:
                    output("C**k Nuggets turned out to be chicken nuggets, only with a little more fowl language.`n`n...`n`n...sorry.`n`nYou gain some Stamina!");
                    $st = 145000;
                    $nu = 30;
                    $fa = 60;
                    $fu = 25;
                    $co = 150;
                    break;
                case 30:
                    output("The Sausage Feast turned out to be less sausage, and more fat, but hey, it's cheap and it tastes halfway decent.`n`nYou gain some Stamina!");
                    $st = 185000;
                    $nu = 40;
                    $fa = 80;
                    $fu = 50;
                    $co = 200;
                    break;
            }
            addstamina($st);
            increment_module_pref("nutrition", $nu);
            increment_module_pref("fat", $fa);
            increment_module_pref("fullness", $fu);
            $full = get_module_pref("fullness");
            if ($full < 0) {
                output("`n`nYou still feel as though you haven't eaten in days.");
            }
            if ($full >= 0 && $full < 50) {
                output("`n`nYou feel a little less hungry.");
            }
            if ($full >= 50 && $full < 100) {
                output("`n`nYou still feel as though you've got room for more!");
            }
            if ($full >= 100) {
                output("`n`nYou're stuffed!  You feel as though you can't possibly eat anything more today.");
            }
            $session['user']['gold'] -= $co;
            break;
    }
    debug(get_module_pref("fat"));
    debug(get_module_pref("nutrition"));
    addnav("Exit");
    addnav("Return to the Outpost", "village.php");
    page_footer();
}
function eboy_run()
{
    global $session, $inventory;
    if (!isset($inventory)) {
        load_inventory();
    }
    page_header("eBoy's Trading Station");
    addnav("Buy Items");
    addnav("Sell Items");
    require_once "modules/cityprefs/lib.php";
    $cid = get_cityprefs_cityid("location", $session['user']['location']);
    $item = httpget('item');
    if ($item) {
        $curstock = get_item_setting("eboy_stock_" . $cid, $item);
        $curprice = get_item_setting("eboy_price_" . $cid, $item);
    }
    eboy_updateprices();
    $eboy_info = get_items_with_settings("eboy");
    if (httpget('op') == "start") {
        output("Already fearing the worst, you head into eBoy's Trading Station.`n`nYour fears are well-founded.  The place is packed with the heaving, sweaty bodies of the hardcore capitalist, shouting \"`iBuy, buy!`i\" and \"`iSell, sell!`i\" and \"`iPut down the chainsaw and let's talk about this!`i\"`n`neBoy himself - although you suspect that this place, like Mike's Chop Shop, is a franchise of which you'll find one in every outpost, so is his name really eBoy?  Whoever he is, he stands on an elevated section of floor behind a tall mahogany counter, grabbing money with one hand and tossing grenades and ration packs over his shoulder with the other.  His arms are a blur.  His speech is the unintelligible, rapid-fire gabble of a professional auctioneer.  His eyes bulge and swivel.  You know he's loving this.`n`n");
    }
    if (httpget('op') == "buy") {
        $pprice = httpget('price');
        if ($pprice == $curprice) {
            if ($curstock > 0) {
                give_item($item);
                $session['user']['gold'] -= $curprice;
                increment_item_setting("eboy_stock_" . $cid, -1, $item);
                output("You fight your way to the front of the crowd and shout your order up to eBoy, slapping your Requisition tokens down on the counter.  Before you can blink, your money is gone and the item you desired sits in its place.  You grab it hastily and stuff it into your backpack as eBoy turns to deal with the next customer.`n`n");
            } else {
                output("eBoy turns to you and gibbers.`n`n\"Sorrymatejustsoldthelastoneyougottabefasteritsthequickandthedeadaroundherepal.\"  He turns to the next customer in line, leaving you trying to piece together whatever it is that he just said.`n`n");
            }
        } else {
            output("You fight your way to the front of the crowd and shout your order up to eBoy, slapping your Requisition tokens down on the counter.  eBoy turns to you and gibbers.`n`n\"Idontmeantobefunnymatebutlookattheboardthepricehasjustbloodychangedagainyousureyoustillwannabuy?\"  After giving you exactly one microsecond to consider what the hell he just asked, he rolls his eyes and turns to the next customer in line.`n`n");
        }
    }
    if (httpget('op') == "sell") {
        $pprice = httpget('price');
        $requiredprefs = array("inventorylocation" => "main");
        $itemid = has_item($item, $requiredprefs);
        if ($pprice == $curprice) {
            delete_item($itemid);
            if ($curstock < 3) {
                $buy = round($curprice * 0.5);
            } else {
                $buy = round($curprice * 0.7);
            }
            $session['user']['gold'] += $buy;
            increment_item_setting("eboy_stock_" . $cid, 1, $item);
            output("You barge your way through the crowd like a battleship through an ice floe, and toss your item up to eBoy.  eBoy snatches the item out of the air with his left hand while tossing your Requisition tokens back at you with his right, and goes on to serve the next customer.`n`n");
        } else {
            output("You fight your way to the front of the crowd and shout your order up to eBoy, slapping your Requisition tokens down on the counter.  eBoy turns to you and gibbers.`n`n\"Idontmeatobefunnymatebutlookattheboardthepricehasjustbloodychangedagainyousureyoustillwannasell?\"  After giving you exactly one microsecond to consider what the hell he just asked, he rolls his eyes and turns to the next customer in line.`n`n");
        }
    }
    output("You look up above eBoy's head at the trading board, the values of each commodity displayed on a mechanical readout which clatters and changes constantly.`n`n");
    $sellable_inventory = array();
    foreach ($inventory as $itemid => $prefs) {
        if (!$prefs['carrieritem'] && $prefs['eboy'] && $prefs['inventorylocation'] == "main") {
            $sellable_inventory[$prefs['item']]['quantity'] += 1;
            $sellable_inventory[$prefs['item']]['itemids'][] = $itemid;
        }
    }
    eboy_updateprices();
    $eboy_info = get_items_with_settings("eboy");
    //inventory-type display routine
    rawoutput("<table width=100% style='border: dotted 1px #000000;'>");
    $classcount = 1;
    foreach ($eboy_info as $item => $settings) {
        if ($settings['eboy_stock_' . $cid] > 0) {
            $stock = number_format($settings['eboy_stock_' . $cid]) . " available";
        } else {
            $stock = "`4Sold Out`0";
        }
        $classcount++;
        $class = $classcount % 2 ? "trdark" : "trlight";
        rawoutput("<tr class='{$class}'><td>");
        if ($settings['image']) {
            rawoutput("<table width=100% cellpadding=0 cellspacing=0><tr><td width=100px align=center><img src=\"images/items/" . $settings['image'] . "\"></td><td>");
        }
        output("`b%s`b`n", stripslashes($settings['verbosename']));
        output("%s`n", stripslashes($settings['description']));
        if ($settings['weight']) {
            output("Weight: %s kg`n", $settings['weight']);
        }
        rawoutput("<table width=100%><tr><td width=50%>");
        output("`bStock:`b %s", $stock);
        if ($settings['eboy_stock_' . $cid] < 3) {
            $buy = round($settings['eboy_price_' . $cid] * 0.5);
        } else {
            $buy = round($settings['eboy_price_' . $cid] * 0.7);
        }
        if ($settings['eboy_price_' . $cid] > 0) {
            output("`n`7Buying at: %s Requisition", number_format($buy));
        } else {
            output("`nNot Buying");
        }
        if ($settings['eboy_stock_' . $cid] > 0) {
            output("`n`2Selling at: %s Requisition`n`n", number_format($settings['eboy_price_' . $cid]));
        } else {
            output("`n`n");
        }
        rawoutput("</td><td width=50%>");
        $requiredprefs = array("inventorylocation" => "main");
        if ($sellable_inventory[$item]) {
            addnav("Sell Items");
            if ($settings['eboy_stock_' . $cid] < 3) {
                $buy = round($settings['eboy_price_' . $cid] * 0.5);
            } else {
                $buy = round($settings['eboy_price_' . $cid] * 0.7);
            }
            if ($sellable_inventory[$item]['quantity'] > 0 && $settings['eboy_price_' . $cid] > 0) {
                addnav(array("%s (%s available)", $settings['verbosename'], $sellable_inventory[$item]['quantity']), "runmodule.php?module=eboy&op=sell&item=" . $item . "&price=" . $settings['eboy_price_' . $cid], true);
                addnav("", "runmodule.php?module=eboy&op=sell&item=" . $item . "&price=" . $settings['eboy_price_' . $cid]);
                rawoutput("<a href=\"runmodule.php?module=eboy&op=sell&item=" . $item . "&price=" . $settings['eboy_price_' . $cid] . "\">Sell for <strong>" . number_format($buy) . " </strong> Requisition (" . $sellable_inventory[$item]['quantity'] . " available to sell)</a><br />");
            }
        } else {
            output("`&You don't have any of this item to sell.`0`n");
        }
        if ($session['user']['gold'] >= $settings['eboy_price_' . $cid] && $settings['eboy_stock_' . $cid]) {
            addnav("Buy Items");
            addnav(array("%s (%s Req)", $settings['verbosename'], $settings['eboy_price_' . $cid]), "runmodule.php?module=eboy&op=buy&item=" . $item . "&price=" . $settings['eboy_price_' . $cid], true);
            addnav("", "runmodule.php?module=eboy&op=buy&item=" . $item . "&price=" . $settings['eboy_price_' . $cid]);
            rawoutput("<a href=\"runmodule.php?module=eboy&op=buy&item=" . $item . "&price=" . $settings['eboy_price_' . $cid] . "\">Buy for <strong>" . number_format($settings['eboy_price_' . $cid]) . "</strong> Requisition</a><br />");
        } else {
            if (!$settings['eboy_stock_' . $cid]) {
                output("`&There are no items of this type available.`0`n");
            } else {
                $difference = $settings['eboy_price_' . $cid] - $session['user']['gold'];
                output("`&You need another %s Requisition to buy this item.`0`n", number_format($difference));
            }
        }
        rawoutput("</td></tr></table>");
        if ($settings['image']) {
            rawoutput("</td></tr></table>");
        }
        rawoutput("</td></tr>");
    }
    rawoutput("</td></tr></table>");
    addnav("Leave");
    addnav("Return to the Outpost", "village.php");
    addnav("Inventory");
    addnav("View your Inventory", "inventory.php?items_context=eboy");
    //set_module_objpref("city",$cid,"eboytrades-intelligent",serialize($info));
    page_footer();
    return true;
}
function hunterslodge_customarmour_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 Custom Armour");
    switch ($op) {
        case "change":
            output("Want to change your Custom Armour?  No problem.  Enter your desired armour in the box below.  You've got 25 characters to play around with.`n(leave this blank to disable custom armour naming and return to default, game-supplied armour names)`n`n");
            rawoutput("<form action='runmodule.php?module=hunterslodge_customarmour&op=confirm&free={$free}&context={$context}' method='POST'>");
            $armour = get_module_pref("customarmour");
            rawoutput("<input id='input' name='newarmour' width='25' maxlength='25' value='" . htmlentities($armour, ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "'>");
            rawoutput("<input type='submit' class='button' value='Preview'>");
            rawoutput("</form>");
            addnav("", "runmodule.php?module=hunterslodge_customarmour&op=confirm&free={$free}&context={$context}");
            addnav("Cancel");
            addnav("Don't set custom armour, just go back to where I came from", $backlink);
            break;
        case "confirm":
            $newarmour = httppost("newarmour");
            $sub = httpget("sub");
            $newarmour = str_replace("`", "", $newarmour);
            $newarmour = comment_sanitize($newarmour);
            $newarmour = substr($newarmour, 0, 25);
            if ($newarmour) {
                output("Your new custom armour is:`n%s`nWould you like to set your new armour now?`n`n", $newarmour);
            } else {
                output("You've chosen to go back to the default, game-supplied armours.  Are you sure that's what you want?`n`n");
            }
            addnav("Confirm");
            addnav("Set custom armour", "runmodule.php?module=hunterslodge_customarmour&op=set&free={$free}&context={$context}&newarmour=" . rawurlencode($newarmour));
            addnav("Cancel");
            addnav("Don't set custom armour, just go back to where I came from", $backlink);
            break;
        case "set":
            $newarmour = rawurldecode(httpget("newarmour"));
            if ($newarmour == "") {
                output("Your custom armour name has been removed.  The next time you change your armour, you'll return to game-supplied armour names.`n`n");
            } else {
                output("Your custom armour has been set to %s!`n`n", $newarmour);
                $session['user']['armor'] = $newarmour;
            }
            set_module_pref("customarmour", $newarmour);
            if (!$free) {
                require_once "modules/iitems/lib/lib.php";
                $id = has_item("hunterslodge_customarmour");
                delete_item($id);
            }
            addnav("Return");
            addnav("Return to where I came from", $backlink);
            break;
    }
    page_footer();
}
<?php 
// zheltyj kamenq, prevrashjaet rybu v fosfor
if (!isset($_GET['part'])) {
    // vyberaem chto prevratitq v fosfor, ato somov vsjakih zhalko budet
    include_once 'modules/f_list_inventory.php';
    $f .= '<b>выберите рыбу, какую не жалко:</b><br/>';
    $f .= list_inventory($LOGIN, 'i.f.foo.fish_', 'use_stand&item=' . $item . '&part=2');
    exit_msg('желтый камень', $f);
} else {
    $to = mysql_real_escape_string(strip_tags($_GET['to']));
    if (substr($to, 0, 12) != 'i.f.foo.fish') {
        put_g_error('ты та что суешь?');
    }
    include_once 'modules/f_has_item.php';
    if (!has_item($to, $LOGIN)) {
        put_g_error('а где рыба?');
    }
    // udaljaem syrqe
    include_once 'modules/f_delete_item.php';
    delete_item($to);
    include_once 'modules/f_gain_item.php';
    gain_item('i.q.que.alch.fosfor', 1, $LOGIN);
}
<?php

if (has_item("toolbox_decorating") || has_item("toolbox_carpentry") || has_item("toolbox_masonry")) {
    output("You look around for your tools, but find none.  Suzie's staff must taken them back during the night.`n`n");
    delete_all_items_of_type("toolbox_decorating");
    delete_all_items_of_type("toolbox_carpentry");
    delete_all_items_of_type("toolbox_masonry");
}
Ejemplo n.º 14
0
<?php 
// fail ispolqzovanija veshej
// tolqko perebiraet tipy i podkljuchjaet drgie nuzhnye faily
$item = preg_replace('/[^a-z0-9_\\.]/i', '', $_GET['item']);
$t = substr($item, 2, 1);
include_once 'modules/f_has_item.php';
include_once 'modules/f_get_it_name.php';
$itname = get_it_name($item);
// infa veshi
//$ii = get_it_info ($item);
if (has_item($item, $LOGIN) == 0) {
    put_g_error('у вас нету этой веши');
}
// handler )
// stranica
switch ($t) {
    case 'w':
        include 'modules/sp/sp_use_weapon.php';
        break;
    case 'a':
        include 'modules/sp/sp_use_armor.php';
        break;
    case 'f':
        include 'modules/sp/sp_use_food.php';
        break;
    case 's':
        include 'modules/sp/sp_use_scroll.php';
        break;
    case 'b':
        include 'modules/sp/sp_use_book.php';
        break;
function improbablehousing_show_build_jobs($house)
{
    //run through the build jobs and show percentage to completion, along with navs to use the relevant item and its associated Stamina cost.
    //For easyness, don't allow the player to build if they're in Amber stamina
    $jobs = $house['data']['buildjobs'];
    require_once "modules/staminasystem/lib/lib.php";
    $storestock = $house['data']['store'];
    $displayjobs = array();
    if (count($jobs)) {
        foreach ($jobs as $key => $vals) {
            if (!isset($displayjobs[$vals['name']])) {
                addnav(array("%s", $vals['name']));
                foreach ($vals['jobs'] as $skey => $svals) {
                    $cando = 1;
                    $displayjobs[$vals['name']][$svals['name']]['req'] = $svals['req'];
                    $displayjobs[$vals['name']][$svals['name']]['done'] = $svals['done'];
                    //check completion
                    if ($svals['completed']) {
                        $cando = 0;
                    }
                    //Check Stamina
                    if (get_stamina() < 100) {
                        $cando = 0;
                        $nostam = 1;
                        $displayjobs[$vals['name']][$svals['name']]['nostamina'] = true;
                    }
                    $store = array();
                    $player = array();
                    foreach ($svals['iitems'] as $ikey => $iitem) {
                        $store[$ikey] = $house['data']['store'][$ikey];
                        if (has_item($ikey)) {
                            $player[$ikey] = 1;
                        }
                    }
                    //check that each item required is present in either the store or the player's inventory... this could be neater...
                    $svals['useplayer'] = true;
                    foreach ($svals['iitems'] as $ikey => $iitem) {
                        if (!$store[$ikey] && !$player[$ikey]) {
                            $cando = 0;
                            $displayjobs[$vals['name']][$svals['name']]['noitem'] = true;
                        }
                        if ($store[$ikey] > 0) {
                            $svals['usestore'] = true;
                        }
                        if (!$player[$ikey]) {
                            $svals['useplayer'] = false;
                        }
                    }
                    // debug($store);
                    // debug($player);
                    if ($cando) {
                        $scost = 0;
                        foreach ($svals['actions'] as $akey => $action) {
                            $scost += stamina_getdisplaycost($akey);
                        }
                        if ($svals['useplayer']) {
                            addnav(array("%s (`Q%s%%`0)", $svals['name'], $scost), "runmodule.php?module=improbablehousing&op=build&hid=" . $house['id'] . "&job=" . $key . "&subjob=" . $skey);
                        }
                        if ($svals['usestore']) {
                            addnav(array("%s (using store) (`Q%s%%`0)", $svals['name'], $scost), "runmodule.php?module=improbablehousing&op=build&hid=" . $house['id'] . "&job=" . $key . "&subjob=" . $skey . "&store=true");
                        }
                    }
                }
            }
        }
    }
    if (count($displayjobs)) {
        output("`b`0Current Construction Jobs`b`n");
        foreach ($displayjobs as $job => $sub) {
            output_notl("`0->%s`n", $job);
            foreach ($sub as $sjob => $vals) {
                $jobout = "<table><tr><td>";
                require_once "lib/bars.php";
                $bar = fadebar($vals['done'], $vals['req']);
                if ($vals['completed']) {
                    $jobout .= "-->" . $sjob . " </td><td>" . $bar . "</td> ";
                } else {
                    $jobout .= "-->" . $sjob . " </td><td>" . $bar . "</td><td> " . $vals['done'] . "/" . $vals['req'] . " ";
                    if ($vals['nostamina']) {
                        $jobout .= "(you don't have enough Stamina to do this job) ";
                    }
                    if ($vals['noitem']) {
                        $jobout .= "(you don't have all the items you need to do this job) ";
                    }
                }
                $jobout .= "</td></tr></table>";
                rawoutput($jobout);
            }
            output_notl("`n");
        }
        output_notl("`n");
    }
    if ($nostam) {
        output("You have the brains to know that doing construction work when you're anything but wide awake is an idea so bad you're not even willing to entertain it.`n`n");
    }
}
function meatsystem_run()
{
    global $session;
    require_once "modules/staminasystem/lib/lib.php";
    page_header("Meat!");
    addnav("Meat Skills");
    $from = httpget('from');
    switch (httpget('op')) {
        case "devour":
            //special ability for Zombies only - Zombies can eat raw meat, so we're giving them the ability to simply devour the carcass where it lies.
            $carcasses = unserialize(get_module_pref("carcasses"));
            if (!is_array($carcasses)) {
                $carcasses = array();
            }
            debug($carcasses);
            foreach ($carcasses as $carcassnum => $creatureid) {
                $sql = "SELECT creaturename FROM " . db_prefix("creatures") . " WHERE creatureid = " . $creatureid . " ";
                $result = db_query_cached($sql, "creaturename-" . $creatureid, 86400);
                $creature = db_fetch_assoc($result);
                output("Giving in to your primal urges, you lean down and begin ripping meat from the still-twitching %s with your teeth.`n`n", $creature['creaturename']);
                $meat1 = get_module_objpref("creatures", $creatureid, "meat1");
                $meat2 = get_module_objpref("creatures", $creatureid, "meat2");
                $meat3 = get_module_objpref("creatures", $creatureid, "meat3");
                for ($i = 0; $i < $meat1; $i++) {
                    increment_module_pref("nutrition", 1, "staminafood");
                    increment_module_pref("fat", 3, "staminafood");
                    increment_module_pref("fullness", 1, "staminafood");
                    addstamina(1000);
                }
                for ($i = 0; $i < $meat2; $i++) {
                    increment_module_pref("nutrition", 2, "staminafood");
                    increment_module_pref("fat", 2, "staminafood");
                    increment_module_pref("fullness", 1, "staminafood");
                    addstamina(2000);
                }
                for ($i = 0; $i < $meat3; $i++) {
                    increment_module_pref("nutrition", 3, "staminafood");
                    increment_module_pref("fat", 1, "staminafood");
                    increment_module_pref("fullness", 1, "staminafood");
                    addstamina(5000);
                }
                output("For the record, and since it's nice to know these things even if you're too busy tearing cartilage and muscle from the bone to really pay attention to them, in this meal you have eaten %s bite's-worth of Crap Meat, %s bite's-worth of Half-Decent Meat, and %s bite's-worth of Tasty Meat.`n", $meat1, $meat2, $meat3);
                $full = get_module_pref("fullness", "staminafood");
                if ($full < 0) {
                    output("You still feel as though you haven't eaten in days.`n`n");
                }
                if ($full >= 0 && $full < 50) {
                    output("You feel a little less hungry.`n`n");
                }
                if ($full >= 50 && $full < 100) {
                    output("You still feel as though you've got room for more!`n`n");
                }
                if ($full >= 100) {
                    output("You're stuffed!  You feel as though you can't possibly eat anything more today.`n`n");
                }
                unset($carcasses[$carcassnum]);
                set_module_pref("carcasses", serialize($carcasses));
            }
            break;
        case "clean":
            $creatureid = httpget('creatureid');
            $carcass = httpget('carcass');
            $meat1 = get_module_objpref("creatures", $creatureid, "meat1");
            $meat2 = get_module_objpref("creatures", $creatureid, "meat2");
            $meat3 = get_module_objpref("creatures", $creatureid, "meat3");
            $amber = get_stamina();
            $return = process_action("Cleaning the Carcass");
            if ($return['lvlinfo']['levelledup'] == true) {
                output("`n`c`b`0You gained a level in Cleaning Carcasses!  You are now level %s!  This action will cost fewer Stamina points now, so you can butcher more creatures each day!`b`c`n", $return['lvlinfo']['newlvl']);
            }
            $failchance = e_rand(0, 100);
            if ($failchance > $amber) {
                //failure - the nice meat gets turned into Crap Meat
                $meat1 += $meat2;
                $meat1 += $meat3;
                output("`4You sit down to clean the carcass.  Your exhausted, clumsy incisions make a mockery of the choicest cuts - what is left over can only be described as Crap Meat.  %s bite's-worth, to be precise.  It looks like it was hacked into chunks by a blind woodsman.", $meat1);
                //todo
                for ($i = 0; $i < $meat1; $i++) {
                    give_item("meat_low", false, false, true);
                }
                load_inventory();
                $carcasses = unserialize(get_module_pref("carcasses"));
                unset($carcasses[$carcass]);
                $carcasses = array_values($carcasses);
                set_module_pref("carcasses", serialize($carcasses));
            } else {
                //success - all meat is sorted
                output("You spend a few minutes up to your elbows in gore, and getting rather hungry.`n");
                if ($meat1 > 0) {
                    output("You tear off enough to make %s rough bite's-worth of what the locals affectionately call Crap Meat.  It's mostly wobbling chunks of stinking yellow fat, intermingled with the occasional squirmy tendon.`n", $meat1);
                }
                if ($meat2 > 0) {
                    output("You make swift work of the fattier muscle, and before too long you have %s rough bite's-worth of Half-Decent Meat.`n", $meat2);
                }
                if ($meat3 > 0) {
                    output("The red, tender slivers of muscle slide easily from the bone, and you wind up with %s rough bite's-worth of Tasty Meat.`n", $meat3);
                }
                //todo
                for ($i = 0; $i < $meat1; $i++) {
                    give_item("meat_low", false, false, true);
                }
                for ($i = 0; $i < $meat2; $i++) {
                    give_item("meat_medium", false, false, true);
                }
                for ($i = 0; $i < $meat3; $i++) {
                    give_item("meat_high", false, false, true);
                }
                load_inventory();
                $carcasses = unserialize(get_module_pref("carcasses"));
                unset($carcasses[$carcass]);
                $carcasses = array_values($carcasses);
                set_module_pref("carcasses", serialize($carcasses));
                $pmeat1 = has_item("meat_low");
                $pmeat2 = has_item("meat_medium");
                $pmeat3 = has_item("meat_high");
                if (($pmeat1 || $pmeat2 || $pmeat3) && $session['user']['race'] != "Robot") {
                    if (get_module_pref("fullness", "staminafood") < 100) {
                        $cookcost = stamina_getdisplaycost("Cooking");
                        addnav(array("Cook up some meat (`Q%s%%`0)", $cookcost), "runmodule.php?module=meatsystem&op=cook&from=" . $from);
                    } else {
                        addnav("You're too full to cook, let alone eat", "");
                    }
                }
            }
            break;
        case "cook":
            $pmeat1qty = has_item_quantity("meat_low");
            $pmeat2qty = has_item_quantity("meat_medium");
            $pmeat3qty = has_item_quantity("meat_high");
            output("You whip out your camping stove.  It's time to cook!`n`nWhat will you put in the pan?  You can fit up to 20 bite's-worth of meat in there.  Right now you have %s bite's-worth of Crap Meat, %s bite's-worth of Half-Decent Meat, and %s bite's-worth of Tasty Meat.`n`n", $pmeat1qty, $pmeat2qty, $pmeat3qty);
            rawoutput("<form action='runmodule.php?module=meatsystem&op=cookfinal&from=" . $from . "' method='POST'>");
            rawoutput("Put in <input name='meat1' width='2' value='0'> bite's-worth of Crap Meat.<br />");
            rawoutput("Put in <input name='meat2' width='2' value='0'> bite's-worth of Half-Decent Meat.<br />");
            rawoutput("Put in <input name='meat3' width='2' value='0'> bite's-worth of Tasty Meat.<br />");
            rawoutput("<input type='submit' class='button' value='" . translate_inline("Cook!") . "'>");
            rawoutput("</form>");
            addnav("", "runmodule.php?module=meatsystem&op=cookfinal&from=" . $from);
            break;
        case "cookfinal":
            $pmeat1qty = has_item_quantity("meat_low");
            $pmeat2qty = has_item_quantity("meat_medium");
            $pmeat3qty = has_item_quantity("meat_high");
            $meat1 = httppost("meat1");
            $meat2 = httppost("meat2");
            $meat3 = httppost("meat3");
            //check for the dumbass player cooking meat that they don't have
            if ($meat1 > $pmeat1qty || $meat2 > $pmeat2qty || $meat3 > $pmeat3qty) {
                output("You don't `ihave`i that much meat!`n`n");
                addnav("Whoops");
                addnav("Sorry, I forgot how to count for a second there.  Let's try this again.", "runmodule.php?module=meatsystem&op=cook&from=" . $from);
                break;
            }
            //check for the dumbass player inputting a negative number
            if ($meat1 < 0 || $meat2 < 0 || $meat3 < 0) {
                page_header("Either taking vegetarianism to whole new levels, or trying to grow meat from an empty pan");
                output("You want to cook `inegative`i meat?  How very Zen of you.`n`n");
                addnav("You sneaky bugger");
                addnav("Abandon your efforts to produce the opposite of meat and try again, pretending that you weren't just trying to cheat.", "runmodule.php?module=meatsystem&op=cook&from=" . $from);
                break;
            }
            //check for the dumbass player trying to put too much meat in the pan
            $totalmeat = $meat1 + $meat2 + $meat3;
            if ($totalmeat > 20) {
                output("Your pan can't hold that much meat, pal.`n`n");
                addnav("Whoops");
                addnav("Try again, without filling the pan up so much", "runmodule.php?module=meatsystem&op=cook&from=" . $from);
                break;
            }
            //check for the dumbass player trying to cook no meat at all
            $totalmeat = $meat1 + $meat2 + $meat3;
            if ($totalmeat == 0) {
                output("You start the process of cooking up your tasty meat.  After a few minutes of poking around in your pan, growing hungrier by the second, you realise that you've forgotten something.`n`n");
                addnav("Whoops");
                addnav("Try again, with meat this time", "runmodule.php?module=meatsystem&op=cook&from=" . $from);
                break;
            }
            //Stamina interaction, including consequences and level-up details.
            $amber = get_stamina();
            $return = process_action("Cooking");
            if ($return['lvlinfo']['levelledup'] == true) {
                output("`n`c`b`0You gained a level in Cooking!  You are now level %s!  This action will cost fewer Stamina points now, so you can cook more tasty meals each day!`b`c`n", $return['lvlinfo']['newlvl']);
            }
            $failchance = e_rand(0, 100);
            if ($failchance > $amber) {
                output("`4You put your meat into the pan, and sit down to stir-fry it.  The hypnotic motion and white-noise sizzling, combined with your tiredness, sends you staring into space.  While your concentration is impaired, the meat bursts into flames.  You jerk back into awareness, and look down sadly at the flaming chunks.  Bummer.");
                for ($i = 0; $i < $meat1; $i++) {
                    delete_item(has_item("meat_low"));
                }
                for ($i = 0; $i < $meat2; $i++) {
                    delete_item(has_item("meat_medium"));
                }
                for ($i = 0; $i < $meat3; $i++) {
                    delete_item(has_item("meat_high"));
                }
                break;
            }
            //we can now assume that the player is not some sort of cheating reprobate, or trying to cook while dog-tired, and do some cooking!
            for ($i = 0; $i < $meat1; $i++) {
                increment_module_pref("nutrition", 1, "staminafood");
                increment_module_pref("fat", 3, "staminafood");
                increment_module_pref("fullness", 1, "staminafood");
                delete_item(has_item("meat_low"));
                addstamina(1000);
            }
            for ($i = 0; $i < $meat2; $i++) {
                increment_module_pref("nutrition", 2, "staminafood");
                increment_module_pref("fat", 2, "staminafood");
                increment_module_pref("fullness", 1, "staminafood");
                delete_item(has_item("meat_medium"));
                addstamina(2000);
            }
            for ($i = 0; $i < $meat3; $i++) {
                increment_module_pref("nutrition", 3, "staminafood");
                increment_module_pref("fat", 1, "staminafood");
                increment_module_pref("fullness", 1, "staminafood");
                delete_item(has_item("meat_high"));
                addstamina(5000);
            }
            output("You fry up your lovely meaty loveliness, and sit down to eat.  You gain some Stamina!`n`n");
            $full = get_module_pref("fullness", "staminafood");
            if ($full < 0) {
                output("You still feel as though you haven't eaten in days.`n`n");
            }
            if ($full >= 0 && $full < 50) {
                output("You feel a little less hungry.`n`n");
            }
            if ($full >= 50 && $full < 100) {
                output("You still feel as though you've got room for more!`n`n");
            }
            if ($full >= 100) {
                output("You're stuffed!  You feel as though you can't possibly eat anything more today.`n`n");
            }
            break;
    }
    $carcasses = unserialize(get_module_pref("carcasses"));
    if (!is_array($carcasses)) {
        $carcasses = array();
    }
    if (count($carcasses) > 0) {
        output("You look at the spoils of your most recent battle.  They lie bloodied and broken on the ground.  What will you do with them?");
        foreach ($carcasses as $carcassnum => $creatureid) {
            $sql = "SELECT creaturename FROM " . db_prefix("creatures") . " WHERE creatureid = " . $creatureid . " ";
            $result = db_query_cached($sql, "creaturename-" . $creatureid, 86400);
            $creature = db_fetch_assoc($result);
            $cleancost = stamina_getdisplaycost("Cleaning the Carcass");
            addnav(array("Clean the carcass of %s (`Q%s%%`0)", $creature['creaturename'], $cleancost), "runmodule.php?module=meatsystem&op=clean&creatureid=" . $creatureid . "&carcass=" . $carcassnum . "&from=" . $from);
        }
    } else {
        if (httpget('op') != "cook" && httpget('op') != "cookfinal") {
            output("Now only bloody bones lie strewn around the area.`n`n");
        }
    }
    addnav("Ah, screw it.");
    if ($from == "forest") {
        addnav("Return to the Jungle", "forest.php");
    } else {
        if ($from == "world") {
            addnav("Return to the World Map", "runmodule.php?module=worldmapen&op=continue");
        }
    }
    page_footer();
    return true;
}
function hunterslodge_namedmount_run()
{
    require_once "lib/sanitize.php";
    require_once "lib/names.php";
    global $session;
    global $playermount;
    $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("Name your Mount");
    switch ($op) {
        case "change":
            output("Want to change your Mount's name?  No problem.  Enter your desired name in the box below.  You've got 25 characters to play around with.`n(leave this blank to disable mount naming)`n`n");
            rawoutput("<form action='runmodule.php?module=hunterslodge_namedmount&op=confirm&context={$context}&free=" . $free . "' method='POST'>");
            rawoutput("<input id='input' name='newname' width='25' maxlength='25' value='" . htmlentities($race, ENT_COMPAT, getsetting("charset", "ISO-8859-1")) . "'>");
            rawoutput("<input type='submit' class='button' value='Preview'>");
            rawoutput("</form>");
            addnav("", "runmodule.php?module=hunterslodge_namedmount&op=confirm&context={$context}&free=" . $free);
            addnav("Cancel");
            addnav("Don't set a mount name, just go back to where I came from", $backlink);
            break;
        case "confirm":
            $newname = httppost("newname");
            $sub = httpget("sub");
            $newname = comment_sanitize($newname);
            $newname = substr($newname, 0, 25);
            if ($newname) {
                output("Your Mount's name is now:`n%s`0 the %s`nWould you like to set your mount's name now?`n`n", $newname, $playermount['mountname']);
            } else {
                output("You've chosen to go back to having an unnamed Mount.  Are you sure that's what you want?`n`n");
            }
            addnav("Confirm");
            addnav("Set mount name", "runmodule.php?module=hunterslodge_namedmount&op=set&free={$free}&context={$context}&newname=" . rawurlencode($newname));
            addnav("Cancel");
            addnav("Don't set a mount name, just go back to where I came from", $backlink);
            break;
        case "set":
            $newname = rawurldecode(httpget("newname"));
            output("You now ride %s`0 the %s!`n`n", $newname, $playermount['mountname']);
            set_module_pref("mountname", $newname);
            if (!$free) {
                $id = has_item("hunterslodge_namedmount");
                delete_item($id);
            }
            addnav("Return");
            addnav("Back to where I came from", $backlink);
            break;
    }
    page_footer();
}
function use_item($item, $context = "default")
{
    global $session, $inventory;
    if (!isset($inventory)) {
        load_inventory();
    }
    if (!is_numeric($item)) {
        $item = has_item($item);
    }
    if ($item) {
        $useitem = $inventory[$item];
        $useitem['id'] = $item;
        $useitem['context'] = $context;
        $useitem = modulehook("use_item", $useitem);
        if ($useitem['break_use_operation']) {
            return false;
        }
        if ($useitem['require_file']) {
            require_once "items/" . $useitem['require_file'];
        }
        if ($useitem['call_function']) {
            $useitem = call_user_func($useitem['call_function'], $useitem);
        }
        if ($useitem['usetext']) {
            output("`0%s`n`n", $useitem['usetext']);
        }
        if ($useitem['destroyafteruse']) {
            delete_item($useitem['id']);
        }
    } else {
        debug("No such item exists in this player's inventory (looked for " . $item . ")");
        return false;
    }
}
function misterstern_run()
{
    global $session;
    switch (httpget("op")) {
        case "start":
            page_header("Mister Stern");
            $name = $session['user']['name'];
            output("\"`6Hello!`0\"`n`nYour heart puts on its running shoes and tears off around the track.  After roughly half a second of panic, you realise that the voice sounded quite friendly.  Jolly, even.  Male, British - a little upper class, perhaps, but not snooty with it.  Rather warm and sophisticated, in fact.`n`nYou look in the direction of the voice, and in the dim light you make out the outline of a figure standing behind the desk in the lobby.  You step forward.  \"`#Um, hello?`0\" you say.  \"`#I'm sorry, I thought I was alone.`0\"`n`nAs you step closer, the figure walks around from behind his desk.  \"`6I can't blame you, in this gloom,`0\" he says, walking across the room to a window and opening it.  Warm sunlight floods the lobby, little specks of dust dancing and reflecting in the air.  \"`6There,`0\" says the man.  \"`6That's better.`0\"`n`nThe tall, rather slender man wears a grey waistcoat, white shirt, and smart grey trousers.  A little pair of round-framed glasses sits on his nose, its arms connected via a chain around his neck.  When he turns to face you, you can see the outline of a pocket watch resting in his waistcoat pocket, silver chain sparkling.  His age is hard to tell.  Clearly he's been around a few years; he's old enough to make you think of the librarian or dusty old academic who can't quite bring himself to retire, despite it being more than time to do so.`n`nYou can't help but grin.  This guy is the ultimate stereotype of dusty British museum curators.`n`nHe grins back and steps towards you, hand outstretched.  \"`6Mister Havelock Stern, Stern by name but not by nature, pleased to make your acquiaintance.`0\"  You get the impression that he says this every time he meets someone - and that when he said he was pleased to meet you, he actually meant it.  You take the hand, give it a shake, and say \"`#%s`#.  Nice to meet you.`0\"`n`n\"`6Sorry to give you a fright,`0\" says Mister Stern.  \"`6Only I'd just nipped into the cupboard to put the kettle on.  I don't get many visitors here, you see.`0\"`n`n\"`#That's okay,`0\" you say, a little sheepishly.  \"`#Honestly I think I was just full of adrenaline anyway.`0\"`n`nMister Stern shows you another grin.  \"`6Aha.  Did `\$The Watcher`6 send you here, by any chance?  Blonde lady, glasses, looks somewhere in her thirties?  Always wears a red turtleneck?`0\"`n`n\"`#Utterly insane and rather frightening?`0\"`n`nMister Stern chuckles.  \"`6Yes, that's the one.  I see.  Well, you must be a new recruit, then.  Well, I remember my first day.  It's rough, isn't it?  Well, the kettle should be boiled by now, if you'd like a break from it all...?`0\"`n`nYou've been kidnapped and thrust into a war against a reality-altering machine, and now a kindly gentleman is offering you a cup of tea.  Well, what happens next?", $name);
            addnav("Mister Stern");
            addnav("I have to admit, it's all a bit confusing.  A cup of tea sounds nice.", "runmodule.php?module=misterstern&op=tea");
            addnav("No, I think I'm doing okay.  Thanks for the offer, but I'd best be on my way.", "runmodule.php?module=misterstern&op=notea");
            break;
        case "tea":
            page_header("Mister Stern");
            set_module_pref("hadtea", 1);
            output("\"`6Jolly good,`0\" says Mister Stern, and again, you get the impression that he means it.`n`n\"`6So,`0\" he says a few minutes later, while pouring and adulterating the tea, \"`6tell me honestly.  What do you think of the exhibits?`0\"`n`n\"`#To be completely honest,`0\" you say, \"`#I wouldn't have thought there would `ibe`i a museum here.  I mean, this is Improbable Island, after all...`0\" you trail off.  \"`#I still can't believe I'm actually here.  I mean, I watched the show and everything, but you never think your number's gonna come up, do you?  Anyway.  Yes, the exhibits were very nice, but they made me miss the old days a bit.`0\"`n`nMister Stern sits down and hands you your cup.  \"`6Yes,`0\" he says, taking a sip.  \"`6I know exactly what you mean.  It's quite a culture shock, isn't it?  On both sides, I mean - coming to the Island, and getting thrown back into the Renaissance practically overnight.  They're both a big blow to the system, really.`0\"`n`n\"`#Tell me about it,`0\" you mutter into your cup.`n`nMister Stern takes you literally.  \"`6I remember the day the mines went off.  I think we all do, really.  I remember waking up and wondering why my alarm clock wasn't playing.  I assumed we'd had a power cut when I saw the display was blank.`0\"  He blows on his tea.  \"`6So, of course, I checked my phone, and that was dead, too.  Although to be fair, the battery was on its way out, and I always charge it overnight.`0\"  He takes a sip.  \"`6So, I assumed that the battery had run out in the night.  I practically jumped out of bed and ran all around the house trying to find a working clock, worried that I was going to be late.`0\"  He grins.  \"`6I ran a museum in my past life too, you see.  It's become something of a habit.`0\"  You nod and grin back.  \"`6Anyway,`0\" continues Mister Stern, \"`6I picked up the landline to try to call the speaking clock, and couldn't get a dial tone.  That was when I started to think that maybe something very bad had happened.`0\"`n`nMister Stern's eyes seem to focus somewhere in the middle distance, left of your head.  \"`6I remembered I had a little travel alarm clock, powered by a nine volt battery.  I dashed upstairs and rummaged around until I found it.`0\"  He blows on his tea.  \"`6It was dead as a doornail.  I took the battery out, and tested it on my tongue.  It gave a little tingle, so I knew the battery was fine.`0\"  He sips his tea, staring off into nowhere.  \"`6In fact, it gave quite a big tingle - almost as if it had been overcharged.  And that's when I noticed the smell, coming from the alarm clock...`0\"`n`n\"`#I remember that smell,`0\" you mutter.  \"`#Burning solder.`0\"`n`nMister Stern gives you a sad little nod.  You sit in silence for a moment.`n`n\"`6When did you catch on?`0\" asks Mister Stern after some seconds.`n`nYou shrug.  \"`#What, that the world had ended?  I honestly can't remember.  It was a very busy day.  I know my neighbour didn't realise until his car didn't start.  And even then, he didn't understand what was going on.`0\"`n`n\"`6I see,`0\" sighs Mister Stern.  \"`6You know, I think I understand why I don't get many visitors here.  The memories are too much for most people.`0\"`n`nYou nod.  \"`#The other exhibits, though - the dummies, they're not bad.`0\"`n`n\"`6Yes.  Yes, we certainly do need some more exhibits, don't we?  Maybe some cheerful ones.`0\"  Mister Stern looks out of the window.  \"`6You know, there's a world of interesting things out there.  If I could get around a little more, I'd head out and find some things to show off myself.`0\"`n`n\"`#What sort of things?`0\" you ask.`n`n\"`6Oh, just anything interesting, really.  Some herbs from the KittyMorph village, maybe some artefacts from Cyber City, that sort of thing.  I'd like to get a good range of things to show to people, you know?  But since the accident, I just haven't been able to get around too much.`0\"`n`n\"`#Accident?`0\"`n`nMister Stern points to his left knee.  \"`6Shrapnel.  Shrapnel from a piece of the equipment surrounding the Improbability Drive, no less.  It's impossible to walk terribly far, and I daren't use any of these new-fangled teleporter devices - who knows how such a machine would interact with a piece of Improbability-infused metal?`0\"`n`nYou shrug.  \"`#Hell, I'm going to be heading out into the Big Bad Jungle just as soon as I've finished this tea; if I come across anything interesting, I'll be sure to let you know.`0\"`n`nMister Stern smiles.  \"`6I'm sure you'll come across a great `imany`i interesting things.  It's a jungle out there.`0\"`n`nYou grin back.`n`nA few minutes of idle chitchat later, you finish your tea, bid your farewells and leave the Museum.");
            addnav("Continue");
            addnav("Head back into the Outpost", "village.php");
            break;
        case "notea":
            page_header("Mister Stern");
            output("\"`6Right enough,`0\" says Mister Stern.  \"`6I expect you've got all sorts of monsters and creatures and things to be getting on with.  The offer remains open, though - I'm here rain or shine.`0\"`n`nYou bid your farewell and head out of the Museum.");
            addnav("Continue");
            addnav("Continue back into the Outpost", "village.php");
            break;
        case "getrelic":
            page_header("Got any Relics?");
            output("You ask if there are any interesting things handy that could help illustrate the local culture.`n`n");
            switch ($session['user']['location']) {
                case "NewHome":
                    output("`0The man behind the desk furrows his brow.  \"`1`iMuseum`i exhibits?  This'll be for that Mister Stern, won't it?`0\"  He rummages in a desk drawer.  \"`1Yup, he's been after some new stuff for his museum for a while now, or so I gather.  Now, let's see...  Ah, maybe this'll do.`0\"  He pulls out what looks like an old service revolver, rusted with age.  \"`1I've been meaning to give this to him for a while.  It's not much good as an actual weapon, but I reckon that's probably the oldest firearm on the whole Island.  Well pre-EMP.  He should like that.`0\"`n`nYou thank the man and make your farewells.");
                    give_item("stern_revolver");
                    set_module_pref("gotnh", 1);
                    break;
                case "Kittania":
                    output("`0The KittyMorph smiles.  \"`1Oh, Mister Stern must have sent you!  Here, you can have this.`0\"  She reaches into her desk drawer and hands you a dead mouse.`n`nYou stare at it for a moment.`n`n\"`1Oh!  Whoops, sorry...`0\" she takes the mouse back from your hand, giggling as she puts it back in the drawer.  \"`1That's not what I meant to give you at all!  Deary me, what on Earth would a human want with one of `ithose`i?  Here.`0\"`n`nShe hands you a dead rat.`n`nWell, it's better than nothing.  Maybe this is how KittyMorphs pay respect to one another.`n`nMaybe.");
                    give_item("stern_rat");
                    set_module_pref("gotki", 1);
                    break;
                case "New Pittsburgh":
                    output("The Zombie behind the desk nods, slowly.  She reaches under her desk, and brings up a brain in a jar.  \"`1He's a lovely man.  He can have this BRAAAAAAAAAAIIINS,`0\" she slurs.  \"`1I was saving it for my lunch, but I'm sure it'd be a good conversation piece.  I know our eating habits differ quite a bit.`0\"`n`nYou nod.  \"`#I'm sure it'll prove very useful, thanks.`0\"`n`nYou leave hastily, in case she changes her mind and decides on a fresh brain instead.");
                    give_item("stern_brain");
                    set_module_pref("gotnp", 1);
                    break;
                case "Squat Hole":
                    output("\"`1Is this for tha' fookin' old geezer in der 'umin town, yeah?`0\"`n`nYou nod.`n`n\"`1Tell 'im 'e can 'ave dis,`0\" says the Midget.  With a loud snort and a cringe-inducing squishing sound, he shifts some phlegm into his mouth and spits into his hand.  He holds it out to you.`n`n\"`1Whassa' fookin' matter, eh?`0\" he asks, seeing that you're less than enthusiastic about his gift.  \"`1I tell yer, you lot've got no fookin' `iclue`i about 'ow we live, do ya?  Thass' a `ivaluable commodity,`i is tha'!  We use it fer all sorts!  This Stern feller, 'e should consider 'imself 'ighly respected fer a gift like dis!`0\"  He looks down at his hand.  \"`1Oh, right.  Never mind, I get yer now.  Sorry mate, I completely forgot me fookin' manners.  I'll get yer a little bag, shall I?`0\"`n`nYou cringe as the Midget pours the contents of his hand into a little sandwich bag, and tosses it to you.  It splats into your hand, mercifully dry but still soft and squishy, and... `iwarm.`i`n`nYou mutter a hasty \"`#Thanks,`0\" and leave quickly before the Midget can give you anything else.");
                    give_item("stern_phlegm");
                    set_module_pref("gotsq", 1);
                    break;
                case "Pleasantville":
                    output("\"`1This would be for Mister Stern, I assume.  Fine fellow.  Very understanding, easy to talk to.  It's a terrible shame about his accident.`0\"  The Mutant behind the desk hesitates.  \"`1Although to be honest, I've no idea what I can give you.`0\"`n`nYou shrug.  \"`#Anything, really.  Anything that makes it easier to understand Mutants.`0\"`n`nThe Mutant's eyes seem to light up.  \"`1I have some poetry.  Would you like to hear it?`0\"`n`nYou shuffle your feet.  \"`#Ah, well, see, thing is, I've really got to -`0\"`n`n\"`1Black is the pit where my heart once lurked,`0\" says the Mutant, reading from a piece of paper pulled from his pocket.  \"`1`iBlack`i is the pupil of my one working eye.`0\"`n`n\"`#Oh, God...`0\"`n`n\"`1`iBlack`i is the stubbed toenail that sprouts from my left ear.  `iBlack`i is the gunge that seeps from the festering hole in my torso.  `iBLACK`i are the teeth within that festering hole, how I long for a toothbrush that will reach!`0\"`n`nYou begin to feel a little faint.`n`n\"`1`iBlack`i is the colour of my `isoul`i, the colour of my `imind`i, the colour of my heavily-altered `iT-shirt`i, the colour of my `iPAIN!`i  `iBlack`i are the sightless, staring eyes that cover my knees and my penis.`0\"`n`nGrey fuzz seems to be seeping in around the edges of your vision.  You can hear a high-pitched whine, but it doesn't drown out the sounds of the Mutant's poetry.`n`n\"`1`iMy penis!`i  Oh, cruel and sadistic fate!  My instrument of `ilove`i, my rod of passion, studded with the `iblack gems`i that drive women `iscreaming`i and `iurinating`i into the night!  The eyes, the `ieyes!`i  They do not see, they can not look in love and wonder upon a newborn babe or a majestic waterfall!  But if you cut me, do I not bleed?  If you poke my penis-eyes, do they not blink as one in soundless anguish?`0\"`n`n\"`#I'M SURE HE'LL LOVE IT!`0\" you scream.  \"`#THANK YOU VERY VERY MUCH!`0\"  You snatch the paper from his hand, and run gibbering out of the hut.");
                    give_item("stern_poetry");
                    set_module_pref("gotpl", 1);
                    break;
                case "Cyber City 404":
                    output("\"`1Affirmative.  The fleshling Stern wishes to create a permament record of your primitive, chemical-based knowledge, yes?  An excellent aspiration, given that your memories are flawed and untrustworthy.`0\"  The Robot behind the desk nods his appreciation.  \"`1I will give you this.`0\"`n`nHe hands over a tiny memory card.  \"`#Oh, thank you very much,`0\" you say.  \"`#He seems to be really into his pre-EMP technology.  What is it, exactly?`0\"`n`n\"`1Oddly enough, the collected thoughts and memories of your home town.  A complete record of every personality, ready to be transplanted into Robot bodies should the need arise.  I believe you are in there somewhere.`0\"`n`nYou stare at the card.  Your entire life, and the lives of those around you, on a memory card smaller than a suppository.  You stuff it moodily into your pocket, mutter something like \"`#Thanks,`0\" and head out of the door, leaving the Robot wondering why the display of his superior technology and mental capacity seemed to lose him a potential friend, rather than make one.`n`nHe shrugs.  It seems appropriate to do so.  He's good at shrugging.  He's practiced in front of a mirror.");
                    give_item("stern_memorycard");
                    set_module_pref("gotcc", 1);
                    break;
                case "AceHigh":
                    output("\"`1You needn't say another word,`0\" says the lady behind the desk, dressed in an immaculate Victorian suit.  \"`1I know what you're here for, and I know who sent you.  Give him this.`0\"`n`nThe green glow around her eyes seems to intensify as she pulls a coin out of her pocket.  She hands it to you, and the light dies away a little.`n`nYou turn it over.  It's an old British penny, one of the really huge ones from the 1940's.  But there's something wrong.  \"`#This is a double-headed one,`0\" you say.`n`n\"`1Flip it,`0\" says the woman, smiling.`n`nYou do as commanded.  When you catch it, both sides show tails.  \"`#Wow, that's really neat!`0\" you say, and flip it again.  It comes up heads on both sides.  \"`#You know, this is probably the best thing I've gotten on this little adventure.`0\"`n`nThe lady nods, watching you flip the coin a third time, clearly enjoying your interest in her artefact.  \"`1It's certainly a fascinating piece.  Full of rather complex equations and Improbabilities.  Each time the faces are reversed, there's a one in seven chance of folding a localised area of time and space, generating a potentially universe-shattering paradox.  Isn't that exciting?`0\"`n`nYou catch the coin and slip it into your pocket.  \"`#I'll just keep this safe in here for now.`0\"");
                    give_item("stern_penny");
                    set_module_pref("gotah", 1);
                    break;
            }
            addnav("Return");
            addnav("Back to the Outpost", "village.php");
            break;
        case "show":
            page_header("Mister Stern");
            set_module_pref("subplotcomplete", 1);
            output("\"`6My goodness!`0\" says Mister Stern, pushing his glasses further up on his nose and examining the array of objects you've just placed on his desk.  \"`6What an excellent find!  Let's see, here...  A dead rat, some phlegm, a rusty pistol, a brain, some sort of memory card, some... goodness, some Mutant poetry from the look of things...`0\"`n`n\"`#Do you think they'll be useful?`0\" you ask, somewhat dubious.`n`n\"`6Oh, yes!  These are superb!`0\" says Mister Stern.  \"`6Oh, and this must be one of those Joker coins!`0\"  He flips it into the air.`n`n\"`6My goodness!`0\" says Mister Stern, pushing his glasses further up on his nose and examining the array of objects you've just placed on his desk.  \"`6What an excellent find!  Let's see, here...  A dead rat, some phlegm, a rusty pistol, a brain, some sort of memory card, some... my goodness, some Mutant poetry from the look of things...`0\"`n`n\"`#Do you think they'll be useful?`0\" you ask, somewhat dubious.`n`n\"`6Oh, yes!  These are superb!`0\" says Mister Stern.  \"`6Oh, and this must be one of those Joker coins!`0\"  He flips it into the air.`n`nYou pull out a cigarette and light it, knowing that there are questions to be asked and answered - like what you're going to do with the rest of your life - but for the moment, at least, you're content to just lie here for a little while.`n`nA metallic creaking sound jars you out of your contemplation. You sit up, staring at the jagged edges of the Improbability Drive's remains, the jagged edges that are now trying to bend themselves back into shape...`n`n\"`6Oh, and this must be one of those Joker coins!`0\"  He flips it into the air.`n`nYou snatch the coin out of the air mid-flip.  \"`#Might want to go easy on that.`0\"`n`n\"`6Oh,`0\" says Mister Stern.  \"`6Yes, I see what you mean.  Gives one a belter of a headache, doesn't it?  Well, listen, I can't thank you enough for all this, but I want to give you your time's worth.`0\"`n`nHe hands you a pack of ten cigarettes.  Result!`n`n\"`#Well, thanks very much,`0\" you say, \"`#and I really should get going.  I've monsters to kill, and I expect you'll be wanting to arrange your exhibits and write up cards for them, and that sort of thing.`0\"`n`n\"`6Indeed, indeed.  Come back any time!  And thank you once again!`0\"");
            delete_item(has_item("stern_revolver"));
            delete_item(has_item("stern_rat"));
            delete_item(has_item("stern_brain"));
            delete_item(has_item("stern_phlegm"));
            delete_item(has_item("stern_poetry"));
            delete_item(has_item("stern_memorycard"));
            delete_item(has_item("stern_penny"));
            $session['user']['gems'] += 10;
            addnav("Continue");
            addnav("Back to the Outpost", "village.php");
            if (is_module_active("medals")) {
                require_once "modules/medals.php";
                medals_award_medal("mister_stern", "Museum Marketeer", "This player helped Mister Stern restore his museum to popularity!", "medal_museumquest.png");
            }
            break;
    }
    page_footer();
}
function rail_discard_item($search)
{
    // we need this because delete_item takes a numeric key, and we want to delete by name
    // this will delete the first one found
    global $session, $inventory;
    if (!isset($inventory)) {
        load_inventory();
    }
    $found = has_item($search);
    if ($found === false) {
        return false;
    } else {
        delete_item($found);
        return true;
    }
}
function luggagehut_run()
{
    global $session;
    page_header("The Luggage Hut");
    $backpackprefs = array("carrieritem" => "main");
    $backpack = get_items_with_prefs($backpackprefs, true);
    // debug($backpack);
    foreach ($backpack as $key => $prefs) {
        $currentbackpack = $prefs;
        $currentbackpackid = $key;
    }
    $bandolierprefs = array("carrieritem" => "fight");
    $bandolier = get_items_with_prefs($bandolierprefs, true);
    // debug($bandolier);
    foreach ($bandolier as $key => $prefs) {
        $currentbandolier = $prefs;
        $currentbandolierid = $key;
    }
    global $inventory;
    // debug($inventory);
    $tradein_main = round($currentbackpack['invshop_price'] * 0.6);
    $tradein_fight = round($currentbandolier['invshop_price'] * 0.6);
    switch (httpget('op')) {
        case "start":
            output("`0You head into the Luggage Hut.  A tall woman in her mid-twenties greets you.  From the dimensions of her mullet, you suspect she may be related to Sheila.`n`n\"`2Well, hey there!  Name's Sharon, nice to meet you.  Here for some new luggage?  We've got three different types of Backpacks and Bandoliers available.  Here, take a look around.  I can give you a trade-in value of %s cigarettes on your old backpack, and %s on your old bandolier.`0\"`n`nYou look around the shop a little, finding three different types of Bandoliers and Backpacks on sale:`n`n`bStandard Backpack`b`nA bog-standard backpack made from reasonably good materials.  Comfortably holds up to twenty kilos, and costs ten cigarettes.`n`n`bImproved Backpack`b`nA more well-designed backpack with extra pockets and good balance.  Holds up to forty kilos, and costs fifty cigarettes.`n`n`bAdvanced Backpack`b`nA superior-quality backpack designed by the famous B. P. BackPack, who changed his name by deed poll after working in the backpack design business for sixty years.  The man's completely bonkers, but he knows how to design a damned good backpack.  Comfortably holds up to eighty kilos, and costs one hundred cigarettes.`n`n`n`bStandard Bandolier`b`nA slightly more advanced version of the Basic bandolier given to new recruits.  Holds up to five kilos and costs ten cigarettes.`n`n`bImproved Bandolier`b`nThis leather bandolier looks cool, and has more pockets to store more things to use in fights.  Holds up to seven kilos and costs fifty cigarettes.`n`n`bAdvanced Bandolier`b`nThe Rolls-Royce of bandoliers, these things only tend to get purchased by the serious combat nut.  Holds up to ten kilos, and costs one hundred cigarettes.", $tradein_main, $tradein_fight);
            break;
        case "buy":
            $item = httpget('buy');
            if ($item == "backpack2" || $item == "backpack3" || $item == "backpack4") {
                $invloc = "main";
                $tradein = $tradein_main;
            } else {
                $invloc = "fight";
                $tradein = $tradein_fight;
            }
            $price = get_item_setting("invshop_price", $item);
            //debug($price);
            if ($price > $session['user']['gems'] + $tradein) {
                //todo
                output("Sharon shakes her head, her mullet swaying back and forth.  \"`2Sorry love - even with the trade-in, that's just not going to be enough.`0\"`n`nYou don't actually `ihave`i that many cigarettes.  Shame.");
            } else {
                $has = has_item($item);
                if ($has) {
                    output("Sharon smiles as she takes your cigarettes.  She pauses when she sees your old equipment.`n`n\"`2Uh, mate...  That's `iexactly`i the same as the one you're buying.  I'm not gonna take your cigs and then give you something that's no different to what you've already got - I'm not Sheila, you know?`0\"`n`nEmbarrassed, you nod, and take back your cigarettes.");
                } else {
                    output("Sharon smiles as you hand over your cigarettes and your old equipment.  \"`2Great stuff.  Here you go, one lovely new shiny piece of luggage!  Treat it well, now!`0\"");
                    $session['user']['gems'] += $tradein;
                    $session['user']['gems'] -= $price;
                    $price = $price - $tradein;
                    if ($invloc == "main") {
                        delete_item($currentbackpackid);
                    } else {
                        if ($invloc == "fight") {
                            delete_item($currentbandolierid);
                        }
                    }
                    give_item($item);
                    debuglog("spent " . $price . " cigarettes on " . $item . " at the Luggage Hut.");
                }
            }
            break;
    }
    addnav("Backpacks");
    addnav("Buy Standard Backpack", "runmodule.php?module=luggagehut&op=buy&buy=backpack2");
    addnav("Buy Improved Backpack", "runmodule.php?module=luggagehut&op=buy&buy=backpack3");
    addnav("Buy Advanced Backpack", "runmodule.php?module=luggagehut&op=buy&buy=backpack4");
    addnav("Bandoliers");
    addnav("Buy Standard bandolier", "runmodule.php?module=luggagehut&op=buy&buy=bandolier2");
    addnav("Buy Improved bandolier", "runmodule.php?module=luggagehut&op=buy&buy=bandolier3");
    addnav("Buy Advanced bandolier", "runmodule.php?module=luggagehut&op=buy&buy=bandolier4");
    addnav("Other");
    addnav("Back to the Outpost", "village.php");
    page_footer();
    return true;
}
addnav("Services");
if ($session['user']['gems'] >= $stakecost && !has_item('housing_stake')) {
    //Ask the player if they'd like to buy a stake
    addnav("Buy a land claim stake (100 cigarettes)", "runmodule.php?module=improbablehousing&op=landregistry&sub=buystake");
} else {
    if ($session['user']['gems'] < $stakecost) {
        addnav("You don't have enough cigarettes to buy a stake", "");
    } else {
        addnav("You already have a land claim stake.", "");
    }
}
if ($session['user']['gems'] >= $toolcost) {
    if (!has_item('toolbox_masonry')) {
        addnav("Rent a Masonry toolbox (1 cigarette)", "runmodule.php?module=improbablehousing&op=landregistry&sub=buymasonry");
    } else {
        addnav("You already have a Masonry toolbox", "");
    }
    if (!has_item('toolbox_carpentry')) {
        addnav("Rent a Carpentry toolbox (1 cigarette)", "runmodule.php?module=improbablehousing&op=landregistry&sub=buycarpentry");
    } else {
        addnav("You already have a Carpentry toolbox", "");
    }
    if (!has_item('toolbox_decorating')) {
        addnav("Rent a Decorating toolbox (1 cigarette)", "runmodule.php?module=improbablehousing&op=landregistry&sub=buydecorating");
    } else {
        addnav("You already have a Decorating toolbox", "");
    }
}
addnav("Return");
addnav("O?Back to the Outpost", "village.php");
page_footer();
    $f .= gen_footer();
    exit($f);
}
if ($_GET['part'] == 3) {
    // teperq sobstvenno vse i delaem
    $scroll = preg_replace('/[^a-z0-9_\\.]/i', '', $_GET['scroll']);
    $weapon = preg_replace('/[^a-z0-9_\\.]/i', '', $_GET['to']);
    if (!$weapon || !$scroll) {
        put_error('netu dannyh');
    }
    // proverjaem nalichie
    include_once 'modules/f_has_item.php';
    if (!has_item($scroll, $LOGIN)) {
        put_error('netu etogo svitka');
    }
    if (!has_item($weapon, $LOGIN)) {
        put_error('netu etogo oruzhija');
    }
    // berem nazvanija magii -
    $q = do_mysql("SELECT on_take  FROM items WHERE fullname = '" . $scroll . "';");
    $spell = mysql_result($q, 0);
    // berem effect
    $q = do_mysql("SELECT effect FROM magic WHERE fullname = '" . $spell . "';");
    $eff = mysql_result($q, 0);
    if (!$eff) {
        put_g_error('этот свиток без эффекта');
    }
    // dalee udaljaem svitok
    include_once 'modules/f_delete_item.php';
    delete_item($scroll, $LOGIN);
    // kazhdyj +1 k navyku daet 10%
$f .= '<div class="y" id="layfa"><b>Столик Архимага:</b></div><p>';
if (!isset($_GET['part'])) {
    // chastq pervaja:  vyberaem svitok:
    $f .= 'выберите свиток (также имейте при себе пустой):<br/>';
    include_once 'modules/f_list_inventory.php';
    $f .= list_inventory($LOGIN, 'i.s.', 'clone_scroll&part=2');
    $f .= '';
    $f .= '<a class="blue" href="game.php?sid=' . $sid . '">в игру</a>';
    $f .= gen_footer();
    exit($f);
}
if ($_GET['part'] == 2) {
    // teperq sobstvenno vse i delaem
    $scroll = preg_replace('/[^a-z0-9_\\.]/i', '', $_GET['to']);
    include_once 'modules/f_has_item.php';
    if (!has_item($scroll, $LOGIN)) {
        put_error('netu etogo svitka');
    }
    // proverim estq li u igroka pustoj svitok:
    include_once 'modules/f_has_count.php';
    include_once 'modules/f_delete_count.php';
    if (!has_count('i.q.que.scroll', 1, $LOGIN)) {
        put_g_error('при себе надо иметь пустой свиток для записи');
    }
    // udaljaem -
    delete_count('i.q.que.scroll', 1, $LOGIN);
    // berem nazvanie svitka
    include_once 'modules/f_real_name.php';
    $rn = real_name($scroll);
    // berem cebnu svitka
    $q = do_mysql("SELECT price FROM items WHERE fullname = '" . $scroll . "';");
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 hunterslodge_customcolours_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 Custom Colours");
    switch ($op) {
        case "change":
            output("Want to change your name colours?  No problem.  Enter your desired name, using colour codes, in the box below.  You've got 30 characters to play around with, including colour codes.`n`n");
            namecolour_form();
            addnav("Cancel");
            addnav("Don't change colours, just go back to where I came from", $backlink);
            break;
        case "confirm":
            $newname = httppost("newname");
            $newname = str_replace("`0", "", httppost("newname"));
            $newname = str_replace("`b", "", $newname);
            $newname = str_replace("`i", "", $newname);
            $newname = str_replace("`n", "", $newname);
            $newname = preg_replace("/[`][cHw]/", "", $newname);
            $regname = get_player_basename();
            $comp1 = strtolower(sanitize($regname));
            $comp2 = strtolower(sanitize($newname));
            $err = 0;
            if ($comp1 != $comp2) {
                if (!$err) {
                    output("`4`bInvalid name`b`0`n");
                }
                $err = 1;
                output("Your new name must contain only the same characters as your current name; you can add or remove colors, and you can change the capitalization, but you may not add or remove anything else. You chose %s.`0`n`n", $newname);
            }
            if (strlen($newname) > 30) {
                if (!$err) {
                    output("`4`bInvalid name`b`0`n");
                }
                $err = 1;
                output("Your new name is too long.  Including the color markups, you are not allowed to exceed 30 characters in length.`n`n");
            }
            if (!$err) {
                output("`0Your name will look this this: %s`n`n`0Do you want to set your new name colours now?`n`n", $newname);
                addnav("Confirm");
                addnav("Set the new name colours", "runmodule.php?module=hunterslodge_customcolours&op=set&free={$free}&context={$context}&newname=" . rawurlencode($newname));
                addnav("Cancel");
                addnav("Don't change colours, just go back to where I came from", $backlink);
            } else {
                addnav("Cancel");
                addnav("Don't change colours, just go back to where I came from", $backlink);
            }
            output("`0Change your name again below, if you like.`n`n");
            namecolour_form();
            break;
        case "set":
            $fromname = $session['user']['name'];
            $newname = change_player_name(rawurldecode(httpget('newname')));
            $session['user']['name'] = $newname;
            output("You are now known as %s!`0`n`n", $session['user']['name']);
            if (!$free) {
                $id = has_item("hunterslodge_customcolours");
                delete_item($id);
            }
            addnav("Return");
            addnav("Go back to where I came from", $backlink);
            break;
    }
    page_footer();
}
//set initial store iitems
if (!isset($house['data']['store']['wood'])) {
    $house['data']['store']['wood'] = 0;
    improbablehousing_sethousedata($house);
}
if (!isset($house['data']['store']['stone'])) {
    $house['data']['store']['stone'] = 0;
    improbablehousing_sethousedata($house);
}
$giveitem = httpget('giveiitem');
$giveall = httpget('giveall');
$takeitem = httpget('takeiitem');
$takeall = httpget('takeall');
if ($giveitem) {
    if (!$giveall) {
        delete_item(has_item($giveitem));
        $house['data']['store'][$giveitem] += 1;
        output("You drop the item in the Dwelling's storehold.  The item that you dropped can now only be used for building, or taken out by the owner or someone with a Master Key.`n`n");
    } else {
        //give all iitems
        $q = delete_all_items_of_type($giveitem);
        $house['data']['store'][$giveitem] += $q;
    }
    improbablehousing_sethousedata($house);
} else {
    if ($takeitem) {
        if ($takeall) {
            $q = $house['data']['store'][$takeitem];
            // for ($i=0; $i<$q; $i++){
            // give_item($takeitem,false,false,true);
            // $house['data']['store'][$takeitem]-=1;
        include_once 'modules/f_list_inloc.php';
        $f = gen_header('магия');
        $f .= '<div class="y" id="lagfi"><b>цель</b></div><p>';
        $f .= list_inloc($LOGIN, 'cast_from_book&spell=' . $spell . '&book=' . $book);
        $f .= '<hr/>';
        $f .= '<a class="blue" href="game.php?sid=' . $sid . '&action=showinventory">в инвентарь</a><br/>';
        $f .= '<a class="blue" href="game.php?sid=' . $sid . '">в игру</a>';
        $f .= gen_footer();
        exit($f);
    }
} else {
    $to = preg_replace('/[^a-z0-9_\\.-]/i', '', $_GET['to']);
}
// snachala proverim, estq li kniga:
include_once 'modules/f_has_item.php';
if (!has_item($book, $LOGIN)) {
    put_error('у вас нету книги магии');
}
// proverim estq li v knige zaklinanie:
$q = do_mysql("SELECT on_take FROM items WHERE fullname = '" . $book . "' AND type = 'b';");
$magic = mysql_result($q, 0);
if (strpos($magic, $spell) === false) {
    put_g_error('в этой книге нету этого заклинания!');
}
// proverka na poslednee kastovanie:
include_once 'modules/f_check_last_cast.php';
if (!check_last_cast($LOGIN)) {
    // formiruem blokirujusheju stranicu, no na nej pomestim ssylku prodolzhitq dejstvie:
    $str = $_SERVER['QUERY_STRING'];
    // iz $str nado vyreatq sid
    // nam pomozhet strpos
function rail_collector_dohook($hookname, $args)
{
    global $session;
    switch ($hookname) {
        case "newday":
            set_module_pref("cardstoday", 0);
            $wherefound = array();
            set_module_pref("wherefound", serialize($wherefound));
            // calculate cardluck:
            // (we do it this way to have better control over the shape of the curve - bell is too generous)
            $c0 = get_module_setting("cardluckchance0");
            $c2 = get_module_setting("cardluckchance2");
            $c3 = get_module_setting("cardluckchance3");
            $c4 = get_module_setting("cardluckchance4");
            // a little paranoia never hurt anyone
            $c1 = 100 - $c0 - $c2 - $c3 - $c4;
            if ($c1 <= 0) {
                // the module settings are fubar'd. Go with the defaults
                $c0 = 5;
                $c1 = 60;
                $c2 = 25;
                $c3 = 5;
            }
            $t0 = $c0;
            $t1 = $t0 + $c1;
            $t2 = $t1 + $c2;
            $t3 = $t2 + $c3;
            $d100 = e_rand(1, 100);
            switch ($d100) {
                case $d100 <= $t0:
                    $luck = 0;
                    break;
                case $d100 <= $t1:
                    $luck = 1;
                    break;
                case $d100 <= $t2:
                    $luck = 2;
                    break;
                case $d100 <= $t3:
                    $luck = 3;
                    break;
                default:
                    $luck = 4;
            }
            set_module_pref("cardluck", $luck);
            if (rail_hascard("cardcase")) {
                if ($luck == 0) {
                    output("`2Something seems out of kilter today, you're not sure what.`0`n");
                }
                if ($luck >= 3) {
                    output("`2You feel very lucky today! Wonderful things might happen to you.`0`n");
                }
            }
            // award rail passes:
            $val = rail_collector_valuehand();
            if (!$val['firstclass'] && $val['value'] > 0) {
                // no Joker, so give them however many regular rail passes they are entitled to:
                for ($i = 0; $i < $val['value']; $i++) {
                    give_item("railpass");
                }
                // empty their hand (and if they had more than 5 cards, well... tough.)
                $qty = rail_collector_emptyhand();
                if ($val['value'] == 1) {
                    $phrase = "an `bImprobable Island Railway Company RAIL PASS`b";
                } else {
                    $phrase = "not just one, but `b" . $val['value'] . " Improbable Island Railway Company RAIL PASSES`b";
                }
                output("`2Uh-oh, your card case feels much lighter. You had %s valuable cards here and they've all been bloody `istolen!`i Filthy midget bast-- wait, what? What's this? In their place, you now have %s! Awesome! ...um, so maybe it wasn't midgets after all. Critical mass, improbability, whatever. Who cares!`0`n", $qty, $phrase);
            }
            // end - awarding of rail passes
            break;
            // end case 'newday'
        // end case 'newday'
        case "iitems_tradables-top":
            // remove any rail-feature tradables (ie, cards) if recipient has no card case.
            if (has_item("cardcase", false, $args['tradewith']['acctid']) === false) {
                $playerhascards = false;
                if (is_array($args['tradables'])) {
                    foreach ($args['tradables'] as $tkey => $tdetails) {
                        if ($tdetails['feature'] == "rail") {
                            $playerhascards = true;
                            unset($args['tradables'][$tkey]);
                        }
                    }
                }
                if ($playerhascards) {
                    output("Unfortunately, %s has no place to put any cards.`n`n", $args['tradewith']['name']);
                }
            }
            break;
            // end case 'iitems_tradables-top'
        // end case 'iitems_tradables-top'
        case "improbablehousing_interior":
            $hid = $args['hid'];
            $rid = $args['rid'];
            $locs = rail_collector_getlocs();
            $collectspot = 0;
            $key = "unknown";
            $phrase = "in a shadowy corner of the room";
            foreach ($locs as $loc => $locarray) {
                if ($hid == $locarray[0] && $rid == $locarray[1]) {
                    // We're in a place where a card could be found
                    $collectspot = 1;
                    $key = $loc;
                    $phrase = $locarray[2];
                    break;
                    // no need to keep looking through the rest of the array
                }
            }
            if ($collectspot) {
                // not allowed to find more than one card in a location
                $wherefound = unserialize(get_module_pref("wherefound"));
                $foundhere = 0;
                if (is_array($wherefound)) {
                    foreach ($wherefound as $lc => $larray) {
                        if ($larray[0] == $hid && $larray[1] == $rid) {
                            // woops, they already found a card in this location today
                            $foundhere = 1;
                        }
                    }
                }
                if (!$foundhere) {
                    debug("finding card?");
                    // all right, let them try their luck
                    if (rail_collector_findcard()) {
                        $wherefound[$key] = array($hid, $rid);
                        set_module_pref("wherefound", serialize($wherefound));
                        output("`2What luck! You find a smudged, battered old playing card %s. You've heard these can be worth quite a bit to a collector. Carefully you tuck it away in your fine leather card case.`0`n`n", $phrase);
                    }
                } else {
                    debug("Player has already found a card here.");
                }
            }
            break;
    }
    // end $hookname switch
    return $args;
}