/**
 * Buy XP in-game // function is still working with usernames instead of UUID since
 * the /xp command does not work with UUIDs (yet) *
 *
 * @global type $UMC_USER
 */
function umc_do_buyxp()
{
    global $UMC_USER;
    $player = $UMC_USER['username'];
    $args = $UMC_USER['args'];
    $xp_ratio = 1;
    // check to see if player has entered a value of xp to buy
    if (isset($args[2])) {
        // feedback on current xp point values
        $user_xp = $UMC_USER['xp'];
        umc_echo("{white} You started with {$user_xp} experience points.");
        // amount player is trying to spend
        $amount = $args[2];
        // cast argument to type int to sanitise the data
        settype($amount, 'int');
        // amount of xp calculated
        $xp = floor($amount * $xp_ratio);
        // retrieve the players balance to check if they can afford
        $balance = umc_money_check($player);
        if ($xp < 1 || $amount < 1) {
            umc_error("{red}You need to buy at least 1 XP. For {$amount} Uncs you get only {$xp} XP (ratio is {$xp_ratio}!)");
        }
        if ($amount > $balance) {
            umc_error("{red}Sorry, you cannot afford this purchase. You currently have {$balance} uncs.");
        }
        // calculate the total new xp point value
        $new_xp = $user_xp + $xp;
        // apply purchase
        // send the console command to give the player experience
        umc_ws_cmd("exp set {$player} {$new_xp}", 'asConsole');
        // take the purchase amount from players account.
        // take from, give to, positive value
        umc_money($player, false, $amount);
        // announce the purchase to encourage players to consider buying xp
        umc_announce("{gold}{$player}{gray} just bought {purple}{$xp} XP{gray} for{cyan} {$amount} Uncs{gray}!");
        umc_echo("{white} You ended with {$new_xp} experience points.");
        // log the purchase
        umc_log('buyxp', 'buy', "{$player} paid {$amount} for {$xp} XP, going from {$user_xp} to {$new_xp}");
    } else {
        umc_error("{red}You need to specify the amount of Uncs you want to spend. See {yellow}/helpme buyxp");
    }
}
/**
 * Handles money transfers
 * UUID enabled
 *
 * @global type $UMC_USER
 * @param type $source
 * @param type $target
 * @param type $amount
 * @return boolean
 */
