/**
 * Removes an item from stock or deposit; does not record the transaction
 *
 * @param type $table
 * @param type $id
 * @param type $amount
 * @param type $player
 * @return int
 */
function umc_db_take_item($table, $id, $amount, $player)
{
    // $uuid = umc_uuid_getone($player, 'uuid');
    $D = umc_mysql_fetch_all("SELECT amount FROM minecraft_iconomy.{$table} WHERE id='{$id}';");
    $amount_row = $D[0];
    $newstock = $amount_row['amount'] - $amount;
    if ($table == 'stock') {
        if ($newstock == 0) {
            $sql = "DELETE FROM minecraft_iconomy.stock WHERE id='{$id}';";
            umc_log('shop', 'stock_adjust', "Cleared all content from stock for ID {$id} by withdrawing {$amount_row['amount']}");
        } else {
            $sql = "UPDATE minecraft_iconomy.stock SET amount={$newstock} WHERE id='{$id}';";
            umc_log('shop', 'stock_adjust', "Changed stock level for ID {$id} from {$amount_row['amount']} to {$newstock}");
        }
    } else {
        // take from deposit
        if ($newstock == 0) {
            $sql = "DELETE FROM minecraft_iconomy.deposit WHERE id='{$id}';";
            umc_log('shop', 'deposit_adjust', "Cleared all content from deposit for ID {$id} by withdrawing {$amount_row['amount']}");
        } else {
            $sql = "UPDATE minecraft_iconomy.deposit SET amount={$newstock} WHERE id='{$id}';";
            umc_log('shop', 'deposit_adjust', "Changed deposit level for ID {$id} from {$amount_row['amount']} to {$newstock}");
        }
    }
    umc_mysql_query($sql, true);
    // check stock levels
    $sql = "SELECT * FROM minecraft_iconomy.{$table} WHERE id={$id};";
    $D2 = umc_mysql_fetch_all($sql);
    if (count($D2)) {
        return $D2[0]['amount'];
    } else {
        return 0;
    }
}
function run_umc_scheduler()
{
    XMPP_ERROR_trace(__FUNCTION__, func_get_args());
    // list of what to do & undo or temp permissions
    $schedule_arr = array(1 => array('on_cmd' => array(0 => 'ch qm u Today bloody is Monday, beware of the mobs!', 1 => 'bloodmoon start darklands'), 'off_cmd' => array()), 2 => array('on_cmd' => array(0 => 'ch qm u Today is Tuesday, nothing special!', 1 => 'bloodmoon stop darklands', 2 => 'time 00:00 darklands'), 'off_cmd' => array()), 3 => array('on_cmd' => array(0 => 'ch qm u Hungry Wednesday started!', 1 => 'mv modify set autoheal false darklands', 2 => 'mv gamerule naturalRegeneration false darklands', 3 => 'region flag darklands_spawn greeting -w darklands ATTENTION: Today Darklands autoheal is OFF! You being fed does not heal you!'), 'off_cmd' => array(0 => 'ch qm u Hungry Wednesday is over!', 1 => 'mv modify set autoheal true darklands', 2 => 'mv gamerule naturalRegeneration true darklands', 3 => 'region flag darklands_spawn greeting -w darklands Welcome to the Darklands! Today everything is normal. Whatever that means.')), 4 => array('on_cmd' => array(0 => 'ch qm u Today is Thursday, nothing special!'), 'off_cmd' => array()), 5 => array('on_cmd' => array(0 => 'ch qm u Freaky Frydays started!', 1 => 'time 12:00 darklands', 2 => 'sunburn darklands on', 3 => 'region flag darklands_spawn greeting -w darklands ATTENTION: Today it\'s daylight in the Darklands, but the sun will burn you! find shadow!'), 'off_cmd' => array(0 => 'ch qm u Freaky Frydays is over!', 1 => 'time 00:00 darklands', 2 => 'sunburn darklands off', 3 => 'region flag darklands_spawn greeting -w darklands Welcome to the Darklands! Today everything is normal. Whatever that means.')), 6 => array('on_cmd' => array(0 => 'ch qm u Today is Saturday, nothing special!'), 'off_cmd' => array()), 0 => array('on_cmd' => array(0 => 'mv modify set pvp true darklands', 1 => 'region flag darklands_spawn greeting -w darklands ATTENTION: Today Darklands is PVP ON! You are safe here, but further out it\'s dangerous!', 2 => 'ch qm u ATTENTION: PVP is now ON in the darklands (except the area around spawn)!', 3 => 'region flag darklands_spawn farewell -w darklands ATTENTION: You are now entering a PVP area!!'), 'off_cmd' => array(0 => 'mv modify set pvp false darklands', 1 => 'region flag darklands_spawn greeting -w darklands Today Darklands is PVP OFF!', 2 => 'ch qm u ATTENTION: PVP is now OFF in the darklands. You are safe!', 3 => 'region flag darklands_spawn farewell -w darklands Welcome to the Darklands! Today everything is normal. Whatever that means.')));
    // find current day
    $date_new = umc_datetime();
    $today = $date_new->format('w');
    // echo "Echo today is $today: " . $date_new->format("Y-m-d H:i:s");
    if ($today == 0) {
        $yesterday = 6;
    } else {
        $yesterday = $today - 1;
    }
    // execute last day's off-commands
    $cmds = $schedule_arr[$yesterday]['off_cmd'];
    // var_dump($cmds);
    umc_schedule_exec($cmds);
    umc_log('scheduler', "yesterday", "executing commands for yesterday: {$yesterday}");
    // execute todays on-commands
    $cmds = $schedule_arr[$today]['on_cmd'];
    umc_log('scheduler', "today", "executing commands for yesterday: {$today}");
    umc_schedule_exec($cmds);
    $default_commands = array("mv gamerule doDaylightCycle false darklands", "mv gamerule naturalRegeneration false deathlands");
    foreach ($default_commands as $cmd) {
        umc_exec_command($cmd);
    }
    umc_ban_to_database();
    // make a new ID file in case item data has changed
    include_once '/home/minecraft/server/bin/commands/make_id_file.php';
}
/**
 * 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");
    }
}
function umc_lot_addrem()
{
    global $UMC_USER;
    $player = $UMC_USER['username'];
    $args = $UMC_USER['args'];
    /// /lotmember lot world add target
    if (count($args) <= 3) {
        umc_echo("{red}Not enough arguments given");
        umc_show_help($args);
        return;
    }
    $addrem = $args[1];
    $lot = strtolower($args[2]);
    $action = $args[3];
    $worlds = array('emp' => 'empire', 'fla' => 'flatlands', 'dar' => 'darklands', 'aet' => 'aether', 'kin' => 'kingdom', 'dra' => 'draftlands', 'blo' => 'skyblock', 'con' => 'aether');
    $world_abr = substr($lot, 0, 3);
    if (!isset($worlds[$world_abr])) {
        umc_error("Your used an invalid lot name!");
    }
    $world = $worlds[$world_abr];
    if ($player == '@Console') {
        $player = 'uncovery';
    }
    $user_id = umc_get_worldguard_id('user', strtolower($player));
    if (!$user_id) {
        umc_error("Your user id cannot be found!");
    }
    $player_group = umc_get_userlevel($player);
    $world_id = umc_get_worldguard_id('world', $world);
    if (!$world_id) {
        umc_show_help($args);
        umc_error("The lot '{$lot}' cannot be found in any world!");
    }
    if (!umc_check_lot_exists($world_id, $lot)) {
        umc_show_help($args);
        umc_error("There is no lot {$lot} in world {$world}!");
    }
    if ($action == 'snow' || $action == 'ice') {
        // check if the user has DonatorPlus status.
        if ($player_group !== 'Owner') {
            if (!stristr($player_group, 'DonatorPlus')) {
                umc_error("You need to be DonatorPlus level to use the snow/ice features!;");
            }
            $owner_switch = 0;
            // check if player is Owner of lot
            $sql = "SELECT * FROM minecraft_worldguard.region_players WHERE region_id='{$lot}' AND world_id={$world_id} AND user_id={$user_id} and Owner=1;";
            $D = umc_mysql_fetch_all($sql);
            $num = count($D);
            if ($num != 1) {
                umc_error("It appears you {$player} ({$user_id}) are not Owner of lot {$lot} in world {$world}!");
            }
        }
        // get the current status of the flags
        if ($addrem == 'add') {
            $flag = 'allow';
            umc_echo("Allowing {$action} forming on lot {$lot}... ");
        } else {
            if ($addrem == 'rem') {
                $flag = 'deny';
                umc_echo("Preventing {$action} forming on lot {$lot}... ");
            } else {
                umc_show_help($args);
            }
        }
        if ($action == 'snow') {
            $flagname = 'snow-fall';
        } else {
            if ($action == 'ice') {
                $flagname = 'ice-form';
            }
        }
        // does flag exist?
        $check_sql = "SELECT * FROM minecraft_worldguard.region_flag WHERE region_id='{$lot}' AND world_id={$world_id} AND flag='{$flagname}';";
        $D2 = umc_mysql_fetch_all($check_sql);
        $count = count($D2);
        if ($count == 0) {
            // insert
            $ins_sql = "INSERT INTO minecraft_worldguard.region_flag (region_id, world_id, flag, value) VALUES ('{$lot}', {$world_id}, '{$flagname}', '{$flag}');";
            umc_mysql_query($ins_sql, true);
        } else {
            // update
            $upd_sql = "UPDATE minecraft_worldguard.region_flag SET value='{$flag}' WHERE region_id='{$lot}' AND world_id={$world_id} AND flag='{$flagname}';";
            umc_mysql_query($upd_sql, true);
        }
        umc_echo("done!");
        umc_log('lot', 'addrem', "{$player} changed {$action} property of {$lot}");
    } else {
        if ($action == 'owner' || $action == 'give') {
            if ($player != 'uncovery' && $player != '@Console') {
                umc_error("Nice try, {$player}. Think I am stupid? Want to get banned?");
            }
            $owner_switch = 1;
        } else {
            if ($action == 'member') {
                $user_id = umc_get_worldguard_id('user', strtolower($player));
                if (!$user_id && $player !== 'uncovery') {
                    umc_error("Your user id cannot be found!");
                }
                $owner_switch = 0;
                // check if player is Owner of lot
                if ($player_group !== 'Owner') {
                    $sql = "SELECT * FROM minecraft_worldguard.region_players WHERE region_id='{$lot}' AND world_id={$world_id} AND user_id={$user_id} and Owner=1;";
                    $D3 = umc_mysql_fetch_all($sql);
                    $count = count($D3);
                    if ($count != 1) {
                        umc_error("It appears you ({$player} {$user_id}) are not Owner of lot {$lot} in world {$world}!");
                    }
                }
            } else {
                umc_echo("Action {$action} not recognized!");
                umc_show_help($args);
                return;
            }
        }
        // get list of active users
        $active_users = umc_get_active_members();
        for ($i = 4; $i < count($args); $i++) {
            $target = strtolower($args[$i]);
            // check if target player exists
            $target_id = umc_get_worldguard_id('user', strtolower($target));
            if (!$target_id) {
                umc_error("The user {$target} does not exist in the database. Please check spelling of username");
            }
            if ($player != 'uncovery') {
                $targ_group = umc_get_userlevel($target);
                if ($targ_group == 'Guest') {
                    umc_error("You cannnot add Guests to your lot!;");
                } else {
                    if (!in_array($target, $active_users)) {
                        XMPP_ERROR_trigger("{$player} tried to add {$target} to his lot {$lot}, but {$target} is not an active member!");
                        umc_error("{$target} is not an active user! You can only add people who have their own lot! See FAQ entry #32 please.");
                    }
                }
            }
            // add / remove target player from lot
            if ($addrem == 'add') {
                // make sure target is not already there
                $sql = "SELECT * FROM minecraft_worldguard.region_players WHERE region_id='{$lot}' AND world_id={$world_id} AND user_id={$target_id};";
                $D3 = umc_mysql_fetch_all($sql);
                $num = count($D3);
                if ($num == 1) {
                    umc_error("It appears {$target} is already member of lot {$lot} in world {$world}!");
                }
                // add to the lot
                umc_lot_add_player($target, $lot, 0);
                umc_echo("Added {$target} to {$lot} in the {$world}!");
            } else {
                if ($addrem == 'rem') {
                    // check if target is there at all
                    $sql = "SELECT * FROM minecraft_worldguard.region_players WHERE region_id='{$lot}' AND world_id={$world_id} AND user_id={$target_id} AND Owner={$owner_switch} LIMIT 1;";
                    $D3 = umc_mysql_fetch_all($sql);
                    $num = count($D3);
                    if ($num !== 1) {
                        umc_error("It appears user {$target} is not a member of lot {$lot} in world {$world}!");
                    }
                    umc_lot_rem_player($target, $lot, 0);
                    umc_echo("Removed {$target} from {$lot} in the {$world}!");
                } else {
                    if ($addrem == 'give') {
                        // remove all members and owners
                        umc_lot_remove_all($lot);
                        umc_lot_add_player($target, $lot, 1);
                        umc_echo("Gave {$lot} to {$target} in the {$world}! All other user removed!");
                        // logfile entry
                        umc_log('lot', 'addrem', "{$player} gave lot to {$target}");
                    } else {
                        umc_show_help($args);
                    }
                }
            }
        }
    }
    umc_ws_cmd("region load -w {$world}", 'asConsole');
}
/**
 * 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}");
}
Example #6
0
function umc_donation_level($user, $debug = false)
{
    XMPP_ERROR_trace(__FUNCTION__, func_get_args());
    $U = umc_uuid_getboth($user);
    $uuid = $U['uuid'];
    $username = $U['username'];
    $debug_txt = '';
    global $UMC_SETTING;
    $date_now = new DateTime("now");
    $sql = "SELECT amount, date FROM minecraft_srvr.donations WHERE uuid='{$uuid}';";
    $level = umc_get_uuid_level($uuid);
    if ($level == 'Owner') {
        return false;
    }
    $D = umc_mysql_fetch_all($sql);
    // if there are 0 donations, user should not be changes
    if (count($D) == 0 && strstr($level, "Donator")) {
        XMPP_ERROR_trigger("User {$username} ({$uuid}) never donated but has a donator level ({$level})");
    } else {
        if (count($D) == 0) {
            $debug_txt .= "{$username} ({$uuid}) does not have any donations\n";
            return;
        }
    }
    $debug_txt .= "Checking donation upgrade of user {$username}, current UserLevel: {$level}\n";
    $donation_level = 0;
    // go through all donations and find out how much is still active
    foreach ($D as $row) {
        $date_donation = new DateTime($row['date']);
        $interval = $date_donation->diff($date_now);
        $years = $interval->format('%y');
        $months = $interval->format('%m');
        $donation_term = $years * 12 + $months;
        $donation_leftover = $row['amount'] - $donation_term;
        if ($donation_leftover < 0) {
            $donation_leftover = 0;
            // do not create negative carryforward
        }
        $donation_level = $donation_level + $donation_leftover;
        $debug_txt .= "Amount donated {$row['amount']} {$years} years {$months} m ago = {$donation_term} months ago, {$donation_leftover} leftover, level: {$donation_level}\n";
    }
    $donation_level_rounded = ceil($donation_level);
    // get userlevel and check if demotion / promotion is needed
    $debug_txt .= "user {$username} ({$uuid}) has donation level of {$donation_level_rounded}, now is {$level}\n";
    // current userlevel
    $ranks_lvl = array_flip($UMC_SETTING['ranks']);
    $cur_lvl = $ranks_lvl[$level];
    // get current promotion level
    if (strpos($level, 'DonatorPlus')) {
        $current = 2;
    } else {
        if (strpos($level, 'Donator')) {
            $current = 1;
        } else {
            $current = 0;
        }
    }
    // get future promotion level
    if (count($D) == 0) {
        // this never happens since it's excluded above
        $future = 0;
    } else {
        if ($donation_level_rounded >= 1) {
            $future = 2;
        } else {
            if ($donation_level_rounded < 1) {
                $future = 1;
            }
        }
    }
    $debug_txt .= "future = {$future}, current = {$current}\n";
    $change = $future - $current;
    if ($change == 0) {
        $debug_txt .= "User has right level, nothing to do\n";
        return false;
        // bail if no change needed
    } else {
        // we have a change in level, let's get an error report
        $debug = true;
    }
    $debug_txt .= "User will change {$change} levels\n";
    // get currect rank index
    $debug_txt .= "Current Rank index = {$cur_lvl}\n";
    // calculate base level
    $base_lvl = $cur_lvl - $current;
    $debug_txt .= "User base level = {$base_lvl}\n";
    $new_lvl = $base_lvl + $future;
    if ($new_lvl == $cur_lvl) {
        XMPP_ERROR_send_msg("Donations upgrade: Nothing to do, CHECK this should have bailed earlier!");
        return false;
    }
    $new_rank = $UMC_SETTING['ranks'][$new_lvl];
    $debug_txt .= "User {$username} upgraded from {$level} to {$new_rank}\n";
    umc_exec_command("pex user {$uuid} group set {$new_rank}");
    umc_log('Donations', 'User Level de/promotion', "User {$username} upgraded from {$level} to {$new_rank}");
    if ($debug) {
        XMPP_ERROR_send_msg($debug_txt);
    }
    return $donation_level_rounded;
    // . "($donation_level $current - $future - $change)";
}
Example #7
0
function umc_timer_get($user, $type)
{
    // check if a timer is set
    $sql = "SELECT time_out FROM minecraft_srvr.timers WHERE username='******' AND type='{$type}';";
    $D = umc_mysql_fetch_all($sql);
    if (count($D) > 0) {
        // no, check if timed out
        $date_now = umc_datetime();
        // substract the current day
        $date_row = umc_datetime($D[0]['time_out']);
        // difference in seconds ofr check
        $diff = $date_row->getTimestamp() - $date_now->getTimestamp();
        if ($diff > 0) {
            return $date_row;
        } else {
            $sql_del = "DELETE FROM minecraft_srvr.timers WHERE username='******' AND type='{$type}';";
            umc_log('timer', 'removed', "{$type} timer for {$user}");
            umc_mysql_query($sql_del, true);
            return false;
        }
    } else {
        return false;
        // no such timer set
    }
}
Example #8
0
/**
 * promotes a user to Citizen if applicable
 *
 * @param type $user_login
 * @param type $userlevel
 * @return type
 */
