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 worldmap_items_dohook($hookname, $args)
{
    global $session, $itemprefs;
    switch ($hookname) {
        case "inventory":
            //debug($args);
            if ($args['context'] == "worldmap") {
                $inv = $args['inventory'];
                $sort = $args['sort'];
                foreach ($inv as $itemid => $prefs) {
                    //debug($prefs);
                    if ($prefs['dropworldmap']) {
                        //						debug("Found something!");
                        addnav("", "inventory.php?items_context=" . $args['context'] . "&items_mapdrop=" . $prefs['itemid'] . "&items_sort={$sort}");
                        $args['inventory'][$itemid]['inventoryactions'] .= "<a href=\"inventory.php?items_context=" . $args['context'] . "&items_mapdrop=" . $prefs['itemid'] . "&items_sort={$sort}\">Drop this item on the Map</a> | ";
                        if ($args['inventory'][$itemid]['quantity'] > 1 && !$prefs['dropworldmap_blockdropall']) {
                            addnav("", "inventory.php?items_context=" . $args['context'] . "&items_mapdrop=" . $prefs['itemid'] . "&items_sort={$sort}&dropall=true");
                            $args['inventory'][$itemid]['inventoryactions'] .= "<a href=\"inventory.php?items_context=" . $args['context'] . "&items_mapdrop=" . $prefs['itemid'] . "&items_sort={$sort}&dropall=true\">Drop all</a> | ";
                        }
                        $args['inventory'][$itemid]['cannotdiscard'] = true;
                    }
                }
            }
            break;
        case "inventory-predisplay":
            if ($args['context'] == "worldmap") {
                $drop = httpget("items_mapdrop");
                if ($drop) {
                    $loc = get_module_pref("worldXYZ", "worldmapen");
                    if (httpget("dropall")) {
                        $todrop = get_all_items($drop);
                        $dropids = array();
                        foreach ($todrop as $id => $vals) {
                            $dropids[] = $id;
                        }
                        change_item_owner($dropids, "worldmap_" . $loc);
                    } else {
                        change_item_owner($drop, "worldmap_" . $loc);
                    }
                }
            }
            break;
        case "worldnav":
            $ploc = implode(",", $args);
            $squarestuff = load_inventory("worldmap_" . $ploc, true);
            $itemid = httpget('item-pickup');
            if ($itemid) {
                //Pick up iitems
                if (httpget('pickupall')) {
                    //Pick up all iitems
                    $itemtype = $squarestuff[$itemid]['item'];
                    $pickup = array();
                    foreach ($squarestuff as $sqitemid => $sqprefs) {
                        //debug($sqprefs);
                        if ($sqprefs['item'] == $itemtype) {
                            $pickup[] = $sqitemid;
                        }
                    }
                    //debug($pickup);
                    change_item_owner($pickup, $session['user']['acctid']);
                    output("`0You pick up the %s.`n", $squarestuff[$itemid]['plural']);
                } else {
                    //Pick up single iitem
                    if ($squarestuff[$itemid]) {
                        output("`0You pick up the %s.`n", $squarestuff[$itemid]['verbosename']);
                        change_item_owner($itemid, $session['user']['acctid']);
                    } else {
                        output("`0You bend over to pick up the item, but it's suddenly not there anymore!  Some crafty bastard has pinched it from right under your nose!`n");
                    }
                }
                //reload this square's inventory
                $squarestuff = load_inventory("worldmap_" . $ploc, true);
            }
            $squarestuff = group_items($squarestuff);
            //debug($squarestuff);
            foreach ($squarestuff as $sortid => $prefs) {
                $itemid = $prefs['itemid'];
                $showmsg = true;
                if ($prefs['quantity'] > 1 && !$prefs['dropworldmap_blockdropall']) {
                    addnav("Pick up items");
                    addnav(array("Pick up %s", $prefs['verbosename']), "runmodule.php?module=worldmapen&op=continue&item-pickup=" . $itemid);
                    addnav(array("Pick up all %s", $prefs['plural']), "runmodule.php?module=worldmapen&op=continue&item-pickup=" . $itemid . "&pickupall=true");
                    output("`0There are %s %s here.`n`n", $prefs['quantity'], $prefs['plural']);
                } else {
                    addnav("Pick up items");
                    addnav(array("Pick up %s", $prefs['verbosename']), "runmodule.php?module=worldmapen&op=continue&item-pickup=" . $itemid);
                    output("`0There is a %s here.`n`n", $prefs['verbosename']);
                }
            }
            if ($showmsg && $session['user']['dragonkills'] < 1 && $session['user']['level'] < 10) {
                output("`JLogs and stone are only really useful if you're building a Dwelling.  To build a Dwelling, you'll need a Land Claim stake from Improbable Central, which will set you back 100 Cigarettes.  If you're not building a Dwelling, then there's not much reason to pick them up (logs and stone are really heavy!).  This message will disappear once you've got a few more levels under your belt.`0`n");
            }
            break;
    }
    return $args;
}
function giftstation_run()
{
    global $session;
    page_header("The Gifting Station");
    $op = httpget('op');
    $points = $session['user']['donation'] - $session['user']['donationspent'];
    switch ($op) {
        case "start":
            if (httpget("subop") == "continue") {
                output("The KittyMorph shows you a big smile.  \"`1Okay, that'll be delivered first thing in the morning.  Should make for a nice surprise when they wake up.  Anyone else you'd like to send a gift to?`0\"`n`n");
                $player = httpget('player');
                $itemid = httpget('item');
                $box = httpget('box');
                $free = httpget('free');
                $anonymous = httpget('anonymous');
                $boxid = give_item($box, false, "giftstation_" . $player);
                //	debug($boxid);
                //	debug($itemid);
                change_item_owner($itemid, $boxid);
                set_item_pref("giftbox_contains", $itemid, $boxid);
                if (!$anonymous) {
                    $desc = get_item_pref("description", $boxid);
                    $desc .= "`nThere's a gift tag attached to the box, telling you that this present came from " . $session['user']['name'] . "`0.";
                    set_item_pref("description", $desc, $boxid);
                }
                //notify player that they've got something awesome waiting for them
                require_once "lib/systemmail.php";
                $body = "Someone has used the Gifting Station in Common Ground to send you something.  Whatever it is, it'll turn up on your next new Game Day.";
                systemmail($player, "Someone sent you something awesome!", $body);
                if (!$free) {
                    $session['user']['donationspent'] += 1;
                    //log purchase
                    $sql = "INSERT INTO " . db_prefix("purchaselog") . " (acctid,purchased,amount,data,giftwrap,timestamp) VALUES ('" . $session['user']['acctid'] . "','giftstation_giftwrap','1','none','0','" . date("Y-m-d H:i:s") . "')";
                    $points = $session['user']['donation'] - $session['user']['donationspent'];
                }
                addnav("No, I think that'll do, thanks.", "gardens.php");
            } else {
                if (httpget("subop") == "searchagain") {
                    output("The KittyMorph nods, scratching out the contestant's name on his clipboard.  \"`1No problem.  Let's take it from the top.`0\"`n`n");
                    addnav("Actually, forget the whole thing.", "gardens.php");
                } else {
                    output("`0You head into the Gift Exchange.  A black-furred KittyMorph stands behind a counter.`n`n\"`1Hey there!`0\" he says.  \"`1As part of our continued diplomatic efforts, we provide a gift-wrapping service for items you'd like to send to your fellow contestants.  Interested?`0\"`n`n");
                    output("It costs one Supporter Point to gift-wrap and transfer (nearly) any item to any player.  Some items can be transferred for free.  You currently have %s Supporter Points.`n`n", number_format($points));
                    addnav("No thanks.", "gardens.php");
                }
            }
            if ($points > 0) {
                output("Search below for a player to send a present to.");
                rawoutput("<form action='runmodule.php?module=giftstation&op=findplayer' method='post'>");
                rawoutput("<input name='name'>");
                rawoutput("<input type='submit' class='button' value='" . translate_inline("search") . "'>");
                rawoutput("</form>");
                addnav("", "runmodule.php?module=giftstation&op=findplayer");
            } else {
                output("You don't have any Supporter Points!`n`n");
            }
            break;
        case "findplayer":
            $search = "%";
            $n = httppost('name');
            for ($x = 0; $x < strlen($n); $x++) {
                $search .= substr($n, $x, 1) . "%";
            }
            $search = " AND name LIKE '" . addslashes($search) . "' ";
            $uid = $session['user']['uniqueid'];
            $lastip = $session['user']['lastip'];
            $sql = "SELECT uniqueid, acctid, name FROM " . db_prefix("accounts") . " WHERE locked=0 {$search} ORDER BY name DESC ";
            $result = db_query($sql);
            output("The KittyMorph nods.  \"`1Okay, let's have a look at who I've got written down here whose name sounds like that...`0\"`n`n");
            $matches = 0;
            for ($i = 0; $i < db_num_rows($result); $i++) {
                $row = db_fetch_assoc($result);
                if ($row['uniqueid'] != $session['user']['uniqueid']) {
                    addnav("", "runmodule.php?module=giftstation&op=chooseitem&player=" . $row['acctid']);
                    output_notl("<a href='runmodule.php?module=giftstation&op=chooseitem&player=" . $row['acctid'] . "'>" . $row['name'] . "</a>", true);
                    output("`n");
                    $matches++;
                }
            }
            if ($matches == 0) {
                output("He looks down at his list.  \"`1Oh.  Actually, it doesn't look like there's `ianyone`i matching that description who you can send a present to.  Bummer.  Wanna try that again?`0\"");
            }
            addnav("Return to Common Ground", "gardens.php");
            addnav("Search Again", "runmodule.php?module=giftstation&op=start");
            break;
        case "chooseitem":
            $player = httpget('player');
            output("The KittyMorph reaches below his counter and brings up a clipboard on which he writes down the name of your nominated contestant.  \"`1Okay, I've got the name - now, what would you like to send?`0\"`n`n");
            $giftables = get_items_with_prefs("giftable");
            if ($giftables) {
                $giftables = group_items($giftables);
                foreach ($giftables as $sortid => $prefs) {
                    $itemid = $prefs['itemid'];
                    if ($prefs['freegift']) {
                        addnav("Send for free");
                        addnav(array("%s (%s available)", $prefs['verbosename'], $prefs['quantity']), "runmodule.php?module=giftstation&op=choosewrapping&item={$itemid}&player={$player}&free=1");
                    } else {
                        addnav("Send for one Supporter Point");
                        addnav(array("%s (%s available)", $prefs['verbosename'], $prefs['quantity']), "runmodule.php?module=giftstation&op=choosewrapping&item={$itemid}&player={$player}&free=0");
                    }
                }
                addnav("Cancel?");
                addnav("Wait, I've changed my mind.  Let's back up a step.", "runmodule.php?module=giftstation&op=start&subop=searchagain");
                addnav("Actually, forget the whole thing.", "gardens.php");
            } else {
                output("You realise that you have nothing that you can give away.  You shrug your shoulders and give the KittyMorph a big, silly grin.`n`n");
                addnav("This is awkward.");
                addnav("Run out of the shop.  Just run.", "gardens.php");
            }
            break;
        case "choosewrapping":
            $player = httpget('player');
            $itemid = httpget('item');
            $free = httpget('free');
            output("The KittyMorph nods, taking the item from you and beginning to wrap it in tissue paper.  \"`1They should be pleased with that.  Care to choose a box, while I wrap this up?`0\"`n`nClick on any box to confirm the gift.`n`n");
            $boxes = get_items_with_settings("giftwrap");
            foreach ($boxes as $boxid => $prefs) {
                $img = $prefs['image'];
                rawoutput("<a href='runmodule.php?module=giftstation&op=chooseanonymous&player={$player}&item={$itemid}&box={$boxid}&free={$free}'><img src='images/items/{$img}'></a>");
                addnav("", "runmodule.php?module=giftstation&op=chooseanonymous&player={$player}&item={$itemid}&box={$boxid}&free={$free}");
            }
            addnav("Cancel?");
            addnav("Wait, I've changed my mind.  Let's back up a step.", "runmodule.php?module=giftstation&op=start&subop=searchagain");
            addnav("Actually, forget the whole thing.", "gardens.php");
            break;
        case "chooseanonymous":
            $player = httpget('player');
            $itemid = httpget('item');
            $free = httpget('free');
            $box = httpget('box');
            output("The KittyMorph ties a ribbon around the box before reaching below the counter and bringing up a gift tag and a preposterously flamboyant quill pen.`n`n\"`1So, is this an anonymous gift, or would you like your name on it?`0\"`n`n");
            addnav("Anonymous or not?");
            addnav("Tell them who it's from", "runmodule.php?module=giftstation&op=start&subop=continue&player={$player}&item={$itemid}&box={$box}&free={$free}");
            addnav("Give anonymously", "runmodule.php?module=giftstation&op=start&subop=continue&player={$player}&item={$itemid}&box={$box}&free={$free}&anonymous=true");
            break;
    }
    page_footer();
    return true;
}
function iitems_trader_run()
{
    global $session;
    //	global $module_prefs;
    $op = httpget('op');
    $id = httpget('id');
    $ret = httpget('ret');
    $return = rawurlencode($ret);
    $tradables = get_tradables();
    // debug($tradables);
    $sql = "SELECT uniqueid, acctid, name, sex FROM " . db_prefix('accounts') . " WHERE acctid = " . $id;
    $result = db_query($sql);
    $tradewith = db_fetch_assoc($result);
    $bioname = $tradewith['name'];
    if ($tradewith['sex'] == 0) {
        $subj = "he";
        $obj = "him";
        $poss = "his";
    } else {
        $subj = "she";
        $obj = "her";
        $poss = "her";
    }
    $hookargs = array();
    $hookargs['tradables'] = $tradables;
    $hookargs['tradewith'] = $tradewith;
    $hookargs['return'] = $return;
    // This hook is to allow modules to remove items from the tradables list if
    // the proposed trading partner does not qualify -- for instance, has no card case.
    //	debug("before iitems_tradables-top hook:");
    //	debug($hookargs);
    $hookargs = modulehook("iitems_tradables-top", $hookargs);
    //	debug("after iitems_tradables-top hook:");
    //	debug($hookargs);
    $tradables = $hookargs['tradables'];
    page_header("Trade!");
    switch ($op) {
        case "trade":
            $cantrade = true;
            if (!isset($hookargs['specialdesc'])) {
                switch (count($tradables)) {
                    case 0:
                        $phrase = "nothing";
                        $cantrade = false;
                        break;
                    case 1:
                        // I know, this isn't quite accurate. Should be 'one type of item' -
                        // but that's programmer-speak. Let's stick to English as much as we can.
                        $phrase = "one item";
                        break;
                    default:
                        $phrase = count($tradables) . " different items";
                        break;
                }
            } else {
                switch (count($tradables) - 1) {
                    case 0:
                        $phrase = "nothing, except ";
                        break;
                    case 1:
                        $phrase = "one item and ";
                        break;
                    default:
                        $phrase = count($tradables) - 1 . " different items and ";
                        break;
                }
                $phrase .= $hookargs['specialdesc'];
            }
            output("Searching through your possessions, you find you have %s you could trade to %s.`n`n", $phrase, $bioname);
            //			debug($tradables);
            if ($cantrade) {
                addnav("Trade");
                foreach ($tradables as $key => $details) {
                    addnav(array("(%s) %s", $details['quantity'], $details['verbosename']), "runmodule.php?module=iitems_trader&op=tradewarn&id={$id}&item={$key}&ret={$return}");
                }
                $hookargs = modulehook("iitems_tradables-link", $hookargs);
            }
            break;
        case "tradewarn":
            $tradableskey = httpget('item');
            if (!get_module_pref('hastraded')) {
                output("Ah, so you're interested in trading your `b%s`b to someone. All right, that could be a very good move, but listen. You only get to control your own actions. What other people do is up to them. Either... make sure you've agreed on the trade beforehand and `b%s`b is someone you trust to give you whatever you're trading this item for... or think of yourself as a kind philanthropist who's generously giving things away.`n`nNo, seriously. Trading is between you and the other person. Talk to %s, negotiate with %s, haggle with %s, conclude the deal. If %s doesn't deliver the goods this time, hey, you'll know who %s is. You don't have to deal with %s again. The admin and game mods are not police and `iwill not`i intervene, so don't even ask.`n`nWith that obligatory warning out of the way...`0`n`n", $tradables[$tradableskey]['verbosename'], $bioname, $obj, $obj, $obj, $subj, $subj, $obj);
            }
            output("You're quite sure you want to trade your %s to %s?`n`n", $tradables[$tradableskey]['verbosename'], $bioname);
            addnav("Trade");
            addnav("Yes, do it!", "runmodule.php?module=iitems_trader&op=tradefinal&id={$id}&item={$tradableskey}&ret={$return}");
            addnav("Wait, no, not that...", "runmodule.php?module=iitems_trader&op=trade&id={$id}&ret={$return}");
            break;
        case "tradefinal":
            $tradableskey = httpget('item');
            $itemid = $tradables[$tradableskey]['itemid'];
            // This hook is to allow special handling of the transfer for collectibles that need to get fancy.
            // (Example - marbles.) When using this hook, you'll have to:
            //      Do your own transfer to the other player
            //      Change the $item-th row in $hookargs['tradables'] to contain the itemid and verbosename
            //        you want to appear in the trading history and the 'Mission accomplished' message
            //      Set $hookargs['specialhandling'] to 1
            $hookargs['specialhandling'] = 0;
            //	debug("before iitems_tradables-final hook:");
            //	debug($hookargs);
            $hookargs = modulehook("iitems_tradables-final", $hookargs);
            //	debug("after iitems_tradables-final hook:");
            //	debug($hookargs);
            $tradables = $hookargs['tradables'];
            if (!isset($hookargs['specialdesc'])) {
                change_item_owner($itemid, $id);
                $message = $tradables[$tradableskey]['feature'] . ": " . $tradables[$tradableskey]['itemid'] . " (" . $tradables[$tradableskey]['verbosename'] . ") to " . $bioname . ".";
                debuglog($message, $id, false, "trade");
                output("Mission accomplished! %s now has your %s.", $bioname, $tradables[$tradableskey]['verbosename']);
                // send a distraction to tell the other player what they just received.
                require_once "lib/systemmail.php";
                $subj = $tradables[$tradableskey]['verbosename'] . " for your collection";
                $body = $session['user']['name'] . " has just traded you a valuable " . $tradables[$tradableskey]['verbosename'] . "! Awesome!";
                systemmail($id, $subj, $body);
            }
            set_module_pref("hastraded", 1);
            break;
        case "history":
            output("`bRecent Trade History of %s`b`n`n", $bioname);
            $dblog = db_prefix('debuglog');
            $accts = db_prefix('accounts');
            $sql = "SELECT date, actor, target, message FROM " . $dblog . " WHERE actor = " . $id . " AND field = 'trade' ORDER BY date DESC";
            $history = array();
            $result = db_query($sql);
            if (db_num_rows($result) > 0) {
                output("Performed the following trades:`n");
                rawoutput("<table border=0 cellpadding=2 cellspacing=1 bgcolor='#999999'>", true);
                rawoutput("<tr class='trhead'><td>timestamp</td><td>(rel)</td><td>trading action</td></tr>");
                $classcount = 1;
                for ($i = 0; $i < db_num_rows($result); $i++) {
                    $classcount++;
                    $class = $classcount % 2 ? "trdark" : "trlight";
                    rawoutput("<tr class='{$class}'><td>");
                    $row = db_fetch_assoc($result);
                    $time = strtotime($row['date']) + $session['user']['prefs']['timeoffset'] * 60 * 60;
                    $abstime = date("m/d h:ia", $time);
                    $reltime = reltime(strtotime($row['date']));
                    output($abstime);
                    rawoutput("</td><td>");
                    output($reltime);
                    rawoutput("</td><td>");
                    output("traded %s`n", $row['message']);
                    rawoutput("</td></tr>");
                    // end the row
                }
                // end of for
                rawoutput("</table>");
            } else {
                output("Performed no trades.`n");
            }
            $sql = "SELECT date, actor, name, target, message FROM " . $dblog . " LEFT JOIN " . $accts . " ON " . $dblog . ".actor = " . $accts . ".acctid WHERE target = " . $id . " AND field = 'trade' ORDER BY date DESC";
            $rhistory = array();
            $result = db_query($sql);
            if (db_num_rows($result) > 0) {
                output("`nReceived the following items in trade:`n");
                rawoutput("<table border=0 cellpadding=2 cellspacing=1 bgcolor='#999999'>", true);
                rawoutput("<tr class='trhead'><td>timestamp</td><td>(rel)</td><td>who</td><td>trading action</td></tr>");
                $classcount = 1;
                for ($i = 0; $i < db_num_rows($result); $i++) {
                    $classcount++;
                    $class = $classcount % 2 ? "trdark" : "trlight";
                    rawoutput("<tr class='{$class}'><td>");
                    $row = db_fetch_assoc($result);
                    $time = strtotime($row['date']) + $session['user']['prefs']['timeoffset'] * 60 * 60;
                    $abstime = date("m/d h:ia", $time);
                    $reltime = reltime(strtotime($row['date']));
                    output($abstime);
                    rawoutput("</td><td>");
                    output($reltime);
                    rawoutput("</td><td>");
                    output($row['name']);
                    rawoutput("</td><td>");
                    output("traded %s`n", $row['message']);
                    rawoutput("</td></tr>");
                    // end the row
                }
                // end of for
                rawoutput("</table>");
            } else {
                output("`nReceived no items in trade.`n");
            }
            break;
    }
    addnav("Back");
    addnav(array("To %s bio", $poss), "bio.php?char={$id}&ret={$return}");
    page_footer();
    return true;
}