-
-
Notifications
You must be signed in to change notification settings - Fork 663
/
Copy pathhouse.cpp
974 lines (818 loc) · 26.5 KB
/
house.cpp
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
/**
* Canary - A free and open-source MMORPG server emulator
* Copyright (©) 2019-2024 OpenTibiaBR <opentibiabr@outlook.com>
* Repository: https://github.com/opentibiabr/canary
* License: https://github.com/opentibiabr/canary/blob/main/LICENSE
* Contributors: https://github.com/opentibiabr/canary/graphs/contributors
* Website: https://docs.opentibiabr.com/
*/
#include "utils/pugicast.hpp"
#include "map/house/house.hpp"
#include "io/iologindata.hpp"
#include "game/game.hpp"
#include "items/bed.hpp"
#include "game/scheduling/save_manager.hpp"
#include "lib/metrics/metrics.hpp"
House::House(uint32_t houseId) :
id(houseId) { }
void House::addTile(std::shared_ptr<HouseTile> tile) {
tile->setFlag(TILESTATE_PROTECTIONZONE);
houseTiles.push_back(tile);
updateDoorDescription();
}
void House::setNewOwnerGuid(int32_t newOwnerGuid, bool serverStartup) {
auto isTransferOnRestart = g_configManager().getBoolean(TOGGLE_HOUSE_TRANSFER_ON_SERVER_RESTART);
if (!isTransferOnRestart) {
setOwner(newOwnerGuid, true);
return;
}
std::ostringstream query;
query << "UPDATE `houses` SET `new_owner` = " << newOwnerGuid << " WHERE `id` = " << id;
Database &db = Database::getInstance();
db.executeQuery(query.str());
if (!serverStartup) {
setNewOwnership();
}
}
void House::clearHouseInfo(bool preventOwnerDeletion) {
// Remove players from beds
for (const auto &bed : bedsList) {
if (bed->getSleeper() != 0) {
bed->wakeUp(nullptr);
}
}
// Clean access lists
if (!preventOwnerDeletion) {
owner = 0;
ownerAccountId = 0;
}
// Clean access lists
setAccessList(SUBOWNER_LIST, "");
setAccessList(GUEST_LIST, "");
for (const auto &door : doorList) {
door->setAccessList("");
}
}
bool House::tryTransferOwnership(std::shared_ptr<Player> player, bool serverStartup) {
bool transferSuccess = false;
if (player) {
transferSuccess = transferToDepot(player);
} else {
transferSuccess = transferToDepot();
}
for (const auto &tile : houseTiles) {
if (const CreatureVector* creatures = tile->getCreatures()) {
for (int32_t i = creatures->size(); --i >= 0;) {
const auto creature = (*creatures)[i];
kickPlayer(nullptr, creature->getPlayer());
}
}
}
clearHouseInfo(serverStartup);
return transferSuccess;
}
void House::setOwner(uint32_t guid, bool updateDatabase /* = true*/, std::shared_ptr<Player> player /* = nullptr*/) {
if (updateDatabase && owner != guid) {
Database &db = Database::getInstance();
std::ostringstream query;
query << "UPDATE `houses` SET `owner` = " << guid << ", `new_owner` = -1, `paid` = 0, `bidder` = 0, `bidder_name` = '', `highest_bid` = 0, `internal_bid` = 0, `bid_end_date` = 0, `state` = 0 WHERE `id` = " << id;
db.executeQuery(query.str());
}
if (isLoaded && owner == guid) {
return;
}
isLoaded = true;
if (owner != 0) {
tryTransferOwnership(std::move(player), false);
}
if (guid != 0) {
std::string strRentPeriod = asLowerCaseString(g_configManager().getString(HOUSE_RENT_PERIOD));
time_t currentTime = time(nullptr);
if (strRentPeriod == "yearly") {
currentTime += 24 * 60 * 60 * 365;
} else if (strRentPeriod == "monthly") {
currentTime += 24 * 60 * 60 * 30;
} else if (strRentPeriod == "weekly") {
currentTime += 24 * 60 * 60 * 7;
} else if (strRentPeriod == "daily") {
currentTime += 24 * 60 * 60;
} else {
currentTime = 0;
}
paidUntil = currentTime;
} else {
paidUntil = 0;
}
rentWarnings = 0;
if (guid != 0) {
Database &db = Database::getInstance();
std::ostringstream query;
query << "SELECT `name`, `account_id` FROM `players` WHERE `id` = " << guid;
DBResult_ptr result = db.storeQuery(query.str());
if (!result) {
return;
}
std::string name = result->getString("name");
if (!name.empty()) {
owner = guid;
ownerName = name;
ownerAccountId = result->getNumber<uint32_t>("account_id");
m_state = 2;
}
}
updateDoorDescription();
}
void House::updateDoorDescription() const {
std::ostringstream ss;
if (owner != 0) {
ss << "It belongs to house '" << houseName << "'. " << ownerName << " owns this house.";
} else {
ss << "It belongs to house '" << houseName << "'. Nobody owns this house.";
}
if (!g_configManager().getBoolean(CYCLOPEDIA_HOUSE_AUCTION)) {
ss << " It is " << getSize() << " square meters.";
const int32_t housePrice = getPrice();
if (housePrice != -1) {
if (g_configManager().getBoolean(HOUSE_PURSHASED_SHOW_PRICE) || owner == 0) {
ss << " It costs " << formatNumber(getPrice()) << " gold coins.";
}
std::string strRentPeriod = asLowerCaseString(g_configManager().getString(HOUSE_RENT_PERIOD));
if (strRentPeriod != "never") {
ss << " The rent cost is " << formatNumber(getRent()) << " gold coins and it is billed " << strRentPeriod << ".";
}
}
}
for (const auto &it : doorList) {
it->setAttribute(ItemAttribute_t::DESCRIPTION, ss.str());
}
}
AccessHouseLevel_t House::getHouseAccessLevel(std::shared_ptr<Player> player) const {
if (!player) {
return HOUSE_OWNER;
}
if (g_configManager().getBoolean(HOUSE_OWNED_BY_ACCOUNT)) {
if (ownerAccountId == player->getAccountId()) {
return HOUSE_OWNER;
}
}
if (player->hasFlag(PlayerFlags_t::CanEditHouses)) {
return HOUSE_OWNER;
}
if (player->getGUID() == owner) {
return HOUSE_OWNER;
}
if (subOwnerList.isInList(player)) {
return HOUSE_SUBOWNER;
}
if (guestList.isInList(player)) {
return HOUSE_GUEST;
}
return HOUSE_NOT_INVITED;
}
bool House::kickPlayer(std::shared_ptr<Player> player, std::shared_ptr<Player> target) {
if (!target) {
return false;
}
std::shared_ptr<HouseTile> houseTile = std::dynamic_pointer_cast<HouseTile>(target->getTile());
if (!houseTile || houseTile->getHouse() != static_self_cast<House>()) {
return false;
}
if (getHouseAccessLevel(player) < getHouseAccessLevel(target) || target->hasFlag(PlayerFlags_t::CanEditHouses)) {
return false;
}
Position oldPosition = target->getPosition();
if (g_game().internalTeleport(target, getEntryPosition()) == RETURNVALUE_NOERROR) {
g_game().addMagicEffect(oldPosition, CONST_ME_POFF);
g_game().addMagicEffect(getEntryPosition(), CONST_ME_TELEPORT);
}
return true;
}
void House::setAccessList(uint32_t listId, const std::string &textlist) {
if (listId == GUEST_LIST) {
guestList.parseList(textlist);
} else if (listId == SUBOWNER_LIST) {
subOwnerList.parseList(textlist);
} else {
std::shared_ptr<Door> door = getDoorByNumber(listId);
if (door) {
door->setAccessList(textlist);
}
// We dont have kick anyone
return;
}
// kick uninvited players
for (const std::shared_ptr<HouseTile> &tile : houseTiles) {
if (CreatureVector* creatures = tile->getCreatures()) {
for (int32_t i = creatures->size(); --i >= 0;) {
std::shared_ptr<Player> player = (*creatures)[i]->getPlayer();
if (player && !isInvited(player)) {
kickPlayer(nullptr, player);
}
}
}
}
}
bool House::transferToDepot() const {
if (townId == 0) {
return false;
}
std::shared_ptr<Player> player = g_game().getPlayerByGUID(owner);
if (player) {
transferToDepot(player);
} else {
std::shared_ptr<Player> tmpPlayer = std::make_shared<Player>(nullptr);
if (!IOLoginData::loadPlayerById(tmpPlayer, owner)) {
return false;
}
transferToDepot(tmpPlayer);
}
return true;
}
bool House::transferToDepot(std::shared_ptr<Player> player) const {
if (townId == 0 || !player) {
return false;
}
for (const std::shared_ptr<HouseTile> &tile : houseTiles) {
if (!transferToDepot(player, tile)) {
return false;
}
}
return true;
}
bool House::transferToDepot(std::shared_ptr<Player> player, std::shared_ptr<HouseTile> tile) const {
if (townId == 0 || !player) {
return false;
}
if (tile->getHouse().get() != this) {
g_logger().debug("[{}] tile house is not this house", __FUNCTION__);
return false;
}
ItemList moveItemList;
if (const TileItemVector* items = tile->getItemList()) {
for (const std::shared_ptr<Item> &item : *items) {
if (item->isWrapable()) {
handleWrapableItem(moveItemList, item, player, tile);
} else if (item->isPickupable()) {
moveItemList.push_back(item);
} else {
handleContainer(moveItemList, item);
}
}
}
std::unordered_set<std::shared_ptr<Player>> playersToSave = { player };
for (const std::shared_ptr<Item> &item : moveItemList) {
g_logger().debug("[{}] moving item '{}' to depot", __FUNCTION__, item->getName());
auto targetPlayer = player;
if (item->hasOwner() && !item->isOwner(targetPlayer)) {
targetPlayer = g_game().getPlayerByGUID(item->getOwnerId());
if (!targetPlayer) {
g_game().internalRemoveItem(item, item->getItemCount());
continue;
}
playersToSave.insert(targetPlayer);
}
g_game().internalMoveItem(item->getParent(), targetPlayer->getInbox(), INDEX_WHEREEVER, item, item->getItemCount(), nullptr, FLAG_NOLIMIT);
}
for (const auto &playerToSave : playersToSave) {
g_saveManager().savePlayer(playerToSave);
}
return true;
}
bool House::hasItemOnTile() const {
bool foundItem = false;
for (const std::shared_ptr<HouseTile> &tile : houseTiles) {
if (const auto &items = tile->getItemList()) {
for (const std::shared_ptr<Item> &item : *items) {
if (!item) {
continue;
}
if (item->isWrapable()) {
foundItem = true;
g_logger().error("It is not possible to purchase a house with wrap item inside: id '{}', name '{}'", item->getID(), item->getName());
break;
} else if (item->isPickupable()) {
foundItem = true;
g_logger().error("It is not possible to purchase a house with pickupable item inside: id '{}', name '{}'", item->getID(), item->getName());
break;
} else {
if (item->getContainer() && (item->isPickupable() || item->isWrapable())) {
foundItem = true;
g_logger().error("It is not possible to purchase a house with container item inside: id '{}', name '{}'", item->getID(), item->getName());
break;
}
}
}
}
}
return foundItem;
}
bool House::hasNewOwnership() const {
return hasNewOwnerOnStartup;
}
void House::setNewOwnership() {
hasNewOwnerOnStartup = true;
}
void House::handleWrapableItem(ItemList &moveItemList, std::shared_ptr<Item> item, std::shared_ptr<Player> player, std::shared_ptr<HouseTile> houseTile) const {
if (item->isWrapContainer()) {
g_logger().debug("[{}] found wrapable item '{}'", __FUNCTION__, item->getName());
handleContainer(moveItemList, item);
}
std::shared_ptr<Item> newItem = g_game().wrapItem(item, houseTile->getHouse());
if (newItem->isRemoved() && !newItem->getParent()) {
g_logger().warn("[{}] item removed during wrapping - check ground type - player name: {} item id: {} position: {}", __FUNCTION__, player->getName(), item->getID(), houseTile->getPosition().toString());
return;
}
moveItemList.push_back(newItem);
}
void House::handleContainer(ItemList &moveItemList, std::shared_ptr<Item> item) const {
if (const auto container = item->getContainer()) {
for (const std::shared_ptr<Item> &containerItem : container->getItemList()) {
moveItemList.push_back(containerItem);
}
}
}
bool House::getAccessList(uint32_t listId, std::string &list) const {
if (listId == GUEST_LIST) {
guestList.getList(list);
return true;
} else if (listId == SUBOWNER_LIST) {
subOwnerList.getList(list);
return true;
}
std::shared_ptr<Door> door = getDoorByNumber(listId);
if (!door) {
return false;
}
return door->getAccessList(list);
}
void House::addDoor(std::shared_ptr<Door> door) {
doorList.push_back(door);
door->setHouse(static_self_cast<House>());
updateDoorDescription();
}
void House::removeDoor(std::shared_ptr<Door> door) {
auto it = std::find(doorList.begin(), doorList.end(), door);
if (it != doorList.end()) {
doorList.erase(it);
}
}
void House::addBed(std::shared_ptr<BedItem> bed) {
bedsList.push_back(bed);
bed->setHouse(static_self_cast<House>());
}
void House::removeBed(std::shared_ptr<BedItem> bed) {
bed->setHouse(nullptr);
bedsList.remove(bed);
}
std::shared_ptr<Door> House::getDoorByNumber(uint32_t doorId) const {
for (std::shared_ptr<Door> door : doorList) {
if (door->getDoorId() == doorId) {
return door;
}
}
return nullptr;
}
std::shared_ptr<Door> House::getDoorByPosition(const Position &pos) {
for (std::shared_ptr<Door> door : doorList) {
if (door->getPosition() == pos) {
return door;
}
}
return nullptr;
}
bool House::canEditAccessList(uint32_t listId, const std::shared_ptr<Player> &player) const {
switch (getHouseAccessLevel(player)) {
case HOUSE_OWNER:
return true;
case HOUSE_SUBOWNER:
return listId == GUEST_LIST;
default:
return false;
}
}
std::shared_ptr<HouseTransferItem> House::getTransferItem() {
if (transferItem != nullptr) {
return nullptr;
}
transfer_container->resetParent();
transferItem = HouseTransferItem::createHouseTransferItem(static_self_cast<House>());
transfer_container->addThing(transferItem);
return transferItem;
}
void House::resetTransferItem() {
if (transferItem) {
std::shared_ptr<Item> tmpItem = transferItem;
transferItem = nullptr;
transfer_container->resetParent();
transfer_container->removeThing(tmpItem, tmpItem->getItemCount());
}
}
void House::calculateBidEndDate(uint8_t daysToEnd) {
auto currentTimeMs = std::chrono::system_clock::now().time_since_epoch();
auto now = std::chrono::system_clock::time_point(
std::chrono::duration_cast<std::chrono::milliseconds>(currentTimeMs)
);
// Truncate to whole days since epoch
days daysSinceEpoch = std::chrono::duration_cast<days>(now.time_since_epoch());
// Get today's date at 00:00:00 UTC
auto todayMidnight = std::chrono::system_clock::time_point(daysSinceEpoch);
std::chrono::system_clock::time_point targetDay = todayMidnight + days(daysToEnd);
const auto serverSaveTime = g_configManager().getString(GLOBAL_SERVER_SAVE_TIME);
std::vector<int32_t> params = vectorAtoi(explodeString(serverSaveTime, ":"));
int32_t hour = params.front();
int32_t min = 0;
int32_t sec = 0;
if (params.size() > 1) {
min = params[1];
if (params.size() > 2) {
sec = params[2];
}
}
std::chrono::system_clock::time_point targetTime = targetDay + std::chrono::hours(hour) + std::chrono::minutes(min) + std::chrono::seconds(sec);
std::time_t resultTime = std::chrono::system_clock::to_time_t(targetTime);
std::tm* localTime = std::localtime(&resultTime);
auto bidEndDate = static_cast<uint32_t>(std::mktime(localTime));
this->m_bidEndDate = bidEndDate;
}
std::shared_ptr<HouseTransferItem> HouseTransferItem::createHouseTransferItem(std::shared_ptr<House> house) {
std::shared_ptr<HouseTransferItem> transferItem = std::make_shared<HouseTransferItem>(house);
transferItem->setID(ITEM_DOCUMENT_RO);
transferItem->setSubType(1);
std::ostringstream ss;
ss << "It is a house transfer document for '" << house->getName() << "'.";
transferItem->setAttribute(ItemAttribute_t::DESCRIPTION, ss.str());
return transferItem;
}
void HouseTransferItem::onTradeEvent(TradeEvents_t event, std::shared_ptr<Player> owner) {
if (event == ON_TRADE_TRANSFER) {
if (house) {
auto isTransferOnRestart = g_configManager().getBoolean(TOGGLE_HOUSE_TRANSFER_ON_SERVER_RESTART);
auto ownershipTransferMessage = " The ownership will be transferred upon server restart.";
auto boughtMessage = fmt::format("You have successfully bought the house.{}", isTransferOnRestart ? ownershipTransferMessage : "");
auto soldMessage = fmt::format("You have successfully sold your house.{}", isTransferOnRestart ? ownershipTransferMessage : "");
owner->sendTextMessage(MESSAGE_EVENT_ADVANCE, boughtMessage);
auto oldOwner = g_game().getPlayerByGUID(house->getOwner());
if (oldOwner) {
oldOwner->sendTextMessage(MESSAGE_EVENT_ADVANCE, soldMessage);
}
house->executeTransfer(static_self_cast<HouseTransferItem>(), owner);
}
g_game().internalRemoveItem(static_self_cast<HouseTransferItem>(), 1);
} else if (event == ON_TRADE_CANCEL) {
if (house) {
house->resetTransferItem();
}
}
}
bool House::executeTransfer(std::shared_ptr<HouseTransferItem> item, std::shared_ptr<Player> newOwner) {
if (transferItem != item) {
return false;
}
auto isTransferOnRestart = g_configManager().getBoolean(TOGGLE_HOUSE_TRANSFER_ON_SERVER_RESTART);
if (isTransferOnRestart) {
if (hasNewOwnerOnStartup) {
return false;
}
setNewOwnerGuid(newOwner->getGUID(), false);
} else {
setOwner(newOwner->getGUID());
}
transferItem = nullptr;
return true;
}
void AccessList::parseList(const std::string &list) {
std::regex regexValidChars("[^a-zA-Z' \n*!@#]+");
std::string validList = std::regex_replace(list, regexValidChars, "");
// Remove empty lines
std::istringstream iss(validList);
std::ostringstream oss;
std::string line;
while (std::getline(iss, line)) {
if (!line.empty()) {
oss << line << '\n';
}
}
validList = oss.str();
playerList.clear();
guildRankList.clear();
allowEveryone = false;
this->list = validList;
if (list.empty()) {
return;
}
auto lines = explodeString(validList, "\n", 100);
for (auto &m_line : lines) {
trimString(m_line);
trim_left(m_line, '\t');
trim_right(m_line, '\t');
trimString(m_line);
if (m_line.empty() || m_line.front() == '#' || m_line.length() > 100) {
continue;
}
toLowerCaseString(m_line);
std::string::size_type at_pos = m_line.find('@');
if (at_pos != std::string::npos) {
if (at_pos == 0) {
addGuild(m_line.substr(1));
} else {
addGuildRank(m_line.substr(0, at_pos - 1), m_line.substr(at_pos + 1));
}
} else if (m_line == "*") {
allowEveryone = true;
} else if (m_line.find_first_of("!*?") != std::string::npos) {
// Remove regular expressions since they don't make much sense in houses
continue;
} else if (m_line.length() <= NETWORKMESSAGE_PLAYERNAME_MAXLENGTH) {
addPlayer(m_line);
}
}
}
void AccessList::addPlayer(const std::string &name) {
std::shared_ptr<Player> player = g_game().getPlayerByName(name);
if (player) {
playerList.insert(player->getGUID());
} else {
uint32_t guid = IOLoginData::getGuidByName(name);
if (guid != 0) {
playerList.insert(guid);
}
}
}
namespace {
std::shared_ptr<Guild> getGuildByName(const std::string &name) {
uint32_t guildId = IOGuild::getGuildIdByName(name);
if (guildId == 0) {
return nullptr;
}
auto guild = g_game().getGuild(guildId);
if (guild) {
return guild;
}
return IOGuild::loadGuild(guildId);
}
}
void AccessList::addGuild(const std::string &name) {
const auto guild = getGuildByName(name);
if (guild) {
for (const auto &rank : guild->getRanks()) {
guildRankList.insert(rank->id);
}
}
}
void AccessList::addGuildRank(const std::string &name, const std::string &guildName) {
const auto guild = getGuildByName(guildName);
if (guild) {
const GuildRank_ptr rank = guild->getRankByName(name);
if (rank) {
guildRankList.insert(rank->id);
}
}
}
bool AccessList::isInList(std::shared_ptr<Player> player) const {
if (allowEveryone) {
return true;
}
if (playerList.contains(player->getGUID())) {
return true;
}
const auto &rank = player->getGuildRank();
return rank && guildRankList.contains(rank->id);
}
void AccessList::getList(std::string &retList) const {
retList = this->list;
}
Door::Door(uint16_t type) :
Item(type) { }
Attr_ReadValue Door::readAttr(AttrTypes_t attr, PropStream &propStream) {
if (attr == ATTR_HOUSEDOORID) {
uint8_t doorId;
if (!propStream.read<uint8_t>(doorId)) {
return ATTR_READ_ERROR;
}
setDoorId(doorId);
return ATTR_READ_CONTINUE;
}
return Item::readAttr(attr, propStream);
}
void Door::setHouse(std::shared_ptr<House> newHouse) {
if (this->house != nullptr) {
return;
}
this->house = std::move(newHouse);
if (!accessList) {
accessList = std::make_unique<AccessList>();
}
}
bool Door::canUse(std::shared_ptr<Player> player) const {
if (!house) {
return true;
}
if (house->getHouseAccessLevel(player) >= HOUSE_SUBOWNER) {
return true;
}
return accessList->isInList(player);
}
void Door::setAccessList(const std::string &textlist) {
if (!accessList) {
accessList = std::make_unique<AccessList>();
}
accessList->parseList(textlist);
}
bool Door::getAccessList(std::string &list) const {
if (!house) {
return false;
}
accessList->getList(list);
return true;
}
void Door::onRemoved() {
Item::onRemoved();
if (house) {
house->removeDoor(static_self_cast<Door>());
}
}
std::shared_ptr<House> Houses::getHouseByPlayerId(uint32_t playerId) {
for (const auto &it : houseMap) {
if (it.second->getOwner() == playerId) {
return it.second;
}
}
return nullptr;
}
std::vector<std::shared_ptr<House>> Houses::getAllHousesByPlayerId(uint32_t playerId) {
std::vector<std::shared_ptr<House>> playerHouses;
for (const auto &[id, house] : houseMap) {
if (house->getOwner() == playerId) {
playerHouses.emplace_back(house);
}
}
return playerHouses;
}
std::shared_ptr<House> Houses::getHouseByBidderName(const std::string &bidderName) {
for (const auto &[id, house] : houseMap) {
if (house->getBidderName() == bidderName) {
return house;
}
}
return nullptr;
}
uint16_t Houses::getHouseCountByAccount(uint32_t accountId) {
uint16_t count = 0;
for (const auto &[id, house] : houseMap) {
if (house->getOwnerAccountId() == accountId) {
++count;
}
}
return count;
}
bool Houses::loadHousesXML(const std::string &filename) {
pugi::xml_document doc;
pugi::xml_parse_result result = doc.load_file(filename.c_str());
if (!result) {
printXMLError(__FUNCTION__, filename, result);
return false;
}
for (auto houseNode : doc.child("houses").children()) {
pugi::xml_attribute houseIdAttribute = houseNode.attribute("houseid");
if (!houseIdAttribute) {
return false;
}
int32_t houseId = pugi::cast<int32_t>(houseIdAttribute.value());
std::shared_ptr<House> house = getHouse(houseId);
if (!house) {
g_logger().error("[Houses::loadHousesXML] - Unknown house, id: {}", houseId);
return false;
}
house->setName(houseNode.attribute("name").as_string());
Position entryPos(
pugi::cast<uint16_t>(houseNode.attribute("entryx").value()),
pugi::cast<uint16_t>(houseNode.attribute("entryy").value()),
pugi::cast<uint16_t>(houseNode.attribute("entryz").value())
);
if (entryPos.x == 0 && entryPos.y == 0 && entryPos.z == 0) {
g_logger().warn("[Houses::loadHousesXML] - Entry not set for house "
"name: {} with id: {}",
house->getName(), houseId);
}
house->setEntryPos(entryPos);
house->setRent(pugi::cast<uint32_t>(houseNode.attribute("rent").value()));
house->setSize(pugi::cast<uint32_t>(houseNode.attribute("size").value()));
house->setTownId(pugi::cast<uint32_t>(houseNode.attribute("townid").value()));
house->setClientId(pugi::cast<uint32_t>(houseNode.attribute("clientid").value()));
auto guildhallAttr = houseNode.attribute("guildhall");
if (!guildhallAttr.empty()) {
house->setGuildhall(static_cast<bool>(guildhallAttr.as_bool()));
}
auto maxBedsAttr = houseNode.attribute("beds");
int32_t maxBeds = -1;
if (!maxBedsAttr.empty()) {
maxBeds = pugi::cast<int32_t>(maxBedsAttr.value());
}
house->setMaxBeds(maxBeds);
house->setOwner(0, false);
addHouseClientId(house->getClientId(), house);
}
return true;
}
void Houses::payHouses(RentPeriod_t rentPeriod) const {
if (rentPeriod == RENTPERIOD_NEVER) {
return;
}
time_t currentTime = time(nullptr);
for (const auto &it : houseMap) {
std::shared_ptr<House> house = it.second;
if (house->getOwner() == 0) {
continue;
}
const uint32_t ownerId = house->getOwner();
const auto &town = g_game().map.towns.getTown(house->getTownId());
if (!town) {
continue;
}
auto player = g_game().getPlayerByGUID(ownerId, true);
if (!player) {
// Player doesn't exist, reset house owner
house->tryTransferOwnership(nullptr, true);
continue;
}
// Player hasn't logged in for a while, reset house owner
auto daysToReset = g_configManager().getNumber(HOUSE_LOSE_AFTER_INACTIVITY);
if (daysToReset > 0) {
auto daysSinceLastLogin = (currentTime - player->getLastLoginSaved()) / (60 * 60 * 24);
bool vipKeep = g_configManager().getBoolean(VIP_KEEP_HOUSE) && player->isVip();
bool activityKeep = daysSinceLastLogin < daysToReset;
if (vipKeep && !activityKeep) {
g_logger().info("Player {} has not logged in for {} days, but is a VIP, so the house will not be reset.", player->getName(), daysToReset);
} else if (!vipKeep && !activityKeep) {
g_logger().info("Player {} has not logged in for {} days, so the house will be reset.", player->getName(), daysToReset);
house->setOwner(0, true, player);
g_saveManager().savePlayer(player);
continue;
}
}
const uint32_t rent = house->getRent();
if (rent == 0 || house->getPaidUntil() > currentTime) {
continue;
}
if (player->getBankBalance() >= rent) {
g_game().removeMoney(player, rent, 0, true);
g_metrics().addCounter("balance_decrease", rent, { { "player", player->getName() }, { "context", "house_rent" } });
time_t paidUntil = currentTime;
switch (rentPeriod) {
case RENTPERIOD_DAILY:
paidUntil += 24 * 60 * 60;
break;
case RENTPERIOD_WEEKLY:
paidUntil += 24 * 60 * 60 * 7;
break;
case RENTPERIOD_MONTHLY:
paidUntil += 24 * 60 * 60 * 30;
break;
case RENTPERIOD_YEARLY:
paidUntil += 24 * 60 * 60 * 365;
break;
default:
break;
}
house->setPaidUntil(paidUntil);
} else {
if (house->getPayRentWarnings() < 7) {
int32_t daysLeft = 7 - house->getPayRentWarnings();
std::shared_ptr<Item> letter = Item::CreateItem(ITEM_LETTER_STAMPED);
std::string period;
switch (rentPeriod) {
case RENTPERIOD_DAILY:
period = "daily";
break;
case RENTPERIOD_WEEKLY:
period = "weekly";
break;
case RENTPERIOD_MONTHLY:
period = "monthly";
break;
case RENTPERIOD_YEARLY:
period = "annual";
break;
default:
break;
}
std::ostringstream ss;
ss << "Warning! \nThe " << period << " rent of " << house->getRent() << " gold for your house \"" << house->getName() << "\" is payable. Have it within " << daysLeft << " days or you will lose this house.";
letter->setAttribute(ItemAttribute_t::TEXT, ss.str());
g_game().internalAddItem(player->getInbox(), letter, INDEX_WHEREEVER, FLAG_NOLIMIT);
house->setPayRentWarnings(house->getPayRentWarnings() + 1);
} else {
house->setOwner(0, true, player);
}
}
g_saveManager().savePlayer(player);
}
}
uint32_t House::getRent() const {
return static_cast<uint32_t>(g_configManager().getFloat(HOUSE_RENT_RATE) * static_cast<float>(rent));
}
uint32_t House::getPrice() const {
auto sqmPrice = static_cast<uint32_t>(g_configManager().getNumber(HOUSE_PRICE_PER_SQM)) * getSize();
auto rentPrice = static_cast<uint32_t>(static_cast<float>(getRent()) * g_configManager().getFloat(HOUSE_PRICE_RENT_MULTIPLIER));
return sqmPrice + rentPrice;
}