function umc_money($source = false, $target = false, $amount_raw = 0)
{
    global $UMC_ENV;
    XMPP_ERROR_trace(__FUNCTION__, func_get_args());
    if ($source) {
        $source = umc_check_user($source);
    }
    if ($target) {
        $target = umc_check_user($target);
    }
    $amount = abs($amount_raw);
    if ($source) {
        // take from someone
        $source_uuid = umc_uuid_getone($source, 'uuid');
        $balance = umc_money_check($source);
        if ($balance > $amount) {
            $sql = "UPDATE `minecraft_iconomy`.`mineconomy_accounts`\r\n                SET `balance`=`balance`-'{$amount}'\r\n\t\tWHERE `mineconomy_accounts`.`uuid` = '{$source_uuid}';";
            umc_mysql_query($sql);
        } else {
            if ($UMC_ENV == 'websend') {
                umc_error("There is not enough money in the account! You need {$amount} but have only {$balance} Uncs.");
            }
        }
    }
    if ($target) {
        // give to someone
        $target_uuid = umc_uuid_getone($target, 'uuid');
        $balance = umc_money_check($target);
        $sql = "UPDATE `minecraft_iconomy`.`mineconomy_accounts`\r\n\t    SET `balance` = `balance` + '{$amount}'\r\n            WHERE `mineconomy_accounts`.`uuid` = '{$target_uuid}';";
        umc_mysql_query($sql);
    }
    // logging
    if (!$target) {
        $target = "System";
    }
    if (!$source) {
        $source = "System";
    }
    umc_log('money', 'transfer', "{$amount} was transferred from {$source} to {$target}");
}
function umc_contests_join()
{
    global $UMC_USER;
    $args = $UMC_USER['args'];
    $player = $UMC_USER['username'];
    $debug = true;
    if (!isset($args[2])) {
        umc_show_help($args);
        die;
    }
    $id = $args[2];
    umc_pretty_bar("darkblue", "-", "{darkcyan} Joining contest {$id} ");
    if (!is_numeric($id)) {
        umc_error("You have to enter a numeric contest ID ({$id}). See /contest list");
    }
    // find out if the contest is creative or survival
    $sql = "SELECT * FROM minecraft_srvr.contest_contests WHERE id = {$id};";
    $rst = mysql_query($sql);
    $contest = mysql_fetch_array($rst, MYSQL_ASSOC);
    $status = $contest['status'];
    if ($status !== 'active') {
        umc_error("Contest number {$id} is not active. Please chose a different contest!");
    }
    $min = array('aether' => array('x' => -1532, 'z' => -1532, 'y' => 11, 'parent' => 'aet_p1'), 'flatlands' => array('x' => 1028, 'z' => 1028, 'y' => 64, 'parent' => 'flat_b19'));
    $max = array('aether' => array('x' => -1157, 'z' => -1157, 'y' => 255), 'flatlands' => array('x' => 1275, 'z' => 1275, 'y' => 255));
    $gap = 4;
    $type = 'survival';
    $world = 'aether';
    if ($contest['type'] == 'creative') {
        $type = 'creative';
        $world = 'flatlands';
    }
    $parent = $min[$world]['parent'];
    $min_coords = $min[$world];
    $min_x = $min_coords['x'];
    $min_z = $min_coords['z'];
    $min_y = $min_coords['y'];
    if ($debug) {
        umc_echo("Min coords are {$min_x}/{$min_y}/{$min_z}");
    }
    $max_coords = $max[$world];
    $max_x = $max_coords['x'];
    $max_z = $max_coords['z'];
    $max_y = $max_coords['y'];
    if ($debug) {
        umc_echo("MAx coords are {$max_x}/{$max_y}/{$max_z}");
    }
    $user_id = umc_get_worldguard_id('user', strtolower($player));
    $world_id = umc_get_worldguard_id('world', strtolower($world));
    // find out if the user can have additional contest entries in this contest
    $sql = "SELECT * FROM minecraft_worldguard.world LEFT JOIN minecraft_worldguard.region ON world.id=region.world_id\r\n        LEFT JOIN minecraft_worldguard.region_cuboid ON region.id=region_cuboid.region_id\r\n        LEFT JOIN minecraft_worldguard.region_players ON region_cuboid.region_id=region_players.region_id\r\n        WHERE world.name='{$world}' AND region.id LIKE 'con_" . $id . "%' AND user_id={$user_id} AND Owner=1\r\n        ORDER BY max_z, max_x";
    $rst = mysql_query($sql);
    $count = mysql_num_rows($rst);
    if ($count >= $contest['max_entries'] && $player != 'uncovery') {
        umc_error("You have reached the max number of entries for this contest!;");
    }
    // find out if a contest lot already exists
    $sql = "SELECT * FROM minecraft_worldguard.world LEFT JOIN minecraft_worldguard.region ON world.id=region.world_id\r\n        LEFT JOIN minecraft_worldguard.region_cuboid ON region.id=region_cuboid.region_id\r\n        WHERE world.name='{$world}' AND region.id LIKE 'con%' ORDER BY max_z, max_x";
    $rst = mysql_query($sql);
    $count = mysql_num_rows($rst);
    if ($debug) {
        umc_echo("{$count} entries already entered!");
    }
    $lotnumber = $count + 1;
    $lot = 'con_' . $id . '_' . $lotnumber;
    if ($debug) {
        umc_echo("Trying to create entry {$lot}");
    }
    // how many lots can I fit into the space across?
    $fullwidth = $max_x - $min_x;
    if ($debug) {
        umc_echo("Lot width is {$fullwidth}");
    }
    $single_width = $contest['x'] + $gap;
    if ($debug) {
        umc_echo("One lot (with gap) is {$single_width} wide");
    }
    $width_lots = floor($fullwidth / $single_width);
    if ($debug) {
        umc_echo("Fitting {$width_lots} per line");
    }
    $fulldepth = $max_z - $min_z;
    $single_depth = $contest['z'] + $gap;
    if ($debug) {
        umc_echo("One lot (with gap) is {$single_depth} deep");
    }
    $depth_lots = floor($fulldepth / $single_depth);
    if ($debug) {
        umc_echo("Fitting {$depth_lots} per row");
    }
    $full_lines = floor($count / $width_lots);
    if ($debug) {
        umc_echo("{$full_lines} lines already full");
    }
    $lastline_lots = $count - $full_lines * $width_lots;
    if ($debug) {
        umc_echo("Last line has {$lastline_lots} lots");
    }
    $start_x = $lastline_lots * ($contest['x'] + $gap) + $min_coords['x'];
    $start_z = $full_lines * ($contest['z'] + $gap) + $min_coords['z'];
    $start_y = $min_coords['y'];
    if ($debug) {
        umc_echo("Starting coords are {$start_x}/{$start_y}/{$start_z}");
    }
    $end_x = $start_x + $contest['x'] - 1;
    $end_z = $start_z + $contest['z'] - 1;
    $end_y = $min_coords['y'] + $contest['y'] - 1;
    if ($debug) {
        umc_echo("End coords are {$end_x}/{$end_y}/{$end_z}");
    }
    if ($end_x > $max_x || $end_z > $max_z) {
        umc_error('There is no more space for additional contest entries!;');
    }
    umc_echo("New lot {gold}{$lot}{white} in {gold}{$world}{white} was created at ");
    umc_echo("coordinates {gold}{$start_x}/{$start_y}/{$start_z}{white} - {gold}{$end_x}/{$end_y}/{$end_z}{white};");
    umc_echo("Use {gold}/contest warp {$id} {$lotnumber}{white} to get there.");
    // create insert SQL 	id 	world_id 	type 	priority 	parent
    $ins_region_sql = "INSERT INTO region (id, world_id, type, priority, parent)\r\n        VALUES ('{$lot}', {$world_id}, 'cuboid', 0, '{$parent}');";
    $ins_region_rst = mysql_query($ins_region_sql);
    // insert cuboid region_id 	world_id 	min_x 	min_y 	min_z 	max_x 	max_y 	max_z
    $ins_cuboid_sql = "INSERT INTO region_cuboid (region_id, world_id, min_x, min_y, min_z, max_x, max_y, max_z)\r\n        VALUES ('{$lot}', {$world_id}, {$start_x}, {$start_y}, {$start_z}, {$end_x}, {$end_y}, {$end_z});";
    $ins_cuboid_rst = mysql_query($ins_cuboid_sql);
    // add user to lot as Owner  region_id 	world_id 	user_id 	Owner
    $ins_user_sql = "INSERT INTO region_players (region_id, world_id, user_id, Owner)\r\n        VALUES ('{$lot}', {$world_id}, {$user_id}, 1);";
    $inc_user_rst = mysql_query($ins_user_sql);
    umc_ws_cmd("region load -w {$world}", 'asConsole');
    umc_footer();
}
function umc_ticket_new()
{
    global $WSEND;
    $player = $WSEND['player'];
    $player_email = umc_user_email($player);
    $player_id = umc_user_id($player);
    $devOptions = umc_ticket_options();
    $args = $WSEND['args'];
    if (!isset($args[1])) {
        umc_show_help($args);
    }
    array_shift($args);
    array_shift($args);
    $text = trim(implode(' ', $args));
    if (stristr($text, 'have a problem') || strlen($text) < 8) {
        umc_error("You need to specify the problem better!");
    }
    $sql_text = mysql_real_escape_string($text);
    $wpscst_title = base64_encode(strip_tags($text));
    $wpscst_initial_message = base64_encode($text);
    $wpscst_department = base64_encode(strip_tags('in-game'));
    $sql = "\r\n    INSERT INTO minecraft.`wp_wpscst_tickets` (\r\n        `primkey`, `title`, `initial_message`, `user_id`, `email`, `assigned_to`, `severity`, `resolution`,\r\n        `time_posted`, `last_updated`, `last_staff_reply`, `target_response_time`, `type`) VALUES (\r\n            NULL,\r\n            '{$wpscst_title}',\r\n            '{$wpscst_initial_message}',\r\n            '{$player_id}',\r\n            '{$player_email}',\r\n            '0',\r\n            'Normal',\r\n            'Open',\r\n            '" . current_time('timestamp') . "',\r\n            '" . current_time('timestamp') . "',\r\n            '',\r\n            '2 days',\r\n            '{$wpscst_department}'\r\n        );\r\n    ";
    $rst = mysql_query($sql);
    $lastID = mysql_insert_id();
    // user email
    $to = $player_email;
    // Send this to the ticket creator
    $subject = $devOptions['email_new_ticket_subject'] . " Ticket ID [{$lastID}]";
    $message = $devOptions['email_new_ticket_body'] . "\r\nTicket contents: \r\n{$text}";
    $headers = 'From: ' . $devOptions['email'] . "\r\n" . 'Reply-To: ' . $devOptions['email'] . "\r\n" . 'X-Mailer: PHP/' . phpversion();
    mail($to, $subject, $message, $headers);
    // admin email
    $to = $devOptions['email'];
    // Send this to the admin^M
    $subject = __("[Uncovery Minecraft] New Ticket from {$player}", 'wpsc-support-tickets');
    $message = __("New Ticket [{$lastID}] from {$player}:\r\n" . $text . "\r\n", 'wpsc-support-tickets') . get_admin_url() . 'admin.php?page=wpscSupportTickets-edit&primkey=' . $lastID . "\r\n" . var_dump($devOptions);
    $headers = 'From: ' . $player_email . "\r\n" . 'Reply-To: ' . $player_email . "\r\n" . 'X-Mailer: PHP/' . phpversion();
    mail($to, $subject, $message, $headers);
    umc_pretty_bar('red', '-', ' Help Ticket Created ', $width = 52);
    umc_echo('Your question:');
    umc_echo("{yellow}{$text}");
    umc_echo('You also received an email. Please check your inbox.');
    umc_pretty_bar('red', '-', '', $width = 52);
}
function umc_do_deposit_internal($all = false)
{
    global $UMC_USER, $UMC_SETTING, $UMC_DATA;
    $player = $UMC_USER['username'];
    $uuid = $UMC_USER['uuid'];
    $args = $UMC_USER['args'];
    // make sure user holds item
    $all_inv = $UMC_USER['inv'];
    if (!$all) {
        $item_slot = $UMC_USER['current_item'];
        if (!isset($all_inv[$item_slot])) {
            umc_error("{red}You need to hold the item you want to deposit! (current slot: {$item_slot});");
        }
        $all_inv = array($item_slot => $all_inv[$item_slot]);
    }
    $sent_out_of_space_msg = 0;
    $seen = array();
    foreach ($all_inv as $slot) {
        $item_id = $slot['item_name'];
        if (!isset($UMC_DATA[$item_id])) {
            XMPP_ERROR_trigger("Invalid item deposit cancelled!");
            umc_error("Sorry, the item in your inventory is bugged, uncovery was notfied and this should be fixed soon. IF you want to speed it up, please send a ticket with as much detail as possible.");
        }
        $data = $slot['data'];
        if ($slot['meta']) {
            $meta = serialize($slot['meta']);
        } else {
            $meta = false;
        }
        // don't assign the same twice
        $item = umc_goods_get_text($slot['item_name'], $slot['data'], $slot['meta']);
        if (isset($seen[$item['full']])) {
            continue;
        }
        $inv = umc_check_inventory($slot['item_name'], $slot['data'], $slot['meta']);
        if ($inv == 0) {
            XMPP_ERROR_trigger("Item held could not be found in inventory: {$slot['item_name']}, {$slot['data']}, " . var_export($slot['meta'], true));
            umc_error("There was a system error. The admin has been notified. Deposit aborted.");
        }
        if (isset($args[2]) && $args[2] != 'lot_reset') {
            $recipient = umc_sanitize_input($args[2], 'player');
            $recipient_uuid = umc_user2uuid($recipient);
        } else {
            if (isset($args[2]) && $args[2] == 'lot_reset') {
                $recipient_uuid = 'reset000-lot0-0000-0000-000000000000';
                $recipient = $args[2];
            } else {
                $recipient = $player;
                $recipient_uuid = $uuid;
                if (!$all) {
                    umc_echo("{yellow}[!]{gray} No recipient given. Depositing for {gold}{$player}");
                }
            }
        }
        if (!$all && isset($args[3])) {
            $amount = umc_sanitize_input($args[3], 'amount');
            $amount_str = $amount;
            if ($amount > $inv) {
                umc_echo("{yellow}[!]{gray} You do not have {yellow}{$amount} {green}{$item['full']}{gray}. Depositing {yellow}{$inv}{gray}.");
                $amount = $inv;
                $amount_str = $inv;
            }
        } else {
            $amount = $inv;
            $amount_str = $inv;
        }
        umc_echo("{yellow}[!]{gray} You have {yellow}{$inv}{gray} items in your inventory, depositing {yellow}{$amount}");
        // check if recipient has space
        $userlevel = umc_get_uuid_level($recipient_uuid);
        $allowed = $UMC_SETTING['depositbox_limit'][$userlevel];
        $remaining = umc_depositbox_checkspace($recipient_uuid, $userlevel);
        $count = $allowed - $remaining;
        // umc_echo("Group: $userlevel Allowed: $allowed Remaining $remaining");
        $sql = "SELECT * FROM minecraft_iconomy.deposit\r\n            WHERE item_name='{$item['item_name']}' AND recipient_uuid='{$recipient_uuid}'\r\n            AND damage='{$data}' AND meta='{$meta}' AND sender_uuid='{$uuid}';";
        $D = umc_mysql_fetch_all($sql);
        // create the seen entry so we do not do this again
        $seen[$item['full']] = 1;
        // check first if item already is being sold
        if (count($D) > 0) {
            $row = $D[0];
            umc_echo("{green}[+]{gray} You already have {$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`={$row['id']} LIMIT 1;";
        } else {
            //check if recipient has space
            if ($count >= $allowed && $player != 'uncovery' && $recipient != 'lot_reset') {
                if (!$sent_out_of_space_msg) {
                    umc_echo("{red}[!] {gold}{$recipient}{gray} does not have any more deposit spaces left " . "(Used {white}{$count} of {$allowed}{gray} available for group {white}{$userlevel}{gray})!");
                    $sent_out_of_space_msg = 1;
                }
                continue;
            }
            // check if recipient is an active user
            $target_active = umc_user_countlots($recipient);
            if ($target_active == 0 && $recipient != 'lot_reset') {
                umc_error("{red}[!] {gold}{$recipient}{gray} is not an active user, so you cannot deposit items for them!");
            }
            // create a new deposit box
            if (strlen($item['item_name']) < 3) {
                XMPP_ERROR_trigger("Error depositing, item name too short!");
                umc_error("There was an error with the deposit. Please send a ticket to the admin so this can be fixed.");
            }
            $text = "{green}[+]{gray} Depositing {yellow}{$amount_str} {$item['full']}{gray} for {gold}{$recipient}";
            umc_echo($text);
            $sql = "INSERT INTO minecraft_iconomy.`deposit` (`damage` ,`sender_uuid` ,`item_name` ,`recipient_uuid` ,`amount` ,`meta`)\r\n                    VALUES ('{$data}', '{$uuid}', '{$item['item_name']}', '{$recipient_uuid}', '{$amount}', '{$meta}');";
            $count++;
            umc_log("Deposit", "do_deposit", $text);
        }
        umc_mysql_query($sql, true);
        umc_clear_inv($item['item_name'], $data, $amount, $meta);
    }
    if ($recipient == 'lot_reset') {
        $allowed = 'unlimited';
    }
    umc_echo("{green}[+]{gray} You have now used {white}{$count} of {$allowed}{gray} deposit boxes");
}
/**
 * Utility command that connects to teamspeak and returns a hopefully connected
 * Teamspeak object in the teamspeak config array.
 *
 * @global type $UMC_TEAMSPEAK
 * @param boolean $error_reply shall we return an in-game error if connection fails?
 */
function umc_ts_connect($error_reply = false)
{
    XMPP_ERROR_trace(__FUNCTION__, func_get_args());
    global $UMC_TEAMSPEAK;
    // the server query object, including the password for it, is located outside the code.
    $query_string = file_get_contents($UMC_TEAMSPEAK['server_query_string_path']);
    // only reconnect if we did not do so before
    if (!$UMC_TEAMSPEAK['server']) {
        // include the teamspeak php frameworks
        require_once $UMC_TEAMSPEAK['ts_php_path'];
        $ts_connection = TeamSpeak3::factory($query_string);
        if ($ts_connection) {
            $UMC_TEAMSPEAK['server'] = $ts_connection;
        } else {
            XMPP_ERROR_trigger('Could not connect to Teamspeak Server! Is it running?');
            if ($error_reply) {
                umc_error("Sorry, the teamspeak server is down, please send a /ticket!");
            }
        }
    }
}
Beispiel #7
0
function umc_hunger_addplayer()
{
    global $HUNGER, $UMC_USER;
    XMPP_ERROR_trace(__FUNCTION__, func_get_args());
    umc_hunger_find_current_game();
    $player_uuid = $UMC_USER['uuid'];
    $player = $UMC_USER['username'];
    if (isset($HUNGER['current_game'])) {
        $game = $HUNGER['current_game'];
        if ($game['status'] == 'preparing') {
            $game_id = $game['id'];
        } else {
            umc_error("[Hunger] The hunger game has already started, it's too late to join");
        }
    } else {
        umc_error("[Hunger] Could not find any active games to join");
    }
    $sql_find = "SELECT id FROM minecraft_iconomy.hunger_players WHERE game_id = {$game_id} AND uuid='{$player_uuid}'";
    $find_data = umc_mysql_fetch_all($sql_find);
    if (count($find_data) > 0) {
        umc_echo("[Hunger] You already joined this game!");
        return;
    }
    $admin = umc_user2uuid($HUNGER['current_game']['admin']);
    umc_ws_cmd("tell {$admin} The user {$player} just joined the hunger game!", 'asConsole');
    if ($HUNGER['announce']) {
        umc_announce("[Hunger] The user {gold}{$player}{purple} just {green}joined{purple} the hunger game!", $HUNGER['channel']);
    } else {
        umc_echo("[Hunger] The user {gold}{$player}{purple} just {green}joined{purple} the hunger game!");
    }
    // Warp the user
    umc_ws_cmd("pex user {$player_uuid} add essentials.warps.hunger", 'asConsole');
    umc_ws_cmd("warp hunger {$player}");
    $sql = "INSERT INTO minecraft_iconomy.`hunger_players` (`uuid`, `game_id`, `status`) VALUES ('{$player_uuid}', {$game_id}, 'preparing');";
    umc_mysql_query($sql, true);
    umc_echo("[Hunger] {green}You ({gold}{$player}{green}) were added to Hunger Game {white}#{$game_id}.");
    XMPP_ERROR_send_msg("Added user {$player} to the hunger game");
}
function umc_vanity_set()
{
    global $UMC_USER;
    $player = $UMC_USER['username'];
    $args = $UMC_USER['args'];
    $userlevel = umc_get_userlevel($player);
    // umc_echo("$userlevel");
    if (!isset($args[2]) || !is_numeric($args[2]) || $args[2] < 1) {
        umc_error("{red}You need to specify a number of days");
    } else {
        if (!isset($args[3])) {
            umc_error("{red}You need to specify the title you want to have. See {yellow}/helpme vanity");
        }
    }
    $days = $args[2];
    $vanity_raw = '';
    // concatenate all into a string
    for ($i = 3; $i < count($args); $i++) {
        $vanity_raw .= " " . $args[$i];
    }
    $vanity = trim($vanity_raw);
    $donator_str = '';
    if (strstr($userlevel, 'DonatorPlus')) {
        $donator_str = '&6++&f';
    } else {
        if (strstr($userlevel, 'Donator')) {
            $donator_str = '&6+&f';
        } else {
            if ($userlevel == 'Owner') {
                $donator_str = '&6++&f';
            }
        }
    }
    $final_title = ' [' . $vanity . '&f]';
    // check for invalid chars
    umc_vanity_sanitize($vanity);
    $quote_array = umc_vanity_quote_title($vanity);
    $total_cost = $quote_array['cost'] * $days;
    $balance = umc_money_check($player);
    if ($quote_array['length'] > 20) {
        umc_error("Your title is too long ({$quote_array['length']} vs. 20 max!");
    }
    if ($total_cost > $balance) {
        umc_error("You do not have enough money to pay for this title for {$days} days. You need {$total_cost} but have only {$balance}!");
    }
    // check if there is a title already set
    $check = umc_vanity_get_title();
    if ($final_title == $check . $donator_str) {
        umc_header("Vanity Title");
        umc_echo("The same title is already set and will be extended by {$days} days!");
    } else {
        if ($check && $final_title != $check . $donator_str) {
            umc_error("You have a different title already set. You need to cancel that one first or set the same one to extend it!");
        } else {
            // no title set yet
            $uuid = umc_user2uuid($player);
            umc_header("Vanity Title");
            umc_echo("No title yet set, setting new one...");
            umc_exec_command("pex user {$uuid} suffix \"{$final_title}{$donator_str}\"", 'asConsole');
        }
    }
    // set timer
    umc_money($player, false, $total_cost);
    umc_timer_set($player, 'custom_title', $days);
    $date_out = umc_timer_get($player, 'custom_title');
    $time_out = $date_out->format('Y-m-d H:i:s');
    $date_today = umc_datetime();
    $interval = $date_today->diff($date_out);
    $days_interval = $interval->days;
    $hours_interval = $interval->h;
    umc_echo("Your title [{$vanity}{white}] will expire on {$time_out} (in {$days_interval} days and {$hours_interval} hours)!");
    umc_echo("Your account has been debited {$total_cost}!");
    umc_log('vanity', 'set', "{$player} paid {$total_cost} for {$vanity} for {$days} days");
    umc_footer(true);
}
function umc_skyblock_challenge_select()
{
    global $UMC_USER;
    $player = $UMC_USER['username'];
    $args = $UMC_USER['args'];
    if (!is_numeric($args[2])) {
        umc_error("Your challenge ID needs to be a number!");
    } else {
        $lot_sql = "SELECT region_cuboid.region_id as lot FROM `region_cuboid`\r\n            LEFT JOIN region_players ON region_cuboid.region_id=region_players.region_id\r\n            WHERE user_id IS NULL\r\n\t\tAND region_cuboid.`region_id` LIKE 'block%'\r\n\t\tAND min_z<-768\r\n\t\tAND min_x>=-1152\r\n\t\tAND max_x<1024;";
        $D = umc_mysql_fetch_all($lot_sql);
        if (count($D) == 0) {
            XMPP_ERROR_trigger("We ran out of challenge lots!");
            umc_error("Sorry, there are currently no challenge lots free!");
        } else {
            $lot_row = $D[0];
            $challenge_lot = $lot;
        }
        $id = $args[2];
        $sql = "SELECT * FROM minecraft_quiz.block_challenges WHERE challenge_id={$id};";
        $rst = umc_mysql_query($sql);
        $row = umc_mysql_fetch_array($rst);
        $lot = $row['lot'];
        $biome = $row['biome'];
        $inventory = $row['inventory'];
        $name = $row['name'];
        $desc = $row['desc'];
        $win_conditions = $row['win_conditions'];
        umc_header("Challenge {$id}: {$name}");
        umc_echo("{white}{$desc}");
        $lot_str = $lot;
        if ($lot == null) {
            $lot_str = 'standard';
        }
        umc_echo("{green}Lot type: {white}{$lot_str}");
        $biome_str = $biome;
        if ($biome == null) {
            $biome_str = 'standard';
        }
        umc_echo("{green}Lot type: {white}{$biome_str}");
        if (umc_skyblock_web_display_table($id)) {
            umc_echo("{green}Sub challenges: {white}This challenge has subchallenges. Please see the website for details.");
        }
        $inv_str = umc_skyblock_inv_to_desc($inventory);
        umc_echo("{green}Starting Inventory:{white}{$inv_str}");
        $winstr = umc_skyblock_inv_to_desc($win_conditions);
        umc_echo("{green}Winning conditions:{white}{$winstr}");
        $sub_challenge = $row['sub_challenge'];
        $challenge = $id;
        if ($sub_challenge !== null) {
            $challenge = $sub_challenge;
        }
        $sql = "INSERT INTO `minecraft_quiz`.`block_games` (`game_id`, `username`, `start`, `end`, `status`, `challenge_id`, `sub_challenge_id`, `lot`)\r\n            VALUES (NULL, '{$player}', NOW(), NULL, 'selected', '{$challenge}', '{$sub_challenge}', '{$challenge_lot}');";
        umc_mysql_query($sql, true);
        umc_echo("Please type {green}/skyblock start{white} or {green}/skyblock cancel");
        umc_footer();
    }
}
function umc_trivia_solve()
{
    global $UMC_USER;
    $player = $UMC_USER['username'];
    $args = $UMC_USER['args'];
    $quiz_arr = umc_trivia_get_current_quiz();
    $quiz_id = $quiz_arr['id'];
    $question_no = $quiz_arr['question_no'];
    $master = $quiz_arr['master'];
    if (!$quiz_arr) {
        umc_error("There is no active quiz to get answers for. Please start one first.");
    } else {
        if ($player != $master) {
            umc_error("Someone is running a quiz already, it has to stop first!");
        } else {
            if ($quiz_arr['status'] != 'asked') {
                umc_error("You need to ask the next question now!");
            } else {
                if (!isset($args[2], $quiz_arr['answers'][$args[2]])) {
                    umc_error("You need to enter an existing answer id. Use /trivia check!");
                }
            }
        }
    }
    $answer_id = $args[2];
    $update_sql = "UPDATE minecraft_quiz.quiz_answers SET result='right' WHERE answer_id={$answer_id};";
    umc_mysql_query($update_sql);
    $close_sql = "UPDATE minecraft_quiz.quiz_questions SET status='solved' WHERE quiz_id={$quiz_arr['id']} AND question_id={$quiz_arr['question_id']};";
    //umc_echo($close_aql);
    umc_mysql_query($close_sql);
    // get answer user
    $sql = "SELECT * FROM minecraft_quiz.quiz_answers wHERE answer_id={$answer_id};";
    $D = umc_mysql_fetch_all($sql);
    $row = $D[0];
    $username = $row['username'];
    $answer = $row['answer_text'];
    umc_ws_cmd("ch qm o &3[Trivia]&f Quiz No {$quiz_id} Question {$question_no}");
    umc_ws_cmd("ch qm o &3[Trivia]&f The correct answer was: {$quiz_arr['answer']}&4");
    umc_ws_cmd("ch qm o &3[Trivia]&f User &6{$username}&f answered correctly with &2{$answer}&4");
    if ($quiz_arr['question_no'] >= $quiz_arr['questions']) {
        umc_trivia_close_quiz();
    } else {
        umc_ws_cmd("ch qm o &3[Trivia]&f Please stand by for the next question to be picked and annunced.");
        umc_trivia_find_question();
    }
}
Beispiel #11
0
function umc_mail_list()
{
    global $UMC_USER;
    $uuid = $UMC_USER['uuid'];
    $args = $UMC_USER['args'];
    $folders = array('inbox', 'outbox', 'trash');
    if (isset($args[2]) && !in_array($args[2], $folders)) {
        umc_error("You need to chose one of the folders {green}inbox{white}, {green}outbox{white} or {green}trash{white}");
    }
    if (!isset($args[2])) {
        $folder = "All folders";
        $filter = 'all';
        $no_mail = "You have no emails";
    } else {
        $folder = "Folder " . ucwords($args[2]);
        $filter = $args[2];
        $no_mail = "You have no emails in {$folder}";
    }
    umc_header("Uncovery Mail {$folder}");
    $status_arr = array('all' => "(recipient_uuid='{$uuid}' AND status NOT IN ('deleted_recipient','deleted_both')) OR (sender_uuid='{$uuid}' AND status NOT IN ('deleted_sender','deleted_both'))", 'inbox' => "recipient_uuid='{$uuid}' AND (status='sent' OR status='read')", 'outbox' => "sender_uuid='{$uuid}' AND (status='sent')", 'trash' => "(recipient_uuid='{$uuid}' AND status IN ('deleted_recipient','deleted_both')) OR (sender_uuid='{$uuid}' AND status IN ('deleted_sender','deleted_both'))");
    $sql_filter = $status_arr[$filter];
    $sql = "SELECT * FROM minecraft_srvr.`user_mail` WHERE {$sql_filter} ORDER BY date_time ASC;";
    $D = umc_mysql_fetch_all($sql);
    if (count($D) == 0) {
        umc_echo("No emails in this mailbox");
        umc_footer();
        return;
    }
    foreach ($D as $row) {
        if ($row['sender_uuid'] == $uuid) {
            $recipient = umc_user2uuid($row['recipient_uuid']);
            $wholine = "{red}->{white}{$recipient}";
            if ($row['status'] == 'sent') {
                $folder = 'Outbox';
            } else {
                if (strstr($row['status'], 'deleted')) {
                    $folder = 'Trash';
                } else {
                    if ($row['status'] == 'draft') {
                        $folder = 'Draft';
                    }
                }
            }
        } else {
            $sender = umc_user2uuid($row['sender_uuid']);
            $wholine = "{$sender}{red}->{white}";
            if ($row['status'] == 'read') {
                $folder = 'Inbox';
            } else {
                if (strstr($row['status'], 'deleted')) {
                    $folder = 'Trash';
                } else {
                    if ($row['status'] == 'sent') {
                        $folder = 'Unread';
                    }
                }
            }
        }
        umc_echo("{green}#{$row['msg_id']} {yellow}{$folder}{grey} {$row['date_time']}{white} {$wholine}: {$row['title']}");
    }
    umc_footer();
}
Beispiel #12
0
function umc_show_help($args = false)
{
    XMPP_ERROR_trace(__FUNCTION__, func_get_args());
    global $UMC_USER, $WS_INIT;
    $player = $UMC_USER['username'];
    $userlevel = umc_get_userlevel($player);
    if ($args) {
        // if show_help is called from another program, we simulate a /help command being issued.
        $args = array_merge(array('call'), $UMC_USER['args']);
    } else {
        $args = $UMC_USER['args'];
    }
    $command = false;
    $command_name = '';
    $plugin_name = '';
    if (isset($args[1])) {
        $command = umc_wsplg_find_command($args[1]);
        $command_name = $args[1];
    }
    // If we have a help query, a command name, but it didn't match any known commands
    if ($args[0] == 'help' && $command_name && !$command) {
        umc_error("{white}Action {green}{$command_name}{white} not recognized, try {yellow}/helpme");
    }
    umc_header('Uncovery Help', true);
    umc_echo("{gray}   <..> = mandatory   [..] = optional   {ro} = request or offer", true);
    $non_commands = array('default', 'events', 'disabled');
    if ($command_name) {
        if (isset($command['help']['title'])) {
            // This is a 'default' listing
            umc_pretty_bar("darkblue", "-", "{darkcyan}" . $command['help']['title'], 52, true);
            umc_echo($command['help']['long'], true);
            foreach ($WS_INIT[$command_name] as $cmd => $cmd_data) {
                if (!in_array($cmd, $non_commands)) {
                    // This command is restricted to a user level or higher
                    if (isset($cmd_data['security']['level']) && $player != 'uncovery') {
                        if (!umc_rank_check($userlevel, $cmd_data['security']['level'])) {
                            continue;
                        }
                    }
                    if (!isset($cmd_data['top']) || !$cmd_data['top']) {
                        $plugin_name = $command_name . ' ';
                    }
                    $command_args = '';
                    if (isset($cmd_data['help']['args'])) {
                        $command_args = "{yellow}" . $cmd_data['help']['args'];
                    }
                    umc_echo("{green}/{$plugin_name}{$cmd} {$command_args}{gray} => {white}" . $cmd_data['help']['short'], true);
                }
            }
        } else {
            if (isset($command)) {
                // sub-command help
                if (!isset($command['top']) || !$command['top']) {
                    $plugin_name = $command_name . ' ';
                }
                $args_str = '';
                if (isset($command['help']['args'])) {
                    $args_str = "{yellow}" . $command['help']['args'];
                }
                umc_echo("{green}/{$plugin_name}{$command_name} {$args_str}{gray} => {white}" . $command['help']['short'], true);
                umc_pretty_bar("darkgray", "-", "", 49, true);
                foreach (split(';', $command['help']['long']) as $line) {
                    if ($line != '') {
                        umc_echo($line, true);
                    }
                }
            } else {
                umc_echo("{white}No help found for command {red}/{$args[1]} {$args[2]}{white}.", true);
                // umc_show_help($args);
                // umc_echo("{white}Try {yellow}/helpme {$args[1]}{white} to see valid commands.", true);
            }
        }
    } else {
        // Show general help.
        foreach ($WS_INIT as $plugin => $cmd_data) {
            // This command is restricted to a user level or higher
            if (isset($cmd_data['default']['security']['level']) && $player != 'uncovery') {
                if (!umc_rank_check($userlevel, $cmd_data['default']['security']['level'])) {
                    continue;
                }
            }
            umc_echo("{green}/{$plugin}{gray} - " . $cmd_data['default']['help']['short'], true);
        }
        umc_echo("{gray}Use {yellow}/helpme <command>{gray} for more details.", true);
    }
    umc_footer(true);
    return true;
}
function umc_sanitize_input(&$value, $type)
{
    XMPP_ERROR_trace(__FUNCTION__, func_get_args());
    $MAX_UNCS = 10000;
    $MIN_UNCS = 1.0E-5;
    if ($type == "price") {
        # Check that this is a number
        # Check that it is greater than zero
        # Check bounds
        if (!is_numeric($value)) {
            umc_error("{red}Invalid amount of uncs ({yellow}{$value}{red}), must be a number.");
        } elseif ($value < $MIN_UNCS) {
            umc_error("{red}Invalid amount of uncs ({yellow}{$value}{red}), must be at least {yellow}{$MIN_UNCS}{red}.");
        } elseif ($value > $MAX_UNCS) {
            umc_error("{red}Invalid amount of uncs ({yellow}{$value}{red}), cannot be more than {yellow}{$MAX_UNCS}{red}.");
        } else {
            return $value;
        }
    }
    if ($type == "amount") {
        if ($value == NULL) {
            // buying all available
            return NULL;
        }
        if (!is_numeric($value)) {
            umc_error("{red}Invalid amount ({yellow}{$value}{red}), must be an integer.");
        } elseif (intval($value) < 1) {
            umc_error("{red}Invalid amount ({yellow}{$value}{red}), must be at least 1.");
        } else {
            return intval(abs($value));
        }
    }
    if ($type == "player") {
        $player = umc_check_user($value);
        if (!$player) {
            umc_error("{red}Invalid player name ({yellow}{$value}{red}), no such player.");
        } else {
            return $player;
        }
    }
    if ($type == "item") {
        // get a list of all possible item names. REquires exact match of the searched item
        $all_names = umc_item_data_get_namelist();
        if (isset($all_names[$value])) {
            return $all_names[$value];
        } else {
            // we searched only for the EXACT item above. We should be looking for possible matches in the
            // search database too.
            global $ITEM_SEARCH;
            if (isset($ITEM_SEARCH[$value])) {
                return $ITEM_SEARCH[$value];
            }
            return false;
        }
    }
    if ($type == "table") {
        if (isset($value[2]) && ($value[2] == 'request' || $value[2] == 'req' || $value[2] == 'r')) {
            return 'request';
        } elseif (isset($value[2]) && ($value[2] == 'offer' || $value[2] == 'off' || $value[2] == 'o')) {
            return 'stock';
        } else {
            array_splice($value, 2, 0, 'offer');
            umc_echo("{yellow}[!]{gray} Didn't specify {yellow}request{gray} or {yellow}offer{gray}, assuming {yellow}offer", true);
            return 'stock';
        }
    }
    if ($type == "lot") {
        $check = !preg_match('/[^A-Za-z0-9_.#\\-$]/', $value);
        if (!$check) {
            umc_error('You need to enter a valid lot name such as "emp_a1"');
        } else {
            return $value;
        }
    }
    if ($type == "meta") {
        $meta_name = umc_parse_meta_input($value);
        if (is_null($meta_name)) {
            umc_error("Unknown Metavalue name: {white}{$value}");
        } else {
            return $meta_nam;
        }
    }
}
function umc_lot_warp()
{
    global $UMC_USER;
    $player = $UMC_USER['username'];
    $userlevel = $UMC_USER['userlevel'];
    $world = $UMC_USER['world'];
    $args = $UMC_USER['args'];
    $allowed_ranks = array('Owner', 'Guest');
    if (!in_array($userlevel, $allowed_ranks)) {
        umc_error("Sorry, this command is only for Guests!");
    }
    $allowed_worlds = array('empire', 'flatlands');
    if (!in_array($world, $allowed_worlds)) {
        umc_error('Sorry, you need to be in the Empire or Flatlands to warp!');
    } else {
        $lot = strtolower(umc_sanitize_input($args[2], 'lot'));
        // the above one fails already if the lot is not a proper lot
        $target_world = umc_get_lot_world($lot);
        if (!in_array($target_world, $allowed_worlds)) {
            umc_error('Sorry, you need to be in the Empire or Flatlands to warp!');
        }
        if ($target_world != $world) {
            umc_error("Sorry, you need to be in {$target_world} to warp to {$lot}!");
        }
    }
    $sql = "SELECT * FROM minecraft_worldguard.world LEFT JOIN minecraft_worldguard.region ON world.id=region.world_id\r\n        LEFT JOIN minecraft_worldguard.region_cuboid ON region.id=region_cuboid.region_id\r\n        WHERE world.name='{$target_world}' AND region.id = '{$lot}' ";
    $D = umc_mysql_fetch_all($sql);
    if (count($D) != 1) {
        umc_error("There was an error teleporting you to your lot, the admin was notified, please wait for it to be fixed!");
    }
    $lots = $D[0];
    $c_x = $lots['min_x'] + 64;
    $c_z = $lots['min_z'] + 64;
    $c_y = 256;
    $cmd = "tppos {$player} {$c_x} {$c_y} {$c_z} 0";
    umc_ws_cmd($cmd, 'asConsole');
    umc_pretty_bar("darkblue", "-", "{darkcyan} Warping to lot {$lot}");
    umc_echo("You are now in the center of lot {$lot}!");
    umc_footer();
}
Beispiel #15
0
function umc_story_show()
{
    global $UMC_USER, $UMC_COLORS;
    $username = $UMC_USER['username'];
    $uuid = $UMC_USER['uuid'];
    $args = $UMC_USER['args'];
    $mode = $UMC_USER['mode'];
    $world = $UMC_USER['world'];
    if (!isset($args[2])) {
        umc_error("You have to enter a story code!");
    } else {
        $code = $args[2];
    }
    if (strpos($code, '?')) {
        umc_error('Your code is incomplete! Please replace the ? with the code that you received at the last station!');
    }
    if (strlen($code) != 5) {
        umc_error('Your code needs to have 5 letters!');
    }
    $sql = "SELECT * FROM minecraft_iconomy.story WHERE code='{$code}';";
    $D = umc_mysql_fetch_all($sql);
    $disallowed_items = array(0, 8, 9, 10, 11, 34, 36, 43, 51, 52, 55, 26, 59, 60, 63, 64, 68, 71, 75, 78, 83, 90, 92, 93, 94, 95, 97, 99, 100, 104, 105, 115, 117, 118, 119, 120, 122);
    $out = '';
    if (count($D) > 0) {
        $row = $D[0];
        $story = stripslashes($row['story']);
        $title = stripslashes($row['storyline']);
        $warp = stripslashes($row['warp']);
        if ($row['forcesurvival'] == -1 && $mode == 'CREATIVE') {
            umc_ws_cmd("gamemode survival {$username};", 'asConsole');
        }
        if ($row['clear_inv'] == -1 && ($world == 'city' || $world == 'flatlands')) {
            umc_ws_cmd("ci {$username};", 'asConsole');
        }
        $items = stripslashes($row['items']);
        if (strlen($items) > 0 && ($world == 'city' || $world == 'flatlands')) {
            $items = explode(";", $items);
            if (count($items) > 0) {
                foreach ($items as $item) {
                    $data = explode(':', $item);
                    if (count($data) == 3 && !in_array($data[0], $disallowed_items)) {
                        if (is_numeric($data[0]) && is_numeric($data[1]) && is_numeric($data[2])) {
                            umc_ws_cmd("give {$username} {$data[0]}:{$data[1]} {$data[2]};", 'asConsole');
                        }
                    }
                }
            }
        }
        if (strlen($warp) > 0 && $world == 'city') {
            $warp = "story_" . $warp;
            umc_ws_cmd("warp {$warp} {$username};", 'asConsole');
        }
        $uuid = $row['uuid'];
        $creator_name = umc_user2uuid($uuid);
        // check for duplicate entries
        $sql = "SELECT * FROM minecraft_iconomy.story_users WHERE `uuid`='{$uuid}' and `story_id`='{$row['id']}';";
        $D3 = umc_mysql_fetch_all($sql);
        $count = count($D3);
        if ($count == 0) {
            $sql = "INSERT INTO minecraft_iconomy.story_users (`uuid`, `story_id`) VALUES ('{$uuid}', '{$row['id']}');";
            umc_mysql_query($sql, true);
        }
        $pages = explode("[BR]", $story);
        $pagecount = count($pages);
        if (isset($args[2]) && is_numeric($args[2]) && isset($pages[$args[2] - 1])) {
            $page = $args[2];
        } else {
            $page = 1;
        }
        $arr_page = $page - 1;
        $this_page_raw = $pages[$arr_page];
        $search = array('[player]', "\n");
        $replace = array($username, ';');
        foreach ($UMC_COLORS as $colorcode => $data) {
            foreach ($data['names'] as $color_name) {
                $search[] = "[" . $color_name . "]";
                $replace[] = "&" . $colorcode;
            }
        }
        $this_page = str_replace($search, $replace, $this_page_raw);
        $out = "{white}----------------- {green}Story Page ({$page}/{$pagecount}): {white}-----------------;" . "{yellow}{$title} {white}by {$creator_name};" . $this_page;
        if (count($pages) > $page) {
            $nextpage = $page + 1;
            $out .= "{white}------- {green}Please type /ws story {$code} {$nextpage} to read on! {white}--------;";
        } else {
            $out .= ";-----------------------------------------------------;";
        }
    } else {
        $out .= "The story code could not be found!";
    }
    $lines = explode(";", $out);
    foreach ($lines as $line) {
        umc_echo($line, true);
    }
}
Beispiel #16
0
function umc_mod_unmute()
{
    global $UMC_USER, $UMC_PATH_MC;
    // umc_echo('Unmuting...');
    $player = $UMC_USER['username'];
    $args = $UMC_USER['args'];
    if (!isset($args[2])) {
        umc_show_help($args);
        die;
    } else {
        $user = umc_check_user($args[2]);
        if (!$user) {
            XMPP_ERROR_trigger("{$player} tried to un-mute {$user}, but {$user} does not exist!");
            umc_error("{red}The user {$args[2]} does not exist! See {yellow}/helpme mod");
        }
    }
    // umc_echo('checks done... ');
    $user_uuid = umc_uuid_getone($user);
    $file = "{$UMC_PATH_MC}/server/bukkit/plugins/Essentials/userdata/" . $user_uuid . ".yml";
    $txt = file_get_contents($file);
    $search = "muted: true";
    if (strstr($txt, $search)) {
        // YAML library is not installed,
        //$yml = yaml_parse_file($file);
        //if ($yml['muted'] == 'true') {
        $uuid = umc_user2uuid($user);
        umc_ws_cmd("mute {$user}", 'asPlayer');
        umc_ws_cmd("pex user {$uuid} timed remove -herochat.*;", 'asConsole');
        umc_ws_cmd("pex user {$uuid} timed remove -irc.*;", 'asConsole');
        umc_ws_cmd("pex user {$uuid} timed remove -essentials.msg;", 'asConsole');
        umc_ws_cmd("pex user {$uuid} timed remove -essentials.me;", 'asConsole');
        umc_echo("The user {$user} has been un-muted!");
        umc_log('mod', 'un-mute', "{$player} un-muted {$user}");
    } else {
        umc_log('mod', 'un-mute', "{$player} tried to un-mute {$user}, but {$user} was not muted!");
        umc_error("User {$user} was not muted!");
    }
}
function umc_home_rename()
{
    XMPP_ERROR_trace(__FUNCTION__, func_get_args());
    global $UMC_USER;
    $args = $UMC_USER['args'];
    // home name
    if (isset($args[2]) && isset($args[3])) {
        $old_name = umc_mysql_real_escape_string(trim($args[2]));
        // check if the name already exists
        $name_check = umc_home_count($old_name);
        if ($name_check != 1) {
            umc_error("{red}You do not have a home with that name!");
        }
        $new_name = umc_mysql_real_escape_string(trim($args[3]));
        $new_name_check = umc_home_count($new_name);
        if ($new_name_check == 1) {
            umc_error("{red}You already have a home with that name!");
        }
    } else {
        umc_error("{red}You need to specify the name of your new home!");
    }
    $sql = "UPDATE minecraft_srvr.`homes` SET `name`={$new_name} " . "WHERE uuid='{$UMC_USER['uuid']}' AND name={$old_name} LIMIT 1;";
    umc_mysql_query($sql, true);
    umc_log('home', 'rename', "{$UMC_USER['uuid']}/{$UMC_USER['username']} renamed home {$args[2]} to {$args[3]}!");
    umc_echo("The name of home {$args[2]} was updated to {$args[3]}!");
}
/**
 * this returns the karma of a target or the current player, if no target set
 * returns either as value or as websend message, depening on the scenario
 *
 * @global type $UMC_USER
 * @global type $UMC_ENV
 * @param type $target
 * @param type $return
 * @return string
 */
function umc_getkarma($target = false, $return = false)
{
    XMPP_ERROR_trace(__FUNCTION__, func_get_args());
    global $UMC_USER, $UMC_ENV;
    if ($UMC_ENV == 'websend') {
        $user = $UMC_USER['username'];
        $user_uuid = $UMC_USER['uuid'];
        $args = $UMC_USER['args'];
    } else {
        $user = NULL;
        $args = NULL;
    }
    // do we have a target set? If no, assume current user
    if ($target) {
        $receiver_uuid = $target;
        $receiver = umc_user2uuid($target);
    } else {
        if (!isset($args[2])) {
            // get user's own karma
            $receiver = $user;
            $receiver_uuid = $user_uuid;
        } else {
            // get argument from command
            $receiver = umc_sanitize_input($args[2], 'player');
            $receiver_uuid = umc_user2uuid($receiver);
        }
    }
    if ($receiver == 'uncovery') {
        if ($return) {
            return "n/a";
        } else {
            if ($UMC_ENV == 'websend') {
                umc_error("Thou shalt not judge the maker of all things!");
            } else {
                return;
            }
        }
    }
    $banned = umc_user_is_banned($receiver_uuid);
    if ($banned) {
        if ($return) {
            return "(banned)";
        }
        umc_echo("User {$receiver} is banned");
        exit;
    }
    # Get the user's + and - karma entries
    $pos_sql = "SELECT SUM(karma) AS sum_karma\r\n\tFROM minecraft_srvr.karma\r\n        LEFT JOIN minecraft_srvr.UUID AS senders ON sender_uuid=uuid\r\n        WHERE receiver_uuid='{$receiver_uuid}' AND karma > 0\r\n\t  AND senders.lot_count > 0\r\n        GROUP BY receiver_uuid";
    $neg_sql = "SELECT SUM(karma) AS sum_karma\r\n\tFROM minecraft_srvr.karma\r\n        LEFT JOIN minecraft_srvr.UUID AS senders ON sender_uuid=uuid\r\n        WHERE receiver_uuid='{$receiver_uuid}' AND karma < 0\r\n\t  AND senders.lot_count > 0\r\n        GROUP BY receiver_uuid";
    $pos_data = umc_mysql_fetch_all($pos_sql);
    $neg_data = umc_mysql_fetch_all($neg_sql);
    # If the user has no karma entries, use 0
    if (count($pos_data) > 0) {
        $pos_karma = $pos_data[0]['sum_karma'];
    } else {
        $pos_karma = 0;
    }
    if (count($neg_data) > 0) {
        $neg_karma = $neg_data[0]['sum_karma'];
    } else {
        $neg_karma = 0;
    }
    $karma = $pos_karma + $neg_karma;
    if ($pos_karma == NULL && $neg_karma == NULL) {
        if ($return) {
            return 'n/a';
        }
        umc_echo("User {$receiver} has no karma record");
    } else {
        if ($pos_karma == NULL) {
            $pos_karma = 0;
        }
        if ($neg_karma == NULL) {
            $neg_karma = 0;
        }
        if ($return) {
            return "{$pos_karma}/{$neg_karma}";
        }
        umc_echo("User {$receiver} has {$karma} karma ({$pos_karma}/{$neg_karma}).");
    }
}
function umc_hardcore_commit()
{
    global $UMC_USER;
    $uuid = $UMC_USER['uuid'];
    $rates = array('diamond_block' => 100);
    // always the current item
    $all_inv = $UMC_USER['inv'];
    $item_slot = $UMC_USER['current_item'];
    if (!isset($all_inv[$item_slot])) {
        umc_error("{red}You need to hold the item you want to commit! (current slot: {$item_slot});");
    }
    // current held item
    $curr_item = $all_inv[$item_slot];
    if (isset($rates[$curr_item['item_name']])) {
        $inv = umc_check_inventory($curr_item['item_name'], $curr_item['data'], $curr_item['meta']);
        $amount = $inv;
        $block_value = $rates[$curr_item['item_name']];
        $item_txt = umc_goods_get_text($curr_item['item_name'], 0);
        umc_echo("{yellow}[!]{gray} You have {yellow}{$inv} {$item_txt['full_clean']}{gray} in your inventory, committing {yellow}{$amount}{gray} for {yellow}{$block_value}{gray} points each");
        umc_clear_inv($curr_item['item_name'], 0, $inv);
        $points = $inv * $block_value;
        umc_echo("{yellow}[!]{gray} You received {$points} points for this commit!");
        // get current period
        $P = umc_hardcore_get_period();
        $score_sql = "UPDATE minecraft_srvr.hardcore\r\n            SET `score`=score+'{$points}'\r\n            WHERE `uuid`='{$uuid}' AND entry_date >= '{$P['start_date']}' AND entry_date < '{$P['end_date']}'\r\n            LIMIT 1;";
        umc_mysql_query($score_sql, true);
    } else {
        $itemlist = '';
        foreach ($rates as $item_name => $value) {
            $item_txt = umc_goods_get_text($item_name, 0);
            $itemlist .= $item_txt['full_clean'] . "({$value} points) ";
        }
        umc_error("You cannot commit this item. The list of acceptable items are:" . $itemlist);
    }
}
/**
 * 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;
    }
}
/**
 * Create a request
 *
 * @global type $UMC_USER
 * @return type
 */
function umc_do_request()
{
    global $UMC_USER;
    $player = $UMC_USER['username'];
    $uuid = $UMC_USER['uuid'];
    $args = $UMC_USER['args'];
    // this returns a item_array already
    $item_check = umc_sanitize_input($args[2], 'item');
    if (!$item_check) {
        umc_error("{red}Unknown item ({yellow}{$args['2']}{red}). Try using {yellow}/search{red} to find names.");
    } else {
        XMPP_ERROR_trace("item_check", $item_check);
        $item = umc_goods_get_text($item_check['item_name'], $item_check['type']);
    }
    $item_name = $item['item_name'];
    $type = $item['type'];
    $meta = '';
    $meta_txt = '';
    $do_check = false;
    $pos = array_search('check', $args);
    if ($pos) {
        $do_check = true;
        array_splice($args, $pos, 1);
    }
    // TODO: This should be checking for the item type instead of assuming 0
    //if ($UMC_ITEMS[$type][0]['avail'] == false) {
    //    umc_error("{red}Sorry, this item (ID $type) is unavailable in the game!",true);
    //}
    $sql = "SELECT * FROM minecraft_iconomy.request\r\n        WHERE item_name='{$item_name}' AND damage='{$type}' AND meta='{$meta}' AND uuid='{$uuid}';";
    $sql_data = umc_mysql_fetch_all($sql);
    if (count($sql_data) == 0) {
        $row = false;
    } else {
        $row = $sql_data[0];
    }
    // buy item at same price, check if exists
    if (!isset($args[3])) {
        if ($row) {
            $price = $row['price'];
        } else {
            umc_error("{red}Since you do not have the same item already in the shop you need to specify a price.;");
        }
    } else {
        $price = umc_sanitize_input($args[3], 'price');
    }
    // check if an argument was given for amount.
    $amount = umc_sanitize_input($args[4], 'amount');
    if ($amount == NULL) {
        // buying 0 amount available is not possible
        umc_error("{red}You need to specify an amount, too!;");
    }
    $cost = $price * $amount;
    // if there is an existing row, recalculate price accordingly
    if ($row) {
        // give money back from the original request
        $refund = $row['amount'] * $row['price'];
        // calculate how much this one + the old item amount would cost
        $new_cost = ($amount + $row['amount']) * $price;
        // do the sum for the balance, can be negative
        $cost = $new_cost - $refund;
    }
    $balance = umc_money_check($uuid);
    if ($balance < $cost) {
        umc_error("{red}[!]{gray} Insufficient funds ({white}{$cost}{gray} needed). " . "{purple}[?]{white} Why don't you vote for the server and try again?");
    }
    if ($do_check) {
        if ($row) {
            $sum = $amount + $row['amount'];
            umc_echo("{white}[?]{gray} This would update your existing request to " . "{yellow}{$sum} {$item['full']}{darkgray} @ {cyan}{$price}{gray} each.");
        } else {
            umc_echo("{white}[?]{gray} This would create a new request for " . "{yellow}{$amount} {$item['full']}{darkgray} @ {cyan}{$price}{gray} each.");
        }
        if ($cost > 0) {
            umc_echo("{white}[?]{white} Your account would be charged {cyan}{$cost}{gray} Uncs.");
        } else {
            umc_echo("{white}[?]{white} Your account would be credited {cyan}" . $cost * -1 . "{gray} Uncs.");
        }
        return;
    }
    $sum = 0;
    $posted_id = 0;
    if ($row) {
        // Update existing listing
        $sum = $amount + $row['amount'];
        umc_echo("{green}[+]{gray} You already requested {yellow}" . "{$row['amount']} {$item['full']}{gray}. Adding another {yellow}{$amount}{gray}.");
        $sql = "UPDATE minecraft_iconomy.`request` SET `amount` = amount + '{$amount}', price='{$price}' WHERE id={$row['id']};";
        $rst = umc_mysql_query($sql);
        $posted_id = $row['id'];
    } else {
        // Create a new listing.
        $sum = $amount;
        umc_echo("{green}[+]{gray} You are now requesting {yellow}" . "{$sum} {$item['full']}{gray} in the shop.");
        $sql = "INSERT INTO minecraft_iconomy.`request` (`id` ,`damage` ,`uuid` ,`item_name` ,`price` ,`amount` ,`meta`)\r\n                VALUES (NULL , '{$type}', '{$uuid}', '{$item['item_name']}', '{$price}', '{$amount}', '{$meta}');";
        //XMPP_ERROR_trigger($sql);
        $rst = umc_mysql_query($sql);
        $posted_id = umc_mysql_insert_id();
    }
    if ($cost > 0) {
        umc_echo("{yellow}[\$]{white} Your account has been charged {cyan}{$cost}{gray} Uncs.");
    } else {
        umc_echo("{green}[\$]{white} Your account has been credited {cyan}" . $cost * -1 . "{gray} Uncs.");
    }
    umc_money($player, false, $cost);
    umc_announce("{gold}{$player}{gray} is {red}requesting to buy {yellow}{$sum}{$meta_txt}{green} " . "{$item['full']}{darkgray} @ {cyan}{$price}{gray} each{darkgray}, shop-id {gray}{$posted_id}");
}