-
Notifications
You must be signed in to change notification settings - Fork 117
/
Automation.php
4652 lines (3952 loc) · 235 KB
/
Automation.php
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
<?php
#################################################################################
## -= YOU MAY NOT REMOVE OR CHANGE THIS NOTICE =- ##
## --------------------------------------------------------------------------- ##
## Project: TravianZ ##
## Version: 22.06.2015 ##
## Filename Automation.php ##
## Developed by: Mr.php , Advocaite , brainiacX , yi12345 , Shadow , ronix ##
## Fixed by: Shadow - STARVATION , HERO FIXED COMPL. ##
## Fixed by: InCube - double troops ##
## License: TravianZ Project ##
## Copyright: TravianZ (c) 2010-2018. All rights reserved. ##
## URLs: http://travian.shadowss.ro ##
## Source code: https://github.com/Shadowss/TravianZ ##
## ##
#################################################################################
// make sure we only run the automation script once and wait until it's done,
// so concurrent AJAX calls from many different users won't overload the server
if ( !defined('AUTOMATION_MANUAL_RUN') ) {
if(defined('AUTOMATION_LOCK_FILE_NAME')){
if ( file_exists( AUTOMATION_LOCK_FILE_NAME ) ) {
// check that the file is not too old, in which case our PHP script hung
// and we need to remove the lock and run automation again
$fileTime = filemtime( AUTOMATION_LOCK_FILE_NAME );
// allow for 60 seconds of old automation script processing time, which is still way too plenty
if ( ! $fileTime || time() - $fileTime > 60 ) {
@unlink( AUTOMATION_LOCK_FILE_NAME );
} else {
// automation file exists and is valid, don't run another automation
exit;
}
} else {
// create automation lock file
file_put_contents( AUTOMATION_LOCK_FILE_NAME, '' );
}
}
}
include_once("Database.php");
include_once("Data/buidata.php");
include_once("Data/unitdata.php");
include_once("Data/hero_full.php");
include_once("Units.php");
include_once("Battle.php");
include_once("Technology.php");
include_once("Ranking.php");
include_once("Generator.php");
include_once("Multisort.php");
include_once("Building.php");
include_once("Artifacts.php");
class Automation {
/**
* @var object The artifacts class, used to create Natars, artifacts and obtaining info about them
*/
private $artifacts;
public function __construct() {
//Classes initialization
$this->artifacts = new Artifacts();
$autoprefix = "";
for ($i = 0; $i < 5; $i++) {
$autoprefix = str_repeat('../', $i);
if (file_exists($autoprefix.'autoloader.php')) {
// we have our path, let's leave
break;
}
}
$this->procNewClimbers();
$this->ClearUser();
$this->ClearInactive();
$this->pruneResource();
$this->pruneOResource();
$this->checkWWAttacks();
$this->delTradeRoute();
$this->TradeRoute();
$methodsArrays = ["culturePoints", "updateHero", "clearDeleting", "buildComplete",
"demolitionComplete", "marketComplete", "researchComplete",
"trainingComplete", "starvation", "celebrationComplete",
"sendUnitsComplete", "loyaltyRegeneration", "sendreinfunitsComplete",
"returnunitsComplete", "sendSettlersComplete", "spawnNatars",
"spawnWWVillages", "spawnWWBuildingPlans", "activateArtifacts"];
foreach($methodsArrays as $method){
$file = fopen($autoprefix."GameEngine/Prevention/".$method.".txt", "w");
if(flock($file, LOCK_EX)) {
call_user_func(array($this, $method));
flock($file, LOCK_UN);
}
fclose($file);
}
$this->MasterBuilder();
$this->updateGeneralAttack();
$this->checkInvitedPlayes();
$this->updateStore();
$this->CheckBan();
$this->regenerateOasisTroops();
$this->medals();
$this->artefactOfTheFool();
}
public function procResType($ref, $mode = 0) {
//Capital or only 1 village left = cannot be destroyed
return addslashes(empty($build = Building::procResType($ref)) && !$mode ? "Village can't be" : $build);
}
function recountPop($vid, $use_cache = true){
global $database;
$vid = (int) $vid;
$fdata = $database->getResourceLevel($vid, $use_cache);
$popTot = 0;
for ($i = 1; $i <= 40; $i++) {
$lvl = $fdata["f".$i];
$building = $fdata["f".$i."t"];
if($building) $popTot += $this->buildingPOP($building, $lvl);
}
Building::recountCP($database, $vid);
$q = "UPDATE ".TB_PREFIX."vdata set pop = $popTot where wref = $vid";
mysqli_query($database->dblink, $q);
$owner = $database->getVillageField($vid, "owner");
$this->procClimbers($owner);
return $popTot;
}
function buildingPOP($f, $lvl){
$name = "bid".$f;
global $$name;
$popT = 0;
$dataarray = $$name;
for ($i = 0; $i <= $lvl; $i++) {
$popT += ((isset($dataarray[$i]) && isset($dataarray[$i]['pop'])) ? $dataarray[$i]['pop'] : 0);
}
return $popT;
}
private function loyaltyRegeneration() {
global $database;
$array = [];
$array = $database->getProfileVillages(0, 6);
if(!empty($array)) {
foreach($array as $loyalty) {
if (($t25_level = $this->getTypeLevel(25, $loyalty['wref'])) >= 1) {
$value = $t25_level;
}elseif(($t26_level = $this->getTypeLevel(26, $loyalty['wref'])) >= 1){
$value = $t26_level;
}
else $value = 0;
if($value > 0){
$newloyalty = min(100, $loyalty['loyalty'] + $value * (time() - $loyalty['lastupdate2']) / 3600);
$q = "UPDATE ".TB_PREFIX."vdata SET loyalty = $newloyalty, lastupdate2=".time()." WHERE wref = '".$loyalty['wref']."'";
$database->query($q);
}
}
}
$array = [];
$q = "SELECT conqured, loyalty, lastupdated, wref FROM ".TB_PREFIX."odata WHERE loyalty < 100";
$array = $database->query_return($q);
if(!empty($array)) {
foreach($array as $loyalty) {
$value = $this->getTypeLevel(37, $loyalty['conqured']);
if($value > 0){
$newloyalty = min(100, $loyalty['loyalty'] + $value * (time() - $loyalty['lastupdated']) / 3600);
$q = "UPDATE ".TB_PREFIX."odata SET loyalty = $newloyalty, lastupdated=".time()." WHERE wref = '".$loyalty['wref']."'";
$database->query($q);
}
}
}
}
public function getTypeLevel($tid, $vid) {
global $database;
$keyholder = [];
$resourcearray = $database->getResourceLevel($vid);
foreach(array_keys($resourcearray, $tid) as $key) {
if(strpos($key,'t')) {
$key = preg_replace("/[^0-9]/", '', $key);
array_push($keyholder, $key);
}
}
$element = count($keyholder);
if($element >= 2) {
if($tid <= 4) {
$temparray = [];
for($i = 0; $i <= $element - 1; $i++) {
array_push($temparray,$resourcearray['f'.$keyholder[$i]]);
}
foreach ($temparray as $key => $val) {
if ($val == max($temparray)) $target = $key;
}
}
else {
$target = 0;
for($i = 1; $i <= $element - 1; $i++) {
if($resourcearray['f'.$keyholder[$i]] > $resourcearray['f'.$keyholder[$target]]) {
$target = $i;
}
}
}
}
else if($element == 1) $target = 0;
else return 0;
if(!empty($keyholder[$target])) return $resourcearray['f'.$keyholder[$target]];
else return 0;
}
private function clearDeleting() {
global $database;
$needDelete = $database->getNeedDelete();
if(count($needDelete) > 0) {
//Remove the time limit, otherwise deleting players with 80 or more villages couldn't be deleted in one run
@set_time_limit(0);
foreach($needDelete as $need) {
$need['uid'] = (int) $need['uid'];
//Get the villages which have to be deleted
$needVillages = $database->getVillagesID($need['uid']);
//Delete all villages
$database->DelVillage($needVillages);
for($i = 0;$i < 20; $i++){
$q = "SELECT id FROM ".TB_PREFIX."users where friend".$i." = ".$need['uid']." or friend".$i."wait = ".$need['uid']."";
$array = $database->query_return($q);
foreach($array as $friend){
$database->deleteFriend($friend['id'],"friend".$i);
$database->deleteFriend($friend['id'],"friend".$i."wait");
}
}
$database->updateUserField($need['uid'], 'alliance', 0, 1);
if($database->isAllianceOwner($need['uid'])){
$alliance = $database->getUserAllianceID($need['uid']);
$newowner = $database->getAllMember2($alliance);
$newleader = $newowner['id'];
$q = "UPDATE " . TB_PREFIX . "alidata set leader = ".(int) $newleader." where id = ".(int) $alliance."";
$database->query($q);
$database->updateAlliPermissions($newleader, $alliance, "Leader", 1, 1, 1, 1, 1, 1, 1);
Automation::updateMax($newleader);
}
if (isset($alliance)) $database->deleteAlliance($alliance);
$q = "DELETE FROM ".TB_PREFIX."hero where uid = ".$need['uid'];
$database->query($q);
$q = "DELETE FROM ".TB_PREFIX."mdata where target = ".$need['uid']." or owner = ".$need['uid'];
$database->query($q);
$q = "DELETE FROM ".TB_PREFIX."ndata where uid = ".$need['uid'];
$database->query($q);
$q = "DELETE FROM ".TB_PREFIX."users where id = ".$need['uid'];
$database->query($q);
$q = "DELETE FROM ".TB_PREFIX."deleting where uid = ".$need['uid'];
$database->query($q);
}
}
}
private function ClearUser() {
global $database;
if(AUTO_DEL_INACTIVE) {
$time = time() - UN_ACT_TIME;
$q = "INSERT INTO ".TB_PREFIX."deleting SELECT id, UNIX_TIMESTAMP() FROM ".TB_PREFIX."users WHERE timestamp < $time AND tribe IN(1, 2, 3)";
$database->query($q);
}
}
private function ClearInactive() {
global $database;
if(TRACK_USR) {
$timeout = time()-USER_TIMEOUT * 60;
$q = "DELETE FROM ".TB_PREFIX."active WHERE timestamp < $timeout";
$database->query($q);
}
}
private function pruneOResource() {
global $database;
if(!ALLOW_BURST) {
$database->query("UPDATE
".TB_PREFIX."odata
SET
wood = IF(wood < 0, 0, wood),
clay = IF(clay < 0, 0, clay),
iron = IF(iron < 0, 0, iron),
crop = IF(crop < 0, 0, crop),
maxstore = IF(maxstore < ".STORAGE_BASE.", ".STORAGE_BASE.", maxstore),
maxcrop = IF(maxcrop < ".STORAGE_BASE.", ".STORAGE_BASE.", maxcrop)
WHERE
maxstore < ".STORAGE_BASE." OR
maxcrop < ".STORAGE_BASE." OR
wood < 0 OR
clay < 0 OR
iron < 0 OR
crop < 0");
}
}
private function pruneResource() {
global $database;
if(!ALLOW_BURST) {
$database->query("UPDATE
".TB_PREFIX."vdata
SET
wood = IF(wood < 0, 0, wood),
clay = IF(clay < 0, 0, clay),
iron = IF(iron < 0, 0, iron),
crop = IF(crop < 0, 0, crop),
maxstore = IF(maxstore < ".STORAGE_BASE.", ".STORAGE_BASE.", maxstore),
maxcrop = IF(maxcrop < ".STORAGE_BASE.", ".STORAGE_BASE.", maxcrop)
WHERE
maxstore < ".STORAGE_BASE." OR
maxcrop < ".STORAGE_BASE." OR
wood < 0 OR
clay < 0 OR
iron < 0 OR
crop < 0");
$database->query("UPDATE
".TB_PREFIX."vdata
SET
wood = IF(wood > maxstore, maxstore, wood),
clay = IF(clay > maxstore, maxstore, clay),
iron = IF(iron > maxstore, maxstore, iron),
crop = IF(crop > maxcrop, maxcrop, crop)
WHERE
wood > maxstore OR
clay > maxstore OR
iron > maxstore OR
crop > maxcrop");
}
}
private function culturePoints() {
global $database;
$database->updateVSumField('cp');
}
private function buildComplete() {
global $database, $technology, $bid18, $bid10, $bid11, $bid38, $bid39;
$time = time();
// IDs of villages that were affected by this building completion update,
// used to calculate statistical data at the end
$villagesAffected = [];
// holds additional conditions when updating loopcon records in the bdata table
$loopconUpdates = [];
// this will hold IDs of bdata table records to delete
$dbIdsToDelete = [];
// get all pending builds that should be complete by now
$res = $database->query_return(
"SELECT
id, wid, field, level, type, timestamp
FROM
".TB_PREFIX."bdata
WHERE
timestamp < $time and master = 0"
);
// preload village data
$vilIDs = [];
foreach($res as $indi) {
$vilIDs[$indi['wid']] = true;
}
$vilIDs = array_keys($vilIDs);
$database->getProfileVillages($vilIDs, 5);
$database->getEnforceVillage($vilIDs, 0);
// complete buildings
foreach($res as $indi) {
// store village ID for later for statistical updates
$villageData = $database->getVillageFields($indi['wid'],'owner, maxcrop, maxstore, starv, pop');
$villageOwner = $villageData['owner'];
$villagesAffected[] = (int) $indi['wid'];
$fieldsToSet = [];
$q = "UPDATE ".TB_PREFIX."fdata SET f".$indi['field']." = ".$indi['level'].", f".$indi['field']."t = ".$indi['type']." WHERE vref = ".(int) $indi['wid'];
if($database->query($q)) {
// this will be the level we brought the building to now
$level = $indi['level'];
// TODO: magic numbers into constants (for building types below)
// update capacity if we updated a warehouse or a granary
if (in_array($indi['type'], [10, 11, 38, 39])) {
$fieldDbName = (in_array($indi['type'], [10, 38]) ? 'maxstore' : 'maxcrop');
$max = $villageData[$fieldDbName];
if($level == 1 && $max == STORAGE_BASE) $max = STORAGE_BASE;
if ($level != 1) $max -= ${'bid'.$indi['type']}[$level - 1]['attri'] * STORAGE_MULTIPLIER;
$max += ${'bid'.$indi['type']}[$level]['attri'] * STORAGE_MULTIPLIER;
$fieldsToSet[$fieldDbName] = $max;
}
// if we updated Embassy, update maximum members that the alliance can take
if($indi['type'] == 18) Automation::updateMax($villageOwner);
// by SlimShady95 aka Manuel Mannhardt < manuel_mannhardt@web.de >
if ($indi['type'] == 40 && ($indi['level'] % 5 == 0 || $indi['level'] > 95) && $indi['level'] != 100) {
$this->startNatarAttack($indi['level'], $indi['wid'], $indi['timestamp']);
}
//now can't be more than one winner if ww to level 100 is build by 2 users or more on same time
if ($indi['type'] == 40 && $indi['level'] == 100) {
mysqli_query($database->dblink,"TRUNCATE ".TB_PREFIX."bdata");
}
// TODO: find out what exactly these conditions are for
// no special military conditioning for Teutons and Gauls
if ($database->getUserField($villageOwner, "tribe", 0) != 1) $loopconUpdates[$indi['wid']] = '';
else
{
// special condition for Roman military buildings
if ($indi['field'] > 18) $loopconUpdates[$indi['wid']] = ' AND field > 18';
else $loopconUpdates[$indi['wid']] = ' AND field < 19';
}
// Update ww last finish upgrade
if ($indi['type'] == 40) {
$qW = "UPDATE ".TB_PREFIX."fdata set ww_lastupdate = ".time()." where vref = ".(int) $indi['wid'];
$database->query($qW);
}
$dbIdsToDelete[] = (int) $indi['id'];
}
//Update starvation data
$database->addStarvationData($indi['wid']);
// update the requested fields, all at once
$database->setVillageFields($indi['wid'], array_keys($fieldsToSet), array_values($fieldsToSet));
}
// update statistical data for affected villages
foreach ($villagesAffected as $affected_id) $this->recountPop($affected_id, false);
// update data that can be done in one swoop instead of using multiple update queries
// no special checks for Romans
foreach ($loopconUpdates as $villageId => $updateCondition) {
$database->query(
"UPDATE
".TB_PREFIX."bdata
SET
loopcon = 0
WHERE
loopcon = 1 AND
master = 0 AND
wid = ".$villageId.$updateCondition);
}
// delete all processed entries
if (count($dbIdsToDelete)) {
$database->query( "DELETE FROM " . TB_PREFIX . "bdata WHERE id IN(" . implode( ',', $dbIdsToDelete ) . ")" );
}
}
// by SlimShady95 aka Manuel Mannhardt < manuel_mannhardt@web.de >
private function startNatarAttack($level, $vid, $time) {
global $database;
// bad, but should work :D
// I took the data from my first ww (first .org world)
// TODO: get the algo from the real travian with the 100 biggest offs
$troops = [5 => [[3412, 2814, 4156, 3553, 9, 0], [35, 0, 77, 33, 17, 10]],
10 => [[4314, 3688, 5265, 4621, 13, 0], [65, 0, 175, 77, 28, 17]],
15 => [[4645, 4267, 5659, 5272, 15, 0], [99, 0, 305, 134, 40, 25]],
20 => [[6207, 5881, 7625, 7225, 22, 0], [144, 0, 456, 201, 56, 36]],
25 => [[6004, 5977, 7400, 7277, 23, 0], [152, 0, 499, 220, 58, 37]],
30 => [[7073, 7181, 8730, 8713, 27, 0], [183, 0, 607, 268, 69, 45]],
35 => [[7090, 7320, 8762, 8856, 28, 0], [186, 0, 620, 278, 70, 45]],
40 => [[7852, 6967, 9606, 8667, 25, 0], [146, 0, 431, 190, 60, 37]],
45 => [[8480, 8883, 10490, 10719, 35, 0], [223, 0, 750, 331, 83, 54]],
50 => [[8522, 9038, 10551, 10883, 35, 0], [224, 0, 757, 335, 83, 54]],
55 => [[8931, 8690, 10992, 10624, 32, 0], [219, 0, 707, 312, 84, 54]],
60 => [[12138, 13013, 15040, 15642, 51, 0], [318, 0, 1079, 477, 118, 76]],
65 => [[13397, 14619, 16622, 17521, 58, 0], [345, 0, 1182, 522, 127, 83]],
70 => [[16323, 17665, 20240, 21201, 70, 0], [424, 0, 1447, 640, 157, 102]],
75 => [[20739, 22796, 25746, 27288, 91, 0], [529, 0, 1816, 803, 194, 127]],
80 => [[21857, 24180, 27147, 28914, 97, 0], [551, 0, 1898, 839, 202, 132]],
85 => [[22476, 25007, 27928, 29876, 100, 0], [560, 0, 1933, 855, 205, 134]],
90 => [[31345, 35053, 38963, 41843, 141, 0], [771, 0, 2668, 1180, 281, 184]],
95 => [[31720, 35635, 39443, 42506, 144, 0], [771, 0, 2671, 1181, 281, 184]],
96 => [[32885, 37007, 40897, 44130, 150, 0], [795, 0, 2757, 1219, 289, 190]],
97 => [[32940, 37099, 40968, 44235, 150, 0], [794, 0, 2755, 1219, 289, 190]],
98 => [[33521, 37691, 41686, 44953, 152, 0], [812, 0, 2816, 1246, 296, 194]],
99 => [[36251, 40861, 45089, 48714, 165, 0], [872, 0, 3025, 1338, 317, 208]]];
// select the troops^^
if (isset($troops[$level])) $units = $troops[$level];
else return false;
// get the capital village from the natars
$query = mysqli_query($database->dblink,'SELECT `wref` FROM `' . TB_PREFIX . 'vdata` WHERE `owner` = 3 and `capital` = 1 LIMIT 1') or die(mysqli_error($database->dblink));
$row = mysqli_fetch_assoc($query);
// start the attacks
$endtime = $time + round(86400 / INCREASE_SPEED);
// -.-
$vid = (int) $vid;
mysqli_query($database->dblink,'INSERT INTO `' . TB_PREFIX . 'ww_attacks` (`vid`, `attack_time`) VALUES (' . $vid . ', ' . $endtime . ')');
mysqli_query($database->dblink,'INSERT INTO `' . TB_PREFIX . 'ww_attacks` (`vid`, `attack_time`) VALUES (' . $vid . ', ' . ($endtime + 1) . ')');
// wave 1
$ref = $database->addAttack($row['wref'], 0, $units[0][0], $units[0][1], 0, $units[0][2], $units[0][3], $units[0][4], $units[0][5], 0, 0, 0, 3, 0, 0, 0, 0, 20, 20, 0, 20, 20, 20, 20);
$database->addMovement(3, $row['wref'], $vid, $ref, $time, $endtime);
// wave 2
$ref2 = $database->addAttack($row['wref'], 0, $units[1][0], $units[1][1], 0, $units[1][2], $units[1][3], $units[1][4], $units[1][5], 0, 0, 0, 3, 40, 0, 0, 0, 20, 20, 0, 20, 20, 20, 20, ['vid' => $vid, 'endtime' => ($endtime + 1)]);
$database->addMovement(3, $row['wref'], $vid, $ref2, $time, $endtime + 1);
}
private function checkWWAttacks() {
global $database;
$query = mysqli_query($database->dblink,'SELECT vid, attack_time FROM `' . TB_PREFIX . 'ww_attacks` WHERE `attack_time` <= ' . time());
while ($row = mysqli_fetch_assoc($query))
{
// delete the attack
$query3 = mysqli_query($database->dblink,'DELETE FROM `' . TB_PREFIX . 'ww_attacks` WHERE `vid` = ' . (int) $row['vid'] . ' AND `attack_time` = ' . (int) $row['attack_time']);
}
}
private function getPop($tid, $level) {
$name = "bid".$tid;
global $$name;
$dataarray = $$name;
$pop = $dataarray[($level + 1)]['pop'];
$cp = $dataarray[($level + 1)]['cp'];
return [$pop, $cp];
}
private function delTradeRoute() {
global $database;
$database->delTradeRoute();
}
private function TradeRoute() {
global $database;
$time = time();
$q = "SELECT `from`, wood, clay, iron, crop, wid, deliveries, id FROM ".TB_PREFIX."route where timestamp < $time";
$dataarray = $database->query_return($q);
$vilIDs = [];
foreach($dataarray as $data) {
$vilIDs[$data['to']] = true;
$vilIDs[$data['from']] = true;
}
$vilIDs = array_keys($vilIDs);
$database->getVillageByWorldID($vilIDs);
foreach($dataarray as $data) {
$targettribe = $database->getUserField($database->getVillageField($data['from'], "owner"), "tribe", 0);
$this->sendResource2($data['wood'], $data['clay'], $data['iron'], $data['crop'], $data['from'], $data['wid'], $targettribe, $data['deliveries']);
$database->editTradeRoute($data['id'], "timestamp", 86400, 1);
}
}
private function marketComplete() {
global $database, $units;
$time = microtime(true);
$q = "SELECT s.wood, s.clay, s.iron, s.crop, `to`, `from`, endtime, merchant, send, moveid FROM ".TB_PREFIX."movement m, ".TB_PREFIX."send s WHERE m.ref = s.id AND m.proc = 0 AND sort_type = 0 AND endtime < $time";
$dataarray = $database->query_return($q);
foreach($dataarray as $data) {
$userData_from = $database->getUserFields($database->getVillageField($data['from'], "owner"), "alliance, tribe", 0);
$userData_to = $database->getUserFields($database->getVillageField($data['to'], "owner"), "alliance, tribe", 0);
if($data['wood'] >= $data['clay'] && $data['wood'] >= $data['iron'] && $data['wood'] >= $data['crop']) $sort_type = 10;
elseif($data['clay'] >= $data['wood'] && $data['clay'] >= $data['iron'] && $data['clay'] >= $data['crop']) $sort_type = 11;
elseif($data['iron'] >= $data['wood'] && $data['iron'] >= $data['clay'] && $data['iron'] >= $data['crop']) $sort_type = 12;
elseif($data['crop'] >= $data['wood'] && $data['crop'] >= $data['clay'] && $data['crop'] >= $data['iron']) $sort_type = 13;
$to = $database->getMInfo($data['to']);
$from = $database->getMInfo($data['from']);
$ownally = $userData_from['alliance'];
$targetally = $userData_to['alliance'];
$database->addNotice($to['owner'],$to['wref'],$targetally,$sort_type,''.addslashes($from['name']).' send resources to '.addslashes($to['name']).'',''.$from['owner'].','.$from['wref'].','.$data['wood'].','.$data['clay'].','.$data['iron'].','.$data['crop'].'',$data['endtime']);
if($from['owner'] != $to['owner']) {
$database->addNotice($from['owner'],$to['wref'],$ownally,$sort_type,''.addslashes($from['name']).' send resources to '.addslashes($to['name']).'',''.$from['owner'].','.$from['wref'].','.$data['wood'].','.$data['clay'].','.$data['iron'].','.$data['crop'].'',$data['endtime']);
}
$database->modifyResource($data['to'],$data['wood'],$data['clay'],$data['iron'],$data['crop'],1);
$targettribe = $userData_to["tribe"];
$endtime = $units->getWalkingTroopsTime($data['from'], $data['to'], 0, 0, [$targettribe], 0) + $data['endtime'];
$database->addMovement(2, $data['to'], $data['from'], $data['merchant'], time(), $endtime, $data['send'], $data['wood'], $data['clay'], $data['iron'], $data['crop']);
$database->setMovementProc($data['moveid']);
}
$q1 = "SELECT send, moveid, `to`, wood, clay, iron, crop, `from` FROM ".TB_PREFIX."movement WHERE proc = 0 and sort_type = 2 and endtime < $time";
$dataarray1 = $database->query_return($q1);
$vilIDs = [];
foreach($dataarray1 as $data1) {
$vilIDs[$data1['to']] = true;
$vilIDs[$data1['from']] = true;
}
$vilIDs = array_keys($vilIDs);
$database->getVillageByWorldID($vilIDs);
foreach($dataarray1 as $data1) {
$database->setMovementProc($data1['moveid']);
if($data1['send'] > 1){
$targettribe1 = $database->getUserFields($database->getVillageField($data1['to'],"owner"),"alliance, tribe",0)['tribe'];
$send = $data1['send']-1;
$this->sendResource2($data1['wood'],$data1['clay'],$data1['iron'],$data1['crop'],$data1['to'],$data1['from'],$targettribe1,$send);
}
}
}
private function sendResource2($wtrans, $ctrans, $itrans, $crtrans, $from, $to, $tribe, $send) {
global $bid17, $bid28, $database, $units;
$availableWood = $database->getWoodAvailable($from);
$availableClay = $database->getClayAvailable($from);
$availableIron = $database->getIronAvailable($from);
$availableCrop = $database->getCropAvailable($from);
if($availableWood + $availableClay + $availableIron + $availableCrop > 0)
{
if($availableWood < $wtrans) $wtrans = $availableWood;
if($availableClay < $ctrans) $ctrans = $availableClay;
if($availableIron < $itrans) $itrans = $availableIron;
if($availableCrop < $crtrans) $crtrans = $availableCrop;
$merchant2 = ($this->getTypeLevel(17, $from) > 0)? $this->getTypeLevel(17, $from) : 0;
$used2 = $database->totalMerchantUsed($from, false);
$merchantAvail2 = $merchant2 - $used2;
$maxcarry2 = ($tribe == 1)? 500 : (($tribe == 2)? 1000 : 750);
$maxcarry2 *= TRADER_CAPACITY;
if($this->getTypeLevel(28, $from) != 0) {
$maxcarry2 *= $bid28[$this->getTypeLevel(28, $from)]['attri'] / 100;
}
$resource = [$wtrans, $ctrans, $itrans, $crtrans];
$reqMerc = ceil((array_sum($resource) - 0.1) / $maxcarry2);
if($merchantAvail2 > 0 && $reqMerc <= $merchantAvail2) {
if($database->getVillageState($to)) {
$timetaken = $units->getWalkingTroopsTime($from, $to, 0, 0, [$tribe], 0);
$res = $resource[0] + $resource[1] + $resource[2] + $resource[3];
if($res > 0){
$reference = $database->sendResource($resource[0], $resource[1], $resource[2], $resource[3], $reqMerc, 0);
$database->modifyResource($from, $resource[0], $resource[1], $resource[2], $resource[3], 0);
$database->addMovement(0, $from, $to, $reference, microtime(true), microtime(true) + $timetaken, $send);
}
}
}
}
}
private function resolveCatapultsDestruction(&$bdo, &$battlepart, &$info_cat, &$data, $catapultTarget, $twoRowsCatapultSetup, $isSecondRow, $catp_pic, $can_destroy, $isoasis, &$village_destroyed, $tribe) {
global $battle, $database, $bid34;
if(isset($catapultTarget))
{
//Currently targeted building/field level
$tblevel = (int) $bdo['f'.$catapultTarget];
//Currently targetet building/field GID (ID of the building/field type - woodcutter, cropland, embassy...)
$tbgid = (int) $bdo['f'.$catapultTarget.'t'];
//Currently targeted building/field ID in the database (fdata, the fID field, e.g. f1, f2, f3...)
$tbid = (int) $catapultTarget;
//If we're targeting the WW
if($catapultTarget == 40){
$battlepart['catapults']['strongerBuildings'] = 1;
$battlepart['catapults']['moraleBonus'] = 1;
}
$catapultsDamage = $battle->calculateCatapultsDamage($data['t8'],
$battlepart['catapults']['upgrades'],
$battlepart['catapults']['durability'],
$battlepart['catapults']['attackDefenseRatio'],
$battlepart['catapults']['strongerBuildings'],
$battlepart['catapults']['moraleBonus']);
$newLevel = $battle->calculateNewBuildingLevel($tblevel, $catapultsDamage / ($twoRowsCatapultSetup ? 2 : 1));
//If that building was present in the building queue, we have to modify his level or remove it
$database->modifyBData($data['to'], $tbid, [$newLevel, $tblevel], $tribe);
// building/field destroyed
if ($newLevel == 0){
// prepare data to be updated
$fieldsToSet = ["f".$tbid];
$fieldValuesToSet = [0];
// update $bdo, so we don't have to reselect later
$bdo['f'.$catapultTarget] = 0;
if ($tbid >= 19 && $tbid != 99) {
$fieldsToSet[] = "f".$tbid."t";
$fieldValuesToSet[] = 0;
$bdo['f'.$catapultTarget."t"] = 0;
}
// update all that needs updating
$database->setVillageLevel($data['to'], $fieldsToSet, $fieldValuesToSet);
$buildarray = $GLOBALS["bid".$tbgid];
if ( isset( $buildarray[$newLevel] ) ) {
// (great) warehouse level was changed
if ($tbgid == 10 || $tbgid == 38) {
$database->setMaxStoreForVillage($data['to'], $buildarray[$newLevel]['attri']);
}
// (great) granary level was changed
if ($tbgid == 11 || $tbgid == 39) {
$database->setMaxCropForVillage($data['to'], $buildarray[$newLevel]['attri']);
}
}
// oasis cannot be destroyed
$pop = $this->recountPop($data['to'], false);
if ($isoasis == 0 && $pop == 0 && $can_destroy == 1) $village_destroyed = 1;
if ($isSecondRow) {
if ($tbid > 0) {
$info_cat .= "<tbody class=\"goods\"><tr><th>Information</th><td colspan=\"11\">
<img class=\"unit u".$catp_pic."\" src=\"img/x.gif\" alt=\"Catapult\" title=\"Catapult\" /> ".$this->procResType($tbgid, $can_destroy)." <b>destroyed</b>.";
}
// embassy level was changed
if ($tbgid == 18){
$info_cat .= $database->checkEmbassiesAfterBattle($data['to'], $bdo['f'.$catapultTarget], false);
}
$info_cat .= "</td></tr></tbody>";
} else {
$info_cat = "".$catp_pic.", ".$this->procResType($tbgid, $can_destroy)." <b>destroyed</b>.";
// embassy level was changed
if ($tbgid == 18){
$info_cat .= $database->checkEmbassiesAfterBattle($data['to'], $bdo['f'.$catapultTarget], false);
}
}
}
// building/field not damaged
elseif($newLevel == $tblevel){
if($isSecondRow) {
if ($tbid > 0) {
$info_cat .= "<tbody class=\"goods\"><tr><th>Information</th><td colspan=\"11\">
<img class=\"unit u".$catp_pic."\" src=\"img/x.gif\" alt=\"Catapult\" title=\"Catapult\" /> ".$this->procResType($tbgid, $can_destroy)." was not damaged.</td></tr></tbody>";
}
} else {
$info_cat = "".$catp_pic.",".$this->procResType($tbgid, $can_destroy)." was not damaged.";
}
}
// building/field was damaged, let's calculate the actual damage
else
{
// update $bdo, so we don't have to reselect later
$bdo['f'.$catapultTarget] = $newLevel;
// building was damaged to a lower level
$info_cata = " damaged from level <b>".$tblevel."</b> to level <b>".$newLevel."</b>.";
$buildarray = $GLOBALS["bid".$tbgid];
// (great) warehouse level was changed
if ($tbgid == 10 || $tbgid == 38) {
$database->setMaxStoreForVillage($data['to'], $buildarray[$newLevel]['attri']);
}
// (great) granary level was changed
if ($tbgid == 11 || $tbgid == 39) {
$database->setMaxCropForVillage($data['to'], $buildarray[$newLevel]['attri']);
}
$fieldsToSet = ["f".$tbid];
$fieldValuesToSet = [$newLevel];
$database->setVillageLevel($data['to'], $fieldsToSet, $fieldValuesToSet);
// recalculate population and check if the village shouldn't be destroyed at this point
$pop = $this->recountPop($data['to'], false);
if ($isoasis == 0) {
if($pop == 0 && $can_destroy == 1) $village_destroyed = 1;
}
if ($isSecondRow) {
$info_cat .= "<tbody class=\"goods\"><tr><th>Information</th><td colspan=\"11\">
<img class=\"unit u".$catp_pic."\" src=\"img/x.gif\" alt=\"Catapult\" title=\"Catapult\" /> ".$this->procResType($tbgid, $can_destroy).$info_cata;
// embassy level was changed
if ($tbgid == 18) {
$info_cat .= $database->checkEmbassiesAfterBattle($data['to'], $bdo['f'.$catapultTarget], false);
}
$info_cat .= "</td></tr></tbody>";
} else {
$info_cat = "" . $catp_pic . "," . $this->procResType($tbgid, $can_destroy).$info_cata;
// embassy level was changed
if ($tbgid == 18) {
$info_cat .= $database->checkEmbassiesAfterBattle($data['to'], $bdo['f'.$catapultTarget], false);
}
}
}
}else{
if(!isset($info_cat) || empty($info_cat) || $info_cat == ","){
$info_cat = "".$catp_pic.", There are no buildings left to destroy";
}else if(strpos($info_cat, "There are no buildings left") === false){
$info_cat .= "<tbody class=\"goods\"><tr><th>Information</th><td colspan=\"11\">
<img class=\"unit u".$catp_pic."\" src=\"img/x.gif\" alt=\"Catapult\" title=\"Catapult\" /> There are no buildings left to destroy.</td></tr></tbody>";
}
}
}
private function sendunitsComplete() {
global $bid19, $bid23, $bid34, $u99, $database, $battle, $technology, $units;
$time = time();
$q = "
SELECT
`from`, `to`, endtime, ref, ctar1, ctar2, spy, moveid, attack_type,
t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, (SELECT oasistype FROM ".TB_PREFIX."wdata WHERE id = `to`) as oasistype
FROM
".TB_PREFIX."movement,
".TB_PREFIX."attacks
WHERE
".TB_PREFIX."movement.ref = ".TB_PREFIX."attacks.id
AND
".TB_PREFIX."movement.proc = 0
AND
".TB_PREFIX."movement.sort_type = 3
AND
".TB_PREFIX."attacks.attack_type != 2
AND
endtime < $time
ORDER BY endtime ASC";
$dataarray = $database->query_return($q);
$totalattackdead = $data_num = 0;
if ($dataarray && count($dataarray)) {
// preload village data
$vilIDs = [];
foreach($dataarray as $data) {
$vilIDs[$data['from']] = true;
$vilIDs[$data['to']] = true;
}
$vilIDs = array_keys($vilIDs);
$database->getProfileVillages($vilIDs, 5);
$database->getUnit($vilIDs);
$database->getEnforceVillage($vilIDs, 0);
$database->getMovement(34, $vilIDs, 1);
$database->getABTech($vilIDs);
// calculate battles
foreach($dataarray as $data) {
//set base things
$isoasis = $data['oasistype'];
$AttackArrivalTime = $data['endtime'];
$AttackerWref = $data['from'];
$DefenderWref = $data['to'];
$NatarCapital = false;
$Attacker['id'] = $database->getUserArray($database->getVillageField($data['from'],"owner"), 1)["id"];
$AttackerID = $Attacker['id'];
$owntribe = $database->getUserArray($database->getVillageField($data['from'],"owner"), 1)["tribe"];
$ownally = $database->getUserArray($database->getVillageField($data['from'],"owner"), 1)["alliance"];
$from = $database->getMInfo($data['from']);
$fromF = $database->getVillage($data['from']);
//It's a village
if ($isoasis == 0){
$DefenderUserData = $database->getUserArray($database->getVillageField($data['to'],"owner"), 1);
$Defender['id'] = $DefenderUserData["id"];
$DefenderID = $Defender['id'];
$targettribe = $DefenderUserData["tribe"];
$targetally = $DefenderUserData["alliance"];
$to = $database->getMInfo($data['to']);
$toF = $database->getVillage($data['to']);
$conqureby = 0;
$NatarCapital = ($toF['owner'] == 3 && $toF['capital'] == 1);
if(!isset($to['name']) || empty($to['name'])) $to['name'] = "[?]";
$DefenderUnit = [];
$DefenderUnit = $database->getUnit($data['to']);
$evasion = $toF["evasion"];
$maxevasion = $DefenderUserData["maxevasion"];
$gold = $DefenderUserData["gold"];
$playerunit = (($targettribe - 1) * 10);
$cannotsend = false;
$movements = $database->getMovement(34, $data['to'], 1);
for($y = 0; $y < count($movements); $y++){
if(property_exists($units, $y)){
$returntime = $units->$y['endtime'] - time();
if($units->$y['sort_type'] == 4 && $units->$y['from'] != 0 && $returntime <= 10){
$cannotsend = true;
}
}
}
if($evasion == 1 && $maxevasion > 0 && $gold > 1 && !$cannotsend && $dataarray[$data_num]['attack_type'] > 2){
$evaded = true;
$totaltroops = 0;
$evasionUnitModifications_units = [];
$evasionUnitModifications_amounts = [];
$evasionUnitModifications_modes = [];
for($i = 1; $i <= 10; $i++){
$playerunit += $i;
$data['u' . $i] = $DefenderUnit['u' . $playerunit];
$evasionUnitModifications_units[] = $playerunit;
$evasionUnitModifications_amounts[] = $DefenderUnit['u' . $playerunit];
$evasionUnitModifications_modes[] = 0;
$playerunit -= $i;
$totaltroops += $data['u' . $i];
}
$data['u11'] = $DefenderUnit['hero'];
$totaltroops += $data['u11'];
if($totaltroops > 0){
$evasionUnitModifications_units[] = 'hero';
$evasionUnitModifications_amounts[] = $DefenderUnit['hero'];
$evasionUnitModifications_modes[] = 0;
$attackid = $database->addAttack($data['to'], $data['u1'], $data['u2'], $data['u3'], $data['u4'], $data['u5'], $data['u6'], $data['u7'], $data['u8'], $data['u9'], $data['u10'], $data['u11'], 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
$database->addMovement(4, 0, $data['to'], $attackid, microtime(true), microtime(true) + (180 / EVASION_SPEED));
$newgold = $gold - 2;
$newmaxevasion = $maxevasion - 1;
$database->updateUserField($DefenderID, ["gold", "maxevasion"], [$newgold, $newmaxevasion], 1);
}
// modify units in DB
$database->modifyUnit($data['to'], $evasionUnitModifications_units, $evasionUnitModifications_amounts, $evasionUnitModifications_modes);
}
//get defence units
$enforDefender = [];
$rom = $ger = $gal = $nat = $natar = 0;
$Defender = $database->getUnit($data['to'], false);
$enforcementarray = $database->getEnforceVillage($data['to'], 0);
if(count($enforcementarray) > 0) {
foreach($enforcementarray as $enforce) {
for($i = 1; $i <= 50; $i++){
if(!isset($enforDefender['u'.$i])){
$enforDefender['u'.$i] = 0;
}
$enforDefender['u'.$i] += $enforce['u'.$i];
}
if (!isset($enforDefender['hero'])) {
$enforDefender['hero'] = 0;
}
$enforDefender['hero'] += $enforce['hero'];
}
}
for($i = 1; $i <= 50; $i++){
$def_ab[$i] = 0;