Source

Selador / php / base / user.inc.php

Full commit
   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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
<?php

/* user.inc.php - Class representing a Selador user/player, very basic class
 *
 * Copyright (C) 2006, 2007, 2008 Kevin Read, Simone Schaefer
 *
 * This file is part of Selador, a browser-based fantasy strategy game
 *
 * This program is distributed under the terms of the GNU Affero General Public License.
 *
 *
 *   Selador is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Affero General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   any later version.
 *
 *   Selador 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 Affero General Public License for more details.
 *
 *   You should have received a copy of the GNU Affero General Public License
 *   along with Selador.  If not, see <http://www.gnu.org/licenses/>.
 **/


// This code has good and bad side

// Autoload any classes we might require
function __autoload($class_name) {
    require_once ($class_name.'.inc.php');  // All our base classes are called CLASSNAME.inc.php
}

// We need our configuration and DB abstraction layer
require_once ("config.inc.php");
require_once ("GameDB.inc.php");

// If there is no global game DB handle, create one
if (!isset ($gamedb))
	$gamedb = new GameDB;

require_once ("hero.inc.php");

# For calculating execution time:
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1]+$mtime[0];
$phpstart = $mtime;

// Village and world definitions
require_once ("village.inc.php");
require_once ("world.inc.php");

// Setup the include path automagically
// First we need to check if our paths are already in the include path
$incpath = ini_get ("include_path");

if (!strstr ($cwd, BASE_PATH))
{
	ini_set ("include_path", BASE_PATH."php:".BASE_PATH."php/base:".BASE_PATH."var/php:/usr/share/php:.");
}
include_once ("unitmap.php");

$wrapadd_x = 0;
$wrapadd_y = 0;

$races_byid = array (1=>"Mensch", 4=>"Ork");
$races_pl_byid = array (1=>"Menschen", 4=>"Orks");
$classes_byid = array (1=>"Krieger", 2=>"Dieb", 3=>"Miner", 4=>"Händler");



/* This is how it should be done. */
class User
{
   public $user;
   public $uid;
   public $aid;
   public $allydipl = array ();
   public $allymeta = array ();
   public $allywars = array ();
   public $sat_by;
   public $score;
   public $score_to_add;
   public $class;
   public $race;
   public $sex;
   public $flags;
   public $is_authed;
   public $theme;
   public $xdim=1024;
   public $ydim=768;
   public $xmap=180;
   public $ymap=150;
   public $villages = array();
   public $hero;
   public $activevillageid;
   public $activevillage = NULL;

   public $activeoutpost = NULL;
   public $activeoutpostid = 0;

   public $allvillageids = array();

   public $merchant_cap=100;
   public $merchant_speed=200;

   public $commanders=0;
   public $commanders_max=0;
   public $hp_bonus=0;
   public $dam_bonus=0;
   public $offensive_bonus=0;
   public $defensive_bonus=0;
   public $speed_bonus=0;

   public $wood_bonus=0;
   public $stone_bonus=0;
   public $iron_bonus=0;
   public $food_bonus=0;
   public $gold_bonus=0;
   public $spy_level=0;
   public $antispy_level=0;

   public $clicks = 0;

   public $blocked = 0;

   public $villages_to_save = array();	// These villages need income finalized and then ressources saved
   public $invoked_by;	// To save some cycles we record the invokers name here for transport reports


   public $reload_counter;
   public $next_ressource_ends = 0;
   // This is the (DB) time of last update from DB, to be passed to all updates
   public $master_time;

	function __construct ()
	{
		global $gamedb;
		$this->is_authed = 0;

		// db = GameDB();
		if ($gamedb->dblink==FALSE)
		{
			echo 'Leider ist ein Datenbank-Problem aufgetreten. Derzeit ist kein Spielen m&ouml;glich, tut uns leid.';
			die ();
		}
		$master_time = 0;
	}

	function CheckPW ($user, $pw)
	{
		global $gamedb;
		if (!($itspw = $gamedb->DB_ReadPW ($user)))
			return 0;

		$ourpw = md5 ($pw);

		if (!(strcasecmp ($ourpw, $itspw)))
		{
			// echo 'Authentication successful.<br>';
			return 1;
		}
		return 0;
	}

	// Recalculate production of all villages
	function RecalcAllVillages ($time_passed)
	{
		foreach ($this->villages as $villageid => $this_village)
		{
			if (FINITE_RESSOURCES)
				$this->UpdateResTile (0, 0, null, $time_passed, $villageid);

			$this->CalculateVillageProd ($villageid);

			// Check if this village has outposts
			if (count ($this_village->outposts))
			{
				// And calculate 'em too
				foreach ($this_village->outposts as $outpostvid=>$this_outpost)
				{
					if (FINITE_RESSOURCES)
						$this->UpdateResTile (0, 0, null, $time_passed, $villageid);

					$this->CalculateVillageProd ($outpostvid);
				}
			}
			if (!is_object ($this->villages[$villageid]))
			{
				print_r ($this);
				die ();
			}
			$this->villages[$villageid]->update_production();
		}
	}

	function log_debug ($message)
	{
		if(MULTIPLE_LOGFILES)
		{
			$logfile = fopen (BASE_PATH."var/log/".date ("y.m.d")."-debug.log", "ab");
		}
		else
		{
			$logfile = fopen (BASE_PATH."var/log/debug.log", "ab");
		}

		if ($this->invoked_by != $this->user)
		{
			fwrite ($logfile, date ("d.m.y H:i:s ").": ".$this->user."(".$this->uid.") sb (".$this->invoked_by.") score ".$this->score.": ".$message."\n");
		}
		else
		{
			fwrite ($logfile, date ("d.m.y H:i:s ").": ".$this->user."(".$this->uid.") score ".$this->score.": ".$message."\n");
		}

		fclose($logfile);
	}

