function umc_depositbox_consolidate()
{
    global $UMC_USER;
    $uuid = $UMC_USER['uuid'];
    // find all doupliecate entries
    $sql_doubles = " SELECT count(id) AS counter, item_name, damage, meta\r\n        FROM minecraft_iconomy.deposit\r\n        WHERE recipient_uuid='{$uuid}'\r\n        GROUP BY item_name, damage, meta HAVING COUNT(id) > 1";
    $doubles = umc_mysql_fetch_all($sql_doubles);
    $source_boxes = count($doubles);
    $target_boxes = 0;
    if ($source_boxes > 0) {
        foreach ($doubles as $row) {
            // then we take each entry that is not created by the user and move it to a box created by the user
            $sql_fix = "SELECT * FROM minecraft_iconomy.deposit\r\n                WHERE item_name='{$row['item_name']}'\r\n\t\t    AND damage='{$row['damage']}\r\n\t\t    AND meta='{$row['meta']}\r\n\t\t    AND recipient_uuid='{$uuid}'\r\n\t\t    AND sender_uuid !='{$uuid}';;";
            $fix_data = umc_mysql_fetch_all($sql_fix);
            if (count($fix_data) > 0) {
                $target_boxes++;
                foreach ($fix_data as $fix_row) {
                    umc_db_take_item('deposit', $fix_row['id'], $fix_row['amount'], $uuid);
                    umc_deposit_give_item($uuid, $fix_row['item_name'], $fix_row['damage'], $fix_row['meta'], $fix_row['amount'], $uuid);
                }
            }
        }
    }
    if ($source_boxes > 0) {
        umc_echo("{green}[+]{gray} Found {yellow}{$source_boxes}{gray} items spread over several boxes consolidated them to {$target_boxes} deposit boxes!.");
    } else {
        umc_echo("{yellow}[?]{gray} Unable to consolidate depositbox, no compatible items found.");
    }
}
/**
 * Add items to a user inventory. If cancel=true, we check if the current user is owner of the goods
 *
 * @global type $UMC_USER
 * @param type $id
 * @param type $amount
 * @param type $table
 * @param boolean $cancel
 * @param type $to_deposit
 * @param string $uuid
 * @return string
 */