function umc_promote_citizen($username, $userlevel = false)
{
    XMPP_ERROR_trace(__FUNCTION__, func_get_args());
    if (!$userlevel) {
        $userlevel = umc_get_userlevel($username);
    }
    $lower_username = strtolower($username);
    $settlers = array('Settler', 'SettlerDonator', 'SettlerDonatorPlus');
    if (in_array($userlevel, $settlers)) {
        /*
        $age = umc_get_lot_owner_age('array', $lower_login);
        if (!$age) {
            return;
        }
        $age_days = $age[$lower_login]['firstlogin']['days'];
        if ($age_days >= 90) {
        *
        */
        $online_hours = umc_get_online_hours($lower_username);
        if ($online_hours >= 60) {
            //user should be Citizen
            $uuid = umc_user2uuid($lower_username);
            if ($userlevel == 'Settler') {
                // pex user <user> group set <group>
                umc_exec_command("pex user {$uuid} group set Citizen");
                umc_log("users", "promotion", "User {$username} ({$uuid}) was promoted from {$userlevel} to Citizen (online hours: {$online_hours})");
            } else {
                if ($userlevel == 'SettlerDonator') {
                    umc_exec_command("pex user {$uuid} group set CitizenDonator");
                    umc_log("users", "promotion", "User {$username} ({$uuid}) was promoted from {$userlevel} to CitizenDonator (online: {$online_hours})");
                } else {
                    if ($userlevel == 'SettlerDonatorPlus') {
                        umc_exec_command("pex user {$uuid} group set CitizenDonatorPlus");
                        umc_log("users", "promotion", "User {$username} ({$uuid}) was promoted from {$userlevel} to CitizenDonatorPlus (online: {$online_hours})");
                    } else {
                        XMPP_ERROR_trigger("{$username} / {$uuid} has level {$userlevel} and could not be promoted to Citizen! Please report to admin!");
                    }
                }
            }
        }
    }
}
Example #9
0
/**
 * Executes a command without the initiation of Websend
 * always does this as the console since no user initiating it.
 *.
 * @param type $cmd
 * @param type $how (asConsole (default), asPlayer, toConsole, toPlayer, broadcast, doScript
 * @param type $player
 */
function umc_exec_command($cmd, $how = 'asConsole', $player = false)
{
    global $UMC_PATH_MC;
    XMPP_ERROR_trace(__FUNCTION__, func_get_args());
    umc_log('websend', 'outgoing', "{$cmd} {$how} to {$player}");
    require_once "{$UMC_PATH_MC}/server/bin/includes/websend_class.php";
    $ws = new Websend("74.208.45.80");
    //, 4445
    $ws->password = "******";
    if (!$ws->connect()) {
        // try again
        $ws = new Websend("74.208.45.80");
        //, 4445
        $ws->password = "******";
        if (!$ws->connect()) {
            // fail agin? bail.
            XMPP_ERROR_trigger("Could not connect to websend server (umc_exec_command / {$cmd} / {$how} / {$player})");
        }
    }
    // $ws->writeOutputToConsole("starting ws communication;");
    // $ws->writeOutputToConsole("Executing Command '$cmd' Method '$how' Player '$player';");
    switch ($how) {
        case 'asConsole':
            $check = $ws->doCommandAsConsole($cmd);
            break;
        case 'asPlayer':
            $check = $ws->doCommandAsPlayer($cmd, $player);
            break;
        case 'toConsole':
            $check = $ws->writeOutputToConsole($cmd);
            break;
        case 'toPlayer':
            $check = $ws->writeOutputToPlayer($cmd, $player);
            break;
        case 'broadcast':
            $check = $ws->broadcast($cmd);
            break;
        case 'doScript':
            $check = $ws->doScript($cmd);
            break;
    }
    if (!$check) {
        XMPP_ERROR_trigger("Could not verify correct connection to websend (umc_exec_command / {$cmd} / {$how} / {$player})");
    } else {
        //echo "nah.";
        //$check = $ws->writeOutputToConsole("error");
    }
    $ws->disconnect();
}
/**
 * This checks if the username has changed and updates the wordpress table accordingly
 *
 * @param type $username
 * @param type $uuid
 */