	function log_info ($message)
	{
		global $z;

		if(MULTIPLE_LOGFILES)
		{
			$logfile = fopen (BASE_PATH."var/log/".date ("y.m.d")."-info.log", "ab");
		}
		else
		{
			$logfile = fopen (BASE_PATH."var/log/info.log", "ab");
		}

		$logstr = date ("d.m.y H:i:s ").": ".$this->user."(".$this->uid.") ";

		$logstr .= "z: ".$z;

		if (isset ($this->activevillage))
			$logstr .= " D: ".$this->activevillage->name."(".$this->activevillageid.") Ress: ".$this->activevillage->ress[1].", ".$this->activevillage->ress[2].", ".$this->activevillage->ress[3].", ".$this->activevillage->ress[4]."\n";
		else
			$logstr .= "\n";

		fwrite ($logfile, $logstr);
		fwrite ($logfile, date ("d.m.y H:i:s ")." Event: ".$message."\n");

		fclose($logfile);
	}

	function log_err ($message)
	{
		global $z;

		if(MULTIPLE_LOGFILES)
		{
			$logfile = fopen (BASE_PATH."var/log/".date ("y.m.d")."-err.log", "ab");
		}
		else
		{
			$logfile = fopen (BASE_PATH."var/log/err.log", "ab");
		}

		fwrite ($logfile, date ("d.m.y H:i:s ")." Error: ".$this->user."(".$this->uid.") D: ".$this->activevillage->name."(".$this->activevillageid.") z: ".$z." Ress: ".$this->activevillage->ress[1].", ".$this->activevillage->ress[2].", ".$this->activevillage->ress[3].", ".$this->activevillage->ress[4]."\n");
		fwrite ($logfile, date ("d.m.y H:i:s ")." Event: ".$message."\n");

		fclose($logfile);
	}

	/** Calculate how a users research and hero talents influence his gameplay */
	function CalcResearch ($reload_prod, $time_passed=0)
	{
		global $world, $gamedb;

		$prodchanged = false;
		// Iterate over all research rows for this user
		$query = "select A.resid, A.level, B.type from userresearch A join research B where A.resid=B.id and A.uid=".$this->uid;

		// Reset all bonuses to zero
		$this->speed_bonus = $this->mechant_cap = $this->food_bonus = $this->gold_bonus = $this->stone_bonus = $this->wood_bonus = $this->iron_bonus = $this->spy_level = 0;

		if (!($res = $gamedb->query ($query)))
			$this->log_err ("Cannot read user research level. Query: ".$query.", ".$gamedb->error());
		else
		{
			while ($row = mysql_fetch_array ($res))
			{
				switch ($row['type'])
				{
					case 4:	// commanders
						$this->commanders_max = $row['level'];
						break;
					case 18:	// logistics
						$this->speed_bonus = $row['level'] * RESEARCH_STEP / 100;
						break;
					case 1:	// merchandising
						$this->merchant_cap = 100 + $row['level'] * 5;
						break;
					case 10:	// tilling
						$this->food_bonus = $row['level'] * RESEARCH_STEP / 100;
						$prodchanged = true;
						break;
					case 11:	// wood bonus
						$this->wood_bonus = $row['level'] * RESEARCH_STEP / 100;
						$prodchanged = true;
						break;
					case 12:	// stone bonus
						$this->stone_bonus = $row['level'] * RESEARCH_STEP / 100;
						$prodchanged = true;
						break;
					case 13:	// iron bonus
						$this->iron_bonus = $row['level'] * RESEARCH_STEP / 100;
						$prodchanged = true;
						break;
					case 14:	// spying
						$this->spy_level = $row['level'];
						break;
					case 15:
						$this->antispy_level = $row['level'];
						break;
				}
			}

			// Next, we factor the class of the hero into his stats
			switch ($this->class)
			{
				case CLASS_FIGHTER:
					$this->offensive_bonus += 2 * RESEARCH_STEP / 100;
					$this->dam_bonus += 2 * RESEARCH_STEP / 100;
					$this->hp_bonus += 2 * RESEARCH_STEP / 100;
					break;
				case CLASS_THIEF:
					$this->spy_level += 2;
					$this->speed_bonus += RESEARCH_STEP / 100;
					$this->antispy_level += 2;
					break;
				case CLASS_MERCHANT:
					$this->speed_bonus += 2 * RESEARCH_STEP / 100;
					$this->merchant_cap += 10;
					break;
				case CLASS_MINER:
					$this->iron_bonus += 0.1;
					$this->stone_bonus += 0.1;
					$this->wood_bonus += 0.1;
					$this->food_bonus += 0.1;
					$prodchanged = true;
					break;
			}

			if ($this->hero->ressource_bonus[0] ||  $this->hero->ressource_bonus[1] || $this->hero->ressource_bonus[2] || $this->hero->ressource_bonus[3] || $this->hero->ressource_bonus[4])
			{
				log_debug ("Hero ressource bonus");
				$this->wood_bonus += $this->hero->ressource_bonus[2];
				$this->gold_bonus += $this->hero->ressource_bonus[0];
				$this->stone_bonus += $this->hero->ressource_bonus[3];
				$this->iron_bonus += $this->hero->ressource_bonus[4];
				$prodchanged = true;
			}

			$this->merchant_cap = round ($this->merchant_cap * $this->hero->merchant_bonus);

			// A worlds speed is just added as ressource bonus here
			$this->iron_bonus = $this->iron_bonus * WORLD_SPEED + (WORLD_SPEED - 1);
			$this->wood_bonus = $this->wood_bonus * WORLD_SPEED + (WORLD_SPEED - 1);
			$this->stone_bonus = $this->stone_bonus * WORLD_SPEED + (WORLD_SPEED - 1);
			$this->gold_bonus = $this->gold_bonus * WORLD_SPEED + (WORLD_SPEED - 1);

			$this->log_debug ("Ressource bonus: ".$this->wood_bonus.", ".$this->stone_bonus.", ".$this->iron_bonus.", ".$this->gold_bonus.", ".$this->food_bonus.", merchant cap: ".$this->merchant_cap.", Recalc prod: ".$reload_prod.", prod changed: ".$prodchanged);
			if ($prodchanged && $reload_prod)
				$this->RecalcAllVillages ($time_passed);

			$this->merchant_speed = round(200 * (1 + $this->speed_bonus));
		}
	}