function umc_checkout_goods($id, $amount, $table = 'stock', $cancel = false, $to_deposit = false, $uuid = false)
{
    global $UMC_USER, $UMC_ENV;
    XMPP_ERROR_trace(__FUNCTION__, func_get_args());
    if (!$uuid) {
        $player = $UMC_USER['username'];
        $uuid = $UMC_USER['uuid'];
    } else {
        $player = umc_user2uuid($uuid);
    }
    if (!is_numeric($id)) {
        umc_error('{red}Invalid ID. Please use {yellow}/shophelp;');
    }
    // the fact that the source is also a condition prevents people to cancel other users' items.
    if ($table == 'stock') {
        if ($cancel) {
            $sql = "SELECT * FROM minecraft_iconomy.stock WHERE uuid='{$uuid}' AND id='{$id}' LIMIT 1;";
        } else {
            $sql = "SELECT * FROM minecraft_iconomy.stock WHERE id='{$id}' LIMIT 1;";
        }
    } else {
        if ($table == 'deposit') {
            $sql = "SELECT * FROM minecraft_iconomy.deposit WHERE (sender_uuid='{$uuid}' OR recipient_uuid='{$uuid}') AND id='{$id}' LIMIT 1;";
        }
    }
    $D = umc_mysql_fetch_all($sql);
    if (count($D) == 0) {
        umc_error("{red}Id {white}{$id}{red} not found! Please try again.;");
    } else {
        $row = $D[0];
        $item = umc_goods_get_text($row['item_name'], $row['damage'], $row['meta']);
        $meta_cmd = $meta = '';
        if ($row['meta'] != '') {
            $meta_arr = unserialize($row['meta']);
            if (!is_array($meta_arr)) {
                XMPP_ERROR_trigger("Could not get Meta Data array for {$table} id {$id}: " . var_export($row, true));
            }
            if ($row['item_name'] == "banner") {
                $meta_cmd = umc_banner_get_data($meta_arr);
            } else {
                foreach ($meta_arr as $type => $lvl) {
                    $meta_cmd .= " {$type}:{$lvl}";
                }
            }
        }
        // handle unlimited items
        $unlimited = false;
        if ($row['amount'] == -1) {
            $row['amount'] = $amount;
            $unlimited = true;
        }
        //umc_echo('There were ' . $row['amount'] . " pieces of " . $item['item_name'] . "$meta_txt stored.");
        // determine withdrawal amount
        if (is_numeric($amount) && $amount <= $row['amount']) {
            $sellamount = $amount;
        } else {
            if ($amount == 'max') {
                // withdraw all
                $sellamount = $row['amount'];
                //umc_echo("You are withdrawing all ($sellamount) {$item['name']}$meta_txt");
            } else {
                if (is_numeric($amount) && $amount > $row['amount']) {
                    umc_echo("{yellow}[!]{gray} Available amount ({yellow}{$row['amount']}{gray}) less than amount specified ({yellow}{$amount}{gray})");
                    $sellamount = $row['amount'];
                } else {
                    umc_error("{red}Amount {white}'{$amount}'{red} is not numeric;");
                }
            }
        }
        if ($table != 'stock') {
            umc_echo("{green}[+]{gray} You are withdrawing {yellow} {$amount} {gray} of {$item['full']}{gray}.");
        }
        if ($table == 'stock') {
            $cost = $sellamount * $row['price'];
            if ($cancel) {
                $target = $uuid;
                $source = 'cancel00-sell-0000-0000-000000000000';
            } else {
                $target = $uuid;
                $source = $row['uuid'];
            }
        } else {
            if ($table == 'deposit') {
                if ($row['recipient_uuid'] == $uuid) {
                    $cancel = true;
                }
                $cost = 0;
                if ($cancel) {
                    $target = $uuid;
                    $source = 'cancel00-depo-0000-0000-000000000000';
                } else {
                    $target = $row['recipient_uuid'];
                    $source = $row['sender_uuid'];
                }
            }
        }
        if (!$to_deposit) {
            umc_check_space($sellamount, $item['item_name'], $item['type']);
            // the in-game command does not understand item_names yet
            umc_ws_cmd("give {$player} {$item['item_name']}:{$item['type']} {$sellamount}{$meta_cmd};", 'asConsole');
            umc_log('inventory', 'give', "{$player} received {$item['full_clean']} {$sellamount}");
        } else {
            umc_deposit_give_item($target, $item['item_name'], $item['type'], $meta, $sellamount, $source);
            umc_log('inventory', 'give_deposit', "{$player} recived in deposit {$item['full_clean']} {$sellamount}");
        }
        //umc_echo("./give $player {$item['id']}:{$item['type']} $sellamount$meta_cmd");
        // check status
        umc_shop_transaction_record($source, $target, $sellamount, $cost, $item['item_name'], $item['type'], $meta);
        if ($unlimited) {
            return "unlimited";
        }
        // fix the stock levels
        $amount_left = umc_db_take_item($table, $id, $sellamount, $source);
        if ($UMC_ENV == 'websend') {
            if ($amount_left == 0) {
                umc_echo("{green}[+]{gray} No more {green}{$item['full']}{gray} now in stock.");
            } else {
                umc_echo("{green}[+]{yellow} {$amount_left}{green} {$item['full']}{gray} remaining in stock.");
            }
        }
        return $amount_left;
    }
}
function umc_do_sell_internal($from_deposit = false)
{
    global $UMC_USER;
    $player = $UMC_USER['username'];
    $args = $UMC_USER['args'];
    $uuid = $UMC_USER['uuid'];
    if (!isset($args[2]) || !is_numeric($args[2])) {
        umc_error("{red}You need a valid shop_id to sell to a requester. Use {yellow}/find request ...;");
        umc_error("{red}Maybe you meant {yellow}/offer{red}, for posting an offer for sale in the shop.;");
    }
    $do_check = false;
    $pos = array_search('check', $args);
    if ($pos) {
        $do_check = true;
        array_splice($args, $pos, 1);
    }
    $id = $args[2];
    $sql_request = "SELECT * FROM minecraft_iconomy.request WHERE id='{$id}' LIMIT 1;";
    $request_data = umc_mysql_fetch_all($sql_request);
    if (count($request_data) == 0) {
        umc_error("{red}The shop-id {white}{$id}{red} could not be found. Please use {yellow}/find{red} and{yellow} /shophelp sell;");
    }
    $request = $request_data[0];
    $request_item = umc_goods_get_text($request['item_name'], $request['damage'], $request['meta']);
    if ($request['uuid'] == $uuid && $player != 'uncovery') {
        umc_error("{red}You cannot fulfill your own requests. Use {yellow}/cancel r <id>{red} instead!;");
    }
    // do we sell items from deposit?
    if ($from_deposit) {
        $depot_id = $args[3];
        array_splice($args, 3, 1);
        $sql = "SELECT * from minecraft_iconomy.deposit WHERE recipient_uuid='{$uuid}' and id='{$depot_id}'";
        $D = umc_mysql_fetch_all($sql);
        if (count($D) < 1) {
            umc_error("You have no such deposit ID");
        }
        $depot_row = $D[0];
        $inv = $depot_row['amount'];
        $depot_item = umc_goods_get_text($depot_row['item_name'], $depot_row['damage'], $depot_row['meta']);
        if ($depot_item != $request_item) {
            //umc_echo("{green}$type:$data {gray} => {red}".$check_inv[$item_slot]['id'].":".$check_inv[$item_slot]['data']);
            umc_error("{red}The item in deposit-id {white}{$depot_id}{red} doesn't match request {white}{$id}{red}.");
        }
    } else {
        $item_slot = $UMC_USER['current_item'];
        $check_inv = $UMC_USER['inv'];
        if (!isset($check_inv[$item_slot])) {
            umc_error("{red}You need to hold the item you want to sell!;");
        }
        $inv_item = umc_goods_get_text($check_inv[$item_slot]['id'], $check_inv[$item_slot]['data'], $check_inv[$item_slot]['meta']);
        if ($inv_item != $request_item) {
            //umc_error_longmsg("Sell failed");
            //umc_echo("{green}$type:$data {gray} => {red}".$check_inv[$item_slot]['id'].":".$check_inv[$item_slot]['data']);
            umc_error("{red}The item you're holding doesn't match request id {white}{$id}{red}.");
        }
    }
    if (!isset($args[3])) {
        umc_echo("{yellow}[!]{gray} You did not enter an amount. Attempting to sell all.");
        $amount = false;
    } else {
        $args[3] = intval($args[3]);
        $amount = umc_sanitize_input($args[3], 'amount');
    }
    if (!$amount) {
        // sell as much as possible
        $amount = $request['amount'];
    }
    if ($amount > $request['amount']) {
        umc_error("{red}That's too much, the request is only for {yellow}{$request['amount']}{red} pieces.");
    }
    if (!$from_deposit) {
        $inv = umc_check_inventory($request_item['item_name'], $request_item['type'], $request_item['meta']);
        if ($inv == 0) {
            umc_error("{red}You don't have any of the requested item.");
        }
    }
    if ($inv < $amount) {
        umc_echo("{yellow}[!]{gray} Not enough for entire request.  Selling as much as possible.");
        $amount = $inv;
    }
    $recipient_uuid = $request['uuid'];
    $recipient = umc_user2uuid($recipient_uuid);
    if ($do_check) {
        umc_echo("{white}[?]{gray} This would sell {yellow}{$amount} {$request_item['full']}{darkgray} for {cyan}{$request['price']}{gray} each to {gold}{$recipient}");
        $sum = $amount * $request['price'];
        umc_echo("{white}[?]{gray} Your account would be credited {cyan}{$sum}{gray} Uncs.");
        return;
    }
    umc_echo("{green}[+] {gray}Selling {yellow}{$amount} {$request_item['full']}{darkgray} for {cyan}{$request['price']}{gray} each to {gold}{$recipient}");
    if ($from_deposit) {
        umc_db_take_item('deposit', $depot_id, $amount, $uuid);
    } else {
        umc_clear_inv($request_item['item_name'], $request_item['type'], $amount, $request_item['meta']);
    }
    $sum = $amount * $request['price'];
    umc_money(false, $player, $sum);
    umc_echo("{green}[\$]{gray} Your account has been credited {cyan}{$sum}{gray} Uncs.");
    $sql = "SELECT * FROM minecraft_iconomy.deposit\r\n        WHERE item_name='{$request_item['item_name']}'\r\n\t    AND recipient_uuid='{$request['uuid']}'\r\n            AND damage='{$request_item['type']}'\r\n\t    AND meta='{$request_item['meta']}'\r\n\t    AND sender_uuid='shop0000-0000-0000-0000-000000000000';";
    $D = umc_mysql_fetch_all($sql);
    // check first if item already is in the recipient's deposit
    if (count($D) > 0) {
        $update_row = $D[0];
        umc_echo("{green}[+]{gray} There is already {$request_item['full']}{gray} in the deposit for {gold}{$recipient}{gray}, adding {yellow}{$amount}{gray}.");
        $sql = "UPDATE minecraft_iconomy.`deposit` SET `amount`=amount+'{$amount}' WHERE `id`={$update_row['id']} LIMIT 1;";
    } else {
        // create a new deposit box
        umc_echo("{green}[+]{gray} Depositing {yellow} {$amount} {$request_item['full']}{gray} for {gold}{$recipient}");
        $sql = "INSERT INTO minecraft_iconomy.`deposit` (`damage` ,`sender_uuid` ,`item_name` ,`recipient_uuid` ,`amount` ,`meta`)\r\n            VALUES ('{$request_item['type']}', 'shop0000-0000-0000-0000-000000000000', '{$request_item['item_name']}', '{$recipient_uuid}', '{$amount}', '{$request_item['meta']}');";
    }
    umc_mysql_query($sql, true);
    if ($amount < $request['amount']) {
        // Update existing listing
        $sql = "UPDATE minecraft_iconomy.`request` SET `amount`=amount-'{$amount}' WHERE id={$request['id']} LIMIT 1;";
        umc_mysql_query($sql, true);
        //umc_echo("{purple}".$sql);
        //umc_echo("{red}".mysql_error());
    } else {
        // Delete the listing entirely
        $sql = "DELETE FROM minecraft_iconomy.`request` WHERE id={$request['id']}";
        umc_mysql_query($sql, true);
        //umc_echo("{red}".mysql_error());
    }
    // record transaction
    umc_shop_transaction_record($uuid, $request['uuid'], $amount, $sum, $request_item['item_name'], $request_item['type'], $request_item['meta']);
    // message recipient
    $msg = "{$player} sold you {$amount} {$request_item['full']} per your request, check your /depotlist!;";
    umc_msg_user($recipient, $msg);
    // record logfile
    umc_log('shop', 'sell_on_request', "{$player} sold {$amount} of {$request_item['full_clean']} to {$recipient} (ID: {$request['id']})");
}