function umc_uuid_check_usernamechange($uuid)
{
    XMPP_ERROR_trace(__FUNCTION__, func_get_args());
    $sql = "SELECT ID, user_login, display_name, UUID, username, wp_users.user_registered, UUID.lastlogin FROM minecraft.`wp_users`\r\n        LEFT JOIN minecraft.wp_usermeta ON ID=wp_usermeta.user_id\r\n        LEFT JOIN minecraft_srvr.UUID ON UUID.UUID=wp_usermeta.meta_value\r\n        WHERE meta_key='minecraft_uuid' AND meta_value='{$uuid}';";
    $D = umc_mysql_fetch_all($sql);
    foreach ($D as $d) {
        // get proper username from Mojang
        $uuid = $d['UUID'];
        $wordpress_name = strtolower($d['display_name']);
        $uuid_name = strtolower($d['username']);
        $wp_login = $d['user_login'];
        // $wp_id = $d['ID'];
        $mojang_raw = umc_uuid_get_from_mojang($uuid);
        $mojang_name = strtolower($mojang_raw);
        if (!$mojang_name || $mojang_name == '') {
            //XMPP_ERROR_trigger("Tried to check for username change, failed to confirm ($sql)");
            $s_server = filter_input_array(INPUT_SERVER, FILTER_SANITIZE_STRING);
            $referer = "\nREQUEST_URI: " . $s_server['REQUEST_URI'];
            XMPP_ERROR_send_msg("Fail on Username change check umc_uuid_check_usernamechange: Mojang name for {$uuid} is {$mojang_name} {$referer}");
            return;
            // let's try the user_login
            /*    $mojang_uuid = umc_uuid_get_from_mojang($wp_login);
                     // update the meta table
                     $u_sql_meta = "UPDATE minecraft.wp_usermeta SET meta_value='$mojang_uuid' WHERE user_id='$wp_id' AND meta_key='minecraft_uuid'";
                     umc_mysql_query($u_sql_meta, true);
                  *
                  */
        }
        if ($wordpress_name != $mojang_name) {
            $u_sql_wp = "UPDATE minecraft.wp_users SET display_name='{$mojang_name}' WHERE user_login='******'";
            $logtext = "User {$uuid} changed username from {$wordpress_name} to {$mojang_name} in Wordpress";
            XMPP_ERROR_send_msg($logtext);
            umc_log('UUID', 'Username Change', $logtext);
            umc_mysql_query($u_sql_wp, true);
        }
        if ($uuid_name != $mojang_name) {
            $u_sql_uuid = "UPDATE minecraft_srvr.UUID SET username='******' WHERE UUID='{$uuid}'";
            $logtext = "User {$uuid} changed username from {$uuid_name} to {$mojang_name} in UUID table";
            XMPP_ERROR_send_msg($logtext);
            umc_log('UUID', 'Username Change', $logtext);
            umc_mysql_query($u_sql_uuid, true);
        }
    }
}
 public function ban($reason)
 {
     XMPP_ERROR_trace(__CLASS__ . " // " . __FUNCTION__, func_get_args());
     global $UMC_USERS;
     $cmd = "ban {$this->username} {$reason}";
     if ($this->context == 'websend') {
         umc_ws_cmd($cmd, 'asConsole', false, false);
         $admin = $UMC_USERS['current_user']->username;
     } else {
         umc_exec_command($cmd, 'asConsole', false);
         $admin = 'wordpress';
     }
     $sql = "INSERT INTO minecraft_srvr.`banned_users`(`username`, `reason`, `admin`, `uuid`) VALUES ('{$this->username}','{$reason}', '{$admin}', '{$this->uuid}');";
     umc_mysql_query($sql, true);
     // remove shop inventory
     umc_shop_cleanout_olduser($this->uuid);
     // remove from teamspeak
     umc_ts_clear_rights($this->uuid);
     $text = "{$admin} banned \${$this->username} ({$this->uuid}) because of {$reason}";
     umc_log('mod', 'ban', $text);
     XMPP_ERROR_send_msg($text);
     // iterate plugins to check for plugin relared post ban processes
 }
/**
 * This allows users in-game to set karma for another user
 *
 * @global type $UMC_USER
 */