	/** calculating amount of commanders */
	function CalcCommanders ()
	{
		global $gamedb;
		$query = "select sum(B.amount) from armies A, troops B where A.troopid=B.troopid and B.unitid in (19, 4) and A.uid=".$this->uid;
		if (!($res = $gamedb->query ($query)))
			$this->log_err ("Cannot read number of total commanders. Query: ".$query.", ".$gamedb->error ());
		else
		{
			if (($row = mysql_fetch_row ($res)))
			{
				$this->commanders = $row[0];
			}
			else
				$this->commanders = 0;
		}
		$query = "select village2, param2 from event where type=3 and param in (19, 4) and uid1=".$this->uid;	// FIXME, new unit concept

		if (!($res = $gamedb->query ($query)))
		{
			$this->log_err ("Cannot read number of commanders in event queue. Query: ".$query.", ".$gamedb->error());
		}
		else
		{
			while (($row = mysql_fetch_array ($res)))
			{
				$this->commanders += ceil ($row['village2'] / $row['param2']);
			}
		}
	}

	function cleanvillages ()
	{
		foreach ($this->villages as $this_village)
			$this_village->updated = false;
	}

  function BecomeUser ($user)
  {
  	global $gamedb;
    $userdata = $gamedb->DB_ReadUser ($user);

    $this->user = $userdata['user'];
    $this->uid = $userdata['uid'];
    $this->name = $userdata['name'];
    $this->score = $userdata['score'];
    $this->class = $userdata['class'];
    $this->race = $userdata['race'];
    $this->sex = $userdata['sex'];
    $this->theme = $userdata['theme'];
    $this->theme ='new';
    $this->flags = $userdata['perms'];
    $this->aid = $userdata['aid'];
    $this->activevillageid = $userdata['activevillage'];

    $this->hero = new Hero ($userdata);

    $this->CalcResearch (false);

    // Check maximum amount of commanders
    $this->CalcCommanders();

    $this->is_authed = 1;

    $this->reload_counter = 0;
    $this->invoked_by = $user;
  }

	function BecomeUserByUid ($uid)
	{
		global $gamedb;
		$userdata = $gamedb->DB_ReadUserByUid ($uid);

		$this->uid = $uid;
		$this->user = $this->invoked_by = $userdata['user'];
		$this->name = $userdata['name'];
		$this->score = $userdata['score'];
		$this->class = $userdata['class'];
		$this->race = $userdata['race'];
		$this->sex = $userdata['sex'];
		$this->theme = $userdata['theme'];
		    $this->theme ='new';

		$this->aid = $userdata['aid'];
		$this->activevillageid = $userdata['activevillage'];

		$this->hero = new Hero ($userdata);

		$this->CalcResearch (false);
		    $this->CalcCommanders();


		$this->is_authed = 1;
		$this->reload_counter = 0;
	}

   // Fill in village information for this player
	function fetch_villages ()
	{
		global $gamedb, $user_row;

		if (!is_array ($user_row))
			$time_passed = "now()";
		else
			$time_passed = "\"" . $user_row['time'] . "\"";
		// We try to read as much info as possible
		// All villages owned by this player are needed, as are all villages that he is besieging

    if (FINITE_RESSOURCES)
			$query = "select villageid, outpost_of, uid, name, x, y, resprod1, resprod2, resprod3, resprod4, resprod5, buildspeed, resmax, resspeed, recrspeed1, recrspeed2, recrspeed3, recrspeed4, recrspeed5, ress1, ress2, ress3, ress4, recruit_rest, (score/1000) as score, merchants, expansion, out_expansion, besieged_by, besieged_from, abs(time_to_sec(timediff(stamp," . $time_passed. "))) as secs_passed, time_to_sec(timediff(next_exhaust,".$time_passed.")) as exhaustion_in from village where uid=".$this->uid." order by villageid";
	  else
			$query = "select villageid, outpost_of, uid, name, x, y, resprod1, resprod2, resprod3, resprod4, resprod5, buildspeed, resmax, resspeed, recrspeed1, recrspeed2, recrspeed3, recrspeed4, recrspeed5, ress1, ress2, ress3, ress4, recruit_rest, (score/1000) as score, merchants, expansion, out_expansion, besieged_by, besieged_from, abs(time_to_sec(timediff(stamp," . $time_passed. "))) as secs_passed from village where uid=".$this->uid." order by villageid";

	  if (!($res = $gamedb->query ($query)))
	  	$this->log_err ("Cannot fetch villages!!! Query: ".$query.", ".$gamedb->error ());

	  while ($row = mysql_fetch_array ($res))
	  {
	  	// The central villageid repository
	  	// Only place villages here that really belong to me, not those I besiege
	  	if ($row['uid'] == $this->uid)
	 		$this->allvillageids[] = $row['villageid'];

		// This problem cannot appear with the players own villages, as
		// the order here is strict: Outposts and child villages always
		// come after parent (=older) villages!

		// So outposts are added directly to the parent node
		if ($row['outpost_of'])
		{
			$outposts[$row['outpost_of']][] = new Village ($row, $this);
		}
		else
		{
			// Villages might have been added already, if so, just update them
			if (isset ($this->villages[$row['villageid']]))
				$this->villages[$row['villageid']]->set_info ($row, $this);
			else
				$this->villages[$row['villageid']] = new Village ($row, $this);

			// If this is the active village, make a reference to the
			// village object to activevillage
			if ($this->activevillageid == $row['villageid'])
				$this->activevillage = $this->villages[$row['villageid']];
		}
	}

	if (is_array ($outposts))
	{
		foreach ($outposts as $vid=>$outgroup)
		{
			foreach ($outgroup as $this_out)
				$this->villages[$vid]->outposts[$this_out->villageid] = $this_out;
		}
	}

	  // Each outpost shells out its ressource production to its mother village
	  foreach ($this->villages as $vid=>$this_village)
	  {
	  	// $this->log_debug ("Ressources for village ".$vid." without outposts: ".$this_village->ress_prod[1]." ".$this_village->ress_prod[2]." ".$this_village->ress_prod[3]." ".$this_village->ress_prod[4]." ".$this_village->ress_prod[5]);
	  	foreach ($this_village->outposts as $this_outpost)
	  	{
	  		// Out-take, we do not need this at the moment but might re-use it later?
	  		/* $go_ahead = true;
	  		if ($this_outpost->besieged_by > 0)
	  		{
	  			if ($this_outpost->besieged_by == $this->uid)
	  				$this->log_debug ("Ressources for besieged outpost ".$this_oupost->villageid.": ".$this_outpost->ress_prod[1]." ".$this_outpost->ress_prod[2]." ".$this_outpost->ress_prod[3]." ".$this_outpost->ress_prod[4]." ".$this_outpost->ress_prod[5]);
	  			else
	  			{
	  				$this->log_debug ("Subtracting ressources for besieged outpost ".$this_oupost->villageid.": ".$this_outpost->ress_prod[1]." ".$this_outpost->ress_prod[2]." ".$this_outpost->ress_prod[3]." ".$this_outpost->ress_prod[4]." ".$this_outpost->ress_prod[5]);
	  				$go_ahead = false;
	  			}
	  		} */

	  		if (!$this_outpost->besieged_by)
	  		{
					$this_village->ress_prod[1] += (int)($this_outpost->ress_prod[1]);
					$this_village->ress_prod[2] += (int)($this_outpost->ress_prod[2]);
					$this_village->ress_prod[3] += (int)($this_outpost->ress_prod[3]);
					$this_village->ress_prod[4] += (int)($this_outpost->ress_prod[4]);
					$this_village->ress_prod[5] += (int)($this_outpost->ress_prod[5]);
				}
	  	}
	  	// $this->log_debug ("Ressources for village ".$vid." with outposts: ".$this_village->ress_prod[1]." ".$this_village->ress_prod[2]." ".$this_village->ress_prod[3]." ".$this_village->ress_prod[4]." ".$this_village->ress_prod[5]);
	  }

	  // Now construct the reference to the active village, if it wasn't
	  // already constructed by above code. We just take the first item
	  // from the villages array, so it'll be the mother village
	  if (!$this->activevillage)
	  {
	    reset ($this->villages);    // We need the first item
	    $this->activevillage = current ($this->villages);
	    $this->activevillageid = key ($this->villages);
	  }
	  mysql_free_result ($res);
	  // $this->log_debug ("Villages read for ".$this->uid.". Active village ID = ".$this->activevillageid);

	  // Reset a faulty hero location
	  if (($this->hero->location == 0) && ($this->hero->troopid == 0))
	    $this->hero->location = $this->activevillageid;
	}


