/
RegionCommands.java
1118 lines (956 loc) · 47.2 KB
/
RegionCommands.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* WorldGuard, a suite of tools for Minecraft
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldGuard team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.commands.region;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.collect.Sets;
import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.minecraft.util.commands.CommandPermissionsException;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.command.util.AsyncCommandBuilder;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extension.platform.Capability;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.util.formatting.component.ErrorFormat;
import com.sk89q.worldedit.util.formatting.component.LabelFormat;
import com.sk89q.worldedit.util.formatting.component.SubtleFormat;
import com.sk89q.worldedit.util.formatting.text.Component;
import com.sk89q.worldedit.util.formatting.text.TextComponent;
import com.sk89q.worldedit.util.formatting.text.event.ClickEvent;
import com.sk89q.worldedit.util.formatting.text.event.HoverEvent;
import com.sk89q.worldedit.util.formatting.text.format.TextColor;
import com.sk89q.worldedit.util.formatting.text.format.TextDecoration;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.commands.CommandUtils;
import com.sk89q.worldguard.commands.task.RegionAdder;
import com.sk89q.worldguard.commands.task.RegionLister;
import com.sk89q.worldguard.commands.task.RegionManagerLoader;
import com.sk89q.worldguard.commands.task.RegionManagerSaver;
import com.sk89q.worldguard.commands.task.RegionRemover;
import com.sk89q.worldguard.config.ConfigurationManager;
import com.sk89q.worldguard.config.WorldConfiguration;
import com.sk89q.worldguard.internal.permission.RegionPermissionModel;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.flags.FlagContext;
import com.sk89q.worldguard.protection.flags.Flags;
import com.sk89q.worldguard.protection.flags.InvalidFlagFormat;
import com.sk89q.worldguard.protection.flags.RegionGroup;
import com.sk89q.worldguard.protection.flags.RegionGroupFlag;
import com.sk89q.worldguard.protection.flags.registry.FlagRegistry;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.managers.RemovalStrategy;
import com.sk89q.worldguard.protection.managers.migration.DriverMigration;
import com.sk89q.worldguard.protection.managers.migration.MigrationException;
import com.sk89q.worldguard.protection.managers.migration.UUIDMigration;
import com.sk89q.worldguard.protection.managers.storage.DriverType;
import com.sk89q.worldguard.protection.managers.storage.RegionDriver;
import com.sk89q.worldguard.protection.regions.GlobalProtectedRegion;
import com.sk89q.worldguard.protection.regions.ProtectedPolygonalRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion.CircularInheritanceException;
import com.sk89q.worldguard.protection.regions.RegionContainer;
import com.sk89q.worldguard.protection.util.DomainInputResolver.UserLocatorPolicy;
import com.sk89q.worldguard.util.Enums;
import com.sk89q.worldguard.util.logging.LoggerToChatHandler;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
/**
* Implements the /region commands for WorldGuard.
*/
public final class RegionCommands extends RegionCommandsBase {
private static final Logger log = Logger.getLogger(RegionCommands.class.getCanonicalName());
private final WorldGuard worldGuard;
public RegionCommands(WorldGuard worldGuard) {
checkNotNull(worldGuard);
this.worldGuard = worldGuard;
}
/**
* Defines a new region.
*
* @param args the arguments
* @param sender the sender
* @throws CommandException any error
*/
@Command(aliases = {"define", "def", "d", "create"},
usage = "<id> [<owner1> [<owner2> [<owners...>]]]",
flags = "ng",
desc = "Defines a region",
min = 1)
public void define(CommandContext args, Actor sender) throws CommandException {
warnAboutSaveFailures(sender);
LocalPlayer player = worldGuard.checkPlayer(sender);
// Check permissions
if (!getPermissionModel(player).mayDefine()) {
throw new CommandPermissionsException();
}
String id = checkRegionId(args.getString(0), false);
RegionManager manager = checkRegionManager(player.getWorld());
checkRegionDoesNotExist(manager, id, true);
ProtectedRegion region;
if (args.hasFlag('g')) {
region = new GlobalProtectedRegion(id);
} else {
region = checkRegionFromSelection(player, id);
warnAboutDimensions(player, region);
informNewUser(player, manager, region);
}
RegionAdder task = new RegionAdder(manager, region);
task.addOwnersFromCommand(args, 2);
final String description = String.format("Adding region '%s'", region.getId());
AsyncCommandBuilder.wrap(task, sender)
.registerWithSupervisor(worldGuard.getSupervisor(), description)
.onSuccess(String.format("A new region has been made named '%s'.", region.getId()), null)
.onFailure("Failed to add the region '%s'", worldGuard.getExceptionConverter())
.buildAndExec(worldGuard.getExecutorService());
}
/**
* Re-defines a region with a new selection.
*
* @param args the arguments
* @param sender the sender
* @throws CommandException any error
*/
@Command(aliases = {"redefine", "update", "move"},
usage = "<id>",
desc = "Re-defines the shape of a region",
flags = "g",
min = 1, max = 1)
public void redefine(CommandContext args, Actor sender) throws CommandException {
warnAboutSaveFailures(sender);
LocalPlayer player = worldGuard.checkPlayer(sender);
String id = checkRegionId(args.getString(0), false);
RegionManager manager = checkRegionManager(player.getWorld());
ProtectedRegion existing = checkExistingRegion(manager, id, false);
// Check permissions
if (!getPermissionModel(player).mayRedefine(existing)) {
throw new CommandPermissionsException();
}
ProtectedRegion region;
if (args.hasFlag('g')) {
region = new GlobalProtectedRegion(id);
} else {
region = checkRegionFromSelection(player, id);
warnAboutDimensions(player, region);
informNewUser(player, manager, region);
}
region.copyFrom(existing);
RegionAdder task = new RegionAdder(manager, region);
final String description = String.format("Updating region '%s'", region.getId());
AsyncCommandBuilder.wrap(task, sender)
.registerWithSupervisor(worldGuard.getSupervisor(), description)
.sendMessageAfterDelay("(Please wait... " + description + ")")
.onSuccess(String.format("Region '%s' has been updated with a new area.", region.getId()), null)
.onFailure(String.format("Failed to update the region '%s'", region.getId()), worldGuard.getExceptionConverter())
.buildAndExec(worldGuard.getExecutorService());
}
/**
* Claiming command for users.
*
* <p>This command is a joke and it needs to be rewritten. It was contributed
* code :(</p>
*
* @param args the arguments
* @param sender the sender
* @throws CommandException any error
*/
@Command(aliases = {"claim"},
usage = "<id>",
desc = "Claim a region",
min = 1, max = 1)
public void claim(CommandContext args, Actor sender) throws CommandException {
warnAboutSaveFailures(sender);
LocalPlayer player = worldGuard.checkPlayer(sender);
RegionPermissionModel permModel = getPermissionModel(player);
// Check permissions
if (!permModel.mayClaim()) {
throw new CommandPermissionsException();
}
String id = checkRegionId(args.getString(0), false);
RegionManager manager = checkRegionManager(player.getWorld());
checkRegionDoesNotExist(manager, id, false);
ProtectedRegion region = checkRegionFromSelection(player, id);
WorldConfiguration wcfg = WorldGuard.getInstance().getPlatform().getGlobalStateManager().get(player.getWorld());
// Check whether the player has created too many regions
if (!permModel.mayClaimRegionsUnbounded()) {
int maxRegionCount = wcfg.getMaxRegionCount(player);
if (maxRegionCount >= 0
&& manager.getRegionCountOfPlayer(player) >= maxRegionCount) {
throw new CommandException(
"You own too many regions, delete one first to claim a new one.");
}
}
ProtectedRegion existing = manager.getRegion(id);
// Check for an existing region
if (existing != null) {
if (!existing.getOwners().contains(player)) {
throw new CommandException(
"This region already exists and you don't own it.");
}
}
// We have to check whether this region violates the space of any other reion
ApplicableRegionSet regions = manager.getApplicableRegions(region);
// Check if this region overlaps any other region
if (regions.size() > 0) {
if (!regions.isOwnerOfAll(player)) {
throw new CommandException("This region overlaps with someone else's region.");
}
} else {
if (wcfg.claimOnlyInsideExistingRegions) {
throw new CommandException("You may only claim regions inside " +
"existing regions that you or your group own.");
}
}
if (wcfg.maxClaimVolume >= Integer.MAX_VALUE) {
throw new CommandException("The maximum claim volume get in the configuration is higher than is supported. " +
"Currently, it must be " + Integer.MAX_VALUE + " or smaller. Please contact a server administrator.");
}
// Check claim volume
if (!permModel.mayClaimRegionsUnbounded()) {
if (region instanceof ProtectedPolygonalRegion) {
throw new CommandException("Polygons are currently not supported for /rg claim.");
}
if (region.volume() > wcfg.maxClaimVolume) {
player.printError("This region is too large to claim.");
player.printError("Max. volume: " + wcfg.maxClaimVolume + ", your volume: " + region.volume());
return;
}
}
RegionAdder task = new RegionAdder(manager, region);
task.setLocatorPolicy(UserLocatorPolicy.UUID_ONLY);
task.setOwnersInput(new String[]{player.getName()});
final String description = String.format("Claiming region '%s'", id);
AsyncCommandBuilder.wrap(task, sender)
.registerWithSupervisor(WorldGuard.getInstance().getSupervisor(), description)
.sendMessageAfterDelay("(Please wait... " + description + ")")
.onSuccess(TextComponent.of(String.format("A new region has been claimed named '%s'.", id)), null)
.onFailure("Failed to claim region", WorldGuard.getInstance().getExceptionConverter())
.buildAndExec(WorldGuard.getInstance().getExecutorService());
}
/**
* Get a WorldEdit selection from a region.
*
* @param args the arguments
* @param sender the sender
* @throws CommandException any error
*/
@Command(aliases = {"select", "sel", "s"},
usage = "[id]",
desc = "Load a region as a WorldEdit selection",
min = 0, max = 1)
public void select(CommandContext args, Actor sender) throws CommandException {
LocalPlayer player = worldGuard.checkPlayer(sender);
RegionManager manager = checkRegionManager(player.getWorld());
ProtectedRegion existing;
// If no arguments were given, get the region that the player is inside
if (args.argsLength() == 0) {
existing = checkRegionStandingIn(manager, player, "/rg select %id%");
} else {
existing = checkExistingRegion(manager, args.getString(0), false);
}
// Check permissions
if (!getPermissionModel(player).maySelect(existing)) {
throw new CommandPermissionsException();
}
// Select
setPlayerSelection(player, existing);
}
/**
* Get information about a region.
*
* @param args the arguments
* @param sender the sender
* @throws CommandException any error
*/
@Command(aliases = {"info", "i"},
usage = "[id]",
flags = "usw:",
desc = "Get information about a region",
min = 0, max = 1)
public void info(CommandContext args, Actor sender) throws CommandException {
warnAboutSaveFailures(sender);
World world = checkWorld(args, sender, 'w'); // Get the world
RegionPermissionModel permModel = getPermissionModel(sender);
// Lookup the existing region
RegionManager manager = checkRegionManager(world);
ProtectedRegion existing;
if (args.argsLength() == 0) { // Get region from where the player is
if (!(sender instanceof LocalPlayer)) {
throw new CommandException("Please specify the region with /region info -w world_name region_name.");
}
existing = checkRegionStandingIn(manager, (LocalPlayer) sender, true,
"/rg info -w " + world.getName() + " %id%" + (args.hasFlag('u') ? " -u" : "") + (args.hasFlag('s') ? " -s" : ""));
} else { // Get region from the ID
existing = checkExistingRegion(manager, args.getString(0), true);
}
// Check permissions
if (!permModel.mayLookup(existing)) {
throw new CommandPermissionsException();
}
// Let the player select the region
if (args.hasFlag('s')) {
// Check permissions
if (!permModel.maySelect(existing)) {
throw new CommandPermissionsException();
}
setPlayerSelection(worldGuard.checkPlayer(sender), existing);
}
// Print region information
RegionPrintoutBuilder printout = new RegionPrintoutBuilder(world.getName(), existing,
args.hasFlag('u') ? null : WorldGuard.getInstance().getProfileCache(), sender);
AsyncCommandBuilder.wrap(printout, sender)
.registerWithSupervisor(WorldGuard.getInstance().getSupervisor(), "Fetching region info")
.sendMessageAfterDelay("(Please wait... fetching region information...)")
.onSuccess((Component) null, sender::print)
.onFailure("Failed to fetch region information", WorldGuard.getInstance().getExceptionConverter())
.buildAndExec(WorldGuard.getInstance().getExecutorService());
}
/**
* List regions.
*
* @param args the arguments
* @param sender the sender
* @throws CommandException any error
*/
@Command(aliases = {"list"},
usage = "[page]",
desc = "Get a list of regions",
flags = "np:w:",
max = 1)
public void list(CommandContext args, Actor sender) throws CommandException {
warnAboutSaveFailures(sender);
World world = checkWorld(args, sender, 'w'); // Get the world
String ownedBy;
// Get page
int page = args.getInteger(0, 1);
if (page < 1) {
page = 1;
}
// -p flag to lookup a player's regions
if (args.hasFlag('p')) {
ownedBy = args.getFlag('p');
} else {
ownedBy = null; // List all regions
}
// Check permissions
if (!getPermissionModel(sender).mayList(ownedBy)) {
ownedBy = sender.getName(); // assume they only want their own
if (!getPermissionModel(sender).mayList(ownedBy)) {
throw new CommandPermissionsException();
}
}
RegionManager manager = checkRegionManager(world);
RegionLister task = new RegionLister(manager, sender, world.getName());
task.setPage(page);
if (ownedBy != null) {
task.filterOwnedByName(ownedBy, args.hasFlag('n'));
}
AsyncCommandBuilder.wrap(task, sender)
.registerWithSupervisor(WorldGuard.getInstance().getSupervisor(), "Getting region list")
.sendMessageAfterDelay("(Please wait... fetching region list...)")
.onFailure("Failed to fetch region list", WorldGuard.getInstance().getExceptionConverter())
.buildAndExec(WorldGuard.getInstance().getExecutorService());
}
/**
* Set a flag.
*
* @param args the arguments
* @param sender the sender
* @throws CommandException any error
*/
@Command(aliases = {"flag", "f"},
usage = "<id> <flag> [-w world] [-g group] [value]",
flags = "g:w:eh:",
desc = "Set flags",
min = 2)
public void flag(CommandContext args, Actor sender) throws CommandException {
warnAboutSaveFailures(sender);
World world = checkWorld(args, sender, 'w'); // Get the world
String flagName = args.getString(1);
String value = args.argsLength() >= 3 ? args.getJoinedStrings(2) : null;
RegionGroup groupValue = null;
FlagRegistry flagRegistry = WorldGuard.getInstance().getFlagRegistry();
RegionPermissionModel permModel = getPermissionModel(sender);
if (args.hasFlag('e')) {
if (value != null) {
throw new CommandException("You cannot use -e(mpty) with a flag value.");
}
value = "";
}
// Add color codes
if (value != null) {
value = CommandUtils.replaceColorMacros(value);
}
// Lookup the existing region
RegionManager manager = checkRegionManager(world);
ProtectedRegion existing = checkExistingRegion(manager, args.getString(0), true);
// Check permissions
if (!permModel.maySetFlag(existing)) {
throw new CommandPermissionsException();
}
Flag<?> foundFlag = Flags.fuzzyMatchFlag(flagRegistry, flagName);
// We didn't find the flag, so let's print a list of flags that the user
// can use, and do nothing afterwards
if (foundFlag == null) {
ArrayList<String> flagList = new ArrayList<>();
// Need to build a list
for (Flag<?> flag : flagRegistry) {
// Can the user set this flag?
if (!permModel.maySetFlag(existing, flag)) {
continue;
}
flagList.add(flag.getName());
}
Collections.sort(flagList);
final TextComponent.Builder builder = TextComponent.builder("Available flags: ");
final HoverEvent clickToSet = HoverEvent.of(HoverEvent.Action.SHOW_TEXT, TextComponent.of("Click to set"));
for (int i = 0; i < flagList.size(); i++) {
String flag = flagList.get(i);
builder.append(TextComponent.of(flag, i % 2 == 0 ? TextColor.GRAY : TextColor.WHITE)
.hoverEvent(clickToSet).clickEvent(ClickEvent.of(ClickEvent.Action.SUGGEST_COMMAND,
"/rg flag -w " + world.getName() + " " + existing.getId() + " " + flag + " ")));
if (i < flagList.size() + 1) {
builder.append(TextComponent.of(", "));
}
}
sender.printError("Unknown flag specified: " + flagName);
sender.print(builder.build());
if (sender.isPlayer()) {
sender.print(TextComponent.of("Or use the command ", TextColor.LIGHT_PURPLE)
.append(TextComponent.of("/rg flags " + existing.getId(), TextColor.AQUA)
.clickEvent(ClickEvent.of(ClickEvent.Action.RUN_COMMAND,
"/rg flags -w " + world.getName() + " " + existing.getId()))));
}
return;
} else if (value != null) {
if (foundFlag == Flags.BUILD || foundFlag == Flags.BLOCK_BREAK || foundFlag == Flags.BLOCK_PLACE) {
sender.print(TextComponent.empty().append(TextComponent.of("WARNING:", TextColor.RED, Sets.newHashSet(TextDecoration.BOLD)))
.append(ErrorFormat.wrap(" Setting the " + foundFlag.getName() + " flag is not required for protection."))
.append(TextComponent.newline())
.append(TextComponent.of("Setting this flag will completely override default protection, and apply" +
" to members, non-members, pistons, and everything else that can modify blocks."))
.append(TextComponent.newline())
.append(TextComponent.of("Only set this flag if you are sure you know what you are doing. See ")
.append(TextComponent.of("[this documentation page]", TextColor.AQUA)
.clickEvent(ClickEvent.of(ClickEvent.Action.OPEN_URL,
"https://worldguard.enginehub.org/en/latest/regions/flags/#protection-related")))
.append(TextComponent.of(" for more info."))));
if (!sender.isPlayer()) {
sender.printRaw("https://worldguard.enginehub.org/en/latest/regions/flags/#protection-related");
}
} else if (foundFlag == Flags.PASSTHROUGH) {
sender.print(TextComponent.empty().append(TextComponent.of("WARNING:", TextColor.RED, Sets.newHashSet(TextDecoration.BOLD)))
.append(ErrorFormat.wrap(" This flag is unrelated to moving through regions."))
.append(TextComponent.newline())
.append(TextComponent.of("It overrides build checks. If you're unsure what this means, see ")
.append(TextComponent.of("[this documentation page]", TextColor.AQUA)
.clickEvent(ClickEvent.of(ClickEvent.Action.OPEN_URL,
"https://worldguard.enginehub.org/en/latest/regions/flags/#overrides")))
.append(TextComponent.of(" for more info."))));
if (!sender.isPlayer()) {
sender.printRaw("https://worldguard.enginehub.org/en/latest/regions/flags/#overrides");
}
}
}
// Also make sure that we can use this flag
// This permission is confusing and probably should be replaced, but
// but not here -- in the model
if (!permModel.maySetFlag(existing, foundFlag, value)) {
throw new CommandPermissionsException();
}
// -g for group flag
if (args.hasFlag('g')) {
String group = args.getFlag('g');
RegionGroupFlag groupFlag = foundFlag.getRegionGroupFlag();
if (groupFlag == null) {
throw new CommandException("Region flag '" + foundFlag.getName()
+ "' does not have a group flag!");
}
// Parse the [-g group] separately so entire command can abort if parsing
// the [value] part throws an error.
try {
groupValue = groupFlag.parseInput(FlagContext.create().setSender(sender).setInput(group).setObject("region", existing).build());
} catch (InvalidFlagFormat e) {
throw new CommandException(e.getMessage());
}
}
// Set the flag value if a value was set
if (value != null) {
// Set the flag if [value] was given even if [-g group] was given as well
try {
setFlag(existing, foundFlag, sender, value);
} catch (InvalidFlagFormat e) {
throw new CommandException(e.getMessage());
}
if (!args.hasFlag('h')) {
sender.print("Region flag " + foundFlag.getName() + " set on '" + existing.getId() + "' to '" + value + "'.");
}
// No value? Clear the flag, if -g isn't specified
} else if (!args.hasFlag('g')) {
// Clear the flag only if neither [value] nor [-g group] was given
existing.setFlag(foundFlag, null);
// Also clear the associated group flag if one exists
RegionGroupFlag groupFlag = foundFlag.getRegionGroupFlag();
if (groupFlag != null) {
existing.setFlag(groupFlag, null);
}
if (!args.hasFlag('h')) {
sender.print("Region flag " + foundFlag.getName() + " removed from '" + existing.getId() + "'. (Any -g(roups) were also removed.)");
}
}
// Now set the group
if (groupValue != null) {
RegionGroupFlag groupFlag = foundFlag.getRegionGroupFlag();
// If group set to the default, then clear the group flag
if (groupValue == groupFlag.getDefault()) {
existing.setFlag(groupFlag, null);
sender.print("Region group flag for '" + foundFlag.getName() + "' reset to default.");
} else {
existing.setFlag(groupFlag, groupValue);
sender.print("Region group flag for '" + foundFlag.getName() + "' set.");
}
}
// Print region information
if (args.hasFlag('h')) {
int page = args.getFlagInteger('h');
sendFlagHelper(sender, world, existing, permModel, page);
} else {
RegionPrintoutBuilder printout = new RegionPrintoutBuilder(world.getName(), existing, null, sender);
printout.append(SubtleFormat.wrap("(Current flags: "));
printout.appendFlagsList(false);
printout.append(SubtleFormat.wrap(")"));
printout.send(sender);
}
}
@Command(aliases = "flags",
usage = "[-p <page>] [id]",
flags = "p:w:",
desc = "View region flags",
min = 0, max = 2)
public void flagHelper(CommandContext args, Actor sender) throws CommandException {
World world = checkWorld(args, sender, 'w'); // Get the world
// Lookup the existing region
RegionManager manager = checkRegionManager(world);
ProtectedRegion region;
if (args.argsLength() == 0) { // Get region from where the player is
if (!(sender instanceof LocalPlayer)) {
throw new CommandException("Please specify the region with /region info -w world_name region_name.");
}
region = checkRegionStandingIn(manager, (LocalPlayer) sender, true,
"/rg flags -w " + world.getName() + " %id%");
} else { // Get region from the ID
region = checkExistingRegion(manager, args.getString(0), true);
}
final RegionPermissionModel perms = getPermissionModel(sender);
if (!perms.mayLookup(region)) {
throw new CommandPermissionsException();
}
int page = args.hasFlag('p') ? args.getFlagInteger('p') : 1;
sendFlagHelper(sender, world, region, perms, page);
}
private static void sendFlagHelper(Actor sender, World world, ProtectedRegion region, RegionPermissionModel perms, int page) {
final FlagHelperBox flagHelperBox = new FlagHelperBox(world, region, perms);
flagHelperBox.setComponentsPerPage(18);
AsyncCommandBuilder.wrap(() -> flagHelperBox.create(page), sender)
.onSuccess((Component) null, sender::print)
.onFailure("Failed to get region flags", WorldGuard.getInstance().getExceptionConverter())
.buildAndExec(WorldGuard.getInstance().getExecutorService());
}
/**
* Set the priority of a region.
*
* @param args the arguments
* @param sender the sender
* @throws CommandException any error
*/
@Command(aliases = {"setpriority", "priority", "pri"},
usage = "<id> <priority>",
flags = "w:",
desc = "Set the priority of a region",
min = 2, max = 2)
public void setPriority(CommandContext args, Actor sender) throws CommandException {
warnAboutSaveFailures(sender);
World world = checkWorld(args, sender, 'w'); // Get the world
int priority = args.getInteger(1);
// Lookup the existing region
RegionManager manager = checkRegionManager(world);
ProtectedRegion existing = checkExistingRegion(manager, args.getString(0), false);
// Check permissions
if (!getPermissionModel(sender).maySetPriority(existing)) {
throw new CommandPermissionsException();
}
existing.setPriority(priority);
sender.print("Priority of '" + existing.getId() + "' set to " + priority + " (higher numbers override).");
}
/**
* Set the parent of a region.
*
* @param args the arguments
* @param sender the sender
* @throws CommandException any error
*/
@Command(aliases = {"setparent", "parent", "par"},
usage = "<id> [parent-id]",
flags = "w:",
desc = "Set the parent of a region",
min = 1, max = 2)
public void setParent(CommandContext args, Actor sender) throws CommandException {
warnAboutSaveFailures(sender);
World world = checkWorld(args, sender, 'w'); // Get the world
ProtectedRegion parent;
ProtectedRegion child;
// Lookup the existing region
RegionManager manager = checkRegionManager(world);
// Get parent and child
child = checkExistingRegion(manager, args.getString(0), false);
if (args.argsLength() == 2) {
parent = checkExistingRegion(manager, args.getString(1), false);
} else {
parent = null;
}
// Check permissions
if (!getPermissionModel(sender).maySetParent(child, parent)) {
throw new CommandPermissionsException();
}
try {
child.setParent(parent);
} catch (CircularInheritanceException e) {
// Tell the user what's wrong
RegionPrintoutBuilder printout = new RegionPrintoutBuilder(world.getName(), parent, null, sender);
assert parent != null;
printout.append(ErrorFormat.wrap("Uh oh! Setting '", parent.getId(), "' to be the parent of '", child.getId(),
"' would cause circular inheritance.")).newline();
printout.append(SubtleFormat.wrap("(Current inheritance on '", parent.getId(), "':")).newline();
printout.appendParentTree(true);
printout.append(SubtleFormat.wrap(")"));
printout.send(sender);
return;
}
// Tell the user the current inheritance
RegionPrintoutBuilder printout = new RegionPrintoutBuilder(world.getName(), child, null, sender);
printout.append(LabelFormat.wrap("Inheritance set for region '", child.getId(), "'."));
if (parent != null) {
printout.newline();
printout.append(SubtleFormat.wrap("(Current inheritance:")).newline();
printout.appendParentTree(true);
printout.append(SubtleFormat.wrap(")"));
} else {
printout.append(LabelFormat.wrap(" Region is now orphaned."));
}
printout.send(sender);
}
/**
* Remove a region.
*
* @param args the arguments
* @param sender the sender
* @throws CommandException any error
*/
@Command(aliases = {"remove", "delete", "del", "rem"},
usage = "<id>",
flags = "fuw:",
desc = "Remove a region",
min = 1, max = 1)
public void remove(CommandContext args, Actor sender) throws CommandException {
warnAboutSaveFailures(sender);
World world = checkWorld(args, sender, 'w'); // Get the world
boolean removeChildren = args.hasFlag('f');
boolean unsetParent = args.hasFlag('u');
// Lookup the existing region
RegionManager manager = checkRegionManager(world);
ProtectedRegion existing = checkExistingRegion(manager, args.getString(0), true);
// Check permissions
if (!getPermissionModel(sender).mayDelete(existing)) {
throw new CommandPermissionsException();
}
RegionRemover task = new RegionRemover(manager, existing);
if (removeChildren && unsetParent) {
throw new CommandException("You cannot use both -u (unset parent) and -f (remove children) together.");
} else if (removeChildren) {
task.setRemovalStrategy(RemovalStrategy.REMOVE_CHILDREN);
} else if (unsetParent) {
task.setRemovalStrategy(RemovalStrategy.UNSET_PARENT_IN_CHILDREN);
}
final String description = String.format("Removing region '%s' in '%s'", existing.getId(), world.getName());
AsyncCommandBuilder.wrap(task, sender)
.registerWithSupervisor(WorldGuard.getInstance().getSupervisor(), description)
.sendMessageAfterDelay("Please wait... removing region.")
.onSuccess((Component) null, removed -> sender.print(TextComponent.of(
"Successfully removed " + removed.stream().map(ProtectedRegion::getId).collect(Collectors.joining(", ")) + ".",
TextColor.LIGHT_PURPLE)))
.onFailure("Failed to remove region", WorldGuard.getInstance().getExceptionConverter())
.buildAndExec(WorldGuard.getInstance().getExecutorService());
}
/**
* Reload the region database.
*
* @param args the arguments
* @param sender the sender
* @throws CommandException any error
*/
@Command(aliases = {"load", "reload"},
usage = "[world]",
desc = "Reload regions from file",
flags = "w:")
public void load(CommandContext args, final Actor sender) throws CommandException {
warnAboutSaveFailures(sender);
World world = null;
try {
world = checkWorld(args, sender, 'w'); // Get the world
} catch (CommandException ignored) {
// assume the user wants to reload all worlds
}
// Check permissions
if (!getPermissionModel(sender).mayForceLoadRegions()) {
throw new CommandPermissionsException();
}
if (world != null) {
RegionManager manager = checkRegionManager(world);
if (manager == null) {
throw new CommandException("No region manager exists for world '" + world.getName() + "'.");
}
final String description = String.format("Loading region data for '%s'.", world.getName());
AsyncCommandBuilder.wrap(new RegionManagerLoader(manager), sender)
.registerWithSupervisor(worldGuard.getSupervisor(), description)
.sendMessageAfterDelay("Please wait... " + description)
.onSuccess(String.format("Loaded region data for '%s'", world.getName()), null)
.onFailure(String.format("Failed to load region data for '%s'", world.getName()), worldGuard.getExceptionConverter())
.buildAndExec(worldGuard.getExecutorService());
} else {
// Load regions for all worlds
List<RegionManager> managers = new ArrayList<>();
for (World w : WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.GAME_HOOKS).getWorlds()) {
RegionManager manager = WorldGuard.getInstance().getPlatform().getRegionContainer().get(w);
if (manager != null) {
managers.add(manager);
}
}
AsyncCommandBuilder.wrap(new RegionManagerLoader(managers), sender)
.registerWithSupervisor(worldGuard.getSupervisor(), "Loading regions for all worlds")
.sendMessageAfterDelay("(Please wait... loading region data for all worlds...)")
.onSuccess("Successfully load the region data for all worlds.", null)
.onFailure("Failed to load regions for all worlds", worldGuard.getExceptionConverter())
.buildAndExec(worldGuard.getExecutorService());
}
}
/**
* Re-save the region database.
*
* @param args the arguments
* @param sender the sender
* @throws CommandException any error
*/
@Command(aliases = {"save", "write"},
usage = "[world]",
desc = "Re-save regions to file",
flags = "w:")
public void save(CommandContext args, final Actor sender) throws CommandException {
warnAboutSaveFailures(sender);
World world = null;
try {
world = checkWorld(args, sender, 'w'); // Get the world
} catch (CommandException ignored) {
// assume user wants to save all worlds
}
// Check permissions
if (!getPermissionModel(sender).mayForceSaveRegions()) {
throw new CommandPermissionsException();
}
if (world != null) {
RegionManager manager = checkRegionManager(world);
if (manager == null) {
throw new CommandException("No region manager exists for world '" + world.getName() + "'.");
}
final String description = String.format("Saving region data for '%s'.", world.getName());
AsyncCommandBuilder.wrap(new RegionManagerSaver(manager), sender)
.registerWithSupervisor(worldGuard.getSupervisor(), description)
.sendMessageAfterDelay("Please wait... " + description)
.onSuccess(String.format("Saving region data for '%s'", world.getName()), null)
.onFailure(String.format("Failed to save region data for '%s'", world.getName()), worldGuard.getExceptionConverter())
.buildAndExec(worldGuard.getExecutorService());
} else {
// Save for all worlds
List<RegionManager> managers = new ArrayList<>();
final RegionContainer regionContainer = worldGuard.getPlatform().getRegionContainer();
for (World w : WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.GAME_HOOKS).getWorlds()) {
RegionManager manager = regionContainer.get(w);
if (manager != null) {
managers.add(manager);
}
}
AsyncCommandBuilder.wrap(new RegionManagerSaver(managers), sender)
.registerWithSupervisor(worldGuard.getSupervisor(), "Saving regions for all worlds")
.sendMessageAfterDelay("(Please wait... saving region data for all worlds...)")
.onSuccess("Successfully saved the region data for all worlds.", null)
.onFailure("Failed to save regions for all worlds", worldGuard.getExceptionConverter())
.buildAndExec(worldGuard.getExecutorService());
}
}
/**
* Migrate the region database.
*
* @param args the arguments
* @param sender the sender
* @throws CommandException any error
*/
@Command(aliases = {"migratedb"}, usage = "<from> <to>",
flags = "y",
desc = "Migrate from one Protection Database to another.", min = 2, max = 2)
public void migrateDB(CommandContext args, Actor sender) throws CommandException {
// Check permissions
if (!getPermissionModel(sender).mayMigrateRegionStore()) {
throw new CommandPermissionsException();
}
DriverType from = Enums.findFuzzyByValue(DriverType.class, args.getString(0));
DriverType to = Enums.findFuzzyByValue(DriverType.class, args.getString(1));
if (from == null) {
throw new CommandException("The value of 'from' is not a recognized type of region data database.");
}
if (to == null) {
throw new CommandException("The value of 'to' is not a recognized type of region region data database.");
}
if (from == to) {
throw new CommandException("It is not possible to migrate between the same types of region data databases.");
}
if (!args.hasFlag('y')) {
throw new CommandException("This command is potentially dangerous.\n" +
"Please ensure you have made a backup of your data, and then re-enter the command with -y tacked on at the end to proceed.");
}
ConfigurationManager config = WorldGuard.getInstance().getPlatform().getGlobalStateManager();
RegionDriver fromDriver = config.regionStoreDriverMap.get(from);
RegionDriver toDriver = config.regionStoreDriverMap.get(to);
if (fromDriver == null) {
throw new CommandException("The driver specified as 'from' does not seem to be supported in your version of WorldGuard.");
}
if (toDriver == null) {
throw new CommandException("The driver specified as 'to' does not seem to be supported in your version of WorldGuard.");
}
DriverMigration migration = new DriverMigration(fromDriver, toDriver, WorldGuard.getInstance().getFlagRegistry());