function umc_setkarma()
{
    XMPP_ERROR_trace(__FUNCTION__, func_get_args());
    global $UMC_USER;
    $sender_uuid = $UMC_USER['uuid'];
    $sender = $UMC_USER['username'];
    $sender_lvl = $UMC_USER['userlevel'];
    $args = $UMC_USER['args'];
    if ($sender_lvl == 'guest') {
        umc_error('Guests cannot give karma to others');
    }
    // get user age
    $age_sql = "SELECT DATEDIFF(NOW(),firstlogin) as online_days FROM minecraft_srvr.UUID\r\n        WHERE uuid='{$sender_uuid}'";
    $age_data = umc_mysql_fetch_all($age_sql);
    $online_time = $age_data[0]['online_days'];
    if ($online_time < 10) {
        umc_error("You cannot give karma yet, you are too new on the server!");
    }
    $karma_arr = array('+' => 1, '-' => -1, '0' => 0);
    if (isset($args[1]) && array_key_exists($args[1], $karma_arr)) {
        $new_karma = $karma_arr[$args[1]];
    } else {
        umc_error('You need to indicate the karma value with +,- or 0;');
    }
    if (!isset($args[2])) {
        umc_error('You need to enter the user to give karma to!;');
    } else {
        if (strtolower($args[2]) == strtolower($sender)) {
            umc_error('You cannot give karma to yourself!;');
        }
    }
    $receiver = umc_sanitize_input($args[2], 'player');
    if ($receiver == 'uncovery') {
        umc_error("Thou shalt not judge the maker of all things!");
    }
    // get receiver UUID
    $receiver_uuid = umc_user2uuid($receiver);
    // get user age
    $rec_age_sql = "SELECT DATEDIFF(NOW(),firstlogin) as online_days FROM minecraft_srvr.UUID\r\n        WHERE uuid='{$receiver_uuid}'";
    $rec_age_data = umc_mysql_fetch_all($rec_age_sql);
    $rec_online_time = $rec_age_data[0]['online_days'];
    // receiver user level
    $receiver_lvl = umc_get_uuid_level($receiver_uuid);
    if ($rec_online_time < 10 || $receiver_lvl == 'Guest') {
        umc_error("You cannot give karma to this user, he is too new!");
    }
    // check if there is the same karma already, otherwise fix
    $sql = "SELECT karma FROM minecraft_srvr.karma\r\n        WHERE sender_uuid='{$sender_uuid}' AND receiver_uuid='{$receiver_uuid}';";
    $data_arr = umc_mysql_fetch_all($sql);
    if (count($data_arr) > 0) {
        $oldkarma = $data_arr[0]['karma'];
        if ($new_karma == $oldkarma) {
            umc_echo("You already gave {$receiver} {$oldkarma} karma!");
            // show the karma of the recipient to the user
            umc_getkarma($receiver_uuid);
            exit;
        } else {
            umc_echo("Giving {$receiver} {$new_karma} karma instead of {$oldkarma} karma.");
            $update_sql = "UPDATE minecraft_srvr.karma set karma={$new_karma}\r\n                WHERE sender_uuid='{$sender_uuid}' AND receiver_uuid='{$receiver_uuid}';";
            umc_mysql_query($update_sql, true);
        }
    } else {
        umc_echo("Giving {$new_karma} karma to {$receiver}.");
        $update_sql = "INSERT INTO minecraft_srvr.karma (sender_uuid, receiver_uuid, karma)\r\n            VALUES ('{$sender_uuid}', '{$receiver_uuid}', {$new_karma});";
        umc_mysql_query($update_sql, true);
    }
    umc_log('karma', 'set', "{$sender} ({$sender_uuid}) set {$new_karma} for {$receiver} ({$receiver_uuid})");
    umc_getkarma($receiver_uuid);
}
function umc_ws_eventhandler($event)
{
    global $WS_INIT, $UMC_USER;
    XMPP_ERROR_trace(__FUNCTION__, func_get_args());
    $player = $UMC_USER['username'];
    // iterate all plugins
    foreach ($WS_INIT as $data) {
        // check if there is a setting for the current event
        if ($data['events'] != false && isset($data['events'][$event])) {
            // execute function
            $function = $data['events'][$event];
            if (!is_string($function)) {
                XMPP_ERROR_trigger("plugin eventhandler failed event {$event}");
            }
            // execute the function
            $function();
        }
    }
    // non-plugin events
    switch ($event) {
        case 'PlayerQuitEvent':
            umc_log('system', 'logout', "{$player} logged out");
            umc_uuid_record_usertimes('lastlogout');
            break;
        case 'PlayerJoinEvent':
            umc_uuid_check_usernamechange($UMC_USER['uuid']);
            umc_donation_level($player);
            umc_promote_citizen($player, false);
            umc_log('system', 'login', "{$player} logged in");
            umc_uuid_record_usertimes('lastlogin');
            // check if the user has a skin stored, if not, get it
            umc_usericon_get($UMC_USER['uuid'], false);
            break;
        case 'PlayerPreLoginEvent':
            // nothing needed since the fact that websend is called makes it register the UUID already
            break;
        default:
            // all the events not covered above
            // XMPP_ERROR_send_msg("Event $event not assigned to action (umc_ws_eventhandler)");
    }
}
function umc_trivia_close_quiz($quiz_arr = false)
{
    global $UMC_USER;
    $player = $UMC_USER['username'];
    if (!$quiz_arr) {
        $quiz_arr = umc_trivia_get_current_quiz();
    }
    $quiz_id = $quiz_arr['id'];
    // get best user and points
    $sql = "SELECT username, count(result) as points FROM minecraft_quiz.quiz_answers WHERE quiz_id={$quiz_id} AND result='right' GROUP BY username ORDER BY count(result) DESC;";
    $D = umc_mysql_fetch_all($sql);
    $data = array();
    $prev_points = 0;
    foreach ($D as $row) {
        $username = $row['username'];
        $points = $row['points'];
        if ($points < $prev_points) {
            break;
        }
        $data[] = $username;
        // array of the winner(s)
        $prev_points = $points;
    }
    $winner_count = count($data);
    if ($winner_count > 0) {
        $winner_str = implode(", ", $data);
        // how many answers have been given?
        $answer_sql = "SELECT count(answer_id) as counter FROM minecraft_quiz.quiz_answers WHERE quiz_id={$quiz_id};";
        $A = umc_mysql_fetch_all($answer_sql);
        $answer_row = $A[0];
        $answer_count = $answer_row['counter'];
        $prize = $answer_count * $quiz_arr['price'] / $winner_count;
        umc_ws_cmd("ch qm o &3[Trivia]&f We have {$winner_count} winner(s) who each get {$prize}!");
        umc_ws_cmd("ch qm o &3[Trivia]&f Winner(s): {$winner_str}");
        umc_money(false, $row['username'], $prize);
        $sql = "UPDATE minecraft_quiz.quizzes SET end=NOW(), winner='{$winner_str}', points={$prev_points} WHERE quiz_id={$quiz_id};";
    } else {
        $sql = "UPDATE minecraft_quiz.quizzes SET end=NOW(), winner='', points=0 WHERE quiz_id={$quiz_id};";
    }
    umc_mysql_query($sql, true);
    umc_ws_cmd("ch qm o &3[Trivia]&f Thanks for participating. Create your own quiz with /trivia new!");
    umc_log('trivia', 'close', "{$player} closed trivia {$quiz_id} and gave {$prize} to {$winner_str} each");
}
Example #15
0
function umc_lottery()
{
    //  umc_error_notify("User $user, $chance (umc_lottery)");
    global $UMC_USER, $lottery, $ENCH_ITEMS;
    $user_input = $UMC_USER['args'][2];
    $user = umc_check_user($user_input);
    if (!$user) {
        umc_log("lottery", "voting", "user {$user} does not exist");
        return false;
    }
    $uuid = umc_user2uuid($user);
    $chance = false;
    if ($user == 'uncovery' && isset($UMC_USER['args'][3])) {
        $chance = $UMC_USER['args'][3];
    }
    $roll = umc_lottery_roll_dice($chance);
    // umc_echo(umc_ws_vardump($roll));
    $item = $roll['item'];
    $luck = $roll['luck'];
    $prize = $lottery[$item];
    //echo "type = {$prize['type']}<br>;";
    //echo "complete chance: $chance<br>;";
    //var_dump($prize);
    if (isset($prize['detail'])) {
        $detail = $prize['detail'];
    }
    $type = $prize['type'];
    // always give 100 uncs
    umc_money(false, $user, 100);
    $given_block_data = 0;
    $given_block_type = 0;
    //var_dump($prize);
    switch ($type) {
        case 'item':
            umc_deposit_give_item($uuid, $detail['type'], $detail['data'], $detail['ench'], 1, 'lottery');
            $item_txt = $prize['txt'];
            break;
        case 'random_unc':
            $luck2 = mt_rand(1, 500);
            umc_money(false, $user, $luck2);
            $item_txt = "{$luck2} Uncs";
            break;
        case 'random_potion':
            $luck2 = mt_rand(0, 63);
            umc_deposit_give_item($uuid, 373, $luck2, '', 1, 'lottery');
            $item_txt = $prize['txt'];
            break;
        case 'random_ench':
            // pick which enchantment
            $rand_ench = array_rand($ENCH_ITEMS);
            $ench_arr = $ENCH_ITEMS[$rand_ench];
            //pick which item to enchant
            $rand_item = array_rand($ench_arr['items']);
            $rand_item_id = $ench_arr['items'][$rand_item];
            // pick level of enchantment
            $lvl_luck = mt_rand(1, $ench_arr['max']);
            //echo "$item $ench_txt $lvl_luck";
            $item_ench_arr = array($rand_ench => $lvl_luck);
            $item = umc_goods_get_text($rand_item_id, 0, $item_ench_arr);
            $item_name = $item['item_name'];
            $full = $item['full'];
            umc_deposit_give_item($uuid, $item_name, 0, $item_ench_arr, 1, 'lottery');
            $item_txt = "a " . $full;
            break;
        case 'random_pet':
            // same as blocks below but only 1 always
            umc_echo($type);
            $block = $prize['blocks'];
            $luck2 = mt_rand(0, count($prize['blocks']) - 1);
            $given_block = explode(":", $block[$luck2]);
            $given_block_type = $given_block[0];
            $given_block_data = $given_block[1];
            umc_deposit_give_item($uuid, $given_block_type, $given_block_data, '', 1, 'lottery');
            $item = umc_goods_get_text($given_block_type, $given_block_data);
            $item_txt = "a " . $item['full'];
            break;
        case 'random_common':
        case 'random_ore':
        case 'random_manuf':
            $block = $prize['blocks'];
            $luck2 = mt_rand(0, count($prize['blocks']) - 1);
            $luck3 = mt_rand(1, 64);
            $given_block = explode(":", $block[$luck2]);
            $given_block_type = $given_block[0];
            $given_block_data = $given_block[1];
            umc_deposit_give_item($uuid, $given_block_type, $given_block_data, '', $luck3, 'lottery');
            $item = umc_goods_get_text($given_block_type, $given_block_data);
            $item_txt = "{$luck3} " . $item['full'];
            break;
    }
    if ($user != 'uncovery') {
        // testing only
        $item_nocolor = umc_ws_color_remove($item_txt);
        umc_ws_cmd("ch qm N {$user} voted, rolled a {$luck} and got {$item_nocolor}!", 'asConsole');
        umc_log('votelottery', 'vote', "{$user} rolled {$luck} and got {$item_nocolor} ({$given_block_type}:{$given_block_data})");
        $userlevel = umc_get_userlevel($user);
        if (in_array($userlevel, array('Settler', 'Guest'))) {
            $msg = "You received {$item_txt} from the lottery! Use {green}/withdraw @lottery{white} to get it!";
            umc_msg_user($user, $msg);
        }
    } else {
        umc_echo("{$user} voted, rolled a {$luck} and got {$item_txt}!");
    }
    // add vote to the database
    $service = umc_mysql_real_escape_string($UMC_USER['args'][3]);
    $ip = umc_mysql_real_escape_string($UMC_USER['args'][4]);
    $sql = "INSERT INTO minecraft_log.votes_log (`username`, `datetime`, `website`, `ip_address`)\r\n        VALUES ('{$uuid}', NOW(), {$service}, {$ip});";
    umc_mysql_query($sql, true);
    // echo "$user voted for the server and got $item_txt!;";
}
Example #16
0
function umc_home_import()
{
    global $UMC_USER;
    // we automatically import old homes for all players on login, but only once
    $existing_count = umc_home_count();
    if ($existing_count > 0) {
        return;
    }
    // include spyc to parse YAML https://github.com/mustangostang/spyc
    require_once '/home/includes/spyc/Spyc.php';
    $path = '/home/minecraft/server/bukkit/plugins/Essentials/userdata/' . $UMC_USER['uuid'] . ".yml";
    $A = Spyc::YAMLLoad($path);
    if (!isset($A['homes']) || count($A['homes']) == 0) {
        return;
    }
    $H = $A['homes'];
    // iterate homes and import them
    foreach ($H as $home_name => $h) {
        $name = umc_mysql_real_escape_string($home_name);
        // XMPP_ERROR_trigger($h);
        $sql = "INSERT INTO minecraft_srvr.`homes`(`name`, `uuid`, `world`, `x`, `y`, `z`, `yaw`) VALUES " . "({$name},'{$UMC_USER['uuid']}','{$h['world']}','{$h['x']}','{$h['y']}','{$h['z']}','{$h['yaw']}');";
        umc_mysql_query($sql, true);
    }
    umc_log('homes', 'import', "{$UMC_USER['uuid']}/{$UMC_USER['username']}homes have been imported!");
}
function umc_vote_web()
{
    XMPP_ERROR_trace(__FUNCTION__, func_get_args());
    global $vote_ranks, $UMC_DOMAIN, $UMC_USER;
    $lvl_percent = array('a' => 0.3, 'd' => 0.4, 'm' => 0.7, 'e' => 1);
    $out = umc_vote_stats();
    // return "<h1>Sorry, due to technical issues, voting is temporarily suspended</h1>";
    if (!$UMC_USER) {
        $out = "Please <a href=\"{$UMC_DOMAIN}/wp-login.php\">login</a> to vote!";
        return $out;
    } else {
        $out .= "<h2>Proposals & Votes</h2>";
        $username = $UMC_USER['username'];
        $uuid = $UMC_USER['uuid'];
        $user_lvl = $UMC_USER['userlevel'];
    }
    $user_lvl_id = $vote_ranks[$user_lvl]['lvl'];
    if ($user_lvl_id < 3) {
        // start voting only for designers
        return "Sorry, you need to be Designer or above to vote!";
    }
    // get user numbers for levels
    $lvl_str_arr = array('a' => "'Architect', 'ArchitectDonator', 'ArchitectDonatorPlus'", 'd' => "'Designer', 'DesignerDonator', 'DesignerDonatorPlus'", 'm' => "'Master', 'MasterDonator', 'MasterDonatorPlus'", 'e' => "'Elder', 'ElderDonator', 'ElderDonatorPlus'");
    $lvl_amounts = array('a' => 0, 'd' => 0, 'm' => 0, 'e' => 0);
    $lvl_min_req = array('a' => 0, 'd' => 0, 'm' => 0, 'e' => 0);
    foreach ($lvl_str_arr as $lvl_code => $lvl_str) {
        // This takes all lots where the owners are in one of the user 4 levels that can vote
        $sql = "SELECT user_id, UUID.UUID as uuid, username FROM `minecraft_worldguard`.`region_players`\r\n            LEFT JOIN minecraft_worldguard.user ON region_players.user_id=user.id\r\n            LEFT JOIN minecraft_srvr.UUID ON minecraft_worldguard.user.uuid=minecraft_srvr.UUID.UUID\r\n            LEFT JOIN minecraft_srvr.permissions_inheritance ON minecraft_srvr.UUID.UUID=minecraft_srvr.permissions_inheritance.child\r\n            WHERE parent IN ({$lvl_str}) AND type=1 AND owner=1 GROUP BY user_id;";
        $C = umc_mysql_fetch_all($sql);
        // count all the people in the userlevel to know how many votes are needed
        $lvl_amounts[$lvl_code] = count($C);
    }
    // calc needed votes
    $full_vote = $lvl_amounts['e'] * $vote_ranks['Elder']['vote'];
    foreach ($lvl_amounts as $lvl => $lvl_amount) {
        $lvl_min_req[$lvl] = round($full_vote * $lvl_percent[$lvl]);
    }
    // TODO insert here a cleanup process that deletes old votes of non-promoted users
    $proposed = filter_input(INPUT_POST, 'proposal', FILTER_SANITIZE_STRING);
    if (isset($proposed) && strlen($proposed) > 1) {
        $proposed = umc_check_user($proposed);
        if (!$proposed) {
            $out .= "Sorry {$username}, but you need to input an existing user to propose!";
        } else {
            $proposed_data = umc_uuid_getboth($proposed, 'username');
            $proposed_username = $proposed_data['username'];
            $proposed_uuid = $proposed_data['uuid'];
            // what user level is it?
            $prop_lvl = umc_get_uuid_level($proposed_uuid);
            $prop_lvl_id = $vote_ranks[$prop_lvl]['lvl'];
            // check if the user was recently promoted
            $sql = "SELECT UNIX_TIMESTAMP(`date`) as mysql_ts FROM minecraft_srvr.proposals  WHERE `uuid` LIKE '{$proposed_uuid}' ORDER BY `date` DESC;";
            $D = umc_mysql_fetch_all($sql);
            $row = array();
            if (count($D) > 0) {
                $row = $D[0];
                // get the first (latest) entry
            } else {
                $row['mysql_ts'] = 0;
            }
            if (time() - $row['mysql_ts'] < 5270400) {
                $out .= "<strong>Sorry {$username}, but {$proposed_username} was last proposed for promotion less than 2 months ago!</strong>";
            } else {
                if ($user_lvl_id < 6 && $user_lvl_id < $prop_lvl_id + 1) {
                    $out .= "<strong>Sorry {$username}, but you need to be at a higher level to propose {$proposed_username} for a higher rank!</strong>";
                } else {
                    if ($prop_lvl_id > 5) {
                        $out .= "<strong>Sorry {$username}, but {$proposed_username} has reached max level already!</strong>";
                    } else {
                        if (umc_user_countlots($proposed) < 1) {
                            // is this an active user?
                            $out .= "<strong>Sorry {$username}, but you can only propose users who have a lot!</strong>";
                        } else {
                            if ($prop_lvl_id < 2) {
                                $out .= "<strong>Sorry {$username}, but you can only propose users who are at least Citizen level!</strong>";
                            } else {
                                if ($username == $proposed) {
                                    $out .= "<strong>Sorry {$username}, but you cannot propose yourself!</strong>";
                                } else {
                                    // ok to be promoted
                                    $ins_proposal_sql = "INSERT INTO `minecraft_srvr`.`proposals` (`pr_id`, `uuid`, `proposer_uuid`, `date`, `status`)\r\n                    VALUES (NULL, '{$proposed_uuid}', '{$uuid}', NOW(), 'voting');";
                                    umc_mysql_query($ins_proposal_sql);
                                    $pr_id = umc_mysql_insert_id();
                                    $sql = "INSERT INTO minecraft_srvr.`proposals_votes` (`pr_id`, `voter_uuid`, `date`, `vote`) VALUES ({$pr_id}, '{$uuid}', NOW(), 1);";
                                    umc_mysql_query($sql, true);
                                    $out .= "Thanks {$username}, {$proposed_username} as been submitted for voting, and your vote has been set, too!";
                                    if ($prop_lvl_id == 5) {
                                        // we propose a Master for promotion, inform all elders
                                        $sql = "SELECT user_email, UUID, username FROM minecraft_srvr.`UUID`\r\n                        LEFT JOIN minecraft.wp_usermeta ON UUID.UUID=meta_value\r\n                        LEFT JOIN minecraft.wp_users ON user_id=ID\r\n                        WHERE `userlevel` LIKE 'Elder%' AND lot_count > 0";
                                        $D = umc_mysql_fetch_all($sql);
                                        $subject = "{$proposed} proposed for Elder, please vote!";
                                        $content = "Dear Elder, \r\n\r\nthe user {$proposed} has been proposed to be promoted to Elder. Please go to\r\n\r\n{$UMC_DOMAIN}/vote-for-users/\r\n\r\n" . "and vote on this proposal. Please either SUPPORT or VETO the proposal.\r\n" . "Please note that the vote will be closed as 'failed' unless all Elders cast a vote within the coming 2 months.\r\n" . "Thanks a lot for supporting Uncovery Minecraft!\r\n\r\nBest regards,\r\nUncovery";
                                        $headers = 'From:minecraft@uncovery.me' . "\r\nReply-To:minecraft@uncovery.me\r\n" . 'X-Mailer: PHP/' . phpversion();
                                        mail('*****@*****.**', $subject, $content, $headers);
                                        foreach ($D as $row) {
                                            mail($row['user_email'], '[Uncovery Minecraft] ' . $subject, $content, $headers);
                                            umc_mail_send_backend($row['UUID'], 'ab3bc877-4434-45a9-93bd-bab6df41eabf', $content, $subject, 'send');
                                            // send from uncovery's UUID
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    // propose new person
    if ($user_lvl_id > 3) {
        $out .= "<form action=\"\" method=\"post\">\n" . "<span>Propose a person to be upgraded: <input type=\"text\" name=\"proposal\"> " . "<input type=\"submit\" name=\"proposebutton\" value=\"Propose user!\">" . "</span></form>";
    } else {
        $out .= "(Since your level is too low, you cannot propose users yet.)";
    }
    // close old proposals
    $upd_sql = "UPDATE minecraft_srvr.proposals SET `status`='failed' WHERE status = 'voting' AND date < NOW() - INTERVAL 2 month";
    umc_mysql_query($upd_sql, true);
    // list proposed people
    $sql = "SELECT UUID.username, status, pr_id, date, proposals.uuid FROM minecraft_srvr.proposals\r\n        LEFT JOIN minecraft_srvr.UUID ON proposals.uuid=UUID.UUID\r\n        WHERE status IN ('voting','closed') ORDER BY `date` ASC;";
    $D = umc_mysql_fetch_all($sql);
    $header = '';
    if ($username == 'uncovery') {
        $header = '<th>Score</th>';
    }
    $out .= "<br><form action=\"\" method=\"post\">\n<input type=\"hidden\" name=\"uuid\" value=\"{$uuid}\">\n<input type=\"hidden\" name=\"voting\" value=\"true\">\n<table>\n" . "<tr><th>Proposal</th><th>Date</th><th>Current Level</th><th>Your Vote</th><th>Vote date</th>{$header}</tr>\n";
    $proposals = 0;
    $upgraded_users = array();
    foreach ($D as $row) {
        $prop_lvl = umc_get_userlevel($row['username']);
        $prop_status = $row['status'];
        $prop_lvl_id = $vote_ranks[$prop_lvl]['lvl'];
        $proposed = $row['uuid'];
        $proposed_name = $row['username'];
        // check if user is allowed to vote for this person
        if ($user_lvl_id <= $prop_lvl_id) {
            continue;
        }
        $proposals++;
        $sel_support = $sel_veto = '';
        $sel_none = " selected=\"selected\"";
        $vote_date = "n/a";
        $pr_id = $row['pr_id'];
        // check if vote has been cast right now
        if (isset($_POST['voting']) && $_POST['uuid'] == $uuid) {
            if ($prop_status == 'closed' && $username == 'uncovery' && isset($_POST['CL_' . $pr_id]) && $_POST['CL_' . $pr_id] != 'closed') {
                $new_vote = filter_input(INPUT_POST, 'CL_' . $pr_id, FILTER_SANITIZE_STRING);
                // var_dump($_POST);
                $sql = "UPDATE minecraft_srvr.`proposals` SET `status` = '{$new_vote}' WHERE `proposals`.`pr_id`={$pr_id} LIMIT 1;";
                umc_mysql_query($sql);
                // echo $sql;
                if ($new_vote == 'success') {
                    $cmd = "pex promote {$proposed}";
                    umc_exec_command($cmd, 'asConsole', false);
                    umc_exec_command($cmd, 'asConsole', false);
                    umc_exec_command($cmd, 'asConsole', false);
                    $upgraded_users[$proposed_name] = $prop_lvl;
                    umc_log('voting', "promotion", "{$proposed_name} ({$proposed}) was promoted from {$prop_lvl} through votes");
                }
                continue;
            } else {
                if ($prop_status != 'closed') {
                    $new_vote = filter_input(INPUT_POST, 'PR_' . $pr_id, FILTER_SANITIZE_STRING);
                    $sel_support = $sel_veto = $sel_none = '';
                    // find existing votes
                    $sql = "SELECT * FROM minecraft_srvr.`proposals_votes` WHERE pr_id={$pr_id} and voter_uuid='{$uuid}';";
                    $C = umc_mysql_fetch_all($sql);
                    if (count($C) > 0) {
                        $row_check = $C[0];
                        $vote_id = $row_check['vote_id'];
                        if ($new_vote == 0) {
                            $sql = "DELETE FROM minecraft_srvr.`proposals_votes` WHERE pr_id={$pr_id} and voter_uuid='{$uuid}';";
                            umc_mysql_query($sql, true);
                        } else {
                            if ($row_check['vote'] != $new_vote) {
                                $sql = "REPLACE INTO minecraft_srvr.`proposals_votes` (`vote_id`, `pr_id`, `voter_uuid`, `date`, `vote`)\r\n\t\t\t    VALUES ({$vote_id}, {$pr_id}, '{$uuid}', NOW(), {$new_vote});";
                                umc_mysql_query($sql, true);
                            }
                        }
                    } else {
                        if ($new_vote != 0) {
                            $sql = "INSERT INTO minecraft_srvr.`proposals_votes` (`pr_id`, `voter_uuid`, `date`, `vote`)\r\n                        VALUES ({$pr_id}, '{$uuid}', NOW(), {$new_vote});";
                            umc_mysql_query($sql, true);
                        }
                    }
                } else {
                    if ($prop_status == 'closed') {
                        // a user tried to vote on a closed vote... what to do?
                    }
                }
            }
        }
        // load existing votes
        $total_score = 0;
        $sql = "SELECT date, voter_uuid, UUID.username, vote, date FROM minecraft_srvr.proposals_votes\r\n                LEFT JOIN minecraft_srvr.UUID ON voter_uuid=UUID.UUID\r\n                WHERE pr_id={$pr_id} AND vote <> 0 ORDER BY date DESC;";
        $R = umc_mysql_fetch_all($sql);
        $email_close = "{$UMC_DOMAIN}/vote-for-users/\n";
        foreach ($R as $row_calc) {
            $vote_date = $row_calc['date'];
            $voter_lvl = umc_get_uuid_level($row_calc['voter_uuid']);
            $voter_weight = $vote_ranks[$voter_lvl]['vote'];
            $voter_score = $voter_weight * $row_calc['vote'];
            $total_score = $total_score + $voter_score;
            if ($username == 'uncovery') {
                $out .= "<tr><td>Vote:</td><td>{$row_calc['username']}</td><td>{$voter_lvl}</td><td>{$row_calc['vote']}</td><td>{$row_calc['date']}</td><td>{$voter_score}</td></tr>\n";
                // prepare email to send if this will be closed
            }
            $email_close .= "Vote: {$row_calc['username']} ({$voter_lvl}) on {$row_calc['date']} gave points: {$voter_score}\n";
        }
        // close votes that have enough points
        $lvl_code = $vote_ranks[$prop_lvl]['code'];
        $min_req = $lvl_min_req[$lvl_code];
        if (abs($total_score) >= $min_req && $prop_status == 'voting') {
            // close vote
            $sql = "UPDATE minecraft_srvr.`proposals` SET `status` = 'closed' WHERE `proposals`.`pr_id`={$pr_id} LIMIT 1 ";
            umc_mysql_query($sql, true);
            // send email with status report
            $email_text = $email_close . "Total Score: {$total_score}\n\rRequired: " . abs($lvl_min_req[$lvl_code]);
            $headers = 'From:minecraft@uncovery.me' . "\r\nReply-To:minecraft@uncovery.me\r\n" . 'X-Mailer: PHP/' . phpversion();
            mail('*****@*****.**', "Voting closed for " . $row['username'], $email_text, $headers);
            $prop_status = 'closed';
        } else {
            if ($prop_status == 'closed' && $total_score < abs($lvl_min_req[$lvl_code])) {
                //$sql = "UPDATE minecraft_srvr.`proposals` SET `status` = 'voting' WHERE `proposals`.`pr_id`=$pr_id LIMIT 1 ";
                //mysql_query($sql);
            }
        }
        // show total score
        if ($username == 'uncovery') {
            $header = "<td><strong>{$total_score}</strong> (of {$min_req})</td>";
        }
        // load your own score
        $sql = "SELECT * FROM minecraft_srvr.proposals_votes WHERE voter_uuid = '{$uuid}' AND pr_id={$pr_id}";
        $D = umc_mysql_fetch_all($sql);
        $vote_date = "n/a";
        if (count($D) > 0) {
            $row_votes = $D[0];
            $vote_id = $row_votes['vote_id'];
            $your_vote = $row_votes['vote'];
            $vote_date = $row_votes['date'];
            // check if an alternative vote has been cast right now
            if ($your_vote == 1) {
                $sel_support = " selected=\"selected\"";
            } else {
                if ($your_vote == -1) {
                    $sel_veto = " selected=\"selected\"";
                }
            }
        }
        // show voting buttons
        $vote_close = '';
        $min_req = $lvl_min_req[$lvl_code];
        if ($prop_status == 'closed') {
            $vote = "Voting closed!<input type=\"hidden\" name=\"PR_{$pr_id}\" value=\"done\">";
            if ($username == 'uncovery') {
                $vote_date = "<select name=\"CL_{$pr_id}\"><option value=\"closed\">Voting closed</option><option value=\"success\">Upgrade</option><option value=\"failed\">Fail</option></select>";
            }
        } else {
            $vote = "<select name=\"PR_{$pr_id}\"><option value=\"0\" {$sel_none}>Abstain</option><option value=\"1\"{$sel_support}>Supported</option><option value=\"-1\"{$sel_veto}>Vetoed</option></select>";
        }
        $vote_lvl = umc_get_userlevel($row['username']);
        $out .= "<tr><td><strong><a href=\"{$UMC_DOMAIN}/users-2/?u={$row['username']}\">{$row['username']}</a></strong></td><td>{$row['date']}</td><td>{$prop_lvl}</td><td>{$vote}</td><td>{$vote_date}</td>{$header}</tr>\n";
    }
    if ($proposals == 0) {
        $out .= "<tr><td colspan=6>There are no proposals that you can vote for at the moment!</td><tr>\n";
    }
    $out .= "</table>\n<input type=\"submit\" name=\"votebutton\" value=\"Submit votes!\">\n</form><br>\n";
    // process successful votes, create post to blog
    if (count($upgraded_users) > 0) {
        $text = "Please see the latest upgrades from the voting system:<ul>";
        $userlist_arr = array();
        foreach ($upgraded_users as $upgraded_user => $userlvl) {
            $nextrank = $vote_ranks[$userlvl]['next'];
            $text .= "<li>{$upgraded_user} (from {$userlvl} to {$nextrank})</li>";
            $userlist_arr[] = $upgraded_user;
        }
        $userlist = implode(", ", $userlist_arr);
        $text .= "</ul>Congratz and thanks to all voters!";
        $post = array('comment_status' => 'open', 'ping_status' => 'closed', 'post_author' => 1, 'post_content' => $text, 'post_status' => 'publish', 'post_title' => "Today's upgrades: {$userlist}", 'post_type' => 'post');
        wp_insert_post($post);
    }
    return $out;
}
/**
 * Settler  test
 *
 * @global type $UMC_USER
 * @global type $UMC_SETTING
 * @global type $UMC_DOMAIN
 * @return string
 */
function umc_settler_new()
{
    global $UMC_USER, $UMC_SETTING, $UMC_DOMAIN;
    $out = '';
    if (!$UMC_USER) {
        return "You have to be <a href=\"{$UMC_DOMAIN}/wp-login.php\">logged in</a> to use this!";
    }
    $steps = array(1 => array('begging' => true, 'griefing' => true, 'pixel_art' => true, 'minimaps' => false, 'xray_and_cheats' => true, 'not_reading_the_website' => true, 'swearing' => true, 'walls_around_your_lot' => true, 'shaders' => false));
    $player = strtolower($UMC_USER['username']);
    $uuid = $UMC_USER['uuid'];
    $userlevel = $UMC_USER['userlevel'];
    $email = $UMC_USER['email'];
    if ($userlevel != 'Guest') {
        $out .= "You are not a Guest and can use the <a href=\"http://uncovery.me/server-access/lot-manager/\">Lot manager</a> to get a lot!";
    }
    if (umc_user_is_banned($uuid)) {
        return "Sorry, you are banned from the server!";
    }
    $icon_url = umc_user_get_icon_url($player);
    $user_icon = "<img src=\"{$icon_url}\">";
    // get user location
    $s_post = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
    $step = 0;
    if (isset($s_post['step'])) {
        $step = $s_post['step'];
    }
    $loc = umc_read_markers_file('array');
    $lot = false;
    if (isset($s_post['lot'])) {
        $lot = $s_post['lot'];
    }
    $world = false;
    if (isset($s_post['world'])) {
        $world = $s_post['world'];
    }
    if (isset($loc[$player])) {
        $player_world = $loc[$player]['world'];
        $player_lot = umc_lot_get_from_coords($loc[$player]['x'], $loc[$player]['z'], $loc[$player]['world']);
        $x = $loc[$player]['x'];
        $z = $loc[$player]['z'];
    } else {
        $player_lot = false;
        $player_world = false;
        $x = false;
        $z = false;
    }
    $error = '';
    // answer check
    switch ($step) {
        case 2:
            if (!isset($s_post['stepone'])) {
                $step = 1;
                umc_log('settler_test', 'step_1_fail', "{$player} did not answer any questions!");
                $error = "You need to answer the questions on the previous page!";
            } else {
                $problem = false;
                $answers = array();
                foreach ($steps[1] as $choice => $value) {
                    if ($value == true && !in_array($choice, $s_post['stepone'])) {
                        // Bad stuff
                        $problem = true;
                        $answers[] = $choice;
                    } else {
                        if ($value == false && in_array($choice, $s_post['stepone'])) {
                            // but is
                            $problem = true;
                            $answers[] = $choice;
                        }
                    }
                }
                if ($problem) {
                    umc_log('settler_test', 'step_1_fail', "{$player} failed step 1 with wrong answers " . implode("|", $answers));
                    $error = "<h1>Error</h1>One or more answers in the previous page were wrong.<br>Please go back and check before proceeding.<br>" . "If you need help, please read the <a href=\"{$UMC_DOMAIN}/about-this-server/rules/\">rest of the rules</a>";
                    $step = 1;
                }
            }
            break;
        case 3:
            if (!isset($s_post['world'])) {
                $step = 2;
                umc_log('settler_test', 'step_2_fail', "{$player} failed step 2");
                $error = 'You need to choose a playing mode to continue!';
            }
            break;
        case 4:
            if (!isset($s_post['lot'])) {
                $step = 3;
                umc_log('settler_test', 'step_3_fail', "{$player} failed step 3");
                $error = 'You need to choose lot to continue!';
            }
            break;
        case 5:
            if (!$player_world) {
                $step = 4;
                umc_log('settler_test', 'step_4_fail', "{$player} failed step 4 (not in game)");
                $error = 'You need to be in the game to continue!';
                // var_dump($loc);
            } else {
                if ($player_world != 'city' || $x > 953 || $x < 938 || $z < -814 || $z > -793) {
                    $step = 4;
                    umc_log('settler_test', 'step_4_fail', "{$player} failed step 4 (not in spawn house)");
                    $error = 'You need to type /warp spawn and then continue!';
                }
            }
            break;
        case 6:
            if ($player_world != $s_post['world']) {
                $step = 5;
                umc_log('settler_test', 'step_5_fail', "{$player} failed step 5");
                $error = "You need to go through the {$s_post['world']} portal! Type <strong>/warp spawn</strong> and try again!";
            }
            break;
        case 8:
            if (strtolower($player_lot) != strtolower($s_post['check_lot'])) {
                $step = 7;
                umc_log('settler_test', 'step_7_fail', "{$player} failed step 7 by entering " . $s_post['check_lot'] . "instead of {$player_lot}");
                $error = 'You need to enter the lot you see on-screen into the form to continue!';
            }
            break;
        case 9:
            if (!$player_lot) {
                $step = 8;
                umc_log('settler_test', 'step_8_fail', "{$player} failed step 8");
                $error = "We could not find you on the map. Please make sure you are on the server!";
            } else {
                if ($player_lot != $s_post['lot']) {
                    $step = 8;
                    umc_log('settler_test', 'step_8_fail', "{$player} failed step 8");
                    $error = "You need to get lot {$s_post['lot']} before you can continue. Please either walk there or use /jump {$s_post['lot']}. You are now in lot {$player_lot}!";
                }
            }
            break;
    }
    // questions
    $out .= "<strong>{$error}</strong><br>";
    switch ($step) {
        case 0:
            umc_log('settler_test', 'start', "{$player} started the settler test");
            $out .= "<form action=\"{$UMC_DOMAIN}/server-access/buildingrights/\" method=\"post\">\n" . "<h1>Step 1: Welcome!</h1>\n" . "<h2>Once you finish this test, you will be settler!</h2>\n" . "<h2>Before Applying</h2>\n" . "<ul>\n" . "    <li>You must have some experience playing Minecraft.</li>\n" . "    <li>Read the <a href=\"{$UMC_DOMAIN}/faq/\">FAQ</a></li>\n" . "    <li>Read the <a href=\"{$UMC_DOMAIN}/rules/\">Rules</a></li>\n" . "    <li>Read the <a href=\"{$UMC_DOMAIN}/user-levels/\">User Levels and Commands</a> page.</li>\n" . "</ul>\n" . "This process will guide you through the process of getting building rights on the server and at the same time give you a lot and make sure you get there. " . "You will need to login to the server with your minecraft client during the process and keep this website open.<br>" . "<input type=\"hidden\" name=\"step\" value=\"1\">\n" . "<input type=\"submit\" name=\"Next\" value=\"Next\">\n";
            break;
        case 1:
            $warning = '';
            $failcount = umc_settler_get_fails($player);
            if ($failcount > 10) {
                $warning = "<div style=\"color:red;font-weight:bold;font-size:120%;\">You have failed the test more than 10 times. If you fail too often, you will be banned from the server!</div>";
            } else {
                if ($failcount > 20) {
                    umc_user_ban($player, "Settler test failed");
                    return $warning = "<div style=\"color:red;font-weight:bold;font-size:120%;\">You have failed the test too often. You are now banned from the server!</div>";
                }
            }
            umc_log('settler_test', 'step_1', "{$player} is at step 1");
            $out .= "<form action=\"{$UMC_DOMAIN}/server-access/buildingrights/\" method=\"post\">\n" . "<h1>Step 2: Rules & regulations</h1>\n" . $warning . "Here are some basic rules you should know:" . "<ul>\n<li><strong>Do not beg for anything</strong> - Including upgrades, handouts or help with this process.</li>\n" . "<li><strong>No pixel-art</strong>. This is not 'paint by numbers'. We build stuff.</li>\n" . "<li><strong>Be considerate of others</strong>. No griefing, no stealing, no killing. We log everything, we will find out.</li>\n" . "<li><strong>Don't cheat!</strong> No Xray, no mods, no bug abuse.</li>\n" . "<li><strong>Learn yourself!</strong> Look on the <a href=\"{$UMC_DOMAIN}/about-this-server/\">website</a> for answers first, then ask other users.</li>\n" . "<li><strong>We ban forever - no appeals!</strong> You better read the <a href=\"{$UMC_DOMAIN}/about-this-server/rules/\">rest of the rules</a>.</li>\n" . "</ul>\n" . "<strong>Pick the items that are not allowed (and will therefore get you banned) (Note: Asking others about the answers will get you banned, too!): </strong><br>\n" . "<input type=\"hidden\" name=\"step\" value=\"2\">\n";
            foreach ($steps[1] as $image => $check) {
                $image_text = umc_pretty_name($image);
                $out .= "<span style=\"float:left; text-align:center;\"><img height=\"180\" src=\"{$UMC_DOMAIN}/websend/{$image}.png\"><br>" . "<input type=\"checkbox\" name=\"stepone[]\" value=\"{$image}\">{$image_text}</span>\n";
            }
            $out .= '<br style="clear:both;">' . "<input type=\"submit\" name=\"Next\" value=\"Next\">\n";
            break;
        case 2:
            umc_log('settler_test', 'step_2', "{$player} is at step 2");
            $out .= "<form action=\"{$UMC_DOMAIN}/server-access/buildingrights/\" method=\"post\">\n" . '<h1>Step 3: Creative or Survival?</h1>' . 'You can either build in a flat, creative world or a wild, survival world!<br>Choose one:<br>' . "<span style=\"float:left; text-align:center;\"><img width=\"400\" src=\"{$UMC_DOMAIN}/websend/empire.png\"><br><input type=\"radio\" name=\"world\" value=\"empire\">Survival mode in the Empire world</span>" . "<span style=\"float:left; text-align:center;\"><img width=\"400\" src=\"{$UMC_DOMAIN}/websend/flatlands.png\"><br><input type=\"radio\" name=\"world\" value=\"flatlands\">Creative mode in the Flatlands world</span><br style=\"clear:both;\">" . "<input type=\"hidden\" name=\"step\" value=\"3\">\n" . "<input type=\"submit\" name=\"Next\" value=\"Next\">\n";
            break;
        case 3:
            umc_log('settler_test', 'step_3', "{$player} is at step 3");
            $spawn_lot = $UMC_SETTING['world_data'][$world]['spawn'];
            $tile = umc_user_get_lot_tile(strtolower($spawn_lot));
            $out .= "<form action=\"{$UMC_DOMAIN}/admin/index.php?function=create_map&world={$world}&freeonly=true\" method=\"post\">\n" . "<h1>Step 4: Find a lot!</h1>\n" . "<img style=\"float:right;\" width=\"300\" src=\"{$UMC_DOMAIN}/websend/{$world}.png\">Great! You chose to build in the <strong>{$world}</strong> world!<br>" . "You are now ready to pick a lot!<br>" . "If you made a mistake and want to play a different mode, please go back now and chose another mode. There will be no going back later.<br><br>" . "<strong>Now you need to find a lot that you like.</strong><br>" . "When you click 'Next', a map of the {$world} world will open.<br>" . "Click on the \"Find Spawn\" button in the top-left corner. It looks like this:<br>" . "<img src=\"/websend/find_spawn.png\"><br>" . "You will now see a flashing lot, which is the entrance to the {$world} world.<br>" . "It's convenient to find a lot close to it. <br>" . "The spawn lot looks like this:<br>{$tile}" . "<input type=\"hidden\" name=\"settler_test\" value=\"settler_test\">\n" . "<br><br><input type=\"submit\" name=\"Next\" value=\"Next\">\n";
            break;
        case 4:
            umc_log('settler_test', 'step_4', "{$player} is at step 4");
            $tile = umc_user_get_lot_tile(strtolower($lot));
            $out .= "<form action=\"{$UMC_DOMAIN}/server-access/buildingrights/\" method=\"post\">\n" . '<h1>Step 5: You chose a lot!</h1>' . "<span style=\"float:left;\">{$tile}</span>The lot you have chosen is <strong>{$lot} in the {$world}</strong> world. You can see a satellite image of it on the left.<br>You should now go there, to make sure it's what you want!<br>";
            if ($player_world) {
                $out .= "<br>To go there, you need to go to the portal house. From there you can get into the {$world} world.<br>" . "Please type <strong>/warp spawn</strong> in game to get there, it should look like this inside:<br><img src=\"/websend/portals.png\">" . "Once you see this, please come back here and press " . "<input type=\"submit\" name=\"Next\" value=\"Next\">\n" . "<input type=\"hidden\" name=\"lot\" value=\"{$lot}\">\n" . "<input type=\"hidden\" name=\"world\" value=\"{$world}\">\n" . "<input type=\"hidden\" name=\"step\" value=\"5\">\n";
            } else {
                $out .= "Please <strong>login to the server</strong> now with your minecraft client at <strong>uncovery.me</strong> and then press " . "<input type=\"hidden\" name=\"world\" value=\"{$world}\">\n" . "<input type=\"submit\" name=\"action\" value=\"Continue\">\n" . "<input type=\"hidden\" name=\"lot\" value=\"{$lot}\">\n" . "<input type=\"hidden\" name=\"step\" value=\"5\">\n";
            }
            break;
        case 5:
            umc_log('settler_test', 'step_5', "{$player} is at step 5");
            $out .= "<form action=\"{$UMC_DOMAIN}/server-access/buildingrights/\" method=\"post\">\n" . "<h1>Step 6: Get to the {$world} world</h1>";
            // check if the player is actually in the portal house
            // player is not in portal house
            if ($player_world != 'city' || $x > 953 || $x < 938 || $z < -814 || $z > -793) {
                $out .= "You need to be in the portal house to continue. Please type <strong>/warp spawn</strong> again to get there. " . "It should look like this inside:<br><img src=\"/websend/portals.png\"> Once you see this, press\n" . "<input type=\"submit\" name=\"Next\" value=\"Next\">\n" . "<input type=\"hidden\" name=\"lot\" value=\"{$lot}\">\n" . "<input type=\"hidden\" name=\"world\" value=\"{$world}\">\n" . "<input type=\"hidden\" name=\"step\" value=\"5\">\n";
            } else {
                $out .= "Since you chose a lot in the {$world} world, you need to go through the {$world} portal. " . "It looks like this: Notice the name of the world is written on the sign." . "<img src=\"/websend/{$world}_portal.png\">" . "Please step through and press " . "<input type=\"submit\" name=\"Next\" value=\"Next\">\n" . "<input type=\"hidden\" name=\"lot\" value=\"{$lot}\">\n" . "<input type=\"hidden\" name=\"world\" value=\"{$world}\">\n" . "<input type=\"hidden\" name=\"step\" value=\"6\">\n";
            }
            break;
        case 6:
            umc_log('settler_test', 'step_6', "{$player} is at step 6");
            $spawn_lot = strtoupper($UMC_SETTING['world_data'][$world]['spawn']);
            $lower_lot = strtolower($lot);
            $lot_sql = "SELECT region_cuboid.region_id AS lot, sqrt(pow(max_x,2)+pow(max_z,2)) AS distance, max_x, max_z\r\n                FROM minecraft_worldguard.world\r\n                LEFT JOIN minecraft_worldguard.region_cuboid ON world.id=region_cuboid.world_id\r\n                WHERE region_cuboid.region_id='{$lower_lot}';";
            $D = umc_mysql_fetch_all($lot_sql);
            $lot_data = $D[0];
            // north/south difference
            if ($lot_data['max_x'] < 0) {
                $direction1 = "north";
            } else {
                if ($lot_data['max_x'] >= 0) {
                    $direction1 = "south";
                }
            }
            // north/south difference
            if ($lot_data['max_z'] < 0) {
                $direction2 = "west";
            } else {
                if ($lot_data['max_z'] >= 0) {
                    $direction2 = "east";
                }
            }
            $out .= "<form action=\"{$UMC_DOMAIN}/admin/index.php?function=create_map&world={$world}&freeonly=true\" method=\"post\">\n" . "<h1>Step 7: Getting to lot {$lot} in the {$world} world</h1>" . "Getting to your world is easy! You are now at the center of the {$world} world." . "Your lot is <strong>{$direction1}/{$direction2}</strong> from spawn! <br>" . "You can find out which direction you are looking with the <strong>/compass</strong> command.<br>" . "As a Guest level player, you cannot be killed by mobs until you finished this here.<br>" . "So you have to leave the spawn lot either through the {$direction1} or the {$direction2} exit.<br>" . "To know where you are, you can follow your icon {$user_icon} on the map while you get around.<br>" . "Please click NEXT to open the map, there you find your icon click the button next to it!<br><br>" . "<input type=\"submit\" name=\"next\" value=\"Next\">\n" . "<input type=\"hidden\" name=\"track_player\" value=\"{$player}\">\n" . "<input type=\"hidden\" name=\"world\" value=\"{$world}\">\n" . "<input type=\"hidden\" name=\"lot\" value=\"{$lot}\">\n";
            $x = $loc[$player]['x'];
            $z = $loc[$player]['z'];
            break;
        case 7:
            umc_log('settler_test', 'step_7', "{$player} is at step 7");
            // whereami
            $out .= "<h1>Step 8: Find out where you are in-game</h1>" . "<form action=\"{$UMC_DOMAIN}/server-access/buildingrights/\" method=\"post\">\n" . "Now that you know how to find yourself on the map, you need to find out where you are when in-game.<br>" . "The command to find your location in-game is called <strong>/whereami</strong>.<br>" . "Please go into the game and type <strong>/whereami</strong><br>" . "You will see something like this:<br>" . "<img src=\"/websend/whereami.png\"><br>" . "In this example, you can see the Lot (in the first line) is <img src=\"/websend/whereami_detail.png\"> So you would enter 'emp_z7'.<br>" . "Please go now into the game, type <strong>/whereami</strong>, and enter the information here:<br>" . "I am now in lot <input type=\"text\" name=\"check_lot\" value=\"\" size=\"7\"> and then press " . "<input type=\"submit\" name=\"next\" value=\"Next\">\n" . "<input type=\"hidden\" name=\"step\" value=\"8\">\n" . "<input type=\"hidden\" name=\"world\" value=\"{$world}\">\n" . "<input type=\"hidden\" name=\"lot\" value=\"{$lot}\">\n";
            // enter which lot you are in right now
            break;
        case 8:
            // walk to your lot
            umc_log('settler_test', 'step_8', "{$player} is at step 8");
            $lower_lot = strtolower($lot);
            $out .= "<form action=\"{$UMC_DOMAIN}/admin/index.php\" method=\"post\">\n" . "<h1>Step 9: Walk to your lot {$lot}!</h1>" . "Now you have everything you need to get to your lot!<br>You should follow your steps on the 2D map.<br>" . "You can either walk there, or use the command <pre>/lot warp {$lot}</pre> to get there. Please note that this command is only available while you are Guest.<br>" . "Press 'Next' to open the 2D map and follow your icon to lot {$lot}!<br>" . "<input type=\"submit\" name=\"next\" value=\"Next\">\n" . "<input type=\"hidden\" name=\"guide_lot\" value=\"{$player}\">\n" . "<input type=\"hidden\" name=\"world\" value=\"{$world}\">\n" . "<input type=\"hidden\" name=\"freeonly\" value=\"true\">\n" . "<input type=\"hidden\" name=\"function\" value=\"create_map\">\n" . "<input type=\"hidden\" name=\"step\" value=\"9\">\n" . "<input type=\"hidden\" name=\"world\" value=\"{$world}\">\n" . "<input type=\"hidden\" name=\"lot\" value=\"{$lower_lot}\">\n";
            break;
        case 9:
            umc_log('settler_test', 'step_9', "{$player} is at step 9");
            // do you like it? claim it
            $out .= "<h1>Step 10: Do you like the lot {$s_post['lot']}?</h1>" . "<form action=\"{$UMC_DOMAIN}/server-access/buildingrights/\" method=\"post\">\n" . '<input type="radio" name="step" value="10" checked>Yes! I take it! I will type <strong>/homes buy ' . $world . '</strong> now so I can warp back here!<br>' . '<input type="radio" name="step" value="1">No,I would like to start over!<br>' . "<input type=\"hidden\" name=\"lot\" value=\"{$lot}\">\n" . "<input type=\"hidden\" name=\"world\" value=\"{$world}\">\n" . "<input type=\"submit\" name=\"next\" value=\"Finish!\">\n";
            break;
        case 10:
            umc_log('settler_test', 'step_10', "{$player} is at step 10");
            // final confirmation
            $out .= "<h1>Step 11: Congratulations!</h1>" . "You have been promoted to Settler!<br>";
            if ($userlevel == 'Guest') {
                $cmd = "pex promote {$UMC_USER['uuid']}";
                umc_exec_command($cmd);
                // update UUID database
                $sql = "UPDATE minecraft_srvr.UUID SET userlevel='Settler' WHERE UUID='{$UMC_USER['uuid']}';";
                umc_mysql_query($sql);
                umc_exec_command('pex reload');
                umc_exec_command("ch qm u Congrats {$player} for becoming Settler!");
                XMPP_ERROR_send_msg("{$userlevel} {$player} got promoted with command " . $cmd);
                umc_log('settler_test', 'promotion', "{$player} ({$UMC_USER['uuid']})was promoted to settler (new test)");
                $headers = "From: minecraft@uncovery.me\r\n" . "Reply-To: minecraft@uncovery.me\r\n" . 'X-Mailer: PHP/' . phpversion();
                $subject = "[Uncovery Minecraft] Settler applicaton";
                $mailtext = "The user: {$player} (email: {$email}) was promoted to Settler and got lot {$lot}.\n\n";
                $check = mail('*****@*****.**', $subject, $mailtext, $headers);
                if (!$check) {
                    XMPP_ERROR_trigger("The settler promotion email could not be sent!");
                }
                // check userlevel to make sure
                $new_level = umc_get_userlevel($player);
                if ($new_level != 'Settler') {
                    XMPP_ERROR_trigger("{$userlevel} {$player} did NOT got promoted with command " . $cmd . " he's still {$new_level}");
                }
            } else {
                $out .= "Thanks for taking this test! Since you are {$userlevel} already, we will not promote you to Settler.<br>";
            }
            // try to assign the lot
            $check = umc_lot_manager_check_before_assign($uuid, $lot);
            $out .= "Trying to assign this lot to you: <strong>{$check['text']}</strong><br>";
            if ($check['result'] == false) {
                XMPP_ERROR_send_msg("Settler Test lot assignment failed!");
                $out .= "There was an error giving the lot you reserved to you. You can get any other through your <a hreaf=\"{$UMC_DOMAIN}/server-access/lot-manager/\">lot manager</a>!<br>";
            } else {
                umc_lot_add_player($uuid, $lot, 1, $check['cost']);
                $out .= $check['text'];
            }
            break;
        default:
            $out .= "This option was not recognized, please reload the page!";
    }
    $out .= "</form>\n";
    return $out;
}
/**
 * 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;
    }
}
Example #20
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!");
    }
}
/**
 * move all items from the shop to deposit for a specific user
 * Normally only used when users are banned or inactive, on lot reset
 *
 * @param type $uuid
 */
function umc_shop_cleanout_olduser($uuid)
{
    XMPP_ERROR_trace(__FUNCTION__, func_get_args());
    // delete all requests
    $requests_sql = "DELETE FROM minecraft_iconomy.request WHERE uuid='{$uuid}';";
    umc_mysql_query($requests_sql, true);
    // move all items from stock to deposit
    $sql = "SELECT * FROM minecraft_iconomy.stock WHERE uuid='{$uuid}';";
    $rst = umc_mysql_query($sql);
    while ($row = umc_mysql_fetch_array($rst)) {
        umc_checkout_goods($row['id'], 'max', 'stock', true, true, $uuid);
    }
    umc_log('user_manager', 'shop-cleanout', "{$uuid} had his items moved from stock & request to deposit");
}
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_home_import()
{
    XMPP_ERROR_trace(__FUNCTION__, func_get_args());
    // global $UMC_USER;
    // we automatically import old homes for all players on login, but only once
    // include spyc to parse YAML https://github.com/mustangostang/spyc
    require_once '/home/includes/spyc/Spyc.php';
    $users = umc_get_active_members();
    foreach ($users as $uuid => $username) {
        $path = '/home/minecraft/server/bukkit/plugins/Essentials/userdata/' . $uuid . ".yml";
        $A = Spyc::YAMLLoad($path);
        $existing_count = umc_home_count(false, $uuid);
        if ($existing_count > 0) {
            continue;
        }
        if (!isset($A['homes'])) {
            continue;
        }
        $count = count($A['homes']);
        if ($count == 0) {
            continue;
        }
        $H = $A['homes'];
        // iterate homes and import them
        foreach ($H as $home_name => $h) {
            $name = umc_mysql_real_escape_string($home_name);
            // XMPP_ERROR_trigger($h);
            $sql = "INSERT INTO minecraft_srvr.`homes`(`name`, `uuid`, `world`, `x`, `y`, `z`, `yaw`) VALUES " . "({$name},'{$uuid}','{$h['world']}','{$h['x']}','{$h['y']}','{$h['z']}','{$h['yaw']}');";
            umc_mysql_query($sql, true);
        }
        umc_log('home', 'import', "{$uuid}/{$username} {$count} homes have been imported!");
    }
}
Example #24
0
/**
 * tries to find a location far out that was not used as a hunger game before
 * this will also create the warp point in essentials
 *
 * @return array('x' => $center_x, 'z' => $center_z)
 */
function umc_hunger_find_random_location()
{
    // 30 Mio is the MC hard limit
    $min_val = 1000;
    $max_val = 30000000 - 2000;
    //we take the max and some margin
    // find a center
    $center_x = rand($min_val, $max_val);
    $center_z = rand($min_val, $max_val);
    // which quarter of the map?
    $dir_x = rand(0, 1);
    if ($dir_x == 0) {
        $center_x = $center_x * -1;
    }
    $dir_z = rand(0, 1);
    if ($dir_z == 0) {
        $center_z = $center_z * -1;
    }
    // check if a game existed on that location
    $sql = "SELECT id FROM minecraft_iconomy.hunger_games\r\n        WHERE x > ({$center_x} - 500)\r\n\t    AND x < ({$center_x} + 500)\r\n\t    AND z < ({$center_z} + 500)\r\n\t    AND z > ({$center_z} - 500);";
    $data = umc_mysql_fetch_all($sql);
    // too close, try again
    if (count($data) > 0) {
        umc_log('hunger', 'found_location_fail', "Found alrady existing location X: {$center_x} Z: {$center_z} - retrying");
        XMPP_ERROR_trigger("hunger rejected location X: {$center_x} Z: {$center_z}, trying again");
        return umc_hunger_find_random_location();
    } else {
        XMPP_ERROR_send_msg("hunger Found location X: {$center_x} Z: {$center_z}");
        // update warp point
        $text = "yaw: 0.0\nname: hunger\npitch: 0.0\nz: {$center_z}\ny: 250\nworld: hunger\nx: {$center_x}";
        $filename = '/home/minecraft/server/bukkit/plugins/Essentials/warps/hunger.yml';
        file_put_contents($filename, $text);
        // reload essentials
        umc_ws_cmd('ess reload', 'asConsole');
        return array('x' => $center_x, 'z' => $center_z);
    }
}
function umc_lottery()
{
    XMPP_ERROR_trace(__FUNCTION__, func_get_args());
    global $UMC_USER, $lottery, $ENCH_ITEMS;
    $user_input = $UMC_USER['args'][2];
    // check if there is a valid user on the server before applying the vote.
    $user = umc_check_user($user_input);
    if (!$user) {
        umc_log("lottery", "voting", "user {$user} does not exist");
        return false;
    }
    // get the voting players uuid
    $uuid = umc_user2uuid($user);
    // give reinforcing feedback - set subtitle (not displayed)
    $subtitle = 'title ' . $user . ' subtitle {text:"Thanks for your vote!",color:gold}';
    umc_ws_cmd($subtitle, 'asConsole');
    // display the feedback - displays subtitle AND title
    $title = 'title ' . $user . ' title {text:"+100 Uncs",color:gold}';
    umc_ws_cmd($title, 'asConsole');
    // allow uncovery to test chance rolls for debugging purposes
    $chance = false;
    if ($user == 'uncovery' && isset($UMC_USER['args'][5])) {
        $chance = $UMC_USER['args'][5];
    }
    // get the roll array based on chance
    $roll = umc_lottery_roll_dice($chance);
    // umc_echo(umc_ws_vardump($roll));
    // define the rewards and item more legibly
    $item = $roll['item'];
    $luck = $roll['luck'];
    $prize = $lottery[$item];
    //echo "type = {$prize['type']}<br>;";
    //echo "complete chance: $chance<br>;";
    //var_dump($prize);
    // get the metadata if required for the item
    if (isset($prize['detail'])) {
        $detail = $prize['detail'];
    }
    $type = $prize['type'];
    // always give 100 uncs irrespective of roll.
    umc_money(false, $user, 100);
    // instantiate block variables
    $given_block_data = 0;
    $given_block_type = 0;
    //var_dump($prize);
    // based on item type, give reward to the player
    switch ($type) {
        case 'item':
            umc_deposit_give_item($uuid, $detail['type'], $detail['data'], $detail['ench'], 1, 'lottery');
            $item_txt = $prize['txt'];
            break;
        case 'additional_home':
            $newname = 'lottery' . "_" . umc_random_code_gen(4);
            umc_home_add($uuid, $newname, true);
            $item_txt = "an addtional home!!";
            break;
        case 'random_unc':
            $luck2 = mt_rand(1, 500);
            umc_money(false, $user, $luck2);
            $item_txt = "{$luck2} Uncs";
            break;
        case 'random_potion':
            $luck2 = mt_rand(0, 63);
            umc_deposit_give_item($uuid, 373, $luck2, '', 1, 'lottery');
            $item_txt = $prize['txt'];
            break;
        case 'random_ench':
            // pick which enchantment
            $rand_ench = array_rand($ENCH_ITEMS);
            $ench_arr = $ENCH_ITEMS[$rand_ench];
            //pick which item to enchant
            $rand_item = array_rand($ench_arr['items']);
            $rand_item_id = $ench_arr['items'][$rand_item];
            // pick level of enchantment
            $lvl_luck = mt_rand(1, $ench_arr['max']);
            //echo "$item $ench_txt $lvl_luck";
            $item_ench_arr = array($rand_ench => $lvl_luck);
            $item = umc_goods_get_text($rand_item_id, 0, $item_ench_arr);
            $item_name = $item['item_name'];
            $full = $item['full'];
            umc_deposit_give_item($uuid, $item_name, 0, $item_ench_arr, 1, 'lottery');
            $item_txt = "a " . $full;
            break;
        case 'random_pet':
            // same as blocks below but only 1 always
            umc_echo($type);
            $block = $prize['blocks'];
            $luck2 = mt_rand(0, count($prize['blocks']) - 1);
            $given_block = explode(":", $block[$luck2]);
            $given_block_type = $given_block[0];
            $given_block_data = $given_block[1];
            umc_deposit_give_item($uuid, $given_block_type, $given_block_data, '', 1, 'lottery');
            $item = umc_goods_get_text($given_block_type, $given_block_data);
            $item_txt = "a " . $item['full'];
            break;
        case 'random_common':
        case 'random_ore':
        case 'random_manuf':
            $block = $prize['blocks'];
            $luck2 = mt_rand(0, count($prize['blocks']) - 1);
            $luck3 = mt_rand(1, 64);
            $given_block = explode(":", $block[$luck2]);
            $given_block_type = $given_block[0];
            $given_block_data = $given_block[1];
            umc_deposit_give_item($uuid, $given_block_type, $given_block_data, '', $luck3, 'lottery');
            $item = umc_goods_get_text($given_block_type, $given_block_data);
            $item_txt = "{$luck3} " . $item['full'];
            break;
    }
    if ($user != 'uncovery') {
        // testing only
        $item_nocolor = umc_ws_color_remove($item_txt);
        umc_ws_cmd("ch qm N {$user} voted, rolled a {$luck} and got {$item_nocolor}!", 'asConsole');
        umc_log('votelottery', 'vote', "{$user} rolled {$luck} and got {$item_nocolor} ({$given_block_type}:{$given_block_data})");
        $userlevel = umc_get_userlevel($user);
        if (in_array($userlevel, array('Settler', 'Guest'))) {
            $msg = "You received {$item_txt} from the lottery! Use {green}/withdraw @lottery{white} to get it!";
            umc_msg_user($user, $msg);
        }
    } else {
        umc_echo("{$user} voted, rolled a {$luck} and got {$item_txt}!");
    }
    // add vote to the database
    $service_raw = strtolower($UMC_USER['args'][3]);
    // fix service
    $search = array('http://www.', 'https://www.', 'http://', 'https://');
    $service = umc_mysql_real_escape_string(str_replace($search, '', $service_raw));
    // sql log
    $sql_reward = umc_mysql_real_escape_string($type);
    $ip = umc_mysql_real_escape_string($UMC_USER['args'][4]);
    $sql = "INSERT INTO minecraft_log.votes_log (`username`, `datetime`, `website`, `ip_address`, `roll_value`, `reward`)\r\n        VALUES ('{$uuid}', NOW(), {$service}, {$ip}, {$luck}, {$sql_reward});";
    umc_mysql_query($sql, true);
}
/**
 * Moch chunks for lot resets
 *
 * @global array $UMC_PATH_MC
 * @param string $source_lot
 * @param string $source_world
 * @param string $dest_lot
 * @param string $dest_world
 * @param boolean $echo
 * @return boolean
 */
function umc_move_chunks($source_lot, $source_world, $dest_lot, $dest_world, $echo = false)
{
    XMPP_ERROR_trace(__FUNCTION__, func_get_args());
    global $UMC_PATH_MC;
    $exec_path = "{$UMC_PATH_MC}/server/chunk/copychunk";
    // get coordinates
    $sql = "SELECT * FROM minecraft_worldguard.region_cuboid WHERE region_id = '{$source_lot}' LIMIT 1;";
    $D = umc_mysql_fetch_all($sql);
    if (count($D) != 1) {
        XMPP_ERROR_trigger("Tried to reset {$source_lot} from {$source_world} to {$dest_lot} on {$dest_world} but {$source_lot} could not be found");
        return false;
    }
    $row = $D[0];
    $min_x = floor($row['min_x'] / 16);
    $max_x = floor($row['max_x'] / 16);
    $min_z = floor($row['min_z'] / 16);
    $max_z = floor($row['max_z'] / 16);
    if ($source_lot != $dest_lot) {
        $sql_dest = "SELECT * FROM minecraft_worldguard.region_cuboid WHERE region_id = '{$dest_lot}' LIMIT 1;";
        $D_dest = umc_mysql_fetch_all($sql_dest);
        if (count($D_dest) != 1) {
            XMPP_ERROR_trigger("Tried to reset {$source_lot} from {$source_world} to {$dest_lot} on {$dest_world} but {$dest_lot} could not be found");
            return false;
        }
        $row_dest = $D_dest[0];
        $min_x_dest = floor($row_dest['min_x'] / 16);
        $max_x_dest = floor($row_dest['max_x'] / 16);
        $min_z_dest = floor($row_dest['min_z'] / 16);
        $max_z_dest = floor($row_dest['max_z'] / 16);
    }
    // check if craftbukkit is running
    $output = array();
    $exec_cmd = 'ps ax | grep -v grep | grep -v -i SCREEN | grep spigot.jar';
    if (!$echo) {
        exec($exec_cmd, $output);
        if (count($output) > 0) {
            XMPP_ERROR_trigger("Tried to move chunks while Minecraft server was running: {$source_lot}, {$source_world}, {$dest_lot}, {$dest_world}");
            return false;
        }
    }
    if ($source_lot == $dest_lot) {
        $exec_cmd = "{$exec_path} {$source_world} {$dest_world} {$min_x} {$min_z} {$max_x} {$max_z}";
    } else {
        $exec_cmd = "{$exec_path} {$source_world} {$dest_world} {$min_x} {$min_z} {$max_x} {$max_z} {$min_x_dest} {$min_z_dest} {$max_x_dest} {$max_z_dest}";
    }
    // $exec_cmd . "<br>";
    if ($echo) {
        echo $exec_cmd . "\n";
    } else {
        exec($exec_cmd, $output);
    }
    umc_log('lot_manager', 'move chunks', "Moved lot from {$source_lot} to {$dest_lot} with command {$exec_cmd}");
    return true;
}
Example #27
0
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");
}