	/******************************************************************************
		Calculate amount of ressources a given ressource field and level will yield
	 *****************************************************************************/
	function tile_ressource_yield ($type, $level, $factor=1)
	{
		$ress[1] = $ress[2] = $ress[3] = $ress[4] = $ress[5] = 0;
		switch ($type)
		{
			case 0: // Enclave
				$ress[5] += ($level * ENC_FOOD_INC * pow (NEXTLEVEL_YIELD, $level - 1));
				$ress[4] += ($level * ENC_GOLD_INC * pow (NEXTLEVEL_YIELD, $level - 1));
				break;
			case 1: // Food
				$ress[5] += ($level * FOOD_FOOD_INC * pow (NEXTLEVEL_YIELD, $level - 1));
				$ress[4] += ($level * OTHER_GOLD_INC * pow (NEXTLEVEL_YIELD, $level - 1));
				break;
			case 2: // Wood
				$ress[1] += ($level * OTHER_OTHER_INC * pow (NEXTLEVEL_YIELD, $level - 1));
				$ress[4] += ($level * OTHER_GOLD_INC * pow (NEXTLEVEL_YIELD, $level - 1));
				break;
			case 3: // Stone
				$ress[2] += ($level * OTHER_OTHER_INC * pow (NEXTLEVEL_YIELD, $level - 1));
				$ress[4] += ($level * OTHER_GOLD_INC * pow (NEXTLEVEL_YIELD, $level - 1));
				break;
			case 4: // Iron
				$ress[3] += ($level * OTHER_OTHER_INC * pow (NEXTLEVEL_YIELD, $level - 1));
				$ress[4] += ($level * OTHER_GOLD_INC * pow (NEXTLEVEL_YIELD, $level - 1));
				break;
		}

		$ress[5] = (int)round ($ress[5] * (1+$this->food_bonus) * $factor);
		$ress[1] = (int)round ($ress[1] * (1+$this->wood_bonus) * $factor);
		$ress[2] = (int)round ($ress[2] * (1+$this->stone_bonus) * $factor);
		$ress[3] = (int)round ($ress[3] * (1+$this->iron_bonus) * $factor);
		$ress[4] = (int)round ($ress[4] * (1+$this->gold_bonus) * $factor);
		return $ress;
	}

