diff --git a/AreaShop/config.yml b/AreaShop/config.yml index cd9b70a..94f1f98 100644 --- a/AreaShop/config.yml +++ b/AreaShop/config.yml @@ -16,31 +16,165 @@ moneyCharacterAfter: '' debug: false ## The .yml language file that should be used, provided by this plugin: EN, NL language: EN -## Maximum total amount of rents and buys together -maximumTotal: 1 ## Enable Schematic saving and restoring in general enableSchematics: true ## Maximum number of blocks to save to or restore from a .schemetic maximumBlocks: 1000000 ## Enable sending stats to http://mcstats.org/ (Metrics plugin) sendStats: true +## Use colors when sending messages to console and log files +useColorsInConsole: false +## Post error messages in the console when a command run from the config fails (from the 'runCommands' section for example) +postCommandErrors: true ## Version of the config, do not change! -version: 1.3.0 +version: 2.0.0 ## The y location within the region to start searching for safe teleport spots (x and z will be in the middle of the region) ## Possible values: bottom, middle, top teleportLocationY: bottom - +## The different tags you can write on the sign to trigger the plugin +signTags: + ## Tag for adding a rent region + rent: '[rent]' + ## Tag for adding a buy region + buy: '[buy]' + ## Tag for adding a sign to an existing region + add: '[as]' +## Configure the max total regions, max rent regions and max buy regions with different groups (-1 is unlimited) +## Assign a group to players by giving them the permission 'areashop.limits.' +## Every player already has the group 'default' and ops have the unlimited group +## If a player has multiple groups the highest numbers are used +limitGroups: + default: + total: 1 + rents: 1 + buys: 1 + unlimited: + total: -1 + rents: -1 + buys: -1 +## Below are profiles for the signs, you can assign profiles to regions +## by setting 'general.signProfile' in default.yml, groups or individual regions +signProfiles: + default: + ## Below is the format for each sign state, the following tags can be used for signs and commands: + ## %region%, %player%, %uuid%, %price%, %duration%, %world%, %type%, %until%, %untilshort% + ## The following sections can be added for performing certain commands when the sign is clicked: + ## rightClickPlayer, rightClickConsole, shiftRightClickPlayer, shiftRightClickConsole, + ## leftClickPlayer, leftClickConsole, shiftLeftClickPlayer, shiftLeftClickConsole + ## Sections with 'Player' at the end will be run by the clicking player and 'Console' ones from the console + forrent: + line1: '&2&l[For Rent]' + line2: '%region%' + line3: '%duration%' + line4: '%price%' + rightClickPlayer: + - 'as rent %region%' + leftClickPlayer: + - 'as info region %region%' + rented: + line1: '&4&l[Rented]' + line2: '%region%' + line3: '%player%' + line4: '%untilshort%' + rightClickPlayer: + - 'as rent %region%' + leftClickPlayer: + - 'as info region %region%' + shiftRightClickPlayer: + - 'as unrent %region%' + forsale: + line1: '&2&l[For Sale]' + line2: '%region%' + line3: '%price%' + line4: + rightClickPlayer: + - 'as buy %region%' + leftClickPlayer: + - 'as info region %region%' + sold: + line1: '&4&l[Sold]' + line2: '%region%' + line3: '%player%' + line4: + rightClickPlayer: + - 'as buy %region%' + leftClickPlayer: + - 'as info region %region%' + shiftRightClickPlayer: + - 'as sell %region%' +## Option to run certain commands when one of these events happen +## Commands at a 'before' section will execute before the region details are changed in the AreaShop system +## and before any other actions occurred (changing signs, saving/loading schematics, etc.), +## the 'after' commands will be run when all changes are done. +## After 'before' or 'after' you can create a list of commands (see example at the created event) +eventCommandProfiles: + default: + created: + before: + after: + ## - "say An AreaShop region has been created: %region%" + deleted: + before: + after: + rented: + before: + after: + extended: + before: + after: + unrented: + before: + after: + bought: + before: + after: + sold: + before: + after: +## For the following events you can specify if you want to restore or save the region to a schematic +## After 'save:' or 'restore:' you enter the name of the file, %region% will be replaced by the region name (.schematic will be added automatically) +## %type% represents the type of the region, could be 'rent' or 'buy' +## If your regions are all the same size you could use just 1 file as the restore file, just enter a name without %region% +## Be carefull with these options, it could crash your server or destroy (parts of) your world if used wrong! +schematicProfiles: + default: + created: + save: '%type%-%region%' + restore: '' + deleted: + save: '' + restore: '%type%-%region%' + rented: + save: '' + restore: '' + unrented: + save: '' + restore: '%type%-%region%' + bought: + save: '' + restore: '' + sold: + save: '' + restore: '%type%-%region%' +## Flag profiles to specify what flags should be set on the WorldGuard regions +## All region flags can be used + members, owners, priority and parent. +flagProfiles: + default: + forrent: + members: -%player% + greeting: '&2[AreaShop]&f %region% can be rented for %price% per %duration%' + rented: + members: +%player% + greeting: '&2[AreaShop]&f %region% is rented by %player% until %until%' + forsale: + members: -%player% + greeting: '&2[AreaShop]&f %region% can be bought for %price%' + sold: + members: +%player% + greeting: '&2[AreaShop]&f %region% is bought by %player%' + + ########## RENTING ########## -## The tag you have to write on the sign for renting a region -rentSign: '[rent]' -## The line that should be placed on the sign when the region is not rented -signRentable: '&2&l[For Rent]' -## The line that should be placed on the sign when the region is rented -signRented: '&4&l[Rented]' -## How much regions a player can rent at the same time, -1 for not limited -maximumRents: 1 -## The percentage of the renting price you get back if you unrent the region (price of time left will be multiplied by this/100) -rentMoneyBack: 100 ## How much seconds between checking if renting has expired (don't put this to low) checkDelay: 60 ## Timeformat to use on the signs, default is like '30-06 14:52', US format: 'MM-dd KK:mm a' @@ -56,78 +190,5 @@ hours: [h, hour, hours, uur, uren] days: [d, day, days, dag, dagen] months: [M, month, months, maanden, maand] years: [y, year, years, jaar, jaren] -## Flags for the 'For Rent' regions, flags and options to apply when the region is not rented -## All region flags can be used + members, owners, priority and parent. -flagsForRent: - members: -%player% - greeting: '%region% can be rented for %price% per %duration%' -## Flags for the 'Rented' regions, flags and options to apply when the region is rented -## All region flags can be used + members, owners, priority and parent. -flagsRented: - members: +%player% - greeting: '%region% is rented by %player% until %until%' -## Enable or disable saving and restoring for rents that don't have their individual option set -useRentRestore: false -## For the following events you can specify if you want to restore or save the region to a schematic -## After 'save:' or 'restore:' you enter the name of the file, %region% will be replaced by the region name (.schematic will be added automatically) -## If your regions are all the same size you could use just 1 file as the restore file, just enter a name without %region% -## Be carefull with these options, it could crash your server or destroy (parts of) your world if used wrong! -rentSchematicProfiles: - default: - created: - save: 'rent-%region%' - restore: '' - deleted: - save: '' - restore: 'rent-%region%' - rented: - save: '' - restore: '' - unrented: - save: '' - restore: 'rent-%region%' -########## BUYING ########## -## The tag you have to write on the sign for renting a region -buySign: '[buy]' -## The line that should be placed on the sign when the region is not sold -signBuyable: '&2&l[For Sale]' -## The line that should be placed on the sign when the region is sold -signBuyed: '&4&l[Sold]' -## How much regions a player can buy at the same time, -1 for not limited -maximumBuys: 1 -## The percentage of the buying price you get back if you sell the region -buyMoneyBack: 100 -## Flags for the 'For Sale' regions, flags and options to apply when the region is for sale -## All region flags can be used + members, owners, priority and parent. -flagsForSale: - members: -%player% - greeting: '%region% can be bought for %price%' -## Flags for the 'Sold' regions, flags and options to apply when the region is rented -## All region flags can be used + members, owners, priority and parent. -flagsSold: - members: +%player% - greeting: '%region% is bought by %player%' - -## Enable or disable saving and restoring for buys that don't have their individual option set -useBuyRestore: false -## For the following events you can specify if you want to restore or save the region to a schematic -## After 'save:' or 'restore:' you enter the name of the file, %region% will be replaced by the region name (.schematic will be added automatically) -## If your regions are all the same size you could use just 1 file as the restore file, just enter a name without %region% -## Be carefull with these options, it could crash your server or destroy (parts of) your world if used wrong! -## ('bought' and 'sold' are from the players perspective) -buySchematicProfiles: - default: - created: - save: 'buy-%region%' - restore: '' - deleted: - save: '' - restore: 'buy-%region%' - bought: - save: '' - restore: '' - sold: - save: '' - restore: 'buy-%region%' \ No newline at end of file diff --git a/AreaShop/default.yml b/AreaShop/default.yml index faaa918..52cb54b 100644 --- a/AreaShop/default.yml +++ b/AreaShop/default.yml @@ -1,17 +1,56 @@ +### All settings below are default settings and can be overridden +### by group settings or region settings (copy a section to a region or group and change them there) + ########## GENERAL ########## general: - -########## RENTING ########## -rent: - price: 1000 - duration: '1 day' - ### Enable or disable saving and restoring for rents that don't have their individual option set + ## Set this to true to enable saving/restoring for regions as specified in the profile below, which is specified in the config enableRestore: false - restoreProfile: 'default' + ## The schematic profile as specified in the config + schematicProfile: 'default' + ## The event commands profile as specified in the config + eventCommandProfile: 'default' + ## The profile for the format of the sign as specified in the config + signProfile: 'default' + ## The profile for the WorldGuard flags as specified in the config + flagProfile: 'default' + runCommands: + created: + before: + after: + - "say An AreaShop region has been created: %region%" + deleted: + before: + after: + rented: + before: + after: + extended: + before: + after: + unrented: + before: + after: + bought: + before: + after: + sold: + before: + after: + +########## RENTING ########## +rent: + ## The default price of a renting region + price: 1000 + ## The default duration of a renting region + duration: '1 day' + ## The percentage of the renting price you get back if you unrent the region (price of time left will be multiplied by this/100) + moneyBack: 100 + ## Maximum number of extends a player can do (-1 for infinite, 0 for no extending) + maxExtends: -1 ########## BUYING ########## buy: + ## The default price of a buying region price: 1000 - ### Enable or disable saving and restoring for buys that don't have their individual option set - enableRestore: false - restoreProfile: 'default' + ## The percentage of the buying price you get back if you sell the region + moneyBack: 100 diff --git a/AreaShop/lang/EN.yml b/AreaShop/lang/EN.yml index d55b04f..d4c0676 100644 --- a/AreaShop/lang/EN.yml +++ b/AreaShop/lang/EN.yml @@ -6,13 +6,50 @@ # the config to the filename (excluding .yml) # ################################################### -########## Command strings +########## General strings total-maximum: "You can't rent and buy more than %0% region(s) in total" cmd-notValid: "That command is not valid, use '/as help' for info" cmd-onlyByPlayer: "This command can only be run by a player" +cmd-weOnlyByPlayer: "Using a WorldEdit selection is only possible as a player, specify the region name as extra argument" +cmd-noSelection: "You don't have a WorldEdit selection" +cmd-noRegionsFound: "No regions registered in AreaShop are found in your selection" +cmd-noWERegionsFound: "No WorldEdit regions intersecting your selection are found" -rent-help: "/as rent " +########## Help command strings +help-header: "Help page, commands that you can execute" +help-alias: "Command aliases: /areashop, /as" +help-help: "&6/as help &7-&r Shows this help page" +help-info: "&6/as info &7-&r Get info about current regions" +help-rent: "&6/as rent &7-&r Rent a region or extend your current rent" +help-buy: "&6/as buy &7-&r Buy a region" +help-unrent: "&6/as unrent &7-&r Unrent a region" +help-unrentOwn: "&6/as unrent &7-&r Unrent your own region" +help-sell: "&6/as sell &7-&r Sell a region" +help-sellOwn: "&6/as sell &7-&r Sell your own region" +help-updaterents: "&6/as updaterents &7-&r Update all rent signs and regions" +help-updatebuys: "&6/as updatebuys &7-&r Update all buy signs and regions" +help-reload: "&6/as reload &7-&r Reload the config and languages" +help-setrestore: "&6/as setrestore &7-&r Set the profile for restoring and on/off " +help-setprice: "&6/as setprice &7-&r Change the price of a rent region" +help-rentduration: "&6/as rentduration &7-&r Change the duration of a rent region" +help-teleport: "&6/as tp &7-&r Teleport to your bought/rented regions" +help-teleportAll: "&6/as tp &7-&r Teleport to a rent/buy region" +help-setteleport: "&6/as settp &7-&r Set teleport position for bought/rented regions" +help-setteleportAll: "&6/as settp &7-&r Set teleport position for a region" +help-find: "&6/as find &7-&r Find an empty buy or rent" +help-groupadd: "&6/as groupadd &7-&r Add a region to a group" +help-groupdel: "&6/as groupdel &7-&r Delete a region from a group" +help-grouplist: "&6/as grouplist &7-&r Display all groups currently registered" +help-groupinfo: "&6/as groupinfo &7-&r Display information about a group" +help-schemevent: "&6/as schemevent &7-&r Trigger a schematic event for a region" +help-add: "&6/as add &7-&r Register a region as rent or buy" +help-del: "&6/as del &7-&r Delete a registered region from AreaShop" +help-addsign: "&6/as addsign &7-&r Add a sign to an existing region" +help-delsign: "&6/as delsign &7-&r Delete the sign you are looking at" + +############ Other command strings +rent-help: "/as rent [regionname], the region you stand in will be used if not specified" rent-noPermission: "You don't have permission to rent a region" rent-maximum: "You can't rent more than %0% region(s)" rent-payError: "Something went wrong with paying, try again later" @@ -23,8 +60,9 @@ rent-lowMoneyExtend: "You don't have enough money to extend the rent (you have % rent-lowMoneyRent: "You don't have enough money to rent this region (you have %0% and you need %1%)" rent-someoneElse: "Someone else already rented this region" rent-notRentable: "That region is not available for renting" +rent-maxExtends: "You cannot extend this rent anymore (the maximum is %0% times), however after the rent is over you can rent this region again" -buy-help: "/as buy " +buy-help: "/as buy [regionname], the region you stand in will be used if not specified" buy-noPermission: "You don't have permission to buy a region" buy-notBuyable: "That region is not available for buying" buy-maximum: "You can't buy more than %0% region(s)" @@ -34,7 +72,7 @@ buy-lowMoney: "You don't have enough money to buy this region (you have %0% and buy-yours: "You already own this region" buy-someoneElse: "Someone else already bought this region" -unrent-help: "/as unrent " +unrent-help: "/as unrent [regionname], the region you stand in will be used if not specified" unrent-noPermission: "You don't have permission to unrent a region" unrent-noPermissionOther: "You don't have permission to unrent another region" unrent-notRegistered: "The region can't be unrent because it is not registered for renting" @@ -43,7 +81,7 @@ unrent-unrented: "Your region has been unrented" unrent-other: "The region has been unrented for player %0%" unrent-expired: "Your rent of %0% has expired" -sell-help: "/as sell " +sell-help: "/as sell [regionname], the region you stand in will be used if not specified" sell-notRegistered: "The region can't be selled because it is not registered for buying" sell-notBought: "The region can't be selled because it is not someone's property" sell-sold: "The region has been sold for player %0%" @@ -63,89 +101,56 @@ reload-reloaded: "The config has been reloaded successfully" reload-noPermission: "You don't have permission to reload the config" info-help: "/as info " -info-all-rents: "Regions registered for renting: %0%" +info-all-rents: "Regions registered for renting: &7%0%" info-all-noRents: "There are no regions registered for renting" -info-all-buys: "Regions registered for buying: %0%" +info-all-buys: "Regions registered for buying: &7%0%" info-all-noBuys: "There are no regions registered for buying" -info-rented: "Rented regions: %0%" +info-rented: "Rented regions: &7%0%" info-noRented: "No regions are rented" -info-unrented: "Unrented regions: %0%" +info-unrented: "Unrented regions: &7%0%" info-noUnrented: "All regions are rented" -info-sold: "Sold regions: %0%" +info-sold: "Sold regions: &7%0%" info-noSold: "No regions are sold" -info-forsale: "Regions for sale: %0%" +info-forsale: "Regions for sale: &7%0%" info-noForsale: "All regions are sold" info-playerHelp: "/as info player " -info-playerRents: "Regions rented by %0%: %1%" +info-playerRents: "Regions rented by %0%: &7%1%" info-playerNoRents: "%0% has not rented a region" -info-playerBuys: "Regions bought by %0%: %1%" +info-playerBuys: "Regions bought by %0%: &7%1%" info-playerNoBuys: "%0% has not bought a region" -info-regionHelp: "/as info region " +info-regionHelp: "/as info region [name], the region you stand in will be used if not specified" info-regionNoRenting: "%0% is not registered for renting" -info-regionRenting: "&6Renting details for %0%" -info-regionRentedBy: "Rented by: %0% until %1%" +info-regionRenting: "&6Renting details for %0%:" +info-regionRentedBy: "Rented by: &7%0% until %1%" info-regionNotRented: "Currently not rented" -info-regionBuying: "&6Buying details for %0%" +info-regionBuying: "&6Buying details for %0%:" info-regionNoBuying: "%0% is not registered for buying" info-regionNotBought: "Currently not sold" -info-regionBoughtBy: "Bought by: %0%" -info-regionSign: "Sign position: world=%0%, X=%1%, Y=%2%, Z=%3%" -info-regionPriceDuration: "Price: %0% for each %1%" -info-regionPrice: "Price: %0%" -info-regionRestore: "Restoring enabled: %0%" -info-regionRestoreProfile: "Restoring profile: %0%" -info-regionTPLocation: "Teleport position: World=%0%, X=%1%, Y=%2%, Z=%3%, Pitch=%4%, Yaw=%5%" +info-regionBoughtBy: "Bought by: &7%0%" +info-regionSign: "Sign location(s): %0%" +info-regionSignLocation: "&7(%0%, %1%, %2%, %3%)&r" +info-regionNoSign: "There is no sign registered for this region" +info-regionPriceDuration: "Price: &7%0% for each %1%" +info-regionPrice: "Price: &7%0%" +info-regionRestore: "Restoring enabled: &7%0%" +info-regionRestoreProfile: "Restoring profile: &7%0%" +info-regionTPLocation: "Teleport location: &7World=%0%, X=%1%, Y=%2%, Z=%3%, Pitch=%4%, Yaw=%5%" info-regionNoTP: "No teleport location set" +info-regionNotExisting: "Region %0% is not registered" -help-header: "Help page, commands that you can execute" -help-alias: "Command aliases: /areashop, /as" -help-help: "&6/as help &7-&r Shows this help page" -help-info: "&6/as info &7-&r Get info about current regions" -help-rent: "&6/as rent &7-&r Rent a region or extend your current rent" -help-buy: "&6/as buy &7-&r Buy a region" -help-unrent: "&6/as unrent &7-&r Unrent a region" -help-unrentOwn: "&6/as unrent &7-&r Unrent your own region" -help-sell: "&6/as sell &7-&r Sell a region" -help-sellOwn: "&6/as sell &7-&r Sell your own region" -help-updaterents: "&6/as updaterents &7-&r Update all rent signs and regions" -help-updatebuys: "&6/as updatebuys &7-&r Update all buy signs and regions" -help-reload: "&6/as reload &7-&r Reload the config and languages" -help-rentrestore: "&6/as rentrestore &7-&r Set the profile for restoring and on/off " -help-buyrestore: "&6/as buyrestore &7-&r Set the profile for restoring and on/off" -help-rentprice: "&6/as rentprice &7-&r Change the price of a rent region" -help-buyprice: "&6/as buyprice &7-&r Change the price of a buy region" -help-rentduration: "&6/as rentduration &7-&r Change the duration of a rent region" -help-teleport: "&6/as tp &7-&r Teleport to your bought/rented regions" -help-teleportAll: "&6/as tp &7-&r Teleport to a rent/buy region" -help-setteleport: "&6/as settp &7-&r Set teleport position for bought/rented regions" -help-setteleportAll: "&6/as settp &7-&r Set teleport position for a region" +setrestore-help: "/as setrestore [profile]" +setrestore-noPermission: "You don't have permission to change the restore settings" +setrestore-notRegistered: "%0% is not registered" +setrestore-invalidSetting: "'%0%' is not a valid state, should be true, false or general" +setrestore-success: "Succesfully set the restore setting of %0% to '%1%'" +setrestore-successProfile: "Succesfully set the restore setting of %0% to '%1%' and the profile to '%2%'" - -rentrestore-help: "/as rentrestore [profile]" -rentrestore-noPermission: "You don't have permission to change the restore settings of a rent" -rentrestore-notRegistered: "%0% is not registered as a rent" -rentrestore-invalidSetting: "'%0%' is not a valid state, should be true, false or general" -rentrestore-success: "Succesfully set the restore setting of %0% to '%1%'" -rentrestore-successProfile: "Succesfully set the restore setting of %0% to '%1%' and the profile to '%2%'" - -buyrestore-help: "/as buyrestore [profile]" -buyrestore-noPermission: "You don't have permission to change the restore settings of a buy" -buyrestore-notRegistered: "%0% is not registered as a buy" -buyrestore-invalidSetting: "'%0%' is not a valid state, should be true, false or general" -buyrestore-success: "Succesfully set the restore setting of %0% to '%1%'" -buyrestore-successProfile: "Succesfully set the restore setting of %0% to '%1%' and the profile to '%2%'" - -rentprice-noPermission: "You don't have permission to change the price of a rent" -rentprice-help: "/as rentprice " -rentprice-notRegistered: "%0% is not registered as a rent" -rentprice-wrongPrice: "'%0%' is not a valid price" -rentprice-success: "Price of region %0% changed to %1% per %2%" - -buyprice-noPermission: "You don't have permission to change the price of a buy" -buyprice-help: "/as buyprice " -buyprice-notRegistered: "%0% is not registered as a buy" -buyprice-wrongPrice: "'%0%' is not a valid price" -buyprice-success: "Price of region %0% changed to %1%" +setprice-noPermission: "You don't have permission to change the price of a region" +setprice-help: "/as setprice [region], the region you stand in will be used if not specified" +setprice-notRegistered: "%0% is not registered in AreaShop" +setprice-wrongPrice: "'%0%' is not a valid price" +setprice-successRent: "Price of region %0% changed to %1% per %2%" +setprice-successBuy: "Price of region %0% changed to %1%" rentduration-noPermission: "You don't have permission to change the duration of a rent" rentduration-help: "/as rentduration " @@ -173,14 +178,14 @@ destroy-noPermissionBuy: "You don't have permission for destroying a sign for bu destroy-successRent: "Renting of %0% successfully removed" destroy-successBuy: "Buying of %0% successfully removed" -teleport-help: "/as tp " +teleport-help: "/as tp [sign]" teleport-noRentOrBuy: "Region '%0%' is not registered as rent or buy" teleport-noPermission: "You don't have permission to teleport to a region" teleport-noPermissionOther: "You don't have permission to teleport to region you do not own" teleport-success: "You teleported to %0%" teleport-noSafe: "No safe position found in region %0%, change the region or set position yourself" -setteleport-help: "/as settp [reset]" +setteleport-help: "/as settp [region] [reset], the region you stand in will be used if not specified" setteleport-noPermission: "You don't have permission to set the teleport location" setteleport-noPermissionAll: "You don't have permission to set the teleport location for a region you do not own" setteleport-noRentOrBuy: "Region '%0%' is not registered as rent or buy" @@ -188,12 +193,74 @@ setteleport-success: "Teleport location of %0% set" setteleport-notInside: "The location has to be inside the region" setteleport-reset: "Teleport location of %0% has been reset" - - - - - - +find-help: "/as find [maxprice]" +find-noPermission: "You don't have permission to teleport to signs, so you can't use find" +find-success: "Found a %0% region: %1%, while searching with a max price of your balance: %2%" +find-successMax: "Found a %0% region: %1%, while searching with a max price of %2%" +find-wrongMaxPrice: "The specified maximum price is not a correct number: %0%" +find-noneFound: "No %0% region found while searching with a max price of your balance: %1%" +find-noneFoundMax: "No %0% region found while searching with a max price of %1%" + +groupadd-help: "/as groupadd [region], if no region specified all regions from your WorldEdit selection are used" +groupadd-noPermission: "You don't have permission to add regions to groups" +groupadd-noRegion: "The specified region is not registered: %0%" +groupadd-success: "Region %0% has been added to group '%1%', this group now has %2% member(s)" +groupadd-failed: "Region %0% is already a member of group '%1%'" +groupadd-weSuccess: "Added to group %0%: &7%1%" +groupadd-weFailed: "Were already in group %0%: &7%1%" + +groupdel-help: "/as groupdel [region], if no region specified all regions from your WorldEdit selection are used" +groupdel-noPermission: "You don't have permission to remove regions from groups" +groupdel-noRegion: "The specified region is not registered: %0%" +groupdel-success: "Region %0% has been removed from group '%1%', this group now has %2% member(s)" +groupdel-failed: "Region %0% is not a member of group '%1%'" +groupdel-weSuccess: "Removed from group %0%: &7%1%" +groupdel-weFailed: "Were not in group %0% anyway: &7%1%" + +grouplist-noPermission: "You don't have permission to display the registered groups" +grouplist-noGroups: "There are currently no groups registered" +grouplist-success: "The following groups are registered: &7%0%" + +groupinfo-help: "/as groupinfo " +groupinfo-noPermission: "You don't have permission to display information about a group" +groupinfo-noGroup: "There is no group registered with the name '%0%', use /as grouplist to check groups" +groupinfo-members: "The following regions are member of group %0%: &7%1%" +groupinfo-noMembers: "Group %0% does not have any members" + +schemevent-help: "/as schemevent " +schemevent-noRegion: "The specified region is not registered: %0%" +schemevent-wrongEvent: "The specified event '%0%' does not exist, use one of the following: &7%1%" +schemevent-success: "Event '%0%' has succesfully been triggered for region %1%" + +add-help: "/as add [region] [world]" +add-noPermission: "You don't have permission to add a region to AreaShop" +add-success: "Added as %0%: &7%1%" +add-failed: "Already registered: &7%0%" +add-specifyWorld: "Specify the world of the region when using from console" +add-incorrectWorld: "World '%0%' not found, try again (case-sensitive)" +add-noRegion: "Region '%0%' does not exist in this world" + +del-noRegion: "Region '%0%' is not registered in AreaShop" +del-noPermission: "You don't have permission to remove regions" +del-success: "Removed regions: &7%0%" +del-failed: "No permission to remove or not registered: &7%0%" + +addsign-help: "/as addsign [region] [profile]" +addsign-noSign: "You are not looking at a sign" +addsign-noRegion: "Region '%0%' cannot be found" +addsign-noRegions: "No region found around the sign position" +addsign-couldNotDetect: "Found multiple regions around the sign, specify region as extra argument (2 of the regions that were found: %0% and %1%)" +addsign-couldNotDetectSign: "Found multiple regions around the sign, specify region on the second line (2 of the regions that were found: %0% and %1%)" +addsign-wrongProfile: "The specified profile does not exist, use one of the following (check config): &7%0%" +addsign-success: "The sign has been added to %0%" +addsign-successProfile: "The sign has been added to %0% with profile %1%" +addsign-alreadyRegistered: "That sign is already registered for region %0%" +addsign-noPermission: "You don't have permission to add a sign" + +delsign-noSign: "You are not looking at a sign" +delsign-noPermission: "You don't have permission to delete a sign" +delsign-noRegion: "That sign does not belong to an AreaShop region" +delsign-success: "The sign has been removed from region %0%" diff --git a/AreaShop/lang/NL.yml b/AreaShop/lang/NL.yml index 8266b6c..0c66892 100644 --- a/AreaShop/lang/NL.yml +++ b/AreaShop/lang/NL.yml @@ -4,7 +4,7 @@ # Copy this file and change the strings to your # # favor. Then change the 'language' setting in # # the config to the filename (excluding .yml) # -# NOT TOTALLY UPDATED FOR 1.3.0 # +# NOT UPDATED since 1.2.1 # ################################################### ########## Command strings diff --git a/AreaShop/plugin.yml b/AreaShop/plugin.yml index d92bc2c..a654dad 100644 --- a/AreaShop/plugin.yml +++ b/AreaShop/plugin.yml @@ -1,6 +1,6 @@ name: AreaShop main: nl.evolutioncoding.AreaShop.AreaShop -version: 1.4.0 +version: 2.0.0 depend: [Vault, WorldGuard, WorldEdit] softdepend: [Multiverse-Core] commands: @@ -26,15 +26,23 @@ permissions: areashop.updaterents: true areashop.updatebuys: true areashop.reload: true - areashop.rentrestore: true - areashop.buyrestore: true - areashop.rentprice: true - areashop.buyprice: true + areashop.setrestore: true + areashop.setprice: true areashop.rentduration: true areashop.teleportall: true areashop.setteleportall: true + areashop.teleportsign: true areashop.tabcomplete: true areashop.setteleportoutsideregion: true + areashop.find: true + areashop.groupadd: true + areashop.groupdel: true + areashop.grouplist: true + areashop.groupinfo: true + areashop.limits.unlimited: true + areashop.schematicevents: true + areashop.addsign: true + areashop.delsign: true areashop.help: description: Allows you to see the help pages default: true @@ -80,17 +88,11 @@ permissions: areashop.reload: description: Allows you to reload the config default: op - areashop.rentrestore: - description: Allows you to change the restore settings of a rent + areashop.setrestore: + description: Allows you to change the restore settings default: op - areashop.buyrestore: - description: Allows you to change the restore settings of a buy - default: op - areashop.rentprice: - description: Allows you to change the price of a rent - default: op - areashop.buyprice: - description: Allows you to change the price of a buy + areashop.setprice: + description: Allows you to change the price default: op areashop.rentduration: description: Allows you to change the duration of a rent @@ -100,7 +102,10 @@ permissions: default: true areashop.teleportall: description: Teleport to all regions - default: op + default: true + areashop.teleportsign: + description: Teleport to signs of regions + default: true areashop.setteleport: description: Set the teleport spot for your region default: true @@ -112,4 +117,37 @@ permissions: default: op areashop.tabcomplete: description: Allows you to tabcomplete all commands (also where you dont have permission) + default: op + areashop.find: + description: Allows you to teleport to a free region (/as find) + default: true + areashop.groupadd: + description: Allows you to add regions to groups + default: op + areashop.groupdel: + description: Allows you to delete regions from groups + default: op + areashop.grouplist: + description: Allows you to list all the groups currently created + default: op + areashop.groupinfo: + description: Allows you to display information about a group (all members) + default: op + areashop.rentextendbypass: + description: Bypass the extend limit on rents + default: op + areashop.limits.default: + description: Assign limits as set in the 'default' group in the 'limitGroups' section of the config + default: not op + areashop.limits.unlimited: + description: Assign limits as set in the 'unlimited' group in the 'limitGroups' section of the config + default: op + areashop.schematicevents: + description: Allows you to trigger schematic events for regions + default: op + areashop.addsign: + description: Allows you to add signs to existing regions + default: op + areashop.delsign: + description: Allows you to delete signs from existing regions default: op \ No newline at end of file diff --git a/AreaShop/src/nl/evolutioncoding/AreaShop/AreaShop.java b/AreaShop/src/nl/evolutioncoding/AreaShop/AreaShop.java index 519e422..5edaf9c 100644 --- a/AreaShop/src/nl/evolutioncoding/AreaShop/AreaShop.java +++ b/AreaShop/src/nl/evolutioncoding/AreaShop/AreaShop.java @@ -12,6 +12,7 @@ import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.configuration.Configuration; import org.bukkit.entity.Player; +import org.bukkit.permissions.Permission; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.java.JavaPlugin; @@ -55,41 +56,14 @@ public final class AreaShop extends JavaPlugin { /* Keys for replacing parts of flags */ public static final String tagPlayerName = "%player%"; + public static final String tagPlayerUUID = "%uuid%"; + public static final String tagWorldName = "%world%"; public static final String tagRegionName = "%region%"; + public static final String tagRegionType = "%type%"; public static final String tagPrice = "%price%"; public static final String tagDuration = "%duration%"; public static final String tagRentedUntil = "%until%"; - - /* Enum for schematic event types */ - // TODO delete - public enum RegionEventType { - CREATED("Created"), - DELETED("Deleted"), - BOUGHT("Bought"), - SOLD("Sold"); - - private final String value; - private RegionEventType(String value) { - this.value = value; - } - public String getValue() { - return value; - } - } - - /* Enum for region types */ - public enum RegionType { - SELL("sell"), - RENT("rent"); - - private final String value; - private RegionType(String value) { - this.value = value; - } - public String getValue() { - return value; - } - } + public static final String tagRentedUntilShort = "%untilshort%"; public static AreaShop getInstance() { return AreaShop.instance; @@ -101,13 +75,11 @@ public final class AreaShop extends JavaPlugin { public void onEnable(){ AreaShop.instance = this; boolean error = false; - - /* Save a copy of the default config.yml if one is not present */ - this.saveDefaultConfig(); /* Check the config, loads default if errors */ - configOk = this.checkConfig(); - + debug = this.getConfig().getBoolean("debug"); + configOk = true; + /* Check if WorldGuard is present */ Plugin plugin = getServer().getPluginManager().getPlugin("WorldGuard"); if (plugin == null || !(plugin instanceof WorldGuardPlugin)) { @@ -145,26 +117,32 @@ public final class AreaShop extends JavaPlugin { fileManager = new FileManager(this); error = error & !fileManager.loadFiles(); fileManager.checkRents(); + + /* Save a copy of the default config.yml if one is not present */ + this.saveDefaultConfig(); if(error) { this.getLogger().info("The plugin has not started, fix the errors listed above"); } else { - /* Register the event listeners */ + // Register the event listeners this.getServer().getPluginManager().registerEvents(new SignChangeListener(this), this); this.getServer().getPluginManager().registerEvents(new SignBreakListener(this), this); - this.getServer().getPluginManager().registerEvents(new RightClickListener(this), this); + this.getServer().getPluginManager().registerEvents(new SignClickListener(this), this); - /* Start thread for checking renting */ + // Start thread for checking renting int checkDelay = Integer.parseInt(this.config().getString("checkDelay"))*20; new RentCheck(this).runTaskTimer(this, checkDelay, checkDelay); - /* Bind commands for this plugin */ + // Bind commands for this plugin commandManager = new CommandManager(this); + // Enable Metrics if config allows it if(this.config().getBoolean("sendStats")) { this.startMetrics(); } + // Register dynamic permission (things declared in config) + registerDynamicPermissions(); } } @@ -230,13 +208,28 @@ public final class AreaShop extends JavaPlugin { return fileManager; } + /** + * Register dynamic permissions controlled by config settings + */ + public void registerDynamicPermissions() { + // Register limit groups of amount of regions a player can have + for(String group : config().getConfigurationSection("limitGroups").getKeys(false)) { + if(!"unlimited".equals(group) && !"default".equals(group)) { + Permission perm = new Permission("areashop.limits." + group); + Bukkit.getPluginManager().addPermission(perm); + } + } + Bukkit.getPluginManager().recalculatePermissionDefaults(Bukkit.getPluginManager().getPermission("playerwarps.limits")); + } + /** * Method to send a message to a CommandSender, using chatprefix if it is a player * @param target The CommandSender you wan't to send the message to (e.g. a player) * @param key The key to get the translation + * @param prefix Specify if the message should have a prefix * @param params The parameters to inject into the message string */ - public void message(Object target, String key, Object... params) { + public void configurableMessage(Object target, String key, boolean prefix, Object... params) { String langString = this.fixColors(languageManager.getLang(key, params)); if(langString == null) { this.getLogger().info("Something is wrong with the language file, could not find key: " + key); @@ -244,17 +237,34 @@ public final class AreaShop extends JavaPlugin { // Do nothing, message is disabled } else { if(target instanceof Player) { - ((Player)target).sendMessage(this.fixColors(chatprefix) + langString); + if(prefix) { + ((Player)target).sendMessage(this.fixColors(chatprefix) + langString); + } else { + ((Player)target).sendMessage(langString); + } } else if(target instanceof CommandSender) { + if(!config().getBoolean("useColorsInConsole")) { + langString = ChatColor.stripColor(langString); + } ((CommandSender)target).sendMessage(langString); } else if(target instanceof Logger) { + if(!config().getBoolean("useColorsInConsole")) { + langString = ChatColor.stripColor(langString); + } ((Logger)target).info(langString); } else { + langString = ChatColor.stripColor(langString); this.getLogger().info("Could not send message, target is wrong: " + langString); } } } + public void messageNoPrefix(Object target, String key, Object... params) { + configurableMessage(target, key, false, params); + } + public void message(Object target, String key, Object... params) { + configurableMessage(target, key, true, params); + } /** * Convert color and formatting codes to bukkit values @@ -313,192 +323,17 @@ public final class AreaShop extends JavaPlugin { } } + /** + * Start the Metrics stats collection + */ private void startMetrics() { try { Metrics metrics = new Metrics(this); - // Number of rents rented/not rented - /*Graph rentGraph = metrics.createGraph("Rent regions"); - rentGraph.addPlotter(new Metrics.Plotter("For rent") { - @Override - public int getValue() { - int result = 0; - for(String rent : fileManager.getRents().keySet()) { - if(fileManager.getRent(rent).get(keyPlayer) == null) { - result++; - } - } - return result; - } - }); - rentGraph.addPlotter(new Metrics.Plotter("Rented") { - @Override - public int getValue() { - int result = 0; - for(String rent : fileManager.getRents().keySet()) { - if(fileManager.getRent(rent).get(keyPlayer) != null) { - result++; - } - } - return result; - } - }); - // Number of buys bought/not bought - Graph buyGraph = metrics.createGraph("Buy regions"); - buyGraph.addPlotter(new Metrics.Plotter("For sale") { - @Override - public int getValue() { - int result = 0; - for(String buy : fileManager.getBuys().keySet()) { - if(fileManager.getBuy(buy).get(keyPlayer) == null) { - result++; - } - } - return result; - } - }); - buyGraph.addPlotter(new Metrics.Plotter("Sold") { - @Override - public int getValue() { - int result = 0; - for(String buy : fileManager.getBuys().keySet()) { - if(fileManager.getBuy(buy).get(keyPlayer) != null) { - result++; - } - } - return result; - } - }); - */ metrics.start(); } catch (IOException e) { AreaShop.debug("Could not start Metrics"); } - } - - - - /** - * Checks the config for errors, loads default config if they occur - */ - public boolean checkConfig() { - int error = 0; - debug = this.getConfig().getString("debug").equalsIgnoreCase("true"); - - /* GENERAL */ - String chatPrefix = this.getConfig().getString("chatPrefix"); - if (chatPrefix.length() == 0) { - this.getLogger().info("Config-Error: chatPrefix has length zero"); - error++; - } - String maximumTotal = this.getConfig().getString("maximumTotal"); - try { - int maximumTotalInt = Integer.parseInt(maximumTotal); - if(maximumTotalInt < -1) { - this.getLogger().info("Config-Error: maximumTotal must be -1 or higher"); - error++; - } - } catch (NumberFormatException e) { - this.getLogger().info("Config-Error: maximumTotal is not a valid number"); - error++; - } - - /* RENTING */ - String rentSign = this.getConfig().getString("rentSign"); - if (rentSign.length() > 15) { - this.getLogger().info("Config-Error: rentSign is too long, maximum length is 15 characters"); - error++; - } - String signRentable = this.getConfig().getString("signRentable"); - if (signRentable.length() > 15) { - this.getLogger().info("Config-Error: signRentable is too long, maximum length is 15 characters"); - error++; - } - String signRented = this.getConfig().getString("signRented"); - if (signRented.length() > 15) { - this.getLogger().info("Config-Error: signRented is too long, maximum length is 15 characters"); - error++; - } - String maximumRents = this.getConfig().getString("maximumRents"); - try { - int maximumRentsInt = Integer.parseInt(maximumRents); - if(maximumRentsInt < -1) { - this.getLogger().info("Config-Error: maximumRents must be -1 or higher"); - error++; - } - } catch (NumberFormatException e) { - this.getLogger().info("Config-Error: maximumRents is not a valid number"); - error++; - } - String rentMoneyBack = this.getConfig().getString("rentMoneyBack"); - try { - int rentMoneyBackInt = Integer.parseInt(rentMoneyBack); - if(rentMoneyBackInt < 0 || rentMoneyBackInt > 100) { - this.getLogger().info("Config-Error: rentMoneyBack must be between 0 and 100"); - error++; - } - } catch (NumberFormatException e) { - this.getLogger().info("Config-Error: rentMoneyBack is not a valid number"); - error++; - } - String checkDelay = this.getConfig().getString("checkDelay"); - try { - int checkDelayInt = Integer.parseInt(checkDelay); - if(checkDelayInt < 1) { - this.getLogger().info("Config-Error: checkDelay can't be below 1"); - error++; - } - } catch (NumberFormatException e) { - this.getLogger().info("Config-Error: checkDelay is not a valid number"); - error++; - } - - /* BUYING */ - String buySign = this.getConfig().getString("buySign"); - if (buySign.length() > 15) { - this.getLogger().info("Config-Error: buySign is too long, maximum length is 15 characters"); - error++; - } - String signBuyable = this.getConfig().getString("signBuyable"); - if (signBuyable.length() > 15) { - this.getLogger().info("Config-Error: signBuyable is too long, maximum length is 15 characters"); - error++; - } - String signBuyed = this.getConfig().getString("signBuyed"); - if (signBuyed.length() > 15) { - this.getLogger().info("Config-Error: signBuyed is too long, maximum length is 15 characters"); - error++; - } - String maximumBuys = this.getConfig().getString("maximumBuys"); - try { - int maximumBuysInt = Integer.parseInt(maximumBuys); - if(maximumBuysInt < -1) { - this.getLogger().info("Config-Error: maximumBuys must be -1 or higher"); - error++; - } - } catch (NumberFormatException e) { - this.getLogger().info("Config-Error: maximumBuys is not a valid number"); - error++; - } - String buyMoneyBack = this.getConfig().getString("buyMoneyBack"); - try { - int buyMoneyBackInt = Integer.parseInt(buyMoneyBack); - if(buyMoneyBackInt < 0 || buyMoneyBackInt > 100) { - this.getLogger().info("Config-Error: buyMoneyBack must be between 0 and 100"); - error++; - } - } catch (NumberFormatException e) { - this.getLogger().info("Config-Error: buyMoneyBack is not a valid number"); - error++; - } - - /* Load default config if errors have occurred */ - if (error > 0) { - this.getLogger().info("The plugin has " + error + " error(s) in the config, default config will be used"); - } - - /* return true if no errors, false if there are errors */ - return (error == 0); - } + } /** * Checks if the string is a correct time period @@ -544,9 +379,11 @@ public final class AreaShop extends JavaPlugin { public void reload() { this.saveDefaultConfig(); this.reloadConfig(); - configOk = this.checkConfig(); + configOk = true; chatprefix = this.config().getString("chatPrefix"); + debug = this.getConfig().getBoolean("debug"); languageManager = new LanguageManager(this); + fileManager.loadFiles(); fileManager.checkRents(); } diff --git a/AreaShop/src/nl/evolutioncoding/AreaShop/CommandManager.java b/AreaShop/src/nl/evolutioncoding/AreaShop/CommandManager.java index 14340bd..3aaf932 100644 --- a/AreaShop/src/nl/evolutioncoding/AreaShop/CommandManager.java +++ b/AreaShop/src/nl/evolutioncoding/AreaShop/CommandManager.java @@ -5,28 +5,38 @@ import java.util.List; import java.util.SortedSet; import java.util.TreeSet; +import nl.evolutioncoding.AreaShop.commands.AddCommand; +import nl.evolutioncoding.AreaShop.commands.AddsignCommand; import nl.evolutioncoding.AreaShop.commands.BuyCommand; -import nl.evolutioncoding.AreaShop.commands.BuypriceCommand; -import nl.evolutioncoding.AreaShop.commands.BuyrestoreCommand; import nl.evolutioncoding.AreaShop.commands.CommandAreaShop; +import nl.evolutioncoding.AreaShop.commands.DelCommand; +import nl.evolutioncoding.AreaShop.commands.DelsignCommand; +import nl.evolutioncoding.AreaShop.commands.FindCommand; +import nl.evolutioncoding.AreaShop.commands.GroupaddCommand; +import nl.evolutioncoding.AreaShop.commands.GroupdelCommand; +import nl.evolutioncoding.AreaShop.commands.GroupinfoCommand; +import nl.evolutioncoding.AreaShop.commands.GrouplistCommand; import nl.evolutioncoding.AreaShop.commands.HelpCommand; import nl.evolutioncoding.AreaShop.commands.InfoCommand; import nl.evolutioncoding.AreaShop.commands.ReloadCommand; import nl.evolutioncoding.AreaShop.commands.RentCommand; import nl.evolutioncoding.AreaShop.commands.RentdurationCommand; -import nl.evolutioncoding.AreaShop.commands.RentpriceCommand; -import nl.evolutioncoding.AreaShop.commands.RentrestoreCommand; +import nl.evolutioncoding.AreaShop.commands.SchematiceventCommand; import nl.evolutioncoding.AreaShop.commands.SellCommand; +import nl.evolutioncoding.AreaShop.commands.SetpriceCommand; +import nl.evolutioncoding.AreaShop.commands.SetrestoreCommand; import nl.evolutioncoding.AreaShop.commands.SetteleportCommand; import nl.evolutioncoding.AreaShop.commands.TeleportCommand; import nl.evolutioncoding.AreaShop.commands.UnrentCommand; import nl.evolutioncoding.AreaShop.commands.UpdatebuysCommand; import nl.evolutioncoding.AreaShop.commands.UpdaterentsCommand; +import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.command.TabCompleter; +import org.bukkit.entity.Player; public class CommandManager implements CommandExecutor, TabCompleter { AreaShop plugin; @@ -47,14 +57,22 @@ public class CommandManager implements CommandExecutor, TabCompleter { commands.add(new InfoCommand(plugin)); commands.add(new TeleportCommand(plugin)); commands.add(new SetteleportCommand(plugin)); + commands.add(new FindCommand(plugin)); commands.add(new UpdaterentsCommand(plugin)); commands.add(new UpdatebuysCommand(plugin)); - commands.add(new RentrestoreCommand(plugin)); - commands.add(new BuyrestoreCommand(plugin)); - commands.add(new RentpriceCommand(plugin)); - commands.add(new BuypriceCommand(plugin)); + commands.add(new SetrestoreCommand(plugin)); + commands.add(new SetpriceCommand(plugin)); commands.add(new RentdurationCommand(plugin)); commands.add(new ReloadCommand(plugin)); + commands.add(new GroupaddCommand(plugin)); + commands.add(new GroupdelCommand(plugin)); + commands.add(new GrouplistCommand(plugin)); + commands.add(new GroupinfoCommand(plugin)); + commands.add(new SchematiceventCommand(plugin)); + commands.add(new AddCommand(plugin)); + commands.add(new DelCommand(plugin)); + commands.add(new AddsignCommand(plugin)); + commands.add(new DelsignCommand(plugin)); /* Register commands in bukkit */ plugin.getCommand("AreaShop").setExecutor(this); @@ -87,7 +105,11 @@ public class CommandManager implements CommandExecutor, TabCompleter { /* Send the messages to the target */ for(String message : messages) { - target.sendMessage(plugin.fixColors(message)); + if(!plugin.config().getBoolean("useColorsInConsole") && !(target instanceof Player)) { + target.sendMessage(ChatColor.stripColor(plugin.fixColors(message))); + } else { + target.sendMessage(plugin.fixColors(message)); + } } } diff --git a/AreaShop/src/nl/evolutioncoding/AreaShop/FileManager.java b/AreaShop/src/nl/evolutioncoding/AreaShop/FileManager.java index 2a4521a..522670b 100644 --- a/AreaShop/src/nl/evolutioncoding/AreaShop/FileManager.java +++ b/AreaShop/src/nl/evolutioncoding/AreaShop/FileManager.java @@ -17,18 +17,27 @@ import java.util.List; import nl.evolutioncoding.AreaShop.Exceptions.RegionCreateException; import nl.evolutioncoding.AreaShop.regions.BuyRegion; import nl.evolutioncoding.AreaShop.regions.GeneralRegion; +import nl.evolutioncoding.AreaShop.regions.GeneralRegion.RegionEvent; +import nl.evolutioncoding.AreaShop.regions.GeneralRegion.RegionType; import nl.evolutioncoding.AreaShop.regions.RegionGroup; import nl.evolutioncoding.AreaShop.regions.RentRegion; import org.bukkit.Bukkit; +import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.OfflinePlayer; +import org.bukkit.World; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import com.google.common.io.Files; -import com.sk89q.worldguard.protection.flags.DefaultFlag; +import com.sk89q.worldedit.BlockVector; +import com.sk89q.worldedit.bukkit.selections.CuboidSelection; +import com.sk89q.worldedit.bukkit.selections.Selection; +import com.sk89q.worldguard.protection.ApplicableRegionSet; +import com.sk89q.worldguard.protection.managers.RegionManager; +import com.sk89q.worldguard.protection.regions.ProtectedRegion; public class FileManager { private static FileManager instance = null; @@ -144,6 +153,10 @@ public class FileManager { return new ArrayList(regions.values()); } + /** + * Get a list of names of a certain group of things + * @return A String list with all the names + */ public List getBuyNames() { ArrayList result = new ArrayList(); for(BuyRegion region : getBuys()) { @@ -151,7 +164,6 @@ public class FileManager { } return result; } - public List getRentNames() { ArrayList result = new ArrayList(); for(RentRegion region : getRents()) { @@ -159,6 +171,20 @@ public class FileManager { } return result; } + public List getRegionNames() { + ArrayList result = new ArrayList(); + for(GeneralRegion region : getRegions()) { + result.add(region.getName()); + } + return result; + } + public List getGroupNames() { + ArrayList result = new ArrayList(); + for(RegionGroup group : getGroups()) { + result.add(group.getName()); + } + return result; + } /** * Add a rent to the list @@ -166,6 +192,9 @@ public class FileManager { * @param rent Map containing all the info for a rent */ public void addRent(RentRegion rent) { + if(rent == null) { + AreaShop.debug("Tried adding a null rent!"); + } regions.put(rent.getName().toLowerCase(), rent); rent.save(); } @@ -176,32 +205,52 @@ public class FileManager { * @param buy Map containing all the info for a buy */ public void addBuy(BuyRegion buy) { + if(buy == null) { + AreaShop.debug("Tried adding a null buy!"); + } regions.put(buy.getName().toLowerCase(), buy); buy.save(); } + public void addGroup(RegionGroup group) { + groups.put(group.getName().toLowerCase(), group); + String lowGroup = group.getName().toLowerCase(); + ConfigurationSection result = groupsConfig.getConfigurationSection(lowGroup); + if(result == null) { + result = groupsConfig.createSection(lowGroup); + groupsConfig.set(lowGroup + ".name", group.getName()); + groupsConfig.set(lowGroup + ".priority", 0); + } + saveGroups(); + } + /** * Remove a rent from the list * @param regionName */ - public boolean removeRent(String regionName, boolean giveMoneyBack) { - regionName = regionName.toLowerCase(); + public boolean removeRent(RentRegion rent, boolean giveMoneyBack) { boolean result = false; - RentRegion rent = getRent(regionName); if(rent != null) { if(rent.isRented()) { rent.unRent(giveMoneyBack); } + // Handle schematics and run commands + rent.handleSchematicEvent(RegionEvent.DELETED); + rent.runEventCommands(RegionEvent.DELETED, true); + /* Delete the sign and the variable */ if(rent.getWorld() != null) { - rent.getWorld().getBlockAt(rent.getSignLocation()).setType(Material.AIR); + for(Location sign : rent.getSignLocations()) { + sign.getBlock().setType(Material.AIR); + } } - if(rent.getRegion() != null) { - rent.getRegion().setFlag(DefaultFlag.GREET_MESSAGE, null); - rent.getRegion().setFlag(DefaultFlag.FAREWELL_MESSAGE, null); + RegionGroup[] groups = getGroups().toArray(new RegionGroup[getGroups().size()]); + for(RegionGroup group : groups) { + group.removeMember(rent); } - regions.remove(regionName); - File file = new File(plugin.getDataFolder() + File.separator + AreaShop.regionsFolder + File.separator + regionName + ".yml"); + rent.resetRegionFlags(); + regions.remove(rent.getLowerCaseName()); + File file = new File(plugin.getDataFolder() + File.separator + AreaShop.regionsFolder + File.separator + rent.getLowerCaseName() + ".yml"); boolean deleted = true; try { deleted = file.delete(); @@ -211,37 +260,60 @@ public class FileManager { if(!deleted) { plugin.getLogger().warning("File could not be deleted: " + file.toString()); } - for(RegionGroup group : getGroups()) { - group.removeMember(rent); - } + + result = true; + + // Run commands + rent.runEventCommands(RegionEvent.DELETED, false); } return result; } + /** + * Get a region by providing a location of the sign + * @param location The locatin of the sign + * @return The generalRegion that has a sign at this location + */ + public GeneralRegion getRegionBySignLocation(Location location) { + for(GeneralRegion region : getRegions()) { + if(region.isSignOfRegion(location)) { + return region; + } + } + return null; + } + /** * Remove a buy from the list * @param regionName */ - public boolean removeBuy(String regionName, boolean giveMoneyBack) { - regionName = regionName.toLowerCase(); + public boolean removeBuy(BuyRegion buy, boolean giveMoneyBack) { boolean result = false; - BuyRegion buy = getBuy(regionName); if(buy != null) { if(buy.isSold()) { buy.sell(giveMoneyBack); } + // Handle schematics and run commands + buy.handleSchematicEvent(RegionEvent.DELETED); + buy.runEventCommands(RegionEvent.DELETED, true); + // Delete the sign and the variable if(buy.getWorld() != null) { - buy.getWorld().getBlockAt(buy.getSignLocation()).setType(Material.AIR); + for(Location sign : buy.getSignLocations()) { + sign.getBlock().setType(Material.AIR); + } } - regions.remove(regionName); - if(buy.getRegion() != null) { - buy.getRegion().setFlag(DefaultFlag.GREET_MESSAGE, null); - buy.getRegion().setFlag(DefaultFlag.FAREWELL_MESSAGE, null); + regions.remove(buy.getLowerCaseName()); + buy.resetRegionFlags(); + + // Removing from groups + for(RegionGroup group : getGroups()) { + group.removeMember(buy); } + // Deleting the file - File file = new File(plugin.getDataFolder() + File.separator + AreaShop.regionsFolder + File.separator + regionName + ".yml"); + File file = new File(plugin.getDataFolder() + File.separator + AreaShop.regionsFolder + File.separator + buy.getLowerCaseName() + ".yml"); boolean deleted = true; try { deleted = file.delete(); @@ -252,15 +324,24 @@ public class FileManager { plugin.getLogger().warning("File could not be deleted: " + file.toString()); } - // Removing from groups - for(RegionGroup group : getGroups()) { - group.removeMember(buy); - } result = true; + + // Run commands + buy.runEventCommands(RegionEvent.DELETED, false); } return result; } + /** + * Remove a group + * @param group Group to remove + */ + public void removeGroup(RegionGroup group) { + groups.remove(group.getLowerCaseName()); + groupsConfig.set(group.getLowerCaseName(), null); + saveGroups(); + } + /** * Update all rent signs * @return true if all signs are updated, otherwise false @@ -393,6 +474,10 @@ public class FileManager { } } + /** + * Load all files from disk + * @return true + */ public boolean loadFiles() { boolean result = false; @@ -406,7 +491,7 @@ public class FileManager { for(File region : file.listFiles()) { if(region.isFile()) { YamlConfiguration config = YamlConfiguration.loadConfiguration(region); - if(config.isSet("rent")) { + if(RegionType.RENT.getValue().equals(config.getString("general.type"))) { try { RentRegion rent = new RentRegion(plugin, config); addRent(rent); @@ -417,12 +502,14 @@ public class FileManager { } catch(Exception e) {} } - } else if(config.isSet("buy")) { + } else if(RegionType.BUY.getValue().equals(config.getString("general.type"))) { try { BuyRegion buy = new BuyRegion(plugin, config); addBuy(buy); } catch (RegionCreateException exception) { + // This prints out a message in the console that indicates why the region cannot be created plugin.getLogger().warning(exception.getMessage()); + // Catch all exeptions because it just has to try delete the region, if it fails it does not matter try { region.delete(); } catch(Exception e) {} @@ -441,9 +528,6 @@ public class FileManager { } for(String groupName : groupsConfig.getKeys(false)) { RegionGroup group = new RegionGroup(plugin, groupName); - for(String region : groupsConfig.getConfigurationSection(groupName).getStringList("regions")) { - group.addMember(regions.get(region.toLowerCase())); - } groups.put(groupName, group); } @@ -491,6 +575,8 @@ public class FileManager { return; } + plugin.getLogger().info("Conversion to a new version of the file format starts, could take some time"); + // Convert old rent files if(rentFile.exists()) { if(!oldFolderFile.exists()) { @@ -507,7 +593,7 @@ public class FileManager { rents = (HashMap>)input.readObject(); input.close(); } catch (IOException | ClassNotFoundException | ClassCastException e) { - plugin.getLogger().warning("Error: Something went wrong reading file: " + rentPath); + plugin.getLogger().warning(" Error: Something went wrong reading file: " + rentPath); } // Delete the file if it is totally wrong if(rents == null) { @@ -519,7 +605,7 @@ public class FileManager { try { Files.move(new File(rentPath), new File(oldFolderPath + "rents")); } catch (Exception e) { - plugin.getLogger().info("Could not create a backup of '" + rentPath + "', check the file permissions (conversion to next version continues)"); + plugin.getLogger().info(" Could not create a backup of '" + rentPath + "', check the file permissions (conversion to next version continues)"); } // Check if conversion is needed if(versions.get("rents") < 1) { @@ -544,10 +630,9 @@ public class FileManager { /* Change to version 0 */ versions.put("rents", 0); } - plugin.getLogger().info("Updated version of '" + buyPath + "' from -1 to 0 (switch to using lowercase region names, adding default schematic enabling and profile)"); + plugin.getLogger().info(" Updated version of '" + buyPath + "' from -1 to 0 (switch to using lowercase region names, adding default schematic enabling and profile)"); } if(versions.get("rents") < 1) { - plugin.getLogger().info("Starting UUID conversion of '" + buyPath + "', could take a while"); for(String rentName : rents.keySet()) { HashMap rent = rents.get(rentName); if(rent.get("player") != null) { @@ -559,7 +644,7 @@ public class FileManager { /* Change version to 1 */ versions.put("rents", 1); } - plugin.getLogger().info("Updated version of '" + rentPath + "' from 0 to 1 (switch to UUID's for player identification)"); + plugin.getLogger().info(" Updated version of '" + rentPath + "' from 0 to 1 (switch to UUID's for player identification)"); } } // Save rents to new format @@ -569,27 +654,28 @@ public class FileManager { } for(HashMap rent : rents.values()) { YamlConfiguration config = new YamlConfiguration(); - config.set("name", rent.get("name").toLowerCase()); - config.set("rent.world", rent.get("world")); - config.set("rent.signLocation.world", rent.get("world")); - config.set("rent.signLocation.x", Double.parseDouble(rent.get("x"))); - config.set("rent.signLocation.y", Double.parseDouble(rent.get("y"))); - config.set("rent.signLocation.z", Double.parseDouble(rent.get("z"))); + config.set("general.name", rent.get("name").toLowerCase()); + config.set("general.type", "rent"); + config.set("general.world", rent.get("world")); + config.set("general.signs.0.location.world", rent.get("world")); + config.set("general.signs.0.location.x", Double.parseDouble(rent.get("x"))); + config.set("general.signs.0.location.y", Double.parseDouble(rent.get("y"))); + config.set("general.signs.0.location.z", Double.parseDouble(rent.get("z"))); config.set("rent.price", Double.parseDouble(rent.get("price"))); config.set("rent.duration", rent.get("duration")); if(rent.get("restore") != null && !rent.get("restore").equals("general")) { - config.set("rent.enableRestore", rent.get("restore")); + config.set("general.enableRestore", rent.get("restore")); } if(rent.get("profile") != null && !rent.get("profile").equals("default")) { - config.set("rent.restoreProfile", rent.get("profile")); + config.set("general.schematicProfile", rent.get("profile")); } if(rent.get("tpx") != null) { - config.set("rent.teleportLocation.world", rent.get("world")); - config.set("rent.teleportLocation.x", Double.parseDouble(rent.get("tpx"))); - config.set("rent.teleportLocation.y", Double.parseDouble(rent.get("tpy"))); - config.set("rent.teleportLocation.z", Double.parseDouble(rent.get("tpz"))); - config.set("rent.teleportLocation.yaw", Double.parseDouble(rent.get("tpyaw"))); - config.set("rent.teleportLocation.pitch", Double.parseDouble(rent.get("tppitch"))); + config.set("general.teleportLocation.world", rent.get("world")); + config.set("general.teleportLocation.x", Double.parseDouble(rent.get("tpx"))); + config.set("general.teleportLocation.y", Double.parseDouble(rent.get("tpy"))); + config.set("general.teleportLocation.z", Double.parseDouble(rent.get("tpz"))); + config.set("general.teleportLocation.yaw", rent.get("tpyaw")); + config.set("general.teleportLocation.pitch", rent.get("tppitch")); } if(rent.get("playeruuid") != null) { config.set("rent.renter", rent.get("playeruuid")); @@ -598,9 +684,10 @@ public class FileManager { try { config.save(new File(regionsPath + File.separator + rent.get("name").toLowerCase() + ".yml")); } catch (IOException e) { - plugin.getLogger().warning("Error: Could not save region file while converting: " + regionsPath + File.separator + rent.get("name").toLowerCase() + ".yml"); + plugin.getLogger().warning(" Error: Could not save region file while converting: " + regionsPath + File.separator + rent.get("name").toLowerCase() + ".yml"); } } + plugin.getLogger().info(" Updated rent regions to new .yml format (check the /regions folder)"); } // Change version number @@ -624,7 +711,7 @@ public class FileManager { buys = (HashMap>)input.readObject(); input.close(); } catch (IOException | ClassNotFoundException | ClassCastException e) { - plugin.getLogger().warning("Error: Something went wrong reading file: " + buyPath); + plugin.getLogger().warning(" Error: Something went wrong reading file: " + buyPath); } // Delete the file if it is totally wrong if(buys == null) { @@ -636,7 +723,7 @@ public class FileManager { try { Files.move(new File(buyPath), new File(oldFolderPath + "buys")); } catch (Exception e) { - plugin.getLogger().info("Could not create a backup of '" + buyPath + "', check the file permissions (conversion to next version continues)"); + plugin.getLogger().info(" Could not create a backup of '" + buyPath + "', check the file permissions (conversion to next version continues)"); } // Check if conversion is needed if(versions.get("buys") < 1) { @@ -661,10 +748,9 @@ public class FileManager { /* Change to version 0 */ versions.put("buys", 0); } - plugin.getLogger().info("Updated version of '" + buyPath + "' from -1 to 0 (switch to using lowercase region names, adding default schematic enabling and profile)"); + plugin.getLogger().info(" Updated version of '" + buyPath + "' from -1 to 0 (switch to using lowercase region names, adding default schematic enabling and profile)"); } if(versions.get("buys") < 1) { - plugin.getLogger().info("Starting UUID conversion of '" + buyPath + "', could take a while"); for(String buyName : buys.keySet()) { HashMap buy = buys.get(buyName); if(buy.get("player") != null) { @@ -676,7 +762,7 @@ public class FileManager { /* Change version to 1 */ versions.put("buys", 1); } - plugin.getLogger().info("Updated version of '" + buyPath + "' from 0 to 1 (switch to UUID's for player identification)"); + plugin.getLogger().info(" Updated version of '" + buyPath + "' from 0 to 1 (switch to UUID's for player identification)"); } } @@ -687,27 +773,27 @@ public class FileManager { } for(HashMap buy : buys.values()) { YamlConfiguration config = new YamlConfiguration(); - config.set("name", buy.get("name").toLowerCase()); - config.set("buy.world", buy.get("world")); - config.set("buy.signLocation.world", buy.get("world")); - config.set("buy.signLocation.x", Double.parseDouble(buy.get("x"))); - config.set("buy.signLocation.y", Double.parseDouble(buy.get("y"))); - config.set("buy.signLocation.z", Double.parseDouble(buy.get("z"))); + config.set("general.name", buy.get("name").toLowerCase()); + config.set("general.type", "buy"); + config.set("general.world", buy.get("world")); + config.set("general.signs.0.location.world", buy.get("world")); + config.set("general.signs.0.location.x", Double.parseDouble(buy.get("x"))); + config.set("general.signs.0.location.y", Double.parseDouble(buy.get("y"))); + config.set("general.signs.0.location.z", Double.parseDouble(buy.get("z"))); config.set("buy.price", Double.parseDouble(buy.get("price"))); - config.set("buy.duration", buy.get("duration")); if(buy.get("restore") != null && !buy.get("restore").equals("general")) { - config.set("buy.enableRestore", buy.get("restore")); + config.set("general.enableRestore", buy.get("restore")); } if(buy.get("profile") != null && !buy.get("profile").equals("default")) { - config.set("buy.restoreProfile", buy.get("profile")); + config.set("general.schematicProfile", buy.get("profile")); } if(buy.get("tpx") != null) { - config.set("buy.teleportLocation.world", buy.get("world")); - config.set("buy.teleportLocation.x", Double.parseDouble(buy.get("tpx"))); - config.set("buy.teleportLocation.y", Double.parseDouble(buy.get("tpy"))); - config.set("buy.teleportLocation.z", Double.parseDouble(buy.get("tpz"))); - config.set("buy.teleportLocation.yaw", Double.parseDouble(buy.get("tpyaw"))); - config.set("buy.teleportLocation.pitch", Double.parseDouble(buy.get("tppitch"))); + config.set("general.teleportLocation.world", buy.get("world")); + config.set("general.teleportLocation.x", Double.parseDouble(buy.get("tpx"))); + config.set("general.teleportLocation.y", Double.parseDouble(buy.get("tpy"))); + config.set("general.teleportLocation.z", Double.parseDouble(buy.get("tpz"))); + config.set("general.teleportLocation.yaw", buy.get("tpyaw")); + config.set("general.teleportLocation.pitch", buy.get("tppitch")); } if(buy.get("playeruuid") != null) { config.set("buy.buyer", buy.get("playeruuid")); @@ -715,9 +801,10 @@ public class FileManager { try { config.save(new File(regionsPath + File.separator + buy.get("name").toLowerCase() + ".yml")); } catch (IOException e) { - plugin.getLogger().warning("Error: Could not save region file while converting: " + regionsPath + File.separator + buy.get("name").toLowerCase() + ".yml"); + plugin.getLogger().warning(" Error: Could not save region file while converting: " + regionsPath + File.separator + buy.get("name").toLowerCase() + ".yml"); } } + plugin.getLogger().info(" Updated buy regions to new .yml format (check the /regions folder)"); } // Change version number @@ -730,7 +817,10 @@ public class FileManager { try { Files.move(new File(rentPath + ".old"), new File(oldFolderPath + "rents.old")); Files.move(new File(buyPath + ".old"), new File(oldFolderPath + "buys.old")); + Files.move(new File(plugin.getDataFolder() + File.separator + "config.yml"), new File(oldFolderPath + "config.yml")); } catch (Exception e) {} + + plugin.getLogger().info("Conversion to new version of the file format complete, this should not show up anymore next restart/reload"); } /** @@ -741,6 +831,137 @@ public class FileManager { public ConfigurationSection getGroupSettings(String groupName) { return groupsConfig.getConfigurationSection(groupName.toLowerCase()); } + + /** + * Set a setting for a group + * @param group The group to set it for + * @param path The path to set + * @param setting The value to set + */ + public void setGroupSetting(RegionGroup group, String path, Object setting) { + groupsConfig.set(group.getName().toLowerCase() + "." + path, setting); + } + + // UTILITIES + /** + * Get all AreaShop regions intersecting with a WorldEdit selection + * @param selection The selection to check + * @return A list with all the AreaShop regions intersecting with the selection + */ + public List getASRegionsInSelection(Selection selection) { + ArrayList result = new ArrayList(); + for(ProtectedRegion region : getWERegionsInSelection(selection)) { + GeneralRegion asRegion = getRegion(region.getId()); + if(asRegion != null) { + result.add(asRegion); + } + } + return result; + } + public List getASRegionsByLocation(Location location) { + Selection selection = new CuboidSelection(location.getWorld(), location, location); + return getASRegionsInSelection(selection); + } + + public List getWERegionsInSelection(Selection selection) { + // Get all regions inside or intersecting with the WorldEdit selection of the player + World world = selection.getWorld(); + RegionManager regionManager = plugin.getWorldGuard().getRegionManager(world); + ArrayList result = new ArrayList(); + Location selectionMin = selection.getMinimumPoint(); + Location selectionMax = selection.getMaximumPoint(); + for(ProtectedRegion region : regionManager.getRegions().values()) { + BlockVector regionMin = region.getMinimumPoint(); + BlockVector regionMax = region.getMaximumPoint(); + if( + ( // x part, resolves to true if the selection and region overlap anywhere on the x-axis + (regionMin.getBlockX() <= selectionMax.getBlockX() && regionMin.getBlockX() >= selectionMin.getBlockX()) + || (regionMax.getBlockX() <= selectionMax.getBlockX() && regionMax.getBlockX() >= selectionMin.getBlockX()) + || (selectionMin.getBlockX() >= regionMin.getBlockX() && selectionMin.getBlockX() <= regionMax.getBlockX()) + || (selectionMax.getBlockX() >= regionMin.getBlockX() && selectionMax.getBlockX() <= regionMax.getBlockX()) + ) && ( // Y part, resolves to true if the selection and region overlap anywhere on the y-axis + (regionMin.getBlockY() <= selectionMax.getBlockY() && regionMin.getBlockY() >= selectionMin.getBlockY()) + || (regionMax.getBlockY() <= selectionMax.getBlockY() && regionMax.getBlockY() >= selectionMin.getBlockY()) + || (selectionMin.getBlockY() >= regionMin.getBlockY() && selectionMin.getBlockY() <= regionMax.getBlockY()) + || (selectionMax.getBlockY() >= regionMin.getBlockY() && selectionMax.getBlockY() <= regionMax.getBlockY()) + ) && ( // Z part, resolves to true if the selection and region overlap anywhere on the z-axis + (regionMin.getBlockZ() <= selectionMax.getBlockZ() && regionMin.getBlockZ() >= selectionMin.getBlockZ()) + || (regionMax.getBlockZ() <= selectionMax.getBlockZ() && regionMax.getBlockZ() >= selectionMin.getBlockZ()) + || (selectionMin.getBlockZ() >= regionMin.getBlockZ() && selectionMin.getBlockZ() <= regionMax.getBlockZ()) + || (selectionMax.getBlockZ() >= regionMin.getBlockZ() && selectionMax.getBlockZ() <= regionMax.getBlockZ()) + ) + ) { + result.add(region); + } + } + return result; + } + + /** + * Get a list of regions around a location + * - Returns highest priority, child instead of parent regions + * @param location The location to check for regions + * @return empty list if no regions found, 1 member if 1 region is a priority, more if regions with the same priority + */ + public List getApplicableRegions(Location location) { + List result = new ArrayList(); + // If the secondLine does not contain a name try to find the region by location + ApplicableRegionSet regions = plugin.getWorldGuard().getRegionManager(location.getWorld()).getApplicableRegions(location); + if(regions != null) { + boolean first = true; + for(ProtectedRegion pr : regions) { + if(first) { + result.add(pr); + first = false; + } else { + if(pr.getPriority() > result.get(0).getPriority()) { + result.clear(); + result.add(pr); + } else if(pr.getParent() != null && pr.getParent().equals(result.get(0))) { + result.clear(); + result.add(pr); + } else { + result.add(pr); + } + } + } + } + return result; + } + + public List getApplicalbeASRegions(Location location) { + List result = new ArrayList(); + // If the secondLine does not contain a name try to find the region by location + ApplicableRegionSet regions = plugin.getWorldGuard().getRegionManager(location.getWorld()).getApplicableRegions(location); + if(regions != null) { + List candidates = new ArrayList(); + for(ProtectedRegion pr : regions) { + GeneralRegion region = getRegion(pr.getId()); + if(region != null) { + candidates.add(region); + } + } + boolean first = true; + for(GeneralRegion region : candidates) { + if(first) { + result.add(region); + first = false; + } else { + if(region.getRegion().getPriority() > result.get(0).getRegion().getPriority()) { + result.clear(); + result.add(region); + } else if(region.getRegion().getParent() != null && region.getRegion().getParent().equals(result.get(0))) { + result.clear(); + result.add(region); + } else { + result.add(region); + } + } + } + } + return result; + } + } diff --git a/AreaShop/src/nl/evolutioncoding/AreaShop/RightClickListener.java b/AreaShop/src/nl/evolutioncoding/AreaShop/RightClickListener.java deleted file mode 100644 index 5c0ccbd..0000000 --- a/AreaShop/src/nl/evolutioncoding/AreaShop/RightClickListener.java +++ /dev/null @@ -1,85 +0,0 @@ -package nl.evolutioncoding.AreaShop; - -import java.util.List; - -import nl.evolutioncoding.AreaShop.regions.BuyRegion; -import nl.evolutioncoding.AreaShop.regions.GeneralRegion; -import nl.evolutioncoding.AreaShop.regions.RentRegion; - -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.block.Action; -import org.bukkit.event.player.PlayerInteractEvent; - -public class RightClickListener implements Listener { - AreaShop plugin; - - /** - * Constructor - * @param plugin The AreaShop plugin - */ - public RightClickListener(AreaShop plugin) { - this.plugin = plugin; - } - - /** - * Called when a player interacts - * @param event The event - */ - @EventHandler(priority = EventPriority.HIGH) - public void onRightClick(PlayerInteractEvent event) { - Block block = event.getClickedBlock(); - /* Check for clicking a sign and rightclicking */ - if(event.getAction() == Action.RIGHT_CLICK_BLOCK && (block.getType() == Material.SIGN_POST || block.getType() == Material.WALL_SIGN)) { - /* Check if the rent sign is really the same as a saved rent */ - GeneralRegion result = null; - List regions = plugin.getFileManager().getRegions(); - for(int i=0; i regions = plugin.getFileManager().getASRegionsInSelection(new CuboidSelection(event.getBlock().getWorld(), event.getBlock().getLocation(), event.getBlock().getLocation())); + if(regions.isEmpty()) { + plugin.message(player, "addsign-noRegions"); + return; + } else if(regions.size() > 1) { + plugin.message(player, "addsign-couldNotDetectSign", regions.get(0).getName(), regions.get(1).getName()); + return; + } + region = regions.get(0); + } + Sign sign = (Sign)event.getBlock().getState().getData(); + if(thirdLine == null || thirdLine.length() == 0) { + region.addSign(event.getBlock().getLocation(), event.getBlock().getType(), sign.getFacing(), null); + plugin.message(player, "addsign-success", region.getName()); + } else { + region.addSign(event.getBlock().getLocation(), event.getBlock().getType(), sign.getFacing(), thirdLine); + plugin.message(player, "addsign-successProfile", region.getName(), thirdLine); + } + region.save(); + + // Update the sign later because this event will do it first + final GeneralRegion regionUpdate = region; + new BukkitRunnable() { + @Override + public void run() { + regionUpdate.updateSigns(); + } + }.runTaskLater(plugin, 1); + } } } diff --git a/AreaShop/src/nl/evolutioncoding/AreaShop/SignClickListener.java b/AreaShop/src/nl/evolutioncoding/AreaShop/SignClickListener.java new file mode 100644 index 0000000..fb0966a --- /dev/null +++ b/AreaShop/src/nl/evolutioncoding/AreaShop/SignClickListener.java @@ -0,0 +1,89 @@ +package nl.evolutioncoding.AreaShop; + +import nl.evolutioncoding.AreaShop.regions.GeneralRegion; +import nl.evolutioncoding.AreaShop.regions.GeneralRegion.ClickType; + +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; + +public class SignClickListener implements Listener { + AreaShop plugin; + + /** + * Constructor + * @param plugin The AreaShop plugin + */ + public SignClickListener(AreaShop plugin) { + this.plugin = plugin; + } + + /** + * Called when a player interacts + * @param event The event + */ + @EventHandler(priority = EventPriority.HIGH) + public void onSignClick(PlayerInteractEvent event) { + Block block = event.getClickedBlock(); + /* Check for clicking a sign and rightclicking */ + if( (event.getAction() == Action.RIGHT_CLICK_BLOCK || event.getAction() == Action.LEFT_CLICK_BLOCK) + && (block.getType() == Material.SIGN_POST || block.getType() == Material.WALL_SIGN)) { + /* Check if the rent sign is really the same as a saved rent */ + GeneralRegion result = plugin.getFileManager().getRegionBySignLocation(block.getLocation()); + if(result == null) { + return; + } + String signName = result.getSignName(block.getLocation()); + Player player = event.getPlayer(); + // Get the clicktype + ClickType clickType = null; + if(player.isSneaking() && event.getAction() == Action.LEFT_CLICK_BLOCK) { + clickType = ClickType.SHIFTLEFTCLICK; + } else if(!player.isSneaking() && event.getAction() == Action.LEFT_CLICK_BLOCK) { + clickType = ClickType.LEFTCLICK; + } else if(player.isSneaking() && event.getAction() == Action.RIGHT_CLICK_BLOCK) { + clickType = ClickType.SHIFTRIGHTCLICK; + } else if(!player.isSneaking() && event.getAction() == Action.RIGHT_CLICK_BLOCK) { + clickType = ClickType.RIGHTCLICK; + } + // Run the commands + boolean runned = result.runSignCommands(signName, player, clickType); + // Only cancel event if at least one command has been executed + event.setCancelled(runned); + } + } +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/AreaShop/src/nl/evolutioncoding/AreaShop/Utils.java b/AreaShop/src/nl/evolutioncoding/AreaShop/Utils.java index ef390cf..4959c24 100644 --- a/AreaShop/src/nl/evolutioncoding/AreaShop/Utils.java +++ b/AreaShop/src/nl/evolutioncoding/AreaShop/Utils.java @@ -1,5 +1,7 @@ package nl.evolutioncoding.AreaShop; +import java.util.Collection; + import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.configuration.ConfigurationSection; @@ -59,4 +61,36 @@ public class Utils { } return result; } + + public static String createCommaSeparatedList(Collection input) { + String result = ""; + boolean first = true; + for(Object object : input) { + if(first) { + first = false; + result += object.toString(); + } else { + result += ", " + object.toString(); + } + } + return result; + } + + + } + + + + + + + + + + + + + + + diff --git a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/AddCommand.java b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/AddCommand.java new file mode 100644 index 0000000..e4dc02d --- /dev/null +++ b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/AddCommand.java @@ -0,0 +1,164 @@ +package nl.evolutioncoding.AreaShop.commands; + +import java.util.ArrayList; +import java.util.List; + +import nl.evolutioncoding.AreaShop.AreaShop; +import nl.evolutioncoding.AreaShop.Utils; +import nl.evolutioncoding.AreaShop.regions.BuyRegion; +import nl.evolutioncoding.AreaShop.regions.GeneralRegion; +import nl.evolutioncoding.AreaShop.regions.GeneralRegion.RegionEvent; +import nl.evolutioncoding.AreaShop.regions.RentRegion; + +import org.bukkit.Bukkit; +import org.bukkit.World; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import com.sk89q.worldedit.bukkit.selections.Selection; +import com.sk89q.worldguard.protection.regions.ProtectedRegion; + +public class AddCommand extends CommandAreaShop { + + public AddCommand(AreaShop plugin) { + super(plugin); + } + + @Override + public String getCommandStart() { + return "areashop add"; + } + + @Override + public String getHelp(CommandSender target) { + if(target.hasPermission("areashop.createrent") || target.hasPermission("areashop.createbuy")) { + return plugin.getLanguageManager().getLang("help-add"); + } + return null; + } + + @Override + public void execute(CommandSender sender, Command command, String[] args) { + if(args.length < 2 || args[1] == null || (!"rent".equals(args[1].toLowerCase()) && !"buy".equals(args[1].toLowerCase()))) { + plugin.message(sender, "add-help"); + return; + } + boolean isRent = "rent".equals(args[1].toLowerCase()); + if((isRent && !sender.hasPermission("areashop.createrent")) || (!isRent && !sender.hasPermission("areashop.createbuy"))) { + plugin.message(sender, "add-noPermission"); + return; + } + List regions = new ArrayList(); + World world = null; + if(args.length == 2) { + if(!(sender instanceof Player)) { + plugin.message(sender, "cmd-weOnlyByPlayer"); + return; + } + Player player = (Player)sender; + Selection selection = plugin.getWorldEdit().getSelection(player); + if(selection == null) { + plugin.message(player, "cmd-noSelection"); + return; + } + world = selection.getWorld(); + regions = plugin.getFileManager().getWERegionsInSelection(selection); + if(regions.size() == 0) { + plugin.message(player, "cmd-noWERegionsFound"); + return; + } + } else { + if(sender instanceof Player) { + if(args.length == 4) { + world = Bukkit.getWorld(args[3]); + if(world == null) { + plugin.message(sender, "add-incorrectWorld", args[3]); + return; + } + } else { + world = ((Player)sender).getWorld(); + } + } else { + if(args.length < 4) { + plugin.message(sender, "add-specifyWorld"); + return; + } else { + world = Bukkit.getWorld(args[3]); + if(world == null) { + plugin.message(sender, "add-incorrectWorld", args[3]); + return; + } + } + } + ProtectedRegion region = plugin.getWorldGuard().getRegionManager(world).getRegion(args[2]); + if(region == null) { + plugin.message(sender, "add-noRegion", args[2]); + return; + } + regions.add(region); + } + + ArrayList namesSuccess = new ArrayList(); + ArrayList namesFailed = new ArrayList(); + for(ProtectedRegion region : regions) { + GeneralRegion asRegion = plugin.getFileManager().getRegion(region.getId()); + if(asRegion != null) { + namesFailed.add(region.getId()); + } else { + namesSuccess.add(region.getId()); + if(isRent) { + RentRegion rent = new RentRegion(plugin, region.getId(), world); + // Run commands + rent.runEventCommands(RegionEvent.CREATED, true); + plugin.getFileManager().addRent(rent); + rent.handleSchematicEvent(RegionEvent.CREATED); + // Set the flags for the region + rent.updateRegionFlags(); + // Run commands + rent.runEventCommands(RegionEvent.CREATED, false); + } else { + BuyRegion buy = new BuyRegion(plugin, region.getId(), world); + // Run commands + buy.runEventCommands(RegionEvent.CREATED, true); + + plugin.getFileManager().addBuy(buy); + buy.handleSchematicEvent(RegionEvent.CREATED); + // Set the flags for the region + buy.updateRegionFlags(); + // Run commands + buy.runEventCommands(RegionEvent.CREATED, false); + } + } + } + if(namesSuccess.size() != 0) { + plugin.message(sender, "add-success", args[1], Utils.createCommaSeparatedList(namesSuccess)); + } + if(namesFailed.size() != 0) { + plugin.message(sender, "add-failed", Utils.createCommaSeparatedList(namesFailed)); + } + } + + @Override + public List getTabCompleteList(int toComplete, String[] start) { + List result = new ArrayList(); + if(toComplete == 2) { + result.add("rent"); + result.add("buy"); + } else if(toComplete == 3) { + // can't get the world so also can't get applicable regions + } + return result; + } + +} + + + + + + + + + + diff --git a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/AddsignCommand.java b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/AddsignCommand.java new file mode 100644 index 0000000..268d99f --- /dev/null +++ b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/AddsignCommand.java @@ -0,0 +1,132 @@ +package nl.evolutioncoding.AreaShop.commands; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +import nl.evolutioncoding.AreaShop.AreaShop; +import nl.evolutioncoding.AreaShop.Utils; +import nl.evolutioncoding.AreaShop.regions.GeneralRegion; + +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.material.Sign; +import org.bukkit.util.BlockIterator; + +import com.sk89q.worldedit.bukkit.selections.CuboidSelection; + +public class AddsignCommand extends CommandAreaShop { + + public AddsignCommand(AreaShop plugin) { + super(plugin); + } + + @Override + public String getCommandStart() { + return "areashop addsign"; + } + + @Override + public String getHelp(CommandSender target) { + if(target.hasPermission("areashop.addsign")) { + return plugin.getLanguageManager().getLang("help-addsign"); + } + return null; + } + + @Override + public void execute(CommandSender sender, Command command, String[] args) { + if (!(sender instanceof Player)) { + plugin.message(sender, "cmd-onlyByPlayer"); + return; + } + Player player = (Player)sender; + if(!player.hasPermission("areashop.addsign")) { + plugin.message(sender, "addsign-noPermission"); + return; + } + // Get the sign + Block block = null; + BlockIterator blockIterator = new BlockIterator(player, 100); + while(blockIterator.hasNext() && block == null) { + Block next = blockIterator.next(); + if(next.getType() != Material.AIR) { + block = next; + } + } + if(block == null || !(block.getType() == Material.WALL_SIGN || block.getType() == Material.SIGN_POST)) { + plugin.message(sender, "addsign-noSign"); + return; + } + + GeneralRegion region = null; + if(args.length > 1) { + // Get region by argument + region = plugin.getFileManager().getRegion(args[1]); + if(region == null) { + plugin.message(sender, "addsign-noRegion", args[1]); + return; + } + } else { + // Get region by sign position + List regions = plugin.getFileManager().getASRegionsInSelection(new CuboidSelection(block.getWorld(), block.getLocation(), block.getLocation())); + if(regions.isEmpty()) { + plugin.message(sender, "addsign-noRegions"); + return; + } else if(regions.size() > 1) { + plugin.message(sender, "addsign-couldNotDetect", regions.get(0).getName(), regions.get(1).getName()); + return; + } + region = regions.get(0); + } + Sign sign = (Sign)block.getState().getData(); + String profile = null; + if(args.length > 2) { + profile = args[2]; + Set profiles = plugin.config().getConfigurationSection("signProfiles").getKeys(false); + if(!profiles.contains(profile)) { + plugin.message(sender, "addsign-wrongProfile", Utils.createCommaSeparatedList(profiles)); + return; + } + } + GeneralRegion signRegion = plugin.getFileManager().getRegionBySignLocation(block.getLocation()); + if(signRegion != null) { + plugin.message(sender, "addsign-alreadyRegistered", signRegion.getName()); + return; + } + + region.addSign(block.getLocation(), block.getType(), sign.getFacing(), profile); + if(profile == null) { + plugin.message(sender, "addsign-success", region.getName()); + } else { + plugin.message(sender, "addsign-successProfile", region.getName(), profile); + } + region.updateSigns(); + region.save(); + } + + @Override + public List getTabCompleteList(int toComplete, String[] start) { + List result = new ArrayList(); + if(toComplete == 2) { + result.addAll(plugin.getFileManager().getRegionNames()); + } else if(toComplete == 3) { + result.addAll(plugin.config().getStringList("signProfiles")); + } + return result; + } + +} + + + + + + + + + + diff --git a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/BuyCommand.java b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/BuyCommand.java index 06c9e99..5ca192e 100644 --- a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/BuyCommand.java +++ b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/BuyCommand.java @@ -5,6 +5,7 @@ import java.util.List; import nl.evolutioncoding.AreaShop.AreaShop; import nl.evolutioncoding.AreaShop.regions.BuyRegion; +import nl.evolutioncoding.AreaShop.regions.GeneralRegion; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; @@ -32,7 +33,7 @@ public class BuyCommand extends CommandAreaShop { @Override public void execute(CommandSender sender, Command command, String[] args) { if (!(sender instanceof Player)) { - plugin.message(sender, "onlyByPlayer"); + plugin.message(sender, "cmd-onlyByPlayer"); return; } Player player = (Player)sender; @@ -44,7 +45,17 @@ public class BuyCommand extends CommandAreaShop { region.buy(player); } } else { - plugin.message(player, "buy-help"); + // get the region by location + List regions = plugin.getFileManager().getApplicalbeASRegions(player.getLocation()); + if(regions.size() != 1) { + plugin.message(sender, "buy-help"); + } else { + if(!regions.get(0).isRentRegion()) { + plugin.message(sender, "buy-notBuyable"); + } else { + ((BuyRegion)regions.get(0)).buy(player); + } + } } } diff --git a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/BuypriceCommand.java b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/BuypriceCommand.java deleted file mode 100644 index 238eb6e..0000000 --- a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/BuypriceCommand.java +++ /dev/null @@ -1,93 +0,0 @@ -package nl.evolutioncoding.AreaShop.commands; - -import java.util.ArrayList; -import java.util.List; - -import nl.evolutioncoding.AreaShop.AreaShop; -import nl.evolutioncoding.AreaShop.regions.BuyRegion; - -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; - -public class BuypriceCommand extends CommandAreaShop { - - public BuypriceCommand(AreaShop plugin) { - super(plugin); - } - - @Override - public String getCommandStart() { - return "areashop buyprice"; - } - - @Override - public String getHelp(CommandSender target) { - if(target.hasPermission("areashop.buyprice")) { - return plugin.getLanguageManager().getLang("help-buyprice"); - } - return null; - } - - @Override - public void execute(CommandSender sender, Command command, String[] args) { - if(!sender.hasPermission("areashop.buyprice")) { - plugin.message(sender, "buyprice-noPermission"); - return; - } - - if(args.length < 3 || args[1] == null || args[2] == null) { - plugin.message(sender, "buyprice-help"); - return; - } - - BuyRegion buy = plugin.getFileManager().getBuy(args[1]); - if(buy == null) { - plugin.message(sender, "buyprice-notRegistered", args[1]); - return; - } - - double price = 0.0; - try { - price = Double.parseDouble(args[2]); - } catch(NumberFormatException e) { - plugin.message(sender, "buyprice-wrongPrice", args[2]); - return; - } - - buy.setPrice(price); - buy.save(); - plugin.message(sender, "buyprice-success", buy.getName(), args[2]); - } - - @Override - public List getTabCompleteList(int toComplete, String[] start) { - List result = new ArrayList(); - if(toComplete == 2) { - result = plugin.getFileManager().getBuyNames(); - } - return result; - } - -} - - - - - - - - - - - - - - - - - - - - - - diff --git a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/BuyrestoreCommand.java b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/BuyrestoreCommand.java deleted file mode 100644 index 2670d6f..0000000 --- a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/BuyrestoreCommand.java +++ /dev/null @@ -1,95 +0,0 @@ -package nl.evolutioncoding.AreaShop.commands; - -import java.util.ArrayList; -import java.util.List; - -import nl.evolutioncoding.AreaShop.AreaShop; -import nl.evolutioncoding.AreaShop.regions.BuyRegion; - -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; - -public class BuyrestoreCommand extends CommandAreaShop { - - public BuyrestoreCommand(AreaShop plugin) { - super(plugin); - } - - @Override - public String getCommandStart() { - return "areashop buyrestore"; - } - - @Override - public String getHelp(CommandSender target) { - if(target.hasPermission("areashop.buyrestore")) { - return plugin.getLanguageManager().getLang("help-buyrestore"); - } - return null; - } - - @Override - public void execute(CommandSender sender, Command command, String[] args) { - if(!sender.hasPermission("areashop.buyrestore")) { - plugin.message(sender, "buyrestore-noPermission"); - return; - } - if(args.length <= 2 || args[1] == null || args[2] == null) { - plugin.message(sender, "buyrestore-help"); - return; - } - BuyRegion buy = plugin.getFileManager().getBuy(args[1]); - if(buy == null) { - plugin.message(sender, "buyrestore-notRegistered", args[1]); - } else { - String value = null; - if(args[2].equalsIgnoreCase("true") || args[2].equalsIgnoreCase("false") || args[2].equalsIgnoreCase("general")) { - value = args[2].toLowerCase(); - buy.setRestoreSetting(value); - } else { - plugin.message(sender, "buyrestore-invalidSetting", args[2]); - } - if(value != null) { - if(args.length > 3) { - buy.setRestoreProfile(args[3]); - plugin.message(sender, "buyrestore-successProfile", buy.getName(), value, args[3]); - } else { - plugin.message(sender, "buyrestore-success", buy.getName(), value); - } - buy.save(); - } - } - } - - @Override - public List getTabCompleteList(int toComplete, String[] start) { - List result = new ArrayList(); - if(toComplete == 2) { - result = plugin.getFileManager().getBuyNames(); - } else if(toComplete == 3) { - result.add("true"); - result.add("false"); - result.add("general"); - } else if(toComplete == 4) { - result.addAll(plugin.config().getConfigurationSection("buySchematicProfiles").getKeys(false)); - } - return result; - } -} - - - - - - - - - - - - - - - - - diff --git a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/CommandAreaShop.java b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/CommandAreaShop.java index cab16cc..c1a44de 100644 --- a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/CommandAreaShop.java +++ b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/CommandAreaShop.java @@ -1,6 +1,5 @@ package nl.evolutioncoding.AreaShop.commands; -import java.util.ArrayList; import java.util.List; import nl.evolutioncoding.AreaShop.AreaShop; @@ -39,9 +38,7 @@ public abstract class CommandAreaShop { * @param start The already given start of the command * @return A collection with all the possibilities for argument to complete */ - public List getTabCompleteList(int toComplete, String[] start) { - return new ArrayList(); - } + public abstract List getTabCompleteList(int toComplete, String[] start); /** * Get the argument that comes after the base command that this command reacts to diff --git a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/DelCommand.java b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/DelCommand.java new file mode 100644 index 0000000..ef72c58 --- /dev/null +++ b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/DelCommand.java @@ -0,0 +1,133 @@ +package nl.evolutioncoding.AreaShop.commands; + +import java.util.ArrayList; +import java.util.List; + +import nl.evolutioncoding.AreaShop.AreaShop; +import nl.evolutioncoding.AreaShop.Utils; +import nl.evolutioncoding.AreaShop.regions.BuyRegion; +import nl.evolutioncoding.AreaShop.regions.GeneralRegion; +import nl.evolutioncoding.AreaShop.regions.RentRegion; + +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import com.sk89q.worldedit.bukkit.selections.Selection; + +public class DelCommand extends CommandAreaShop { + + public DelCommand(AreaShop plugin) { + super(plugin); + } + + @Override + public String getCommandStart() { + return "areashop del"; + } + + @Override + public String getHelp(CommandSender target) { + if(target.hasPermission("areashop.destroyrent") || target.hasPermission("areashop.destroybuy")) { + return plugin.getLanguageManager().getLang("help-del"); + } + return null; + } + + @Override + public void execute(CommandSender sender, Command command, String[] args) { + if(!sender.hasPermission("areashop.destroybuy") && !sender.hasPermission("areashop.destroyrent")) { + plugin.message(sender, "del-noPermission"); + return; + } + if(args.length < 2) { + // Only players can have a selection + if(!(sender instanceof Player)) { + plugin.message(sender, "cmd-weOnlyByPlayer"); + return; + } + Player player = (Player)sender; + Selection selection = plugin.getWorldEdit().getSelection(player); + if(selection == null) { + plugin.message(player, "cmd-noSelection"); + return; + } + List regions = plugin.getFileManager().getASRegionsInSelection(selection); + if(regions == null || regions.size() == 0) { + plugin.message(player, "cmd-noRegionsFound"); + return; + } + // Start removing the region that he has permission for + ArrayList namesSuccess = new ArrayList(); + ArrayList namesFailed = new ArrayList(); + for(GeneralRegion region : regions) { + if(region.isRentRegion()) { + if(!sender.hasPermission("areashop.destroyrent")) { + namesFailed.add(region.getName()); + } else { + plugin.getFileManager().removeRent((RentRegion)region, true); + namesSuccess.add(region.getName()); + } + } else if(region.isBuyRegion()) { + if(!sender.hasPermission("areashop.destroybuy")) { + namesFailed.add(region.getName()); + } else { + plugin.getFileManager().removeBuy((BuyRegion)region, true); + namesSuccess.add(region.getName()); + } + } + } + // send messages + if(namesSuccess.size() != 0) { + plugin.message(sender, "del-success", Utils.createCommaSeparatedList(namesSuccess)); + } + if(namesFailed.size() != 0) { + plugin.message(sender, "del-failed", Utils.createCommaSeparatedList(namesFailed)); + } + } else { + GeneralRegion region = plugin.getFileManager().getRegion(args[1]); + if(region == null) { + plugin.message(sender, "del-noRegion", args[1]); + return; + } + if(region.isRentRegion()) { + /* Remove the rent if the player has permission */ + if(sender.hasPermission("areashop.destroyrent")) { + plugin.getFileManager().removeRent((RentRegion)region, true); + plugin.message(sender, "destroy-successRent", region.getName()); + } else { + plugin.message(sender, "destroy-noPermissionRent"); + } + } else if(region.isBuyRegion()) { + /* Remove the buy if the player has permission */ + if(sender.hasPermission("areashop.destroybuy")) { + plugin.getFileManager().removeBuy((BuyRegion)region, true); + plugin.message(sender, "destroy-successBuy", region.getName()); + } else { + plugin.message(sender, "destroy-noPermissionBuy"); + } + } + + } + } + + @Override + public List getTabCompleteList(int toComplete, String[] start) { + List result = new ArrayList(); + if(toComplete == 2) { + result = plugin.getFileManager().getRegionNames(); + } + return result; + } + +} + + + + + + + + + + diff --git a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/DelsignCommand.java b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/DelsignCommand.java new file mode 100644 index 0000000..cac902a --- /dev/null +++ b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/DelsignCommand.java @@ -0,0 +1,85 @@ +package nl.evolutioncoding.AreaShop.commands; + +import java.util.ArrayList; +import java.util.List; + +import nl.evolutioncoding.AreaShop.AreaShop; +import nl.evolutioncoding.AreaShop.regions.GeneralRegion; + +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.util.BlockIterator; + +public class DelsignCommand extends CommandAreaShop { + + public DelsignCommand(AreaShop plugin) { + super(plugin); + } + + @Override + public String getCommandStart() { + return "areashop delsign"; + } + + @Override + public String getHelp(CommandSender target) { + if(target.hasPermission("areashop.delsign")) { + return plugin.getLanguageManager().getLang("help-delsign"); + } + return null; + } + + @Override + public void execute(CommandSender sender, Command command, String[] args) { + if (!(sender instanceof Player)) { + plugin.message(sender, "cmd-onlyByPlayer"); + return; + } + Player player = (Player)sender; + if(!player.hasPermission("areashop.delsign")) { + plugin.message(sender, "delsign-noPermission"); + return; + } + // Get the sign + Block block = null; + BlockIterator blockIterator = new BlockIterator(player, 100); + while(blockIterator.hasNext() && block == null) { + Block next = blockIterator.next(); + if(next.getType() != Material.AIR) { + block = next; + } + } + if(block == null || !(block.getType() == Material.WALL_SIGN || block.getType() == Material.SIGN_POST)) { + plugin.message(sender, "delsign-noSign"); + return; + } + GeneralRegion region = plugin.getFileManager().getRegionBySignLocation(block.getLocation()); + if(region == null) { + plugin.message(sender, "delsign-noRegion"); + return; + } + plugin.message(sender, "delsign-success", region.getName()); + region.removeSign(block.getLocation()); + region.updateSigns(); + region.save(); + } + + @Override + public List getTabCompleteList(int toComplete, String[] start) { + return new ArrayList(); + } + +} + + + + + + + + + + diff --git a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/FindCommand.java b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/FindCommand.java new file mode 100644 index 0000000..26b4bae --- /dev/null +++ b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/FindCommand.java @@ -0,0 +1,151 @@ +package nl.evolutioncoding.AreaShop.commands; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.ArrayList; +import java.util.List; + +import nl.evolutioncoding.AreaShop.AreaShop; +import nl.evolutioncoding.AreaShop.regions.BuyRegion; +import nl.evolutioncoding.AreaShop.regions.RentRegion; + +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +public class FindCommand extends CommandAreaShop { + + public FindCommand(AreaShop plugin) { + super(plugin); + } + + @Override + public String getCommandStart() { + return "areashop find"; + } + + @Override + public String getHelp(CommandSender target) { + if(target.hasPermission("areashop.find")) { + return plugin.getLanguageManager().getLang("help-find"); + } + return null; + } + + @Override + public void execute(CommandSender sender, Command command, String[] args) { + if(!sender.hasPermission("areashop.find")) { + plugin.message(sender, "find-noPermission"); + return; + } + if (!(sender instanceof Player)) { + plugin.message(sender, "cmd-onlyByPlayer"); + return; + } + if(args.length <= 1 || args[1] == null || (!args[1].equalsIgnoreCase("buy") && !args[1].equalsIgnoreCase("rent"))) { + plugin.message(sender, "find-help"); + return; + } + Player player = (Player)sender; + double balance = plugin.getEconomy().getBalance(player); + double maxPrice = 0; + boolean maxPriceSet = false; + if(args.length == 3) { + try { + maxPrice = Double.parseDouble(args[2]); + maxPriceSet = true; + } catch(NumberFormatException e) { + plugin.message(sender, "find-wrongMaxPrice", args[2]); + return; + } + } + if(args[1].equalsIgnoreCase("buy")) { + List regions = plugin.getFileManager().getBuys(); + for(BuyRegion region : regions) { + if(!region.isSold() && ((region.getPrice() <= balance && !maxPriceSet) || (region.getPrice() <= maxPrice && maxPriceSet))) { + BigDecimal bigDecimal = new BigDecimal(balance); + bigDecimal = bigDecimal.setScale(2, RoundingMode.HALF_UP); + balance = bigDecimal.doubleValue(); + if(maxPriceSet) { + plugin.message(player, "find-successMax", "buy", region.getName(), maxPrice); + } else { + plugin.message(player, "find-success", "buy", region.getName(), balance); + } + region.teleportPlayer(player, true); + return; + } + } + BigDecimal bigDecimal = new BigDecimal(balance); + bigDecimal = bigDecimal.setScale(2, RoundingMode.HALF_UP); + balance = bigDecimal.doubleValue(); + if(maxPriceSet) { + plugin.message(player, "find-noneFound", "buy", maxPrice); + } else { + plugin.message(player, "find-noneFoundMax", "buy", balance); + } + } else { + List regions = plugin.getFileManager().getRents(); + for(RentRegion region : regions) { + if(!region.isRented() && ((region.getPrice() <= balance && !maxPriceSet) || (region.getPrice() <= maxPrice && maxPriceSet))) { + BigDecimal bigDecimal = new BigDecimal(balance); + bigDecimal = bigDecimal.setScale(2, RoundingMode.HALF_UP); + balance = bigDecimal.doubleValue(); + if(maxPriceSet) { + plugin.message(player, "find-successMax", "rent", region.getName(), maxPrice); + } else { + plugin.message(player, "find-success", "rent", region.getName(), balance); + } + region.teleportPlayer(player, true); + return; + } + } + BigDecimal bigDecimal = new BigDecimal(balance); + bigDecimal = bigDecimal.setScale(2, RoundingMode.HALF_UP); + balance = bigDecimal.doubleValue(); + if(maxPriceSet) { + plugin.message(player, "find-noneFound", "rent", maxPrice); + } else { + plugin.message(player, "find-noneFoundMax", "rent", balance); + } + } + + } + + @Override + public List getTabCompleteList(int toComplete, String[] start) { + ArrayList result = new ArrayList(); + if(toComplete == 2) { + result.add("buy"); + result.add("rent"); + } + return result; + } + +} + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/GroupaddCommand.java b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/GroupaddCommand.java new file mode 100644 index 0000000..e405d9d --- /dev/null +++ b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/GroupaddCommand.java @@ -0,0 +1,117 @@ +package nl.evolutioncoding.AreaShop.commands; + +import java.util.ArrayList; +import java.util.List; + +import nl.evolutioncoding.AreaShop.AreaShop; +import nl.evolutioncoding.AreaShop.Utils; +import nl.evolutioncoding.AreaShop.regions.GeneralRegion; +import nl.evolutioncoding.AreaShop.regions.RegionGroup; + +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import com.sk89q.worldedit.bukkit.selections.Selection; + +public class GroupaddCommand extends CommandAreaShop { + + public GroupaddCommand(AreaShop plugin) { + super(plugin); + } + + @Override + public String getCommandStart() { + return "areashop groupadd"; + } + + @Override + public String getHelp(CommandSender target) { + if(target.hasPermission("areashop.groupadd")) { + return plugin.getLanguageManager().getLang("help-groupadd"); + } + return null; + } + + @Override + public void execute(CommandSender sender, Command command, String[] args) { + if(!sender.hasPermission("areashop.groupadd")) { + plugin.message(sender, "groupadd-noPermission"); + return; + } + if(args.length < 2 || args[1] == null) { + plugin.message(sender, "groupadd-help"); + return; + } + RegionGroup group = plugin.getFileManager().getGroup(args[1]); + if(group == null) { + group = new RegionGroup(plugin, args[1]); + plugin.getFileManager().addGroup(group); + } + if(args.length == 2) { + if(!(sender instanceof Player)) { + plugin.message(sender, "cmd-weOnlyByPlayer"); + return; + } + Player player = (Player)sender; + Selection selection = plugin.getWorldEdit().getSelection(player); + if(selection == null) { + plugin.message(player, "cmd-noSelection"); + return; + } + List regions = plugin.getFileManager().getASRegionsInSelection(selection); + if(regions.size() == 0) { + plugin.message(player, "cmd-noRegionsFound"); + return; + } + ArrayList namesSuccess = new ArrayList(); + ArrayList namesFailed = new ArrayList(); + for(GeneralRegion region : regions) { + if(group.addMember(region)) { + namesSuccess.add(region.getName()); + } else { + namesFailed.add(region.getName()); + } + } + if(namesSuccess.size() != 0) { + plugin.message(player, "groupadd-weSuccess", group.getName(), Utils.createCommaSeparatedList(namesSuccess)); + } + if(namesFailed.size() != 0) { + plugin.message(player, "groupadd-weFailed", group.getName(), Utils.createCommaSeparatedList(namesFailed)); + } + } else { + GeneralRegion region = plugin.getFileManager().getRegion(args[2]); + if(region == null) { + plugin.message(sender, "groupadd-noRegion", args[2]); + return; + } + if(group.addMember(region)) { + plugin.message(sender, "groupadd-success", region.getName(), group.getName(), group.getMembers().size()); + } else { + plugin.message(sender, "groupadd-failed", region.getName(), group.getName()); + } + } + } + + @Override + public List getTabCompleteList(int toComplete, String[] start) { + List result = new ArrayList(); + if(toComplete == 2) { + result = plugin.getFileManager().getGroupNames(); + } else if(toComplete == 3) { + result = plugin.getFileManager().getRegionNames(); + } + return result; + } + +} + + + + + + + + + + diff --git a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/GroupdelCommand.java b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/GroupdelCommand.java new file mode 100644 index 0000000..884d0ba --- /dev/null +++ b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/GroupdelCommand.java @@ -0,0 +1,117 @@ +package nl.evolutioncoding.AreaShop.commands; + +import java.util.ArrayList; +import java.util.List; + +import nl.evolutioncoding.AreaShop.AreaShop; +import nl.evolutioncoding.AreaShop.Utils; +import nl.evolutioncoding.AreaShop.regions.GeneralRegion; +import nl.evolutioncoding.AreaShop.regions.RegionGroup; + +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import com.sk89q.worldedit.bukkit.selections.Selection; + +public class GroupdelCommand extends CommandAreaShop { + + public GroupdelCommand(AreaShop plugin) { + super(plugin); + } + + @Override + public String getCommandStart() { + return "areashop groupdel"; + } + + @Override + public String getHelp(CommandSender target) { + if(target.hasPermission("areashop.groupdel")) { + return plugin.getLanguageManager().getLang("help-groupdel"); + } + return null; + } + + @Override + public void execute(CommandSender sender, Command command, String[] args) { + if(!sender.hasPermission("areashop.groupdel")) { + plugin.message(sender, "groupdel-noPermission"); + return; + } + if(args.length < 2 || args[1] == null) { + plugin.message(sender, "groupdel-help"); + return; + } + RegionGroup group = plugin.getFileManager().getGroup(args[1]); + if(group == null) { + group = new RegionGroup(plugin, args[1]); + plugin.getFileManager().addGroup(group); + } + if(args.length == 2) { + if(!(sender instanceof Player)) { + plugin.message(sender, "cmd-weOnlyByPlayer"); + return; + } + Player player = (Player)sender; + Selection selection = plugin.getWorldEdit().getSelection(player); + if(selection == null) { + plugin.message(player, "cmd-noSelection"); + return; + } + List regions = plugin.getFileManager().getASRegionsInSelection(selection); + if(regions.size() == 0) { + plugin.message(player, "cmd-noRegionsFound"); + return; + } + ArrayList namesSuccess = new ArrayList(); + ArrayList namesFailed = new ArrayList(); + for(GeneralRegion region : regions) { + if(group.removeMember(region)) { + namesSuccess.add(region.getName()); + } else { + namesFailed.add(region.getName()); + } + } + if(namesSuccess.size() != 0) { + plugin.message(player, "groupdel-weSuccess", group.getName(), Utils.createCommaSeparatedList(namesSuccess)); + } + if(namesFailed.size() != 0) { + plugin.message(player, "groupdel-weFailed", group.getName(), Utils.createCommaSeparatedList(namesFailed)); + } + } else { + GeneralRegion region = plugin.getFileManager().getRegion(args[2]); + if(region == null) { + plugin.message(sender, "groupdel-noRegion", args[2]); + return; + } + if(group.removeMember(region)) { + plugin.message(sender, "groupdel-success", region.getName(), group.getName(), group.getMembers().size()); + } else { + plugin.message(sender, "groupdel-failed", region.getName(), group.getName()); + } + } + } + + @Override + public List getTabCompleteList(int toComplete, String[] start) { + List result = new ArrayList(); + if(toComplete == 2) { + result = plugin.getFileManager().getGroupNames(); + } else if(toComplete == 3) { + result = plugin.getFileManager().getRegionNames(); + } + return result; + } + +} + + + + + + + + + + diff --git a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/GroupinfoCommand.java b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/GroupinfoCommand.java new file mode 100644 index 0000000..856a56b --- /dev/null +++ b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/GroupinfoCommand.java @@ -0,0 +1,75 @@ +package nl.evolutioncoding.AreaShop.commands; + +import java.util.ArrayList; +import java.util.List; + +import nl.evolutioncoding.AreaShop.AreaShop; +import nl.evolutioncoding.AreaShop.Utils; +import nl.evolutioncoding.AreaShop.regions.RegionGroup; + +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; + +public class GroupinfoCommand extends CommandAreaShop { + + public GroupinfoCommand(AreaShop plugin) { + super(plugin); + } + + @Override + public String getCommandStart() { + return "areashop groupinfo"; + } + + @Override + public String getHelp(CommandSender target) { + if(target.hasPermission("areashop.groupinfo")) { + return plugin.getLanguageManager().getLang("help-groupinfo"); + } + return null; + } + + + @Override + public void execute(CommandSender sender, Command command, String[] args) { + if(!sender.hasPermission("areashop.groupinfo")) { + plugin.message(sender, "groupinfo-noPermission"); + return; + } + if(args.length < 2 || args[1] == null) { + plugin.message(sender, "groupinfo-help"); + return; + } + RegionGroup group = plugin.getFileManager().getGroup(args[1]); + if(group == null) { + plugin.message(sender, "groupinfo-noGroup", args[1]); + return; + } + List members = group.getMembers(); + if(members.size() == 0) { + plugin.message(sender, "groupinfo-noMembers", group.getName()); + } else { + plugin.message(sender, "groupinfo-members", group.getName(), Utils.createCommaSeparatedList(members)); + } + } + + @Override + public List getTabCompleteList(int toComplete, String[] start) { + List result = new ArrayList(); + if(toComplete == 2) { + result = plugin.getFileManager().getGroupNames(); + } + return result; + } + +} + + + + + + + + + + diff --git a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/GrouplistCommand.java b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/GrouplistCommand.java new file mode 100644 index 0000000..0bfc4ed --- /dev/null +++ b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/GrouplistCommand.java @@ -0,0 +1,60 @@ +package nl.evolutioncoding.AreaShop.commands; + +import java.util.ArrayList; +import java.util.List; + +import nl.evolutioncoding.AreaShop.AreaShop; +import nl.evolutioncoding.AreaShop.Utils; + +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; + +public class GrouplistCommand extends CommandAreaShop { + + public GrouplistCommand(AreaShop plugin) { + super(plugin); + } + + @Override + public String getCommandStart() { + return "areashop grouplist"; + } + + @Override + public String getHelp(CommandSender target) { + if(target.hasPermission("areashop.grouplist")) { + return plugin.getLanguageManager().getLang("help-grouplist"); + } + return null; + } + + @Override + public void execute(CommandSender sender, Command command, String[] args) { + if(!sender.hasPermission("areashop.grouplist")) { + plugin.message(sender, "grouplist-noPermission"); + return; + } + List groups = plugin.getFileManager().getGroupNames(); + if(groups.size() == 0) { + plugin.message(sender, "grouplist-noGroups"); + } else { + plugin.message(sender, "grouplist-success", Utils.createCommaSeparatedList(groups)); + } + } + + @Override + public List getTabCompleteList(int toComplete, String[] start) { + return new ArrayList(); + } + +} + + + + + + + + + + diff --git a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/HelpCommand.java b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/HelpCommand.java index af69e64..6b82d59 100644 --- a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/HelpCommand.java +++ b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/HelpCommand.java @@ -1,5 +1,8 @@ package nl.evolutioncoding.AreaShop.commands; +import java.util.ArrayList; +import java.util.List; + import nl.evolutioncoding.AreaShop.AreaShop; import org.bukkit.command.Command; @@ -28,5 +31,11 @@ public class HelpCommand extends CommandAreaShop { public void execute(CommandSender sender, Command command, String[] args) { plugin.getCommandManager().showHelp(sender); } + + @Override + public List getTabCompleteList(int toComplete, String[] start) { + ArrayList result = new ArrayList(); + return result; + } } diff --git a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/InfoCommand.java b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/InfoCommand.java index e2084bb..4a5009e 100644 --- a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/InfoCommand.java +++ b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/InfoCommand.java @@ -8,10 +8,13 @@ import java.util.Iterator; import java.util.List; import nl.evolutioncoding.AreaShop.AreaShop; +import nl.evolutioncoding.AreaShop.Utils; import nl.evolutioncoding.AreaShop.regions.BuyRegion; +import nl.evolutioncoding.AreaShop.regions.GeneralRegion; import nl.evolutioncoding.AreaShop.regions.RentRegion; import org.bukkit.Bukkit; +import org.bukkit.Location; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -198,43 +201,78 @@ public class InfoCommand extends CommandAreaShop { plugin.message(sender, "info-playerHelp"); } } else if(args[1].equalsIgnoreCase("region")) { - if(args.length > 2 && args[2] != null) { - - RentRegion rent = plugin.getFileManager().getRent(args[2]); - BuyRegion buy = plugin.getFileManager().getBuy(args[2]); - - if(rent == null) { - plugin.message(sender, "info-regionRenting", args[2]); - plugin.message(sender, "info-regionNoRenting", args[2]); + if(args.length > 1) { + RentRegion rent = null; + BuyRegion buy = null; + if(args.length > 2) { + rent = plugin.getFileManager().getRent(args[2]); + buy = plugin.getFileManager().getBuy(args[2]); } else { + if(sender instanceof Player) { + // get the region by location + List regions = plugin.getFileManager().getApplicalbeASRegions(((Player)sender).getLocation()); + if(regions.size() != 1) { + plugin.message(sender, "info-regionHelp"); + return; + } else { + if(regions.get(0).isRentRegion()) { + rent = (RentRegion)regions.get(0); + } else if(regions.get(0).isBuyRegion()) { + buy = (BuyRegion)regions.get(0); + } + } + } else { + plugin.message(sender, "info-regionHelp"); + return; + } + } + + if(rent == null && buy == null) { + plugin.message(sender, "info-regionNotExisting", args[2]); + return; + } + if(rent != null) { plugin.message(sender, "info-regionRenting", rent.getName()); - plugin.message(sender, "info-regionSign", rent.getWorldName(), rent.getSignLocation().getBlockX(), rent.getSignLocation().getBlockY(), rent.getSignLocation().getBlockZ()); + List signLocations = new ArrayList(); + for(Location location : rent.getSignLocations()) { + signLocations.add(plugin.getLanguageManager().getLang("info-regionSignLocation", location.getWorld().getName(), location.getBlockX(), location.getBlockY(), location.getBlockZ())); + } + if(signLocations.isEmpty()) { + plugin.message(sender, "info-regionNoSign"); + } else { + plugin.message(sender, "info-regionSign", Utils.createCommaSeparatedList(signLocations)); + } plugin.message(sender, "info-regionPriceDuration", rent.getFormattedPrice(), rent.getDurationString()); if(!rent.isRented()) { plugin.message(sender, "info-regionNotRented"); } else { - SimpleDateFormat dateFull = new SimpleDateFormat("dd MMMMMMMMMMMMMMMMM yyyy HH:mm"); - plugin.message(sender, "info-regionRentedBy", rent.getPlayerName(), dateFull.format(rent.getDuration())); + SimpleDateFormat dateFull = new SimpleDateFormat(plugin.config().getString("timeFormatChat")); + plugin.message(sender, "info-regionRentedBy", rent.getPlayerName(), dateFull.format(rent.getRentedUntil())); } if(sender.hasPermission("areashop.rentrestore")) { - plugin.message(sender, "info-regionRestore", rent.getRestoreSetting()); + plugin.message(sender, "info-regionRestore", rent.isRestoreEnabled()); plugin.message(sender, "info-regionRestoreProfile", rent.getRestoreProfile()); } if(sender.hasPermission("areashop.teleport")) { if(rent.getTeleportLocation() == null) { plugin.message(sender, "info-regionNoTP"); } else { - plugin.message(sender, "info-regionTPLocation", rent.getTeleportLocation().getWorld().toString(), rent.getTeleportLocation().getBlockX(), rent.getTeleportLocation().getBlockY(), rent.getTeleportLocation().getBlockZ(), rent.getTeleportLocation().getPitch(), rent.getTeleportLocation().getYaw()); + plugin.message(sender, "info-regionTPLocation", rent.getTeleportLocation().getWorld().getName(), rent.getTeleportLocation().getBlockX(), rent.getTeleportLocation().getBlockY(), rent.getTeleportLocation().getBlockZ(), rent.getTeleportLocation().getPitch(), rent.getTeleportLocation().getYaw()); } } } - if(buy == null) { - plugin.message(sender, "info-regionBuying", args[2]); - plugin.message(sender, "info-regionNoBuying", args[2]); - } else { + if(buy != null) { plugin.message(sender, "info-regionBuying", buy.getName()); - plugin.message(sender, "info-regionSign", buy.getWorldName(), buy.getSignLocation().getBlockX(), buy.getSignLocation().getBlockY(), buy.getSignLocation().getBlockZ()); + List signLocations = new ArrayList(); + for(Location location : buy.getSignLocations()) { + signLocations.add(plugin.getLanguageManager().getLang("info-regionSignLocation", location.getWorld().getName(), location.getBlockX(), location.getBlockY(), location.getBlockZ())); + } + if(signLocations.isEmpty()) { + plugin.message(sender, "info-regionNoSign"); + } else { + plugin.message(sender, "info-regionSign", Utils.createCommaSeparatedList(signLocations)); + } plugin.message(sender, "info-regionPrice", buy.getFormattedPrice()); if(!buy.isSold()) { plugin.message(sender, "info-regionNotBought"); @@ -242,7 +280,7 @@ public class InfoCommand extends CommandAreaShop { plugin.message(sender, "info-regionBoughtBy", buy.getPlayerName()); } if(sender.hasPermission("areashop.buyrestore")) { - plugin.message(sender, "info-regionRestore", buy.getRestoreSetting()); + plugin.message(sender, "info-regionRestore", buy.isRestoreEnabled()); plugin.message(sender, "info-regionRestoreProfile", buy.getRestoreProfile()); } if(sender.hasPermission("areashop.teleport")) { diff --git a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/ReloadCommand.java b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/ReloadCommand.java index f016634..78a953a 100644 --- a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/ReloadCommand.java +++ b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/ReloadCommand.java @@ -1,5 +1,8 @@ package nl.evolutioncoding.AreaShop.commands; +import java.util.ArrayList; +import java.util.List; + import nl.evolutioncoding.AreaShop.AreaShop; import org.bukkit.command.Command; @@ -33,5 +36,11 @@ public class ReloadCommand extends CommandAreaShop { plugin.message(sender, "reload-noPermission"); } } + + @Override + public List getTabCompleteList(int toComplete, String[] start) { + ArrayList result = new ArrayList(); + return result; + } } diff --git a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/RentCommand.java b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/RentCommand.java index b171304..8b5b07b 100644 --- a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/RentCommand.java +++ b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/RentCommand.java @@ -4,6 +4,7 @@ import java.util.ArrayList; import java.util.List; import nl.evolutioncoding.AreaShop.AreaShop; +import nl.evolutioncoding.AreaShop.regions.GeneralRegion; import nl.evolutioncoding.AreaShop.regions.RentRegion; import org.bukkit.command.Command; @@ -32,7 +33,7 @@ public class RentCommand extends CommandAreaShop { @Override public void execute(CommandSender sender, Command command, String[] args) { if (!(sender instanceof Player)) { - plugin.message(sender, "onlyByPlayer"); + plugin.message(sender, "cmd-onlyByPlayer"); return; } Player player = (Player)sender; @@ -44,7 +45,17 @@ public class RentCommand extends CommandAreaShop { rent.rent(player); } } else { - plugin.message(sender, "rent-help"); + // get the region by location + List regions = plugin.getFileManager().getApplicalbeASRegions(player.getLocation()); + if(regions.size() != 1) { + plugin.message(sender, "rent-help"); + } else { + if(!regions.get(0).isRentRegion()) { + plugin.message(sender, "rent-notRentable"); + } else { + ((RentRegion)regions.get(0)).rent(player); + } + } } } diff --git a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/RentdurationCommand.java b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/RentdurationCommand.java index 01a9f8e..68dc497 100644 --- a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/RentdurationCommand.java +++ b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/RentdurationCommand.java @@ -54,6 +54,8 @@ public class RentdurationCommand extends CommandAreaShop { return; } rent.setDuration(args[2]+" "+args[3]); + rent.updateRegionFlags(); + rent.updateSigns(); rent.save(); plugin.message(sender, "rentduration-success", rent.getName(), rent.getDurationString()); } diff --git a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/RentpriceCommand.java b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/RentpriceCommand.java deleted file mode 100644 index 87eb3df..0000000 --- a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/RentpriceCommand.java +++ /dev/null @@ -1,67 +0,0 @@ -package nl.evolutioncoding.AreaShop.commands; - -import java.util.ArrayList; -import java.util.List; - -import nl.evolutioncoding.AreaShop.AreaShop; -import nl.evolutioncoding.AreaShop.regions.RentRegion; - -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; - -public class RentpriceCommand extends CommandAreaShop { - - public RentpriceCommand(AreaShop plugin) { - super(plugin); - } - - @Override - public String getCommandStart() { - return "areashop rentprice"; - } - - @Override - public String getHelp(CommandSender target) { - if(target.hasPermission("areashop.rentprice")) { - return plugin.getLanguageManager().getLang("help-rentprice"); - } - return null; - } - - @Override - public void execute(CommandSender sender, Command command, String[] args) { - if(!sender.hasPermission("areashop.rentprice")) { - plugin.message(sender, "rentprice-noPermission"); - return; - } - if(args.length < 3 || args[1] == null || args[2] == null) { - plugin.message(sender, "rentprice-help"); - return; - } - RentRegion rent = plugin.getFileManager().getRent(args[1]); - if(rent == null) { - plugin.message(sender, "rentprice-notRegistered", args[1]); - return; - } - double price = 0.0; - try { - price = Double.parseDouble(args[2]); - } catch(NumberFormatException e) { - plugin.message(sender, "rentprice-wrongPrice", args[2]); - return; - } - rent.setPrice(price); - rent.save(); - plugin.message(sender, "rentprice-success", rent.getName(), args[2], rent.getDurationString()); - } - - @Override - public List getTabCompleteList(int toComplete, String[] start) { - List result = new ArrayList(); - if(toComplete == 2) { - result = plugin.getFileManager().getRentNames(); - } - return result; - } - -} diff --git a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/RentrestoreCommand.java b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/RentrestoreCommand.java deleted file mode 100644 index 6e73cb7..0000000 --- a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/RentrestoreCommand.java +++ /dev/null @@ -1,77 +0,0 @@ -package nl.evolutioncoding.AreaShop.commands; - -import java.util.ArrayList; -import java.util.List; - -import nl.evolutioncoding.AreaShop.AreaShop; -import nl.evolutioncoding.AreaShop.regions.RentRegion; - -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; - -public class RentrestoreCommand extends CommandAreaShop { - - public RentrestoreCommand(AreaShop plugin) { - super(plugin); - } - - @Override - public String getCommandStart() { - return "areashop rentrestore"; - } - - @Override - public String getHelp(CommandSender target) { - if(target.hasPermission("areashop.rentrestore")) { - return plugin.getLanguageManager().getLang("help-rentrestore"); - } - return null; - } - - @Override - public void execute(CommandSender sender, Command command, String[] args) { - if(!sender.hasPermission("areashop.rentrestore")) { - plugin.message(sender, "rentrestore-noPermission"); - return; - } - if(args.length <= 2 || args[1] == null || args[2] == null) { - plugin.message(sender, "rentrestore-help"); - return; - } - RentRegion rent = plugin.getFileManager().getRent(args[1]); - if(rent == null) { - plugin.message(sender, "rentrestore-notRegistered", args[1]); - return; - } - String value = null; - if(args[2].equalsIgnoreCase("true") || args[2].equalsIgnoreCase("false") || args[2].equalsIgnoreCase("general")) { - value = args[2].toLowerCase(); - } else { - plugin.message(sender, "rentrestore-invalidSetting", args[2]); - return; - } - rent.setRestoreSetting(value); - if(args.length > 3) { - rent.setRestoreProfile(args[3]); - plugin.message(sender, "rentrestore-successProfile", rent.getName(), value, args[3]); - } else { - plugin.message(sender, "rentrestore-success", rent.getName(), value); - } - rent.save(); - } - - @Override - public List getTabCompleteList(int toComplete, String[] start) { - List result = new ArrayList(); - if(toComplete == 2) { - result = plugin.getFileManager().getRentNames(); - } else if(toComplete == 3) { - result.add("true"); - result.add("false"); - result.add("general"); - } else if(toComplete == 4) { - result.addAll(plugin.config().getConfigurationSection("rentSchematicProfiles").getKeys(false)); - } - return result; - } -} diff --git a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/SchematiceventCommand.java b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/SchematiceventCommand.java new file mode 100644 index 0000000..13229af --- /dev/null +++ b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/SchematiceventCommand.java @@ -0,0 +1,83 @@ +package nl.evolutioncoding.AreaShop.commands; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import nl.evolutioncoding.AreaShop.AreaShop; +import nl.evolutioncoding.AreaShop.Utils; +import nl.evolutioncoding.AreaShop.regions.GeneralRegion; +import nl.evolutioncoding.AreaShop.regions.GeneralRegion.RegionEvent; + +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; + +public class SchematiceventCommand extends CommandAreaShop { + + public SchematiceventCommand(AreaShop plugin) { + super(plugin); + } + + @Override + public String getCommandStart() { + return "areashop schemevent"; + } + + @Override + public String getHelp(CommandSender target) { + if(target.hasPermission("areashop.schematicevents")) { + return plugin.getLanguageManager().getLang("help-schemevent"); + } + return null; + } + + @Override + public void execute(CommandSender sender, Command command, String[] args) { + if(args.length < 3 || args[1] == null || args[2] == null) { + plugin.message(sender, "schemevent-help"); + return; + } + GeneralRegion region = plugin.getFileManager().getRegion(args[1]); + if(region == null) { + plugin.message(sender, "schemevent-noRegion", args[1]); + return; + } + + RegionEvent event = null; + boolean exception = false; + try { + event = RegionEvent.valueOf(args[2].toUpperCase()); + } catch(IllegalArgumentException e) { + exception = true; + } + // Check for a totally wrong event or a non matching event + if(exception) { + ArrayList values = new ArrayList(); + for(RegionEvent value : RegionEvent.values()) { + values.add(value.getValue().toLowerCase()); + } + plugin.message(sender, "schemevent-wrongEvent", args[2], Utils.createCommaSeparatedList(values)); + return; + } + region.handleSchematicEvent(event); + plugin.message(sender, "schemevent-success", args[2], region.getName()); + } + + @Override + public List getTabCompleteList(int toComplete, String[] start) { + ArrayList result = new ArrayList(); + if(toComplete == 2) { + result.addAll(plugin.getFileManager().getRegionNames()); + } else if(toComplete == 3) { + GeneralRegion region = plugin.getFileManager().getRegion(start[2]); + if(region != null) { + if(region.isRentRegion()) { + result.addAll(Arrays.asList("created", "deleted", "rented", "unrented")); + } else if(region.isBuyRegion()) { + result.addAll(Arrays.asList("created", "deleted", "bought", "sold")); + } + } + } + return result; + } +} diff --git a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/SellCommand.java b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/SellCommand.java index f8fe9bc..16e63e6 100644 --- a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/SellCommand.java +++ b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/SellCommand.java @@ -1,7 +1,11 @@ package nl.evolutioncoding.AreaShop.commands; +import java.util.ArrayList; +import java.util.List; + import nl.evolutioncoding.AreaShop.AreaShop; import nl.evolutioncoding.AreaShop.regions.BuyRegion; +import nl.evolutioncoding.AreaShop.regions.GeneralRegion; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; @@ -30,11 +34,26 @@ public class SellCommand extends CommandAreaShop { @Override public void execute(CommandSender sender, Command command, String[] args) { - if(args.length <= 1 || args[1] == null) { - plugin.message(sender, "sell-help"); - return; + BuyRegion buy = null; + if(args.length <= 1) { + if(sender instanceof Player) { + // get the region by location + List regions = plugin.getFileManager().getApplicalbeASRegions(((Player)sender).getLocation()); + if(regions.size() != 1) { + plugin.message(sender, "sell-help"); + return; + } else { + if(regions.get(0).isBuyRegion()) { + buy = (BuyRegion)regions.get(0); + } + } + } else { + plugin.message(sender, "sell-help"); + return; + } + } else { + buy = plugin.getFileManager().getBuy(args[1]); } - BuyRegion buy = plugin.getFileManager().getBuy(args[1]); if(buy == null) { plugin.message(sender, "sell-notRegistered"); return; @@ -59,6 +78,19 @@ public class SellCommand extends CommandAreaShop { } } } + + @Override + public List getTabCompleteList(int toComplete, String[] start) { + ArrayList result = new ArrayList(); + if(toComplete == 2) { + for(BuyRegion region : plugin.getFileManager().getBuys()) { + if(region.isSold()) { + result.add(region.getName()); + } + } + } + return result; + } } diff --git a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/SetpriceCommand.java b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/SetpriceCommand.java new file mode 100644 index 0000000..4f78103 --- /dev/null +++ b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/SetpriceCommand.java @@ -0,0 +1,94 @@ +package nl.evolutioncoding.AreaShop.commands; + +import java.util.ArrayList; +import java.util.List; + +import nl.evolutioncoding.AreaShop.AreaShop; +import nl.evolutioncoding.AreaShop.regions.BuyRegion; +import nl.evolutioncoding.AreaShop.regions.GeneralRegion; +import nl.evolutioncoding.AreaShop.regions.RentRegion; + +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +public class SetpriceCommand extends CommandAreaShop { + + public SetpriceCommand(AreaShop plugin) { + super(plugin); + } + + @Override + public String getCommandStart() { + return "areashop setprice"; + } + + @Override + public String getHelp(CommandSender target) { + if(target.hasPermission("areashop.setprice")) { + return plugin.getLanguageManager().getLang("help-setprice"); + } + return null; + } + + @Override + public void execute(CommandSender sender, Command command, String[] args) { + if(!sender.hasPermission("areashop.setprice")) { + plugin.message(sender, "setprice-noPermission"); + return; + } + if(args.length < 2 || args[1] == null) { + plugin.message(sender, "setprice-help"); + return; + } + GeneralRegion region = null; + if(args.length < 3) { + if(sender instanceof Player) { + // get the region by location + List regions = plugin.getFileManager().getApplicalbeASRegions(((Player)sender).getLocation()); + if(regions.size() != 1) { + plugin.message(sender, "setprice-help"); + return; + } else { + region = regions.get(0); + } + } else { + plugin.message(sender, "setprice-help"); + return; + } + } else { + region = plugin.getFileManager().getRegion(args[2]); + } + if(region == null) { + plugin.message(sender, "setprice-notRegistered", args[2]); + return; + } + double price = 0.0; + try { + price = Double.parseDouble(args[1]); + } catch(NumberFormatException e) { + plugin.message(sender, "setprice-wrongPrice", args[1]); + return; + } + if(region.isRentRegion()) { + ((RentRegion)region).setPrice(price); + plugin.message(sender, "setprice-successRent", region.getName(), ((RentRegion)region).getFormattedPrice(), ((RentRegion)region).getDurationString()); + } else if(region.isBuyRegion()) { + ((BuyRegion)region).setPrice(price); + plugin.message(sender, "setprice-successBuy", region.getName(), ((BuyRegion)region).getFormattedPrice()); + } + region.updateSigns(); + region.updateRegionFlags(); + region.save(); + } + + @Override + public List getTabCompleteList(int toComplete, String[] start) { + List result = new ArrayList(); + if(toComplete == 2) { + result = plugin.getFileManager().getRegionNames(); + } + return result; + } + +} diff --git a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/SetrestoreCommand.java b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/SetrestoreCommand.java new file mode 100644 index 0000000..50eaf2b --- /dev/null +++ b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/SetrestoreCommand.java @@ -0,0 +1,77 @@ +package nl.evolutioncoding.AreaShop.commands; + +import java.util.ArrayList; +import java.util.List; + +import nl.evolutioncoding.AreaShop.AreaShop; +import nl.evolutioncoding.AreaShop.regions.GeneralRegion; + +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; + +public class SetrestoreCommand extends CommandAreaShop { + + public SetrestoreCommand(AreaShop plugin) { + super(plugin); + } + + @Override + public String getCommandStart() { + return "areashop setrestore"; + } + + @Override + public String getHelp(CommandSender target) { + if(target.hasPermission("areashop.setrestore")) { + return plugin.getLanguageManager().getLang("help-setrestore"); + } + return null; + } + + @Override + public void execute(CommandSender sender, Command command, String[] args) { + if(!sender.hasPermission("areashop.setrestore")) { + plugin.message(sender, "setrestore-noPermission"); + return; + } + if(args.length <= 2 || args[1] == null || args[2] == null) { + plugin.message(sender, "setrestore-help"); + return; + } + GeneralRegion region = plugin.getFileManager().getRegion(args[1]); + if(region == null) { + plugin.message(sender, "setrestore-notRegistered", args[1]); + return; + } + String value = null; + if(args[2].equalsIgnoreCase("true") || args[2].equalsIgnoreCase("false") || args[2].equalsIgnoreCase("general")) { + value = args[2].toLowerCase(); + } else { + plugin.message(sender, "setrestore-invalidSetting", args[2]); + return; + } + region.setRestoreSetting(value); + if(args.length > 3) { + region.setRestoreProfile(args[3]); + plugin.message(sender, "setrestore-successProfile", region.getName(), value, args[3]); + } else { + plugin.message(sender, "setrestore-success", region.getName(), value); + } + region.save(); + } + + @Override + public List getTabCompleteList(int toComplete, String[] start) { + List result = new ArrayList(); + if(toComplete == 2) { + result = plugin.getFileManager().getRegionNames(); + } else if(toComplete == 3) { + result.add("true"); + result.add("false"); + result.add("general"); + } else if(toComplete == 4) { + result.addAll(plugin.config().getConfigurationSection("schematicProfiles").getKeys(false)); + } + return result; + } +} diff --git a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/SetteleportCommand.java b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/SetteleportCommand.java index ca18930..edf078a 100644 --- a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/SetteleportCommand.java +++ b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/SetteleportCommand.java @@ -1,5 +1,8 @@ package nl.evolutioncoding.AreaShop.commands; +import java.util.ArrayList; +import java.util.List; + import nl.evolutioncoding.AreaShop.AreaShop; import nl.evolutioncoding.AreaShop.regions.BuyRegion; import nl.evolutioncoding.AreaShop.regions.GeneralRegion; @@ -37,14 +40,24 @@ public class SetteleportCommand extends CommandAreaShop { if (!(sender instanceof Player)) { plugin.message(sender, "onlyByPlayer"); return; - } - if(args.length <= 1 || args[1] == null) { - plugin.message(sender, "setteleport-help"); - return; } Player player = (Player) sender; + GeneralRegion region = null; + if(args.length <= 1) { + // get the region by location + List regions = plugin.getFileManager().getApplicalbeASRegions(((Player)sender).getLocation()); + if(regions.size() != 1) { + plugin.message(sender, "setteleport-help"); + return; + } else { + region = regions.get(0); + } + } else { + region = plugin.getFileManager().getRegion(args[1]); + } + boolean owner = false; - GeneralRegion region = plugin.getFileManager().getRegion(args[1]); + if(region == null) { plugin.message(player, "setteleport-noRentOrBuy", args[1]); return; @@ -65,15 +78,26 @@ public class SetteleportCommand extends CommandAreaShop { ProtectedRegion wgRegion = region.getRegion(); if(args.length > 2 && args[2] != null && (args[2].equalsIgnoreCase("reset") || args[2].equalsIgnoreCase("yes") || args[2].equalsIgnoreCase("true"))) { region.setTeleport(null); - plugin.message(player, "setteleport-reset", args[1]); + plugin.message(player, "setteleport-reset", region.getName()); return; } if(!wgRegion.contains(player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ()) && !player.hasPermission(" areashop.setteleportoutsideregion")) { - plugin.message(player, "setteleport-notInside", args[1]); + plugin.message(player, "setteleport-notInside", region.getName()); return; } region.setTeleport(player.getLocation()); - plugin.message(player, "setteleport-success", args[1]); + plugin.message(player, "setteleport-success", region.getName()); + } + + @Override + public List getTabCompleteList(int toComplete, String[] start) { + ArrayList result = new ArrayList(); + if(toComplete == 2) { + result.addAll(plugin.getFileManager().getRegionNames()); + } else if(toComplete == 3) { + result.add("reset"); + } + return result; } } diff --git a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/TeleportCommand.java b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/TeleportCommand.java index e274098..7270724 100644 --- a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/TeleportCommand.java +++ b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/TeleportCommand.java @@ -1,5 +1,8 @@ package nl.evolutioncoding.AreaShop.commands; +import java.util.ArrayList; +import java.util.List; + import nl.evolutioncoding.AreaShop.AreaShop; import nl.evolutioncoding.AreaShop.regions.GeneralRegion; @@ -31,7 +34,7 @@ public class TeleportCommand extends CommandAreaShop { @Override public void execute(CommandSender sender, Command command, String[] args) { if (!(sender instanceof Player)) { - plugin.message(sender, "onlyByPlayer"); + plugin.message(sender, "cmd-onlyByPlayer"); return; } if(args.length <= 1 || args[1] == null) { @@ -44,7 +47,23 @@ public class TeleportCommand extends CommandAreaShop { plugin.message(player, "teleport-noRentOrBuy", args[1]); return; } - region.teleportPlayer(player); + if(args.length >= 3 && (args[2].equalsIgnoreCase("sign") || args[2].equalsIgnoreCase("yes") || args[2].equalsIgnoreCase("true"))) { + region.teleportPlayer(player, true); + } else { + region.teleportPlayer(player, false); + } + + } + + @Override + public List getTabCompleteList(int toComplete, String[] start) { + ArrayList result = new ArrayList(); + if(toComplete == 2) { + result.addAll(plugin.getFileManager().getRegionNames()); + } else if(toComplete == 3) { + result.add("sign"); + } + return result; } } diff --git a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/UnrentCommand.java b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/UnrentCommand.java index abc1080..7fa77e3 100644 --- a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/UnrentCommand.java +++ b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/UnrentCommand.java @@ -1,6 +1,10 @@ package nl.evolutioncoding.AreaShop.commands; +import java.util.ArrayList; +import java.util.List; + import nl.evolutioncoding.AreaShop.AreaShop; +import nl.evolutioncoding.AreaShop.regions.GeneralRegion; import nl.evolutioncoding.AreaShop.regions.RentRegion; import org.bukkit.command.Command; @@ -30,11 +34,26 @@ public class UnrentCommand extends CommandAreaShop { @Override public void execute(CommandSender sender, Command command, String[] args) { - if(args.length <= 1 || args[1] == null) { - plugin.message(sender, "unrent-help"); - return; - } - RentRegion rent = plugin.getFileManager().getRent(args[1]); + RentRegion rent = null; + if(args.length <= 1) { + if(sender instanceof Player) { + // get the region by location + List regions = plugin.getFileManager().getApplicalbeASRegions(((Player)sender).getLocation()); + if(regions.size() != 1) { + plugin.message(sender, "unrent-help"); + return; + } else { + if(regions.get(0).isRentRegion()) { + rent = (RentRegion)regions.get(0); + } + } + } else { + plugin.message(sender, "unrent-help"); + return; + } + } else { + rent = plugin.getFileManager().getRent(args[1]); + } if(rent == null) { plugin.message(sender, "unrent-notRegistered"); return; @@ -59,6 +78,19 @@ public class UnrentCommand extends CommandAreaShop { } } } + + @Override + public List getTabCompleteList(int toComplete, String[] start) { + ArrayList result = new ArrayList(); + if(toComplete == 2) { + for(RentRegion region : plugin.getFileManager().getRents()) { + if(region.isRented()) { + result.add(region.getName()); + } + } + } + return result; + } } diff --git a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/UpdatebuysCommand.java b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/UpdatebuysCommand.java index 71aca95..e521368 100644 --- a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/UpdatebuysCommand.java +++ b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/UpdatebuysCommand.java @@ -1,5 +1,8 @@ package nl.evolutioncoding.AreaShop.commands; +import java.util.ArrayList; +import java.util.List; + import nl.evolutioncoding.AreaShop.AreaShop; import org.bukkit.command.Command; @@ -31,11 +34,18 @@ public class UpdatebuysCommand extends CommandAreaShop { return; } boolean result = plugin.getFileManager().updateBuySigns(); + plugin.getFileManager().updateBuyRegions(); if(result) { plugin.message(sender, "buys-updated"); } else { plugin.message(sender, "buys-notUpdated"); } } + + @Override + public List getTabCompleteList(int toComplete, String[] start) { + ArrayList result = new ArrayList(); + return result; + } } diff --git a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/UpdaterentsCommand.java b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/UpdaterentsCommand.java index f98ae07..9d695a0 100644 --- a/AreaShop/src/nl/evolutioncoding/AreaShop/commands/UpdaterentsCommand.java +++ b/AreaShop/src/nl/evolutioncoding/AreaShop/commands/UpdaterentsCommand.java @@ -1,5 +1,8 @@ package nl.evolutioncoding.AreaShop.commands; +import java.util.ArrayList; +import java.util.List; + import nl.evolutioncoding.AreaShop.AreaShop; import org.bukkit.command.Command; @@ -39,4 +42,9 @@ public class UpdaterentsCommand extends CommandAreaShop { } } + @Override + public List getTabCompleteList(int toComplete, String[] start) { + ArrayList result = new ArrayList(); + return result; + } } diff --git a/AreaShop/src/nl/evolutioncoding/AreaShop/regions/BuyRegion.java b/AreaShop/src/nl/evolutioncoding/AreaShop/regions/BuyRegion.java index a3b05e6..b1fb38a 100644 --- a/AreaShop/src/nl/evolutioncoding/AreaShop/regions/BuyRegion.java +++ b/AreaShop/src/nl/evolutioncoding/AreaShop/regions/BuyRegion.java @@ -1,7 +1,6 @@ package nl.evolutioncoding.AreaShop.regions; import java.util.HashMap; -import java.util.Iterator; import java.util.UUID; import net.milkbowl.vault.economy.EconomyResponse; @@ -9,35 +8,33 @@ import nl.evolutioncoding.AreaShop.AreaShop; import nl.evolutioncoding.AreaShop.Exceptions.RegionCreateException; import org.bukkit.Bukkit; -import org.bukkit.Location; +import org.bukkit.OfflinePlayer; import org.bukkit.World; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; public class BuyRegion extends GeneralRegion { - /* Enum for schematic event types */ - public enum BuyEvent { - CREATED("created"), - DELETED("deleted"), - BOUGHT("bought"), - SOLD("sold"); - - private final String value; - private BuyEvent(String value) { - this.value = value; - } - public String getValue() { - return value; - } - } - + public BuyRegion(AreaShop plugin, YamlConfiguration config) throws RegionCreateException { super(plugin, config); } - public BuyRegion(AreaShop plugin, String name, World world, Location signLocation, double price) { - super(plugin, name, world, signLocation); - setSetting("price", price); + public BuyRegion(AreaShop plugin, String name, World world) { + super(plugin, name, world); + } + + @Override + public RegionType getType() { + return RegionType.BUY; + } + + @Override + public RegionState getState() { + if(isSold()) { + return RegionState.SOLD; + } else { + return RegionState.FORSALE; + } } /** @@ -45,7 +42,7 @@ public class BuyRegion extends GeneralRegion { * @return The UUID of the owner of this region */ public UUID getBuyer() { - String buyer = getStringSetting("buyer"); + String buyer = getStringSetting("buy.buyer"); if(buyer != null) { try { return UUID.fromString(buyer); @@ -54,13 +51,31 @@ public class BuyRegion extends GeneralRegion { return null; } + /** + * Check if a player is the buyer of this region + * @param player Player to check + * @return true if this player owns this region, otherwise false + */ + public boolean isBuyer(Player player) { + UUID buyer = getBuyer(); + if(buyer == null || player == null) { + return false; + } else { + return buyer.equals(player.getUniqueId()); + } + } + + /** + * Set the buyer of this region + * @param buyer The UUID of the player that should be set as buyer + */ public void setBuyer(UUID buyer) { if(buyer == null) { - setSetting("buyer", null); - setSetting("buyerName", null); + setSetting("buy.buyer", null); + setSetting("buy.buyerName", null); } else { - setSetting("buyer", buyer.toString()); - setSetting("buyerName", plugin.toName(buyer)); + setSetting("buy.buyer", buyer.toString()); + setSetting("buy.buyerName", plugin.toName(buyer)); } } @@ -85,7 +100,7 @@ public class BuyRegion extends GeneralRegion { * @return The price of the region */ public double getPrice() { - return getDoubleSetting("price"); + return getDoubleSetting("buy.price"); } /** @@ -101,9 +116,19 @@ public class BuyRegion extends GeneralRegion { * @param price */ public void setPrice(double price) { - setSetting("price", price); - updateSigns(); - updateRegionFlags(); + setSetting("buy.price", price); + } + + @Override + public HashMap getSpecificReplacements() { + // Fill the replacements map with things specific to a BuyRegion + HashMap result = new HashMap(); + result.put(AreaShop.tagPrice, getFormattedPrice()); + result.put(AreaShop.tagPlayerName, getPlayerName()); + result.put(AreaShop.tagPlayerUUID, getBuyer()); + // TODO: Add more? + + return result; } /** @@ -115,30 +140,15 @@ public class BuyRegion extends GeneralRegion { /* Check if the player has permission */ if(player.hasPermission("areashop.buy")) { if(!isSold()) { - /* Check if the player can still buy */ - int rentNumber = 0; - Iterator itRent = getFileManager().getRents().iterator(); - while(itRent.hasNext()) { - RentRegion next = itRent.next(); - if(player.getUniqueId().equals(next.getRenter())) { - rentNumber++; - } - } - int buyNumber = 0; - Iterator itBuy = getFileManager().getBuys().iterator(); - while(itBuy.hasNext()) { - BuyRegion next = itBuy.next(); - if(player.getUniqueId().equals(next.getBuyer())) { - buyNumber++; - } - } - int maximumBuys = Integer.parseInt(plugin.config().getString("maximumBuys")); - if(maximumBuys != -1 && buyNumber >= maximumBuys) { + // Check if the player can still buy + int maximumBuys = getMaxBuyRegions(player); + AreaShop.debug("maximumBuys=" + maximumBuys); + if(getCurrentBuyRegions(player) >= maximumBuys) { plugin.message(player, "buy-maximum", maximumBuys); return false; } - int maximumTotal = Integer.parseInt(plugin.config().getString("maximumTotal")); - if(maximumTotal != -1 && (rentNumber+buyNumber) >= maximumTotal) { + int maximumTotal = getMaxTotalRegions(player); + if(getCurrentTotalRegions(player) >= maximumTotal) { plugin.message(player, "total-maximum", maximumTotal); return false; } @@ -152,20 +162,24 @@ public class BuyRegion extends GeneralRegion { plugin.message(player, "buy-payError"); return false; } + // Run commands + this.runEventCommands(RegionEvent.BOUGHT, true); /* Set the owner */ setBuyer(player.getUniqueId()); /* Update everything */ - handleSchematicEvent(BuyEvent.BOUGHT); + handleSchematicEvent(RegionEvent.BOUGHT); updateSigns(); - updateRegionFlags(); + updateRegionFlags(RegionState.SOLD); /* Send message to the player */ plugin.message(player, "buy-succes", getName()); AreaShop.debug(player.getName() + " has bought region " + getName() + " for " + getFormattedPrice()); this.save(); + // Run commands + this.runEventCommands(RegionEvent.BOUGHT, false); return true; } else { /* Player has not enough money */ @@ -189,97 +203,44 @@ public class BuyRegion extends GeneralRegion { * @param regionName */ public void sell(boolean giveMoneyBack) { + // Run commands + this.runEventCommands(RegionEvent.SOLD, true); + /* Give part of the buying price back */ - double percentage = plugin.config().getDouble("buyMoneyBack") / 100.0; + double percentage = getDoubleSetting("buy.moneyBack") / 100.0; double moneyBack = getPrice() * percentage; if(moneyBack > 0 && giveMoneyBack) { /* Give back the money */ - EconomyResponse r = plugin.getEconomy().depositPlayer(Bukkit.getOfflinePlayer(getBuyer()), moneyBack); - if(!r.transactionSuccess()) { - plugin.getLogger().info("Something went wrong with paying back money while unrenting"); - } + OfflinePlayer player = Bukkit.getOfflinePlayer(getBuyer()); + if(player != null) { + EconomyResponse r = null; + boolean error = false; + try { + r = plugin.getEconomy().depositPlayer(Bukkit.getOfflinePlayer(getBuyer()), moneyBack); + } catch(Exception e) { + error = true; + } + if(error || r == null || !r.transactionSuccess()) { + plugin.getLogger().info("Something went wrong with paying back money to " + getPlayerName() + " while selling region " + getName()); + } + } } /* Debug message */ AreaShop.debug(getPlayerName() + " has sold " + getName() + ", got " + plugin.formatCurrency(moneyBack) + " money back"); + + /* Update everything */ + handleSchematicEvent(RegionEvent.SOLD); + updateRegionFlags(RegionState.FORSALE); /* Remove the player */ - setBuyer(null); + setBuyer(null); - /* Update everything */ - handleSchematicEvent(BuyEvent.SOLD); updateSigns(); - updateRegionFlags(); + this.save(); - } - - - public String[] getSignLines() { - String[] lines = new String[3]; - if(isSold()) { - lines[0] = plugin.fixColors(plugin.config().getString("signBuyed")); - lines[1] = getName(); - lines[2] = plugin.toName(getBuyer()); - } else { - lines[0] = plugin.fixColors(plugin.config().getString("signBuyable")); - lines[1] = getName(); - lines[2] = getFormattedPrice(); - } - return lines; - } - - - @Override - public void updateRegionFlags() { - HashMap replacements = new HashMap(); - replacements.put(AreaShop.tagRegionName, getName()); - replacements.put(AreaShop.tagPrice, getFormattedPrice()); - replacements.put(AreaShop.tagPlayerName, getPlayerName()); - if(isSold()) { - this.setRegionFlags(plugin.config().getConfigurationSection("flagsSold"), replacements); - } else { - this.setRegionFlags(plugin.config().getConfigurationSection("flagsForSale"), replacements); - } - } - - - /** - * Checks an event and handles saving to and restoring from schematic for it - * @param type The type of event - */ - public void handleSchematicEvent(BuyEvent type) { - // Check for the general killswitch - if(!plugin.config().getBoolean("enableSchematics")) { - return; - } - // Check the individual options - if("false".equalsIgnoreCase(getRestoreSetting())) { - return; - } else if("true".equalsIgnoreCase(getRestoreSetting())) { - } else { - if(!plugin.config().getBoolean("useBuyRestore")) { - return; - } - } - // Get the safe and restore names - String save = plugin.config().getString("buySchematicProfiles." + getRestoreProfile() + "." + type.getValue() + ".save"); - if(save == null) { - plugin.config().getString("buySchematicProfiles.default." + type.getValue() + ".save"); - } - String restore = plugin.config().getString("buySchematicProfiles." + getRestoreProfile() + "." + type.getValue() + ".restore"); - if(restore == null) { - plugin.config().getString("buySchematicProfiles.default." + type.getValue() + ".restore"); - } - // Save the region if needed - if(save != null && save.length() != 0) { - save = save.replace(AreaShop.tagRegionName, getName()); - this.saveRegionBlocks(save); - } - // Restore the region if needed - if(restore != null && restore.length() != 0) { - restore = restore.replace(AreaShop.tagRegionName, getName()); - this.restoreRegionBlocks(restore); - } + // Run commands + this.runEventCommands(RegionEvent.SOLD, false); } } diff --git a/AreaShop/src/nl/evolutioncoding/AreaShop/regions/GeneralRegion.java b/AreaShop/src/nl/evolutioncoding/AreaShop/regions/GeneralRegion.java index 4c1a599..b62cb76 100644 --- a/AreaShop/src/nl/evolutioncoding/AreaShop/regions/GeneralRegion.java +++ b/AreaShop/src/nl/evolutioncoding/AreaShop/regions/GeneralRegion.java @@ -4,7 +4,9 @@ import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; +import java.util.HashMap; import java.util.Iterator; +import java.util.List; import java.util.Map; import java.util.Set; @@ -20,6 +22,8 @@ import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.Sign; +import org.bukkit.command.CommandException; +import org.bukkit.command.CommandSender; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; @@ -57,6 +61,71 @@ public abstract class GeneralRegion { private static ArrayList cannotSpawnBeside = new ArrayList(Arrays.asList(Material.LAVA, Material.STATIONARY_LAVA, Material.CACTUS)); protected AreaShop plugin = null; + /* Enum for region types */ + public enum RegionType { + RENT("rent"), + BUY("buy"); + + private final String value; + private RegionType(String value) { + this.value = value; + } + public String getValue() { + return value; + } + } + + /* Enum for schematic event types */ + public enum RegionEvent { + CREATED("created"), + DELETED("deleted"), + RENTED("rented"), + EXTENDED("extended"), + UNRENTED("unrented"), + BOUGHT("bought"), + SOLD("sold"); + + private final String value; + private RegionEvent(String value) { + this.value = value; + } + public String getValue() { + return value; + } + } + + /* Enum for Region states */ + public enum RegionState { + FORRENT("forrent"), + RENTED("rented"), + FORSALE("forsale"), + SOLD("sold"); + + private final String value; + private RegionState(String value) { + this.value = value; + } + public String getValue() { + return value; + } + } + + /* Enum for Region states */ + public enum ClickType { + RIGHTCLICK("rightClick"), + LEFTCLICK("leftClick"), + SHIFTRIGHTCLICK("shiftRightClick"), + SHIFTLEFTCLICK("shiftLeftClick"); + + private final String value; + private ClickType(String value) { + this.value = value; + } + public String getValue() { + return value; + } + } + public GeneralRegion(AreaShop plugin, YamlConfiguration config) throws RegionCreateException { this.plugin = plugin; this.config = config; @@ -67,65 +136,108 @@ public abstract class GeneralRegion { || plugin.getWorldGuard().getRegionManager(getWorld()).getRegion(getName()) == null) { throw new RegionCreateException("Region of " + getName() + " does not exist anymore"); - } else { - // If the sign is gone remove the rent - if(getSignLocation() == null) { - throw new RegionCreateException("Sign of region " + getName() + " does not exist anymore"); - } - Block block = getWorld().getBlockAt(getSignLocation()); - if(!(block.getType() == Material.WALL_SIGN || block.getType() == Material.SIGN_POST)) { - throw new RegionCreateException("Sign of region " + getName() + " does not exist anymore"); - } } } - public GeneralRegion(AreaShop plugin, String name, World world, Location signLocation) { + public GeneralRegion(AreaShop plugin, String name, World world) { this.plugin = plugin; config = new YamlConfiguration(); - config.set("name", name); - setSetting("world", world.getName()); - setSetting("signLocation", Utils.locationToConfig(signLocation)); + config.set("general.name", name); + setSetting("general.world", world.getName()); + setSetting("general.type", getType().getValue().toLowerCase()); } - // GETTERS - public Location getSignLocation() { - Location result = null; + // ABSTRACT + /** + * Get the region type of the region + * @return The RegionType of this region + */ + public abstract RegionType getType(); + + /** + * Update the region flags according the region data + */ + public void updateRegionFlags(RegionState toState) { + // Get state setting + String setting = toState.getValue(); + ConfigurationSection section = plugin.config().getConfigurationSection("flagProfiles." + getStringSetting("general.flagProfile") + "." + setting); + setRegionFlags(section); + } + + /** + * Update the region flags according the region data + */ + public void updateRegionFlags() { + // Get state setting + RegionState toState = null; if(isRentRegion()) { - result = Utils.configToLocation(config.getConfigurationSection("rent.signLocation")); - } else { - result = Utils.configToLocation(config.getConfigurationSection("buy.signLocation")); + if(((RentRegion)this).isRented()) { + toState = RegionState.RENTED; + } else { + toState = RegionState.FORRENT; + } + } else if(isBuyRegion()) { + if(((BuyRegion)this).isSold()) { + toState = RegionState.SOLD; + } else { + toState = RegionState.FORSALE; + } + } + updateRegionFlags(toState); + } + + /** + * Get the tag replacements, used in commands or signs + * @return A map with strings like '%region%' linking to the value to replace it with + */ + public abstract HashMap getSpecificReplacements(); + + /** + * Get the state of a region + * @return The RegionState of the region + */ + public abstract RegionState getState(); + + // GETTERS + public List getSignLocations() { + List result = new ArrayList(); + if(config.getConfigurationSection("general.signs") == null) { + return result; + } + for(String signName : config.getConfigurationSection("general.signs").getKeys(false)) { + result.add(Utils.configToLocation(config.getConfigurationSection("general.signs." + signName + ".location"))); } return result; } public Location getTeleportLocation() { Location result = null; - if(isRentRegion()) { - result = Utils.configToLocation(config.getConfigurationSection("rent.teleportLocation")); - } else { - result = Utils.configToLocation(config.getConfigurationSection("buy.teleportLocation")); - } + result = Utils.configToLocation(config.getConfigurationSection("general.teleportLocation")); return result; } public String getName() { - return config.getString("name"); + return config.getString("general.name"); + } + public String getLowerCaseName() { + return getName().toLowerCase(); } - public String getRestoreSetting() { - return getStringSetting("enableRestore"); + public boolean isRestoreEnabled() { + return getBooleanSetting("general.enableRestore"); } public String getRestoreProfile() { - return getStringSetting("restoreProfile"); + return getStringSetting("general.schematicProfile"); } public String getWorldName() { - if(getStringSetting("world") == null) { + String world = getStringSetting("general.world"); + if(world == null) { return null; } - return getStringSetting("world"); + return world; } public World getWorld() { @@ -146,12 +258,41 @@ public abstract class GeneralRegion { return plugin.getWorldGuard().getRegionManager(getWorld()).getRegion(getName()); } - public boolean hasTeleportLocation() { - if(isRentRegion()) { - return config.isSet("rent.teleportLocation"); - } else { - return config.isSet("buy.teleportLocation"); + public HashMap getAllReplacements() { + HashMap result = getSpecificReplacements(); + + result.put(AreaShop.tagRegionName, getName()); + result.put(AreaShop.tagRegionType, getType().getValue().toLowerCase()); + result.put(AreaShop.tagWorldName, getWorldName()); + // TODO: add more? + + return result; + } + + /** + * Get the name of the sign at the specified location + * @param location The location to check + * @return The name of the sign if found, otherwise null + */ + public String getSignName(Location location) { + String result = null; + if(config.getConfigurationSection("general.signs") == null) { + return null; } + for(String signName : config.getConfigurationSection("general.signs").getKeys(false)) { + if(location.equals(Utils.configToLocation(config.getConfigurationSection("general.signs." + signName + ".location")))) { + result = signName; + } + } + return result; + } + + /** + * Check if the region has a teleportLocation specified + * @return true if the region has a teleportlocation, false otherwise + */ + public boolean hasTeleportLocation() { + return config.isSet("general.teleportLocation"); } /** @@ -159,7 +300,7 @@ public abstract class GeneralRegion { * @return true if this region is a RentRegion otherwise false */ public boolean isRentRegion() { - return this instanceof RentRegion; + return getType() == RegionType.RENT; } /** @@ -167,46 +308,186 @@ public abstract class GeneralRegion { * @return true if this region is a BuyRegion otherwise false */ public boolean isBuyRegion() { - return this instanceof BuyRegion; + return getType() == RegionType.BUY; } + /** + * Add a sign to this region + * @param location The location of the sign + * @param signType The type of the sign (WALL_SIGN or SIGN_POST) + * @param facing The orientation of the sign + * @param profile The profile to use with this sign (null for default) + */ + public void addSign(Location location, Material signType, BlockFace facing, String profile) { + int i = 0; + while(config.isSet("general.signs." + i)) { + i++; + } + String signPath = "general.signs." + i + "."; + config.set(signPath + "location", Utils.locationToConfig(location)); + config.set(signPath + "facing", facing.name()); + config.set(signPath + "signType", signType.name()); + if(profile != null && profile.length() != 0) { + config.set(signPath + "profile", profile); + } + } + + /** + * Remove a sign + * @param name Name of the sign to be removed + */ + public void removeSign(String name) { + config.set("general.signs." + name, null); + } + public void removeSign(Location location) { + if(location == null) { + return; + } + String name = getSignName(location); + location.getBlock().setType(Material.AIR); + if(name != null) { + removeSign(name); + } + } + + /** + * Checks if there is a sign from this region at the specified location + * @param location Location to check + * @return true if this region has a sign at the location, otherwise false + */ + public boolean isSignOfRegion(Location location) { + Set signs = null; + if(config.getConfigurationSection("general.signs") == null) { + return false; + } + signs = config.getConfigurationSection("general.signs").getKeys(false); + for(String sign : signs) { + Location signLocation = Utils.configToLocation(config.getConfigurationSection("general.signs." + sign + ".location")); + if(signLocation != null + && signLocation.getWorld().equals(location.getWorld()) + && signLocation.getBlockX() == location.getBlockX() + && signLocation.getBlockY() == location.getBlockY() + && signLocation.getBlockZ() == location.getBlockZ()) { + return true; + } + } + return false; + } /** * Update the signs connected to this region * @return true if the update was successful, otherwise false */ public boolean updateSigns() { - boolean result = false; - if(getSignLocation() == null || getSignLocation().getWorld() == null) { - return false; + boolean result = true; + Set signs = null; + if(config.getConfigurationSection("general.signs") != null) { + signs = config.getConfigurationSection("general.signs").getKeys(false); } - Block block = getSignLocation().getBlock(); - if(block.getType() == Material.WALL_SIGN || block.getType() == Material.SIGN_POST) { - Sign sign = (Sign)block.getState(); - String[] lines = getSignLines(); - for(int i=0; i replacements = getAllReplacements(); + for(String sign : signs) { + AreaShop.debug("sign name: " + sign); + Location location = Utils.configToLocation(config.getConfigurationSection("general.signs." + sign + ".location")); + if(location == null) { + // TODO: Remove the sign if the location is wrong? + AreaShop.debug(" location null"); + result = false; + continue; } - sign.update(); - result = true; - } + // Get the profile set in the config + String profile = config.getString("general.signs." + sign + ".profile"); + if(profile == null || profile.length() == 0) { + profile = getStringSetting("general.signProfile"); + } + AreaShop.debug(" profile=" + profile); + // Get the prefix + String prefix = "signProfiles." + profile + "." + getState().getValue().toLowerCase() + "."; + // Get the lines + String[] signLines = new String[4]; + signLines[0] = plugin.config().getString(prefix + "line1"); + signLines[1] = plugin.config().getString(prefix + "line2"); + signLines[2] = plugin.config().getString(prefix + "line3"); + signLines[3] = plugin.config().getString(prefix + "line4"); + // DEBUG + for(String line : signLines) { + AreaShop.debug(" signLine: " + line); + } + // Check if the sign should be present + Block block = location.getBlock(); + if(!plugin.config().isSet(prefix) + || ( (signLines[0] == null || signLines[0].length() == 0) + && (signLines[1] == null || signLines[1].length() == 0) + && (signLines[2] == null || signLines[2].length() == 0) + && (signLines[3] == null || signLines[3].length() == 0) )) { + AreaShop.debug(" set to air"); + block.setType(Material.AIR); + } else { + Sign signState = null; + if(block.getType() != Material.WALL_SIGN && block.getType() != Material.SIGN_POST) { + Material signType = null; + try { + signType = Material.valueOf(config.getString("general.signs." + sign + ".signType")); + } catch(NullPointerException | IllegalArgumentException e) { + signType = null; + } + if(signType != Material.WALL_SIGN && signType != Material.SIGN_POST) { + block.setType(Material.AIR); + AreaShop.debug(" setting sign failed"); + continue; + } + block.setType(signType); + signState = (Sign)block.getState(); + org.bukkit.material.Sign signData = (org.bukkit.material.Sign)signState.getData(); + BlockFace signFace; + try { + signFace = BlockFace.valueOf(config.getString("general.signs." + sign + ".signType")); + } catch(NullPointerException | IllegalArgumentException e) { + signFace = null; + } + if(signFace != null) { + signData.setFacingDirection(signFace); + signState.setData(signData); + } + } + signState = (Sign)block.getState(); + org.bukkit.material.Sign signData = (org.bukkit.material.Sign)signState.getData(); + if(!config.isString("general.signs." + sign + ".signType")) { + config.set("general.signs." + sign + ".signType", signState.getType().toString()); + this.save(); + } + if(!config.isString("general.signs." + sign + ".facing")) { + config.set("general.signs." + sign + ".facing", signData.getFacing().toString()); + this.save(); + } + // Apply replacements and color and then set it on the sign + for(int i=0; i flag : DefaultFlag.getFlags()) { + region.setFlag(flag, null); + } + } + } + /** * Set the region flags/options to the values of a ConfigurationSection * @param player The player that does it @@ -306,9 +599,13 @@ public abstract class GeneralRegion { * @return */ @SuppressWarnings({ "unchecked", "rawtypes" }) - protected boolean setRegionFlags(ConfigurationSection flags, Map valueReplacements) { + protected boolean setRegionFlags(ConfigurationSection flags) { boolean result = true; + if(flags == null) { + AreaShop.debug("Flags section is null"); + return false; + } Set flagNames = flags.getKeys(false); WorldGuardPlugin worldGuard = plugin.getWorldGuard(); Flag flagType = null; @@ -321,6 +618,8 @@ public abstract class GeneralRegion { return false; } + Map replacements = getAllReplacements(); + Iterator it = flagNames.iterator(); while(it.hasNext()) { String flagName = it.next(); @@ -328,9 +627,9 @@ public abstract class GeneralRegion { // Apply replacements if(value != null) { - for(String key : valueReplacements.keySet()) { - if(valueReplacements.get(key) != null) { - value = value.replace(key, valueReplacements.get(key)); + for(String key : replacements.keySet()) { + if(replacements.get(key) != null) { + value = value.replace(key, replacements.get(key).toString()); } } } @@ -341,7 +640,9 @@ public abstract class GeneralRegion { String[] names = value.split("\\s*,\\s*"); DefaultDomain members = region.getMembers(); for(int i=0; i signs = getSignLocations(); + if(!signs.isEmpty()) { + // Use the location 1 below the sign to prevent weird spawing above the sign + startLocation = signs.get(0).subtract(0.0, 1.0, 0.0); + startLocation.setPitch(player.getLocation().getPitch()); + startLocation.setYaw(player.getLocation().getYaw()); + } + + } else if(this.hasTeleportLocation()) { startLocation = getTeleportLocation(); } if(isRentRegion()) { @@ -526,10 +844,10 @@ public abstract class GeneralRegion { owner = player.getUniqueId().equals(((BuyRegion)this).getBuyer()); } // Check permissions - if(!player.hasPermission("areashop.teleport")) { + if((!player.hasPermission("areashop.teleport") && !toSign) || (!player.hasPermission("areashop.teleportsign") && toSign)) { plugin.message(player, "teleport-noPermission"); return false; - } else if(!owner && !player.hasPermission("areashop.teleportall")) { + } else if(!owner && !player.hasPermission("areashop.teleportall") && !toSign) { plugin.message(player, "teleport-noPermissionOther"); return false; } @@ -560,22 +878,17 @@ public abstract class GeneralRegion { // radius around that (until no block in the region is found at all cube sides) Location saveLocation = startLocation; int radius = 1; - boolean blocksInRegion = region.contains(startLocation.getBlockX(), startLocation.getBlockY(), startLocation.getBlockZ()); - boolean done = isSave(saveLocation) && blocksInRegion; + boolean done = isSave(saveLocation); boolean north=false, east=false, south=false, west=false, top=false, bottom=false; boolean track; - while(blocksInRegion && !done) { - blocksInRegion = false; + while(!done) { // North side track = false; for(int x=-radius+1; x<=radius && !done && !north; x++) { for(int y=-radius+1; y=-radius && !done && !south; x--) { for(int y=-radius+1; y=-radius && !done && !west; z--) { for(int y=-radius+1; y=-r && !done; x--) { saveLocation = startLocation.clone().add(x, radius, r); - if(region.contains(saveLocation.getBlockX(), saveLocation.getBlockY(), saveLocation.getBlockZ())) { - done = isSave(saveLocation); - blocksInRegion = true; - track = true; - } + done = isSave(saveLocation); + track = true; checked++; } // West side for(int z=r-1; z>=-r && !done; z--) { saveLocation = startLocation.clone().add(-r, radius, z); - if(region.contains(saveLocation.getBlockX(), saveLocation.getBlockY(), saveLocation.getBlockZ())) { - done = isSave(saveLocation); - blocksInRegion = true; - track = true; - } + done = isSave(saveLocation); + track = true; checked++; } } @@ -689,52 +976,37 @@ public abstract class GeneralRegion { // Middle block of the bottom if(!done && !bottom) { saveLocation = startLocation.clone().add(0, -radius, 0); - if(region.contains(saveLocation.getBlockX(), saveLocation.getBlockY(), saveLocation.getBlockZ())) { - done = isSave(saveLocation); - blocksInRegion = true; - track = true; - } + done = isSave(saveLocation); + track = true; checked++; } for(int r=1; r<=radius && !done && !bottom; r++) { // North for(int x=-r+1; x<=r && !done; x++) { saveLocation = startLocation.clone().add(x, -radius, -r); - if(region.contains(saveLocation.getBlockX(), saveLocation.getBlockY(), saveLocation.getBlockZ())) { - done = isSave(saveLocation); - blocksInRegion = true; - track = true; - } + done = isSave(saveLocation); + track = true; checked++; } // East for(int z=-r+1; z<=r && !done; z++) { saveLocation = startLocation.clone().add(r, -radius, z); - if(region.contains(saveLocation.getBlockX(), saveLocation.getBlockY(), saveLocation.getBlockZ())) { - done = isSave(saveLocation); - blocksInRegion = true; - track = true; - } + done = isSave(saveLocation); + track = true; checked++; } // South side for(int x=r-1; x>=-r && !done; x--) { saveLocation = startLocation.clone().add(x, -radius, r); - if(region.contains(saveLocation.getBlockX(), saveLocation.getBlockY(), saveLocation.getBlockZ())) { - done = isSave(saveLocation); - blocksInRegion = true; - track = true; - } + done = isSave(saveLocation); + track = true; checked++; } // West side for(int z=r-1; z>=-r && !done; z--) { saveLocation = startLocation.clone().add(-r, -radius, z); - if(region.contains(saveLocation.getBlockX(), saveLocation.getBlockY(), saveLocation.getBlockZ())) { - done = isSave(saveLocation); - blocksInRegion = true; - track = true; - } + done = isSave(saveLocation); + track = true; checked++; } } @@ -743,7 +1015,7 @@ public abstract class GeneralRegion { // Increase cube radius radius++; } - if(done) { + if(done) { plugin.message(player, "teleport-success", getName()); player.teleport(saveLocation); AreaShop.debug("Found location: " + saveLocation.toString() + " Tries: " + checked); @@ -754,6 +1026,9 @@ public abstract class GeneralRegion { return false; } } + public boolean teleportPlayer(Player player) { + return teleportPlayer(player, false); + } /** * Checks if a certain location is safe to teleport to @@ -821,11 +1096,6 @@ public abstract class GeneralRegion { // CONFIG public boolean getBooleanSetting(String path) { - if(isRentRegion()) { - path = "rent." + path; - } else { - path = "buy." + path; - } if(config.isBoolean(path)) { return config.getBoolean(path); } @@ -845,12 +1115,27 @@ public abstract class GeneralRegion { return this.getFileManager().getDefaultSettings().getBoolean(path); } - public double getDoubleSetting(String path) { - if(isRentRegion()) { - path = "rent." + path; - } else { - path = "buy." + path; + public int getIntegerSetting(String path) { + if(config.isInt(path)) { + return config.getInt(path); } + int result = 0; + int priority = Integer.MIN_VALUE; + boolean found = false; + for(RegionGroup group : plugin.getFileManager().getGroups()) { + if(group.isMember(this) && group.getSettings().isInt(path) && group.getPriority() > priority) { + result = group.getSettings().getInt(path); + priority = group.getPriority(); + found = true; + } + } + if(found) { + return result; + } + return this.getFileManager().getDefaultSettings().getInt(path); + } + + public double getDoubleSetting(String path) { if(config.isDouble(path)) { return config.getDouble(path); } @@ -858,7 +1143,7 @@ public abstract class GeneralRegion { int priority = Integer.MIN_VALUE; boolean found = false; for(RegionGroup group : plugin.getFileManager().getGroups()) { - if(group.isMember(this) && group.getSettings().isBoolean(path) && group.getPriority() > priority) { + if(group.isMember(this) && group.getSettings().isDouble(path) && group.getPriority() > priority) { result = group.getSettings().getDouble(path); priority = group.getPriority(); found = true; @@ -871,11 +1156,6 @@ public abstract class GeneralRegion { } public long getLongSetting(String path) { - if(isRentRegion()) { - path = "rent." + path; - } else { - path = "buy." + path; - } if(config.isLong(path)) { return config.getLong(path); } @@ -883,7 +1163,7 @@ public abstract class GeneralRegion { int priority = Integer.MIN_VALUE; boolean found = false; for(RegionGroup group : plugin.getFileManager().getGroups()) { - if(group.isMember(this) && group.getSettings().isBoolean(path) && group.getPriority() > priority) { + if(group.isMember(this) && group.getSettings().isLong(path) && group.getPriority() > priority) { result = group.getSettings().getLong(path); priority = group.getPriority(); found = true; @@ -896,11 +1176,6 @@ public abstract class GeneralRegion { } public String getStringSetting(String path) { - if(isRentRegion()) { - path = "rent." + path; - } else { - path = "buy." + path; - } if(config.isString(path)) { return config.getString(path); } @@ -920,16 +1195,244 @@ public abstract class GeneralRegion { return this.getFileManager().getDefaultSettings().getString(path); } - public void setSetting(String path, Object value) { - if(isRentRegion()) { - path = "rent." + path; - } else { - path = "buy." + path; + public List getStringListSetting(String path) { + if(config.isList(path)) { + return config.getStringList(path); } + List result = null; + int priority = Integer.MIN_VALUE; + boolean found = false; + for(RegionGroup group : plugin.getFileManager().getGroups()) { + if(group.isMember(this) && group.getSettings().isString(path) && group.getPriority() > priority) { + result = group.getSettings().getStringList(path); + priority = group.getPriority(); + found = true; + } + } + if(found) { + return result; + } + return this.getFileManager().getDefaultSettings().getStringList(path); + } + + public void setSetting(String path, Object value) { config.set(path, value); } + + // LIMIT FUNCTIONS + /** + * Get the total number of regions a player has + * @param player The player to check + * @return The total number of regions the player has + */ + public int getCurrentTotalRegions(Player player) { + int result = 0; + for(GeneralRegion region : plugin.getFileManager().getRegions()) { + if(region.isRentRegion() && ((RentRegion)region).isRenter(player)) { + result++; + } else if(region.isBuyRegion() && ((BuyRegion)region).isBuyer(player)) { + result++; + } + } + return result; + } + + /** + * Get the number of rents a player has + * @param player The player to check + * @return The number of rent regions a player has + */ + public int getCurrentRentRegions(Player player) { + int result = 0; + for(RentRegion region : plugin.getFileManager().getRents()) { + if(region.isRenter(player)) { + result++; + } + } + return result; + } + + /** + * Get the number of buys a player has + * @param player The player to check + * @return The number of buy regions a player has + */ + public int getCurrentBuyRegions(Player player) { + int result = 0; + for(BuyRegion region : plugin.getFileManager().getBuys()) { + if(region.isBuyer(player)) { + result++; + } + } + return result; + } + + + /** + * Get the total number of regions the player can have + * @param player The player to check + * @return Integer.MAX_VALUE if unlimited, otherwise a number + */ + public int getMaxRegions(Player player, String setting) { + int result = 0; + Set groups = plugin.config().getConfigurationSection("limitGroups").getKeys(false); + for(String group : groups) { + if(player.hasPermission("areashop.limits." + group)) { + int w = plugin.config().getInt("limitGroups." + group + "." + setting); + if(w > result) { + result = w; + } else if(w == -1) { + result = Integer.MAX_VALUE; + } + } + } + return result; + } + // Functions for accessing the different limits + public int getMaxTotalRegions(Player player) { + return getMaxRegions(player, "total"); + } + public int getMaxRentRegions(Player player) { + return getMaxRegions(player, "rents"); + } + public int getMaxBuyRegions(Player player) { + return getMaxRegions(player, "buys"); + } + + + + + /** + * Checks an event and handles saving to and restoring from schematic for it + * @param type The type of event + */ + public void handleSchematicEvent(RegionEvent type) { + // Check for the general killswitch + if(!plugin.config().getBoolean("enableSchematics")) { + return; + } + // Check the individual>group>default setting + if(!isRestoreEnabled()) { + return; + } + // Get the safe and restore names + String save = plugin.config().getString("schematicProfiles." + getRestoreProfile() + "." + type.getValue() + ".save"); + String restore = plugin.config().getString("schematicProfiles." + getRestoreProfile() + "." + type.getValue() + ".restore"); + // Save the region if needed + if(save != null && save.length() != 0) { + save = save.replace(AreaShop.tagRegionName, getName()); + save = save.replace(AreaShop.tagRegionType, getType().getValue().toLowerCase()); + this.saveRegionBlocks(save); + } + // Restore the region if needed + if(restore != null && restore.length() != 0) { + restore = restore.replace(AreaShop.tagRegionName, getName()); + restore = restore.replace(AreaShop.tagRegionType, getType().getValue().toLowerCase()); + this.restoreRegionBlocks(restore); + } + } + + // COMMAND EXECUTING + + /** + * Run commands as the CommandsSender, replacing all tags with the relevant values + * @param sender The sender that should perform the command + * @param commands A list of the commands to run (without slash and with tags) + */ + public void runCommands(CommandSender sender, List commands) { + if(commands == null || commands.isEmpty()) { + return; + } + + boolean postCommandErrors = plugin.config().getBoolean("postCommandErrors"); + for(String command : commands) { + if(command == null || command.length() == 0) { + continue; + } + + // Apply replacements + HashMap replacements = getAllReplacements(); + for(String tag : replacements.keySet()) { + Object replacement = replacements.get(tag); + if(replacement != null) { + command = command.replace(tag, replacement.toString()); + } + } + + boolean result = false; + String error = null; + try { + result = plugin.getServer().dispatchCommand(sender, command); + } catch(CommandException e) { + result = false; + error = e.getMessage(); + } + if(error == null) { + AreaShop.debug("Command run, executor=" + sender.getName() + ", command=" + command + ", result=" + result); + } else { + AreaShop.debug("Command run, executor=" + sender.getName() + ", command=" + command + ", result=" + result + ", error=" + error); + } + if(!result && postCommandErrors) { + if(error != null) { + plugin.getLogger().info("Command execution failed, command=" + command + ", error=" + error); + } else { + plugin.getLogger().info("Command execution failed, command=" + command); + } + } + } + } + + /** + * Run command for a certain event + * @param event The event + * @param before The 'before' or 'after' commands + */ + public void runEventCommands(RegionEvent event, boolean before) { + String profile = getStringSetting("general.eventCommandProfile"); + if(profile == null || profile.length() == 0) { + return; + } + String path = "eventCommandProfiles." + profile + "." + event.getValue().toLowerCase(); + if(before) { + path += ".before"; + } else { + path += ".after"; + } + List commands = plugin.config().getStringList(path); + // Don't waste time if there are no commands to be run + if(commands == null || commands.isEmpty()) { + return; + } + runCommands(Bukkit.getConsoleSender(), commands); + } + + /** + * Run commands when a player clicks a sign + * @param signName The name of the sign + * @param clicker The player that clicked the sign + * @param clickType The type of clicking + */ + public boolean runSignCommands(String signName, Player clicker, ClickType clickType) { + // Get the profile set in the config + String profile = config.getString("general.signs." + signName + ".profile"); + if(profile == null || profile.length() == 0) { + profile = getStringSetting("general.signProfile"); + } + // Run player commands if specified + String playerPath = "signProfiles." + profile + "." + getState().getValue().toLowerCase() + "." + clickType.getValue() + "Player"; + List playerCommands = plugin.config().getStringList(playerPath); + runCommands(clicker, playerCommands); + + // Run console commands if specified + String consolePath = "signProfiles." + profile + "." + getState().getValue().toLowerCase() + "." + clickType.getValue() + "Console"; + List consoleCommands = plugin.config().getStringList(consolePath); + runCommands(Bukkit.getConsoleSender(), consoleCommands); + + return !playerCommands.isEmpty() || !consoleCommands.isEmpty(); + } + } @@ -945,5 +1448,11 @@ public abstract class GeneralRegion { + + + + + + diff --git a/AreaShop/src/nl/evolutioncoding/AreaShop/regions/RegionGroup.java b/AreaShop/src/nl/evolutioncoding/AreaShop/regions/RegionGroup.java index ec6ef62..a28fe35 100644 --- a/AreaShop/src/nl/evolutioncoding/AreaShop/regions/RegionGroup.java +++ b/AreaShop/src/nl/evolutioncoding/AreaShop/regions/RegionGroup.java @@ -1,5 +1,6 @@ package nl.evolutioncoding.AreaShop.regions; +import java.util.ArrayList; import java.util.List; import nl.evolutioncoding.AreaShop.AreaShop; @@ -11,43 +12,139 @@ public class RegionGroup { private AreaShop plugin; private String name; + /** + * Constructor, used when creating new groups or restoring them from groups.yml at server boot + * @param plugin The AreaShop plugin + * @param name Name of the group, has to be unique + */ public RegionGroup(AreaShop plugin, String name) { this.plugin = plugin; this.name = name; + setSetting("name", name); + // Delete duplicates + List members = getMembers(); + List newMembers = new ArrayList(); + while(!members.isEmpty()) { + String member = members.remove(0); + // If the region has been deleted also clean it from the group + if(plugin.getFileManager().getRegion(member) != null) { + newMembers.add(member); + } + while(members.contains(member)) { + members.remove(member); + } + } + if(newMembers.size() != members.size()) { + setSetting("regions", newMembers); + save(); + } + if(getMembers().size() == 0) { + plugin.getFileManager().removeGroup(this); + } } - public void addMember(GeneralRegion region) { + /** + * Adds a member to a group + * @param region The region to add to the group (GeneralRegion or a subclass of it) + * @return true if the region was not already added, otherwise false + */ + public boolean addMember(GeneralRegion region) { List members = getMembers(); - members.add(region.getName()); - plugin.getFileManager().getGroupSettings(name).set("regions", members); + if(members.contains(region.getLowerCaseName())) { + return false; + } else { + members.add(region.getName()); + setSetting("regions", members); + save(); + region.updateSigns(); + region.updateRegionFlags(); + return true; + } } - public void removeMember(GeneralRegion region) { + /** + * Remove a member from the group + * @param region The region to remove + * @return true if the region was in the group before, otherwise false + */ + public boolean removeMember(GeneralRegion region) { List members = getMembers(); + boolean result = isMember(region); members.remove(region.getName()); - plugin.getFileManager().getGroupSettings(name).set("regions", members); + if(members.isEmpty()) { + plugin.getFileManager().removeGroup(this); + } else { + setSetting("regions", members); + } + save(); + region.updateSigns(); + region.updateRegionFlags(); + return result; } + /** + * Get all members of the group + * @return A list with the names of all members of the group + */ public List getMembers() { + if(getSettings() == null || getSettings().getStringList("regions") == null) { + return new ArrayList(); + } return getSettings().getStringList("regions"); } + /** + * Get the name of the group + * @return The name of the group + */ public String getName() { return name; + } + /** + * Get the lowercase name of the group (used for getting the config etc) + * @return The name of the group in lowercase + */ + public String getLowerCaseName() { + return getName().toLowerCase(); } + /** + * Check if a region is member of the group + * @param region Region to check + * @return true if the region is in the group, otherwise false + */ public boolean isMember(GeneralRegion region) { - return getMembers().contains(region); + return getMembers().contains(region.getName()); } + /** + * Get the priority of the group (higher overwrites) + * @return The priority of the group + */ public int getPriority() { return getSettings().getInt("priority"); } + /** + * Get the configurationsection with the settings of this group + * @return The ConfigurationSection with the settings of the group + */ public ConfigurationSection getSettings() { return plugin.getFileManager().getGroupSettings(name); } + + /** + * Set a setting of this group + * @param path The path to set + * @param setting The value to set + */ + public void setSetting(String path, Object setting) { + plugin.getFileManager().setGroupSetting(this, path, setting); + } + /** + * Save the group to disk (currently saves all groups because they are all in 1 file) + */ public void save() { plugin.getFileManager().saveGroups(); } diff --git a/AreaShop/src/nl/evolutioncoding/AreaShop/regions/RentRegion.java b/AreaShop/src/nl/evolutioncoding/AreaShop/regions/RentRegion.java index 3165c02..d4d3702 100644 --- a/AreaShop/src/nl/evolutioncoding/AreaShop/regions/RentRegion.java +++ b/AreaShop/src/nl/evolutioncoding/AreaShop/regions/RentRegion.java @@ -5,7 +5,6 @@ import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; -import java.util.Iterator; import java.util.UUID; import net.milkbowl.vault.economy.EconomyResponse; @@ -13,30 +12,12 @@ import nl.evolutioncoding.AreaShop.AreaShop; import nl.evolutioncoding.AreaShop.Exceptions.RegionCreateException; import org.bukkit.Bukkit; -import org.bukkit.Location; +import org.bukkit.OfflinePlayer; import org.bukkit.World; -import org.bukkit.block.Block; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; -public class RentRegion extends GeneralRegion { - - /* Enum for schematic event types */ - public enum RentEvent { - CREATED("created"), - DELETED("deleted"), - RENTED("rented"), - UNRENTED("unrented"); - - private final String value; - private RentEvent(String value) { - this.value = value; - } - public String getValue() { - return value; - } - } - +public class RentRegion extends GeneralRegion { /** * Constructor * @param plugin The areashop plugin @@ -47,10 +28,28 @@ public class RentRegion extends GeneralRegion { super(plugin, config); } - public RentRegion(AreaShop plugin, String name, World world, Location signLocation, double price, String duration) { - super(plugin, name, world, signLocation); - setSetting("price", price); - setSetting("duration", duration); + /** + * Create a new RentRegion + * @param plugin The AreaShop plugin + * @param name The name of the region (correct casing) + * @param world The world of the WorldGuard region + */ + public RentRegion(AreaShop plugin, String name, World world) { + super(plugin, name, world); + } + + @Override + public RegionType getType() { + return RegionType.RENT; + } + + @Override + public RegionState getState() { + if(isRented()) { + return RegionState.RENTED; + } else { + return RegionState.FORRENT; + } } /** @@ -58,7 +57,7 @@ public class RentRegion extends GeneralRegion { * @return The UUID of the renter */ public UUID getRenter() { - String renter = getStringSetting("renter"); + String renter = getStringSetting("rent.renter"); if(renter != null) { try { return UUID.fromString(renter); @@ -67,16 +66,80 @@ public class RentRegion extends GeneralRegion { return null; } + /** + * Check if a player is the renter of this region + * @param player Player to check + * @return true if this player rents this region, otherwise false + */ + public boolean isRenter(Player player) { + UUID renter = getRenter(); + if(player == null || renter == null) { + return false; + } else { + return renter.equals(player.getUniqueId()); + } + } + + /** + * Set the renter of this region + * @param renter The UUID of the player that should be set as the renter + */ public void setRenter(UUID renter) { if(renter == null) { - setSetting("renter", null); - setSetting("renterName", null); + setSetting("rent.renter", null); + setSetting("rent.renterName", null); } else { - setSetting("renter", renter.toString()); - setSetting("renterName", plugin.toName(renter)); + setSetting("rent.renter", renter.toString()); + setSetting("rent.renterName", plugin.toName(renter)); } } + /** + * Get the max number of extends of this region + * @return -1 if infinite otherwise the maximum number + */ + public int getMaxExtends() { + return getIntegerSetting("rent.maxExtends"); + } + + /** + * Get how many times the rent has already been extended + * @return The number of times extended + */ + public int getTimesExtended() { + return config.getInt("rent.timesExtended"); + } + + /** + * Set the number of times the region has been extended + * @param times The number of times the region has been extended + */ + public void setTimesExtended(int times) { + if(times < 0) { + config.set("rent.timesExtended", null); + } else { + config.set("rent.timesExtended", times); + } + } + + @Override + public HashMap getSpecificReplacements() { + // Fill the replacements map with things specific to a RentRegion + HashMap result = new HashMap(); + result.put(AreaShop.tagPrice, getFormattedPrice()); + result.put(AreaShop.tagDuration, getDurationString()); + result.put(AreaShop.tagPlayerName, getPlayerName()); + result.put(AreaShop.tagPlayerUUID, getRenter()); + SimpleDateFormat date = new SimpleDateFormat(plugin.config().getString("timeFormatChat")); + String dateString = date.format(new Date(getRentedUntil())); + result.put(AreaShop.tagRentedUntil, dateString); + date = new SimpleDateFormat(plugin.config().getString("timeFormatSign")); + dateString = date.format(new Date(getRentedUntil())); + result.put(AreaShop.tagRentedUntilShort, dateString); + + return result; + } + /** * Check if the region is rented * @return true if the region is rented, otherwise false @@ -98,14 +161,18 @@ public class RentRegion extends GeneralRegion { * @return */ public long getRentedUntil() { - return getLongSetting("rentedUntil"); + return getLongSetting("rent.rentedUntil"); } + /** + * Set the time until the region is rented (milliseconds from 1970, system time) + * @param rentedUntil The time until the region is rented + */ public void setRentedUntil(Long rentedUntil) { if(rentedUntil == null) { - setSetting("rentedUntil", null); + setSetting("rent.rentedUntil", null); } else { - setSetting("rentedUntil", rentedUntil); + setSetting("rent.rentedUntil", rentedUntil); } } @@ -114,7 +181,7 @@ public class RentRegion extends GeneralRegion { * @return The price of the region */ public double getPrice() { - return getDoubleSetting("price"); + return getDoubleSetting("rent.price"); } /** @@ -164,7 +231,7 @@ public class RentRegion extends GeneralRegion { * @return The duration string */ public String getDurationString() { - return getStringSetting("duration"); + return getStringSetting("rent.duration"); } /** @@ -172,49 +239,15 @@ public class RentRegion extends GeneralRegion { * @param price */ public void setPrice(double price) { - setSetting("price", price); - updateSigns(); - updateRegionFlags(); + setSetting("rent.price", price); } + /** + * Set the duration of the rent + * @param duration The duration of the rent (as specified on the documentation pages) + */ public void setDuration(String duration) { - setSetting("duration", duration); - updateSigns(); - updateRegionFlags(); - } - - public String[] getSignLines() { - String[] lines = new String[4]; - if(isRented()) { - SimpleDateFormat date = new SimpleDateFormat(plugin.config().getString("timeFormatSign")); - String dateString = date.format(new Date(getRentedUntil())); - - lines[0] = plugin.fixColors(plugin.config().getString("signRented")); - lines[1] = getName(); - lines[2] = getPlayerName(); - lines[3] = dateString; - } else { - lines[0] = plugin.fixColors(plugin.config().getString("signRentable")); - lines[1] = getName(); - lines[2] = getDurationString(); - lines[3] = getFormattedPrice(); - } - return lines; - } - - @Override - public void updateRegionFlags() { - HashMap replacements = new HashMap(); - replacements.put(AreaShop.tagRegionName, getName()); - replacements.put(AreaShop.tagPrice, getFormattedPrice()); - replacements.put(AreaShop.tagDuration, getDurationString()); - replacements.put(AreaShop.tagPlayerName, getPlayerName()); - if(isRented()) { - replacements.put(AreaShop.tagRentedUntil, new SimpleDateFormat(plugin.config().getString("timeFormatChat")).format(getRentedUntil())); - this.setRegionFlags(plugin.config().getConfigurationSection("flagsRented"), replacements); - } else { - this.setRegionFlags(plugin.config().getConfigurationSection("flagsForRent"), replacements); - } + setSetting("rent.duration", duration); } /** @@ -223,46 +256,36 @@ public class RentRegion extends GeneralRegion { * @param regionName The name of the region you want to rent * @return true if it succeeded and false if not */ - public boolean rent(Player player) { - Block block = getSignLocation().getBlock(); - + public boolean rent(Player player) { /* Check if the player has permission */ if(player.hasPermission("areashop.rent")) { boolean extend = false; if(getRenter() != null && player.getUniqueId().equals(getRenter())) { extend = true; } - /* Check if the region is available for renting */ + // Check if the region is available for renting or if the player wants to extend the rent if(!isRented() || extend) { if(!extend) { - /* Check if the player can still rent */ - int rentNumber = 0; - Iterator itRent = getFileManager().getRents().iterator(); - while(itRent.hasNext()) { - RentRegion next = itRent.next(); - if(player.getUniqueId().equals(next.getRenter())) { - rentNumber++; - } - } - int buyNumber = 0; - Iterator itBuy = getFileManager().getBuys().iterator(); - while(itBuy.hasNext()) { - BuyRegion next = itBuy.next(); - if(player.getUniqueId().equals(next.getBuyer())) { - buyNumber++; - } - } - int maximumRents = Integer.parseInt(plugin.config().getString("maximumRents")); - if(maximumRents != -1 && rentNumber >= maximumRents) { + // Check if the player can still rent more regions + int maximumRents = getMaxRentRegions(player); + if(getCurrentRentRegions(player) >= maximumRents) { plugin.message(player, "rent-maximum", maximumRents); return false; } - int maximumTotal = Integer.parseInt(plugin.config().getString("maximumTotal")); - if(maximumTotal != -1 && (rentNumber+buyNumber) >= maximumTotal) { + int maximumTotal = getMaxTotalRegions(player); + if(getCurrentTotalRegions(player) >= maximumTotal) { plugin.message(player, "total-maximum", maximumTotal); return false; } - } + } + + // Check if the player can still extend this rent + if(extend && !player.hasPermission("areashop.rentextendbypass")) { + if(getMaxExtends() >= 0 && getTimesExtended() >= getMaxExtends()) { + plugin.message(player, "rent-maxExtends", getMaxExtends()); + return false; + } + } if(plugin.getEconomy().has(player, getWorldName(), getPrice())) { /* Substract the money from the players balance */ @@ -271,6 +294,13 @@ public class RentRegion extends GeneralRegion { plugin.message(player, "rent-payError"); return false; } + if(!extend) { + // Run commands + runEventCommands(RegionEvent.RENTED, true); + } else { + // Run commands + runEventCommands(RegionEvent.EXTENDED, true); + } /* Get the time until the region will be rented */ Calendar calendar = Calendar.getInstance(); @@ -285,13 +315,17 @@ public class RentRegion extends GeneralRegion { setRentedUntil(calendar.getTimeInMillis()); setRenter(player.getUniqueId()); + // Fire schematic event and updated times extended if(!extend) { - this.handleSchematicEvent(RentEvent.RENTED); + this.handleSchematicEvent(RegionEvent.RENTED); + setTimesExtended(0); + } else { + setTimesExtended(getTimesExtended() + 1); } /* Change the sign and the region flags */ updateSigns(); - updateRegionFlags(); + updateRegionFlags(RegionState.RENTED); /* Send message to the player */ if(extend) { @@ -303,13 +337,20 @@ public class RentRegion extends GeneralRegion { AreaShop.debug(player.getName() + " has rented region " + getName() + " for " + getFormattedPrice() + " until " + dateFull.format(calendar.getTime())); this.save(); + if(!extend) { + // Run commands + this.runEventCommands(RegionEvent.RENTED, false); + } else { + // Run commands + this.runEventCommands(RegionEvent.EXTENDED, false); + } return true; } else { /* Player has not enough money */ if(extend) { - plugin.message(player, "rent-lowMoneyExtend", plugin.formatCurrency(plugin.getEconomy().getBalance(player, block.getWorld().getName())), getFormattedPrice()); + plugin.message(player, "rent-lowMoneyExtend", plugin.formatCurrency(plugin.getEconomy().getBalance(player, getWorldName())), getFormattedPrice()); } else { - plugin.message(player, "rent-lowMoneyRent", plugin.formatCurrency(plugin.getEconomy().getBalance(player, block.getWorld().getName())), getFormattedPrice()); + plugin.message(player, "rent-lowMoneyRent", plugin.formatCurrency(plugin.getEconomy().getBalance(player, getWorldName())), getFormattedPrice()); } } } else { @@ -325,80 +366,52 @@ public class RentRegion extends GeneralRegion { * Unrent a region, reset to unrented * @param regionName Region that should be unrented */ - public void unRent(boolean giveMoneyBack) { + public void unRent(boolean giveMoneyBack) { + // Run commands + this.runEventCommands(RegionEvent.UNRENTED, true); /* Get the time until the region will be rented */ Long currentTime = Calendar.getInstance().getTimeInMillis(); Double timeLeft = (double) ((getRentedUntil() - currentTime)); - double percentage = (plugin.config().getDouble("rentMoneyBack")) / 100.0; + double percentage = (getDoubleSetting("rent.moneyBack")) / 100.0; Double timePeriod = (double) (getDuration()); double periods = timeLeft / timePeriod; double moneyBack = periods * getPrice() * percentage; if(moneyBack > 0 && giveMoneyBack) { /* Give back the money */ - EconomyResponse r = plugin.getEconomy().depositPlayer(Bukkit.getOfflinePlayer(getRenter()), moneyBack); - if(!r.transactionSuccess()) { - plugin.getLogger().info("Something went wrong with paying back money while unrenting"); - } + OfflinePlayer player = Bukkit.getOfflinePlayer(getRenter()); + if(player != null) { + EconomyResponse r = null; + boolean error = false; + try { + r = plugin.getEconomy().depositPlayer(Bukkit.getOfflinePlayer(getRenter()), moneyBack); + } catch(Exception e) { + error = true; + } + if(error || r == null || !r.transactionSuccess()) { + plugin.getLogger().info("Something went wrong with paying back to " + getPlayerName() + " money while unrenting region " + getName()); + } + } } - /* Debug message */ AreaShop.debug(getPlayerName() + " has unrented " + getName() + ", got " + plugin.formatCurrency(moneyBack) + " money back"); + /* Update the signs and region flags */ + handleSchematicEvent(RegionEvent.UNRENTED); + updateRegionFlags(RegionState.FORRENT); + /* Remove the player and renteduntil values */ setRenter(null); setRentedUntil(null); + setTimesExtended(-1); - /* Update the signs and region flags */ - handleSchematicEvent(RentEvent.UNRENTED); updateSigns(); - updateRegionFlags(); this.save(); + // Run commands + this.runEventCommands(RegionEvent.UNRENTED, false); } - - - /** - * Checks an event and handles saving to and restoring from schematic for it - * @param type The type of event - */ - public void handleSchematicEvent(RentEvent type) { - // Check for the general killswitch - if(!plugin.config().getBoolean("enableSchematics")) { - return; - } - // Check the individual options - if("false".equalsIgnoreCase(getRestoreSetting())) { - return; - } else if("true".equalsIgnoreCase(getRestoreSetting())) { - } else { - if(!plugin.config().getBoolean("useRentRestore")) { - return; - } - } - // Get the safe and restore names - String save = plugin.config().getString("rentSchematicProfiles." + getRestoreProfile() + "." + type.getValue() + ".save"); - if(save == null) { - plugin.config().getString("rentSchematicProfiles.default." + type.getValue() + ".save"); - } - String restore = plugin.config().getString("rentSchematicProfiles." + getRestoreProfile() + "." + type.getValue() + ".restore"); - if(restore == null) { - plugin.config().getString("rentSchematicProfiles.default." + type.getValue() + ".restore"); - } - // Save the region if needed - if(save != null && save.length() != 0) { - save = save.replace(AreaShop.tagRegionName, getName()); - this.saveRegionBlocks(save); - } - // Restore the region if needed - if(restore != null && restore.length() != 0) { - restore = restore.replace(AreaShop.tagRegionName, getName()); - this.restoreRegionBlocks(restore); - } - } - - }