	function UpdateResTile ($x, $y, $newlevel = 0, $time_passed=0, $villageid=0)
	{
		global $gamedb, $user_row;

		if (FINITE_RESSOURCES)
		{
			$this->log_debug ("Updating ress tiles. X:".$x.", Y:".$y.", newlevel:".$newlevel.", tp: ".$time_passed.", VID: ".$villageid);
			// We need the new values for reserves, lastchanged and time_exhaust first
			if ($villageid)
				$query = "select A.level,A.resprod1,A.resprod2,A.resprod3,A.resprod4,A.resprod5,B.reserves,time_to_sec(timediff(\"" . $user_row['time'] . "\",B.lastchange)) as lastchange,floor(B.type/100) as type, A.x, A.y from tileres A, map B where A.villageid=".$villageid." and B.x=A.x and B.y=A.y";
			else
				$query = "select A.level,A.resprod1,A.resprod2,A.resprod3,A.resprod4,A.resprod5,B.reserves,time_to_sec(timediff(\"" . $user_row['time'] . "\",B.lastchange)) as lastchange,floor(B.type/100) as type, A.x, A.y from tileres A, map B where A.x=".$x." and A.y=".$y." and B.x=".$x." and B.y=".$y;

			// For this we query the old values, calculate new reserves and update the row
			if (!($res = $gamedb->query ($query)))
				$this->log_err ("Cannot read old ressource exhaustion parameters. Query: ".$query.", ".$gamedb->error ());
			else
			{
				while (($row = mysql_fetch_array ($res)))
				{
					// Maybe this field wasn't even in use before...
					$prod = array (1=>$row['resprod1'], 2=>$row['resprod2'], 3=>$row['resprod3'], 4=>$row['resprod4'], 5=>$row['resprod5']);
					//$prod = $this->tile_ressource_yield ($row['type'], $row['level']);

					if ($newlevel)
						$tolevel = $newlevel;
					else
						$tolevel = $row['level'];

					$nextlevel_prod = $this->tile_ressource_yield ($row['type'], $tolevel);

					switch ($row['type'])
					{
						case 0:	// enclave
							$exhausted = 0;
							$newprod = 0;
							break;
						case 1:	// plains
							$exhausted = 0;
							$newprod = 0;
							break;
						case 2:	// forests
							if ($prod[1] < FOREST_REGROWTH * WORLD_SPEED)
								$exhausted = 0;
							else
								$exhausted = max (0, ($prod[1] - (FOREST_REGROWTH * WORLD_SPEED))/3600 * ($row['lastchange'] - abs ($time_passed)));

							$newprod = max (0, ($nextlevel_prod[1] - (FOREST_REGROWTH * WORLD_SPEED)) / 3600);
							break;
						case 3:	// hills
							$exhausted = $prod[2]/3600 * ($row['lastchange'] - abs ($time_passed));
							$newprod = $nextlevel_prod[2]/3600;
							break;
						case 4:	// mountains
							$exhausted = $prod[3]/3600 * ($row['lastchange'] - abs ($time_passed));
							$newprod = $nextlevel_prod[3]/3600;
							break;
					}

					$exhausted += $newprod * abs ($time_passed);

					// echo "EX1: ".$exhausted."<br>\n";

					// Hero talents can push down exhaustion
					$exhausted = $exhausted * $this->hero->less_exhaust[$row['type']];

					// echo "EX2: ".$exhausted."<br>\n";

					$new_reserves = max (0, $row['reserves'] - $exhausted);

					// Cap the exhaustion time at a sane limit, otherwise mysql might add it up to 0 and the
					// field will fail immediately!
					if ($newprod > 0)
						$time_exhaust = min (72000000, (int)($new_reserves / $newprod));
					else
						$time_exhaust = -1;

					$querypart = "";
					// Now create a part of the update query from the ressources array
					// via this black magic
					foreach ($nextlevel_prod as $currency=>$amount)
					{
						$querypart .= ",resprod".$currency."=".$amount;
					}

					$this->log_debug ("Oldreserves: ".$row['reserves'].", last change: ".$row['lastchange'].", exhausted: ".$exhausted.", Newprod: ".$newprod.", new reserves: ".$new_reserves.", time_exhaust: ".$time_exhaust);
					// First update the tile level in the DB, just to be sure
					if ($time_exhaust >= 0)
						$query = "update tileres set level=".$tolevel.",time_exhaust=timestampadd(second, ".$time_exhaust.", now())".$querypart." where x=".$row['x']." and y=".$row['y'];
					else
						$query = "update tileres set level=".$tolevel.",time_exhaust=\"2038-01-01 00:00:00\"".$querypart." where x=".$row['x']." and y=".$row['y'];

          $this->log_debug ("UpdateResTile: tile update query: ".$query);

					if (!$gamedb->query ($query))
						$this->log_err ("Cannot update tileres after resstile is done. Query: ".$query.", ".$gamedb->error ());
					else
					{
						$query = "update map set reserves=".$new_reserves.",lastchange=subtime(now(), sec_to_time(".abs ($time_passed).")) where x=".$row['x']." and y=".$row['y'];
						$this->log_debug ("UpdateResTile: map update query: ".$query);

						if (!$gamedb->query ($query))
							$this->log_err ("Cannot update tileres after resstile is done. Query: ".$query.", ".$gamedb->error ());
					}
				}
			}
		}
	}

	function CalculateVillageProd ($villageid, $update=true)
	{
		global $world, $gamedb;
		$delete_cache = false;

		if (FINITE_RESSOURCES)
		{
			$query = "select A.x,A.y,A.villageid, A.level, B.type, B.reserves,A.time_exhaust from tileres A, map B where A.x=B.x and A.y=B.y and A.uid=".$this->uid." and A.time_exhaust<=now() and A.level>0";
			if (!($res = $gamedb->query ($query)))
			{
				$this->log_err ("Cannot read exhausted tiles when transforming them ".$query.", ".$gamedb->error ());
			}
			else
			{

				while ($row = mysql_fetch_array ($res))
				{
        			$this->log_debug ("CalculateVillageProd: tile empty ".$row['x'].', '.$row['y'].' type '.$row['type'].' '.$row['level'].' res '.$row['reserves'].' te '.$row['time_exhaust']);
					$newtype = 0;
					// Now this depends on what type of tile this is
					switch ((int)($row['type'] / 100))
					{
						case 0:
							$newtype = 0;
							break;
						case 2:
							$newtype = 1;
							break;
						case 3:
							$newtype = 1;
							break;
						case 4:
							$newtype = 3;
							break;
					}

					$newtile = $world->select_specific_tile ($newtype);

					if ($newtype)
					{
						$this->log_debug ("Setting ".$row['x'].", ".$row['y']." to ".$newtile." (".$newtype.")");

						$query = "update map set reserves=".RESS_RESERVE.",type=".$newtile." where x=".$row['x']." and y=".$row['y'];

						if (!$gamedb->query ($query))
							$this->log_err ("Cannot set new tile type after ressource exhaustion. Query: ".$query.", ".$gamedb->error ());
						else
						{
							$world->ClearLandCache ($row['x'], $row['y']);

							$this->UpdateResTile ($row['x'], $row['y'], 1);
							$lastrow = $row;
						}
					}
				}

				if ($delete_cache)
				{
					$world->ClearMapCache ($lastrow['x'], $lastrow['y']);
				}
			}

			$query = "select villageid, min(time_exhaust) as next_exhaust,sum(resprod1) as resprod1, sum(resprod2) as resprod2, sum(resprod3) as resprod3, sum(resprod4) as resprod4, sum(resprod5) as resprod5 from tileres where uid=".$this->uid." and time_exhaust>now() group by villageid";

			if (!($res = $gamedb->query ($query)))
				$this->log_err ("Cannot read all villages when calculating production ".$query.", ".$gamedb->error ());
			else
			{
				while ($row = mysql_fetch_array ($res))
				{
					if (!$row['next_exhaust'])
						$row['next_exhaust'] = "2038-01-01 00:00:00";

					$this->log_debug ("For VID ".$row['villageid']." newres1 ".$row['resprod1']." newres2 ".$row['resprod2']);
					$query = "update village set resprod1=".$row['resprod1'].", resprod2=".$row['resprod2'].", resprod3=".$row['resprod3'].", resprod4=".$row['resprod4'].", resprod5=".$row['resprod5'].", next_exhaust=\"".$row['next_exhaust']."\" where villageid=".$row['villageid'];

					if (!$gamedb->query ($query))
						$this->log_err ("Cannot update village production after calculating it. Query: ".$query.", ".$gamedb->error ());
					/* else
					{
						$this->villages[$row['villageid']]->ress_prod[1] = $row['resprod1'];
						$this->villages[$row['villageid']]->ress_prod[2] = $row['resprod2'];
						$this->villages[$row['villageid']]->ress_prod[3] = $row['resprod3'];
						$this->villages[$row['villageid']]->ress_prod[4] = $row['resprod4'];
						$this->villages[$row['villageid']]->ress_prod[5] = $row['resprod5'];
					} */
				}

				/* Obsoleted by above next_exhaust?
				$query = "select min(time_exhaust) from tileres where uid=".$this->uid." and time_exhaust>now()";

				if (!($res = mysql_query ($query)))
				{
					$this->log_err ("Cannot read next date of tile exhaustion. Query: ".$query.", ".mysql_error ());
				}
				else
				{
					if ($row = mysql_fetch_array ($res))
					{
						if ($row[0])
						{
							$query = 'update user set end_ressource="'.$row['0'].'"';
						}
						else
							$query = 'update user set end_ressource="2038-01-01 00:00:00"';

							if (!mysql_query ($query))
								$this->log_err ("Cannot set new ressource end in user.inc.php. Query: ".$query.", ".mysql_error ());

					}
					else
						$this->log_err ("No rows for date of tile exhaustion. Query: ".$query.", ".mysql_error ());
				} */
			}
		}
		else
		{
			// $erz = $holz = $stein = 1;

			// first update the lastchange and reserve IMPLEMENTME!
			$query = "select T.x, T.y, T.level, T.staff, M.type from tileres T, map M where T.x=M.x and T.y=M.y and T.villageid=".$villageid;
			if (!($res = $gamedb->query ($query)))
			{
				$this->log_err ("Cannot fetch production for village ".$villageid.". Query: ".$query.", ".$gamedb->error ());
				return (false);
			}
			else
			{
				$food = $mana = $holz = $stein = $erz = 0;

				// echo $query."\n";
				while ($row = mysql_fetch_array ($res))
				{
					// echo "X: ".$row['x'].", Y: ".$row['y'].": Type is ".(int)($row['type'] / 100);
					switch ((int)($row['type'] / 100))
					{
						case 0:
							$mana += ($row['level'] * ENC_GOLD_INC * pow (NEXTLEVEL_YIELD, $row['level'] - 1));
							$food += ($row['level'] * ENC_FOOD_INC * pow (NEXTLEVEL_YIELD, $row['level'] - 1));
							break;
						case 1:
							$food += ($row['level'] * FOOD_FOOD_INC * pow (NEXTLEVEL_YIELD, $row['level'] - 1));
							$mana += ($row['level'] * OTHER_GOLD_INC * pow (NEXTLEVEL_YIELD, $row['level'] - 1));
							break;
						case 2:
							$holz += ($row['level'] * OTHER_OTHER_INC * pow (NEXTLEVEL_YIELD, $row['level'] - 1));
							$mana += ($row['level'] * OTHER_GOLD_INC * pow (NEXTLEVEL_YIELD, $row['level'] - 1));
							break;
						case 3:
							$stein += ($row['level'] * OTHER_OTHER_INC * pow (NEXTLEVEL_YIELD, $row['level'] - 1));
							$mana += ($row['level'] * OTHER_GOLD_INC * pow (NEXTLEVEL_YIELD, $row['level'] - 1));
							break;
						case 4:
							$erz += ($row['level'] * OTHER_OTHER_INC * pow (NEXTLEVEL_YIELD, $row['level'] - 1));
							$mana += ($row['level'] * OTHER_GOLD_INC * pow (NEXTLEVEL_YIELD, $row['level'] - 1));
							break;
					}
                }
                
				$new_food = (int)round($food * (1+$this->food_bonus));
				$new_holz = (int)round($holz * (1+$this->wood_bonus));
				$new_stein = (int)round($stein * (1+$this->stone_bonus));
				$new_erz = (int)round($erz * (1+$this->iron_bonus));
				$new_mana = (int)round($mana * (1+$this->gold_bonus));

				// Also calculate the point in time of the first ressource exhaustion
				// for all land tiles contributing to this particular village

				if ($update)
				{
					// $this->log_debug ("New ressources for ".$villageid.": ".$holz." (".$new_holz.") ".$stein." (".$new_stein.") ".$erz." (".$new_erz.") ".$mana." ".$food." (".$new_food.")");
					$query = "update village set resprod1=".$new_holz.", resprod2=".$new_stein.", resprod3=".$new_erz.", resprod4=".$new_mana.", resprod5=".$new_food.", stamp=stamp where villageid=".$villageid;
					$gamedb->query ($query);
				}
				else
				{
					$new_income = array (1=>$new_holz, 2=>$new_stein, 3=>$new_erz, 5=>$new_food, 4=>$new_mana);
					return ($new_income);
				}
			}
		}
  }

	public function lookup_outpost ($villageid)
	{
		if (in_array ($villageid, array_keys ($this->villages)))
			return false;
		else
		{
			foreach ($this->villages as $vid=>$this_village)
			{
				if (isset ($this_village->outposts[$villageid]))
					return ($vid);
			}
		}

		return false;
	}

	public function merge_troops ($villageid, $location, $troopid, $battleid=0, $time_since_ret=0)
	{
		global $gamedb;

		// If the troops carry loot, we deposit it in the destination
		if ($battleid != 0)
		{
		// In param2 we will find the battleid, so that it is protocoled in the eventlog, and
		// that we can look up the loot values
			$query = "select coin,param from rep_loot where reportid=".$battleid." and value=".$this->uid." and coin in (0,1,2,3,50)";
			$loot = array ();

			if (!($res = $gamedb->query ($query)))
			{
				$this->log_err ("Can't lookup loot stuff on troop merge. Query: ".$query.", ".$gamedb->error());
			}
			else
			{
				while ($row = mysql_fetch_array ($res))
				{
					if ($row['coin'] < 4)
						$loot[($row['coin']+1)] = $row['param'];
					else
					{
						// A flag has been dumped into the village by the troops
					//	$query = "update village A, user B, war_flags C set C.current_troopid=0 where A.villageid=".$row['param']." and A.uid=B.uid and C.villageid=".$row['param']." and ((B.aid=C.aid1 and C.aid2=".$this->aid.") or (B.aid=C.aid2 and C.aid1=".$this->aid."))";
						$query = "update war_flags set current_troopid=0 where current_troopid=".$troopid;

						if (!$gamedb->query ($query))
							log_err ("Cannot set flag to arrived state. Query: ".$query.", ".$gamedb->error ());
					}
				}
				$this->log_debug ("Return to ".$villageid.": Ress before: ".$this->villages[$villageid]->ress[1].", ".$this->villages[$villageid]->ress[2].", ".$this->villages[$villageid]->ress[3].", ".$this->villages[$villageid]->ress[4]);

				$this->villages[$villageid]->spend (-$loot[1], -$loot[2], -$loot[3], -$loot[4]);

				$this->villages[$villageid]->updated = true;
				$this->log_debug ("Return to ".$villageid.": Ress after: ".$this->villages[$villageid]->ress[1].", ".$this->villages[$villageid]->ress[2].", ".$this->villages[$villageid]->ress[3].", ".$this->villages[$villageid]->ress[4]);
				mysql_free_result ($res);
			}
		}
		$query = "select * from armies A left join troops B on (A.troopid=B.troopid) where ((A.location=".$location." and A.villageid=".$villageid." and A.flag=0) or A.troopid=".$troopid.")";

		if (!($res = $gamedb->query ($query)))
		{
			$this->log_err ("Cannot read returning and/or home troop numbers for troop merge in user.inc.php. Query: ".$query.", ".$gamedb->error());
		}
		else
		{
			$logstr = array ();
			$this->log_debug ("Mergequery: ".$query.", returned rows ".mysql_num_rows ($res));
			while ($row = mysql_fetch_array ($res))
			{
				// Is this row about returning troops?
				if ($row['troopid'] != $troopid)
				{
					if (isset ($hometroopid))
					{
						if ($hometroopid != $row['troopid'])
							$this->log_err ("Da'zang! Double troops at home, eh? Query was: ".$query);
					}

					// Nope, these are the guys at home
					$hometroopid = $row['troopid'];
				}


				// The hero unit needs special care
				if (($row['unitid'] == 1000) && ($row['amount'] > 0))
				{
					$update_hero = true;
					$row['amount'] = 1;
					$amount[1000] = 1;
					$this->hero->last_healed = $time_since_ret;
				}
				else
				{
					// FIXME: We really don't need to update all those rows, only those that have changed!!!
					if (!isset ($amount[$row['unitid']]))
						$amount[$row['unitid']] = $row['amount'];
					else
						$amount[$row['unitid']] += $row['amount'];

					$logstr[] = $row['amount']." of ".$row['unitid'];
				}
			}

			unset ($query);
			$this->log_debug ("Troops at home are ".implode (", ", $logstr));

			if (isset ($hometroopid))
			{
				foreach ($amount as $unit_id => $this_amount)
				{
						if (!isset ($query))
							$query = "(".$hometroopid.", ".$unit_id.", ".$this_amount.")";
						else
							$query .= ", (".$hometroopid.", ".$unit_id.", ".$this_amount.")";
				}

				unset ($amount);	// w00t000t000w!
				if (isset ($query))
				{
					$this->log_debug ("Troop replace query ".$query);
					$query = "replace into troops values ".$query;
					// echo $query;

					if (!$gamedb->query ($query))
						$this->log_err ("Cannot replace hometroops after troop return. Query: ".$query.", ".$gamedb->error ());
					else
					{
						$query = "delete from troops where troopid=".$troopid;

						if (!$gamedb->query ($query))
							$this->log_err ("Cannot delete returned troop entry. Query: ".$query.", ".$gamedb->error ());

						$query = "delete from armies where troopid=".$troopid;

						if (!$gamedb->query ($query))
							$this->log_err ("Cannot delete returned army entry. Query: ".$query.", ".$gamedb->error ());
					}
				}
				else
					$this->log_err ("Troop replace query after return isn't set!");
			}
			else
			{
				// When support arrives, we just set them to hold state
				$query = "update armies set flag=0,location=".$location." where troopid=".$troopid;

				$this->log_debug ("Setting troops to hold state with ".$query);
				// echo $query;

				if (!$gamedb->query ($query))
					$this->log_err ("Cannot hold supporting troops that just arrived. Query: ".$query.", ".$gamedb->error());
			}

			if (isset ($update_hero))
			{
				$this->hero->location = $location;
				if ($location == $villageid)
					$this->hero->troopid = 0;
				else
					$this->hero->troopid = $hometroopid;
				$this->hero->needs_updating = true;
			}

			mysql_free_result ($res);
		}
	}

	function get_ally_perms ()
	{
		global $gamedb;
		if (!$this->aid)
			return 0;

		$query = "select perms from allyperms where uid=".$this->uid." and aid=".$this->aid;

		if (!($res = $gamedb->query ($query)))
		{
			$perms = 0;
			log_err ("Cannot read ally permissions while browsing. Query: ".$query.", ".$gamedb->error ());
		}
		else
		{
			if ($row = mysql_fetch_row ($res))
				$perms = $row[0];

			mysql_free_result ($res);
		}

		return ($perms);
	}

	public function update_score ($to_add, $villageid = 0)
	{
	  $this->score_to_add += $to_add;

	  if ($villageid > 0)
	  {
	  	if (!isset ($this->villages[$villageid]))
	  		log_err ("Villageid ".$villageid." doesn't exist while I was trying to add a score of ".$to_add." - oops");
	  	else
	  		$this->villages[$villageid]->score_to_add = $to_add;
	  }
	}

	public function save_score ($is_me = true)
	{
		global $gamedb;
		if (($this->score_to_add != 0) || $this->hero->needs_updating)
		{
			if ($this->score_to_add)
				$this->log_debug ("Score to add: ".round ($this->score_to_add/1000, 2));

		if ($is_me)
		{
			$query = "update user set score=score+".(int)$this->score_to_add.", changed=";
			if ($this->master_time)
				$query .= '"' . $this->master_time . '"';
			else
				$query .= 'now()';
			$query .= ", clicks=clicks+".(int)$this->clicks;
			$this->clicks = 0;
		}
		else
			$query = "update user set score=score+".(int)$this->score_to_add;

		if ($this->hero->needs_updating)
			$query .= ", hero_location=".(int)$this->hero->location.", last_healed=now(), hero_troopid=".(int)$this->hero->troopid.", hero_health=hero_health+".(float)$this->hero->new_hp;

		$this->hero->needs_updating = false;
		$this->hero->new_hp = 0;

		$query .= " where uid=".$this->uid;
		if (!$gamedb->query ($query))
			$this->log_err ("Cannot update score. Query: ".$query.", error: ".$gamedb->error ());
		else
			$this->score_to_add = 0;
    }
    /* else
    {
  	  $query = "update user set changed=".$this->score_to_add." where uid=".$this->uid;
  	  if (!@mysql_query ($query))
  	    $this->log_err ("Cannot update score. Query: ".$query.", error: ".mysql_error());
    } */
	}

	function merge_local_events ($retevents, &$local_events, &$local_event_idx)
	{
		global $debug;

		// If we have no return events, the transports are still on the way
		if ($retevents)
		{
			if ($debug)
			{
				echo "Received new local events: ";
				print_r ($retevents);
			}
			// If not, we have a new local event, and have to re-sort the local event queue
			foreach ($retevents as $this_ev)
			{
				$local_events[] = $this_ev;
				$local_event_idx[] = $this_ev['dif'];
			}
			array_multisort ($local_event_idx, SORT_DESC, SORT_NUMERIC, $local_events);
		}
	}

	// Add a delegate event which serves to refresh local information that might be saved in
	// the session in case an event was calculated in a non-local context
	function add_delegate ($type, $for_all=false, $param2=0, $village1=0)
	{
		global $gamedb;

		if (!$village1)
			$village1=$this->activevillageid;

		if ($for_all)
			$do_for_all = 1;
		else
			$do_for_all = 0;

		log_debug ("Adding delegate for ".$type." for all ".$do_for_all." with p2 ".$param2." in ".$village1);

		$query = "insert into event values (NULL, ".$this->uid.", ".$village1.", 0, 0, now(), ".$type.", 0, ".$param2.", ".$do_for_all.", 0)";

		if (!$gamedb->query ($query))
			$this->log_err ("Cannot add delegate event. Query: ".$query.", ".$gamedb->error ());
	}

	function add_my_event ($uid2, $village2, $type, $param, $param2, $time_from_now, $score, $errmsg)
	{
		global $gamedb;

		$query = "insert into event (uid1, village1, uid2, village2, type, param, param2, score) values (".$this->uid.", ".$this->activevillageid.", ".$uid2.", ".$village2.", ".$type.", ".$param.", ".$param2.", ".$score.")";
		if (!$gamedb->query ($query))
		{
			log_err ($errmsg." ".$query.", ".$gamedb->error());
			return (false);
		}
		else
		{
			$eid = mysql_insert_id ();
			$query = "insert into eventuid (uid,eid,flag,timestamp) values (".$me->uid.", ".$eid.", addtime(now(), sec_to_time(".$time_from_now."))";
			if (!$gamedb->query ($query))
			{
				log_err ($errmsg." ".$query.", ".$gamedb->error());
				return (false);
			}
		}

		return (true);
	}

	function display_reserve ($row)
	{
		switch ((int)($row['type']/100))
		{
			case 0:	// enclave
				$pic = "gfx/mana.gif";
				$remaining = RESS_RESERVE;
				break;
			case 2: // woods
				$pic = "gfx/holz.gif";
				$remaining =  max (0, (int)($row['reserves'] - ($this->hero->less_exhaust[2] * ($row['resprod1'] - (FOREST_REGROWTH * WORLD_SPEED)) * ($row['lastchange2']/3600))));
				// echo $row['reserves']."-".$this->hero->less_exhaust[2]." * (".$row['resprod1']." - (".(FOREST_REGROWTH * WORLD_SPEED).")) * (".($row['lastchange2']/3600)."))); = ".$remaining."<br>";
				break;
			case 3:
				$pic = "gfx/lehm.gif";
				$remaining =  max (0, (int)($row['reserves'] - ($this->hero->less_exhaust[3] * $row['resprod2'] * ($row['lastchange2']/3600))));
				break;
			case 4:
				$pic = "gfx/iron.gif";
				$remaining =  max (0, (int)($row['reserves'] - ($this->hero->less_exhaust[4] * $row['resprod3'] * ($row['lastchange2']/3600))));
				break;
			case 1:
				$pic = "gfx/food.gif";
				$remaining = RESS_RESERVE;
				break;
		}

		return ($remaining);
	}

	function refresh_villages ()
	{
		$this->allvillageids = array ();
		$this->villages = array ();
		$this->fetch_villages ();

		// The active outpost might have been the one that was captured
		if ($this->activeoutpostid)
		{
			if (!in_array ($this->activeoutpostid, $this->allvillageids))
			{
				$this->activeoutpostid = 0;
				$this->activeoutpost = NULL;
			}
		}
	}

	function evaluate_delegates ($flags)
	{
		// Commanders have died and we need to recalculate how many we can recruit
		if ($flags & 1)
		{
			$this->CalcCommanders ();
			$this->log_debug ("Recalced Commanders");
		}

		// In the meantime, research has happened and we need to re-check our limits
		if ($flags & 2)
		{
			$this->CalcResearch(true);
		}

		// The diplomatical status of the ally has changed
		if ($flags & 4)
		{
			require_once ("ally.inc.php");
			$this->allymeta = array ();

			if ($this->aid)
				$this->allymeta[] = $this->aid;
			$this->allydipl = ally_reload_diplomacy ($this->aid, $this->allymeta);
			$newallywars = ally_reload_wars ($this->aid);
			$this->allywars = $newallywars;
		}

		if ($flags & 8)
		{
			$this->refresh_villages ();
		}
	}
}


?>