Source

Selador / units / units_send.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
<?php
$no_reload = 1;

if ($me->activeoutpostid)
	$here = $me->activeoutpostid;
else
	$here = $me->activevillageid;

if (isset ($_REQUEST['x']))
	$x = $_REQUEST['x'];

if (isset ($_REQUEST['y']))
	$y = $_REQUEST['y'];

if (isset ($_REQUEST['u']) && isset ($_REQUEST['send']) && isset ($_REQUEST['stage']))
{
	$u = $_REQUEST['u'];
	$stage = (int)$_REQUEST['stage'];
	$hero_health_irrelevant = false;

	// Check if enough units all in all have been selected
	if (array_sum ($u) > 0)
	{
		if (isset ($_REQUEST['c']))
		{
			$troopid = (int)$_REQUEST['c'];
			$query = "select A.troopid, A.uid, A.villageid, B.unitid, B.amount, C.speed, C.flags, D.villageid as fromvid, D.name as fromvill, D.uid as touser, D.x as fromx, D.y as fromy, E.villageid as tovid, E.name as tovill, E.uid as touser, E.x as tox, E.y as toy, F.user as ownername from armies A join troops B on (A.troopid=B.troopid)  left join units C on (B.unitid=C.unitid) join village D on (A.location=D.villageid) join village E on (A.villageid=E.villageid) join user F on (A.uid=F.uid) where A.flag=0 and A.troopid=".$troopid." and (A.villageid=".$here." or A.location=".$here.")";
			$hero_health_irrelevant = true;

			if ($debug)
				echo $query;
		}
		else
			$query = "select A.troopid, B.unitid, B.amount, C.speed, C.flags from armies A join troops B on (A.troopid=B.troopid) left join units C on (C.speed>0 and B.unitid=C.unitid) where A.flag=0 and A.villageid=".$me->activevillageid." and A.location=".$me->activevillageid;

		if (!($res = mysql_query ($query)))
			log_err ("Troop sending query failed. Query: ".$query.", ".mysql_error ());

	      while ($row = mysql_fetch_array ($res))
	      {
			$home_troopid = $row['troopid'];
			$units_here[$row['unitid']] = $row['amount'];
			if ($row['speed'])
				$unit_speed[$row['unitid']] = (int)($row['speed'] * (1+$me->speed_bonus));
			else
				$unit_speed[$row['unitid']] = $me->hero->speed;

			if (isset ($troopid))
				$lastrow = $row;	// Pass this information on for later
		}


		mysql_free_result ($res);

		$slowest_speed = 10000;
		$commander_there = false;
		$all_gone = true;
		$total_units = 0;
		$all_commanders_coming = false;
		$hero_cometh = false;

        //print_r($u);
		foreach ($u as $idx => $this_unit)
		{
			if ($this_unit > 0)
			{
				if ($idx == 1000)
				{
					if (($units_here[1000] >= 1) && ($this_unit == 1) && ((round ($me->hero->health) > 0) || $hero_health_irrelevant))
					{
						$commander_there = 1;
						$hero_cometh = true;
					}
					else
					{
						$send_err = "Der Held ist nicht in dieser Stadt. - Cheater ;)";
					}
				}

				if ((int)$this_unit > $units_here[$idx])
				{
					$send_err = "Nicht genügend Einheiten vorhanden!";
				}
				$total_units += (int)$this_unit;

				if (($idx == 4||$idx == 19) && ((int)$this_unit > 0))
				{
					$commander_there = 2;
					if ($units_here[$idx] == (int)$this_unit)
						$all_commanders_coming = true;
				}

				if ($unit_speed[$idx] < $slowest_speed)
				{
					if ($debug)
						echo "Replacing old speed ".$slowest_speed." with ".$unit_speed[$idx]." ";
					$slowest_speed = $unit_speed[$idx];
				}
			}
		}


        if (((int)$units_here[4] - $u[4] == 0) && ((int)$units_here[19] - $u[19] == 0)
            && ((int)$units_here[1000] - $u[1000] == 0))//...and no hero
            $all_commanders_coming = true;
        else
            $all_commanders_coming = false;


		if (isset ($troopid))
		{
			foreach ($units_here as $idx=>$amount)
			{
				if ($amount > (int)$u[$idx])
				{
					// if ($debug)
						// log_debug ("ID: ".$idx." here ".$amount.", to go ".(int)$u[$idx].", so not all gone");
					$all_gone = false;
				}
			}
		}

		$sendidx = $_REQUEST['sendtroops'];
		$cost_fac = 2;
		switch (key($sendidx))
		{
			case GROUPATTACK_PART:
				$type = GROUPATTACK_PART;
				$what = "Teilnahme an Gruppenangriff";
				$commander_needed = true;
				$setup_time = SETUP_GROUP_PART;
				$allflag = 1;
				$cost_fac = 2;
				break;
			case GROUPATTACK:
				$type = GROUPATTACK;
				$what = "Gruppenangriff";
				$commander_needed = true;
				$setup_time = SETUP_GROUP_LEAD;
				$allflag = 1;
				$cost_fac = 2;
				break;
			case RETURNING:
				$type = RETURNING;
				$what = "Heimschicken zu ";
				$commander_needed = true;
				$allflag = 0;
				$setup_time = SETUP_RETURN;
				$cost_fac = 0;
				break;
			case SIEGE:
                if (SIEGE_POSSIBLE)
                {
				  $type = SIEGE;
				  $what = "Erobern von ";
				  $commander_needed = true;
				  $setup_time = SETUP_SIEGE;
				  $allflag = 1;
                }
                else
                    $send_err = "Erobern ist in dieser Welt nicht m&ouml;glich.";
				  break;
			case ATTACK:
				  $type = ATTACK;
				  $what = "Angriff auf ";
				  $commander_needed = true;
				  $setup_time = SETUP_ATTACK;
				  $allflag = 1;
				break;
			case RAID:
				  $type = RAID;
				  $what = "Raubzug auf ";
				  $commander_needed = true;
				  $setup_time = SETUP_RAID;
				  $allflag = 1;
				  break;
			case SUPPORT:
				  $type = SUPPORT;
				  $what = "Unterst&uuml;tzung für ";
				  $commander_needed = true;
				  $setup_time = SETUP_SUPPORT;
				  $cost_fac = 4;
				  $allflag = 0;
				  break;
			case SPY:
				  $type = SPY;
				  $what = "Aussp&auml;hen von ";
				  $commander_needed = false;
				  $setup_time = SETUP_SPY;
				  $allflag = 1;
				  if ((int)$u[$spy_byrace[$me->race]] == 0)
				    $send_err = "Keine Sp&auml;her angewählt";
				  break;
			case MOVE:
				$type = MOVE;
				$what = "Stationieren in ";
				$commander_needed = false;
				$setup_time = SETUP_MOVE;
				$cost_fac = 1;
				$allflag = 0;
				break;
		}


		if ($commander_needed)
		{
			if (!$commander_there)
			$send_err = "Ein Heerführer muss mitgehen!";
		}

		if (!isset ($send_err))
		{
			if (isset ($lastrow))	// Only true if we are talking about returning troops
			{
				$x = $lastrow['tox'];
				$y = $lastrow['toy'];
                $dist = sqrt (abs((($lastrow['fromx'] - $lastrow['tox']) * ($lastrow['fromx'] - $lastrow['tox'])) + (($lastrow['fromy'] - $lastrow['toy']) * ($lastrow['fromy'] - $lastrow['toy']))));

               // $dist = sqrt ( (($x - $me->activevillage->x) * ($x - $me->activevillage->x)) + (($y - $me->activevillage->y) * ($y - $me->activevillage->y)));
				$targetuid = $lastrow['touid'];
				$fromvill = $lastrow['tovid'];
				$targetvill = $lastrow['fromvid'];

				$targetvname = $lastrow['tovill'];
				$targetuid = $lastrow['touser'];

				$fromvname = $lastrow['fromvill'];
				$fromuid = $lastrow['uid'];
				$ownerusername = $lastrow['ownername'];

				$dur = (int)(($dist/$slowest_speed)*3600 / WORLD_UNIT_SPEED);
				if ($all_commanders_coming && !$all_gone)
					$send_err = 'Du kannst nicht alle Heerführer abziehen. <a href="javascript:history.back()">Probiere es hier noch einmal</a>';
			}
			else
			{
				if (isset ($x) && isset ($y))
				{
					if (!is_numeric ($x) && !is_numeric ($y))
						$send_err = "Koordinaten falsch!";
					else
					{
						// Alle Checks soweit erfolgreich, nun noch das Ziel untersuchen
						$query = "select A.name as vname, A.uid, A.outpost_of, A.villageid, B.user, B.aid, round(B.score/1000) as score, B.inactivity from village A, user B where A.uid=B.uid and A.x=".$x." and A.y=".$y;

						$res = mysql_query ($query);

						if ($row = mysql_fetch_array ($res))
						{
							// Ok, the village exists
							$targetuid = $row['uid'];
							$targetvill = $row['villageid'];
							$targetvname = $row['vname'];
							$targetuser = $row['user'];
							$targetuid = $row['uid'];

							if ($me->sat_by && $targetuid != $me->uid)
							{
								$send_err = "Als Sitter darfst du Einheiten nur innerhalb des Accounts verschicken. ";
							}
							else
							{

								$fromvill = $me->activevillageid;
								$fromuid = $me->uid;

								if (($type == SIEGE) && ($row['outpost_of'] == 0))
									$send_err = "Du kannst nur Aussenposten erobern!";
								else
								{
									if (($type == SIEGE) && ($me->activevillage->outpost_expansion == 0))
										$send_err = "Du musst erst dein Hauptgeb&auml;ude ausbauen, um einen Aussenposten erobern zu k&ouml;nnen!";
									else
									{
										// We don't allow attacks on our own villages!
										// FIXME This will be allowed later on to break sieges
										if ((($type == ATTACK) || ($type == RAID) || ($type == GROUPATTACK) || ($type == GROUPATTACK_PART) || ($type == SPY) || ($type == SIEGE)) && ($me->uid == $targetuid))
										{
											$send_err = "Du willst doch nicht etwa deine eigenen Leute angreifen??? Schande! ;)";
										}
										else
										{
											if (($type == MOVE) && (($me->uid != $targetuid) || ($row['outpost_of'])))
												$send_err = "Du kannst deine Truppen nur in deinen eigenen D&ouml;rfern (nicht Aussenposten) stationieren!";
											else
											{
												// Check that this guy isn't newbie protected
												if ((($type == ATTACK) || ($type == RAID) || ($type == GROUPATTACK) || ($type == GROUPATTACK_PART) || ($type == SPY) || ($type == SIEGE)) && ($row['score'] < round ($me->score/4)) && ($row['inactivity'] == 0) && (!in_array($row['aid'], $me->allywars)))
												{
													$send_err = "Dieser Spieler ist f&uuml;r dich im Noob-Schutz und kann nicht angegriffen werden, bis er st&auml;rker ist.";
												}
												else
												{
												// Check that I'm not newbie protected
													if ((($type == ATTACK) || ($type == RAID) || ($type == GROUPATTACK) || ($type == GROUPATTACK_PART)|| ($type == SPY) || ($type == SIEGE)) && ($row['score'] > $me->score*4) && (!$row['inactivity']) && (!in_array($row['aid'], $me->allywars)))
													{
														$send_err = "Du bist f&uuml;r diesen Spieler im Noob-Schutz und kannst ihn erst angreifen, wenn du st&auml;rker bist.";
													}
													else
													{
														mysql_free_result ($res);

														if ($type == MOVE)
														{
															// Now calculate food and population of destination village if this is a move action
															// First we run its event handler, so that we get a feeling for the number of units
															// in the recruit queue
															$me->villages[$targetvill]->update_to_latest ();
															$dummygui = new Gui;
															$eh = new EventHandler ($me, $dummygui, $user_row, $gamedb, $targetvill);

															if (!$eh->run())
																$me->log_debug ("Moving units: Restarting because of transaction fail!");

															$me->villages[$targetvill]->do_income ();  // Update the income to this point in time
															$me->villages[$targetvill]->update_stamp_nounlock ();  // And save it
															$me->save_score ();

															// Now sum up the population there
															$targetpop = $me->villages[$targetvill]->sum_population ($dummygui);

															if ($targetpop + $total_units > $me->villages[$targetvill]->ress_prod[5])
																$send_err = "Die Zielstadt kann nicht mehr als ".($me->villages[$targetvill]->ress_prod[5] - $targetpop)." Einheiten ern&auml;hren!";
														}

														$dist = sqrt ( (($x - $me->activevillage->x) * ($x - $me->activevillage->x)) + (($y - $me->activevillage->y) * ($y - $me->activevillage->y)));
														$dur = (int)(($dist/$slowest_speed)*3600 / WORLD_UNIT_SPEED);
														// Add setup time
														$dur += $setup_time;

														// For participation in group attacks we need some additional checks
														if ($type == GROUPATTACK_PART)
														{
															// First one: Are all needed variables set?
															if (isset ($_REQUEST['grattid']))
															{
																$groupattack_id = (int)$_REQUEST['grattid'];
																// Then we have to check if this group attack exists
																$query = "select A.grattid,A.targetvillage,time_to_sec(timediff(A.eta,now())) as dif,A.eta from groupatts A join groupatt_invites B on (A.grattid=".$groupattack_id." and B.grattid=".$groupattack_id." and B.uid=".$me->uid.")";

																if (!($res = mysql_query ($query)))
																{
																	$send_err = "Leider ist ein Datenbank-Fehler aufgetreten.";
																	log_err ("Cannot read group attack info when sending troops. Query: ".$query.", ".mysql_error ());
																}
																else
																{
																	if ($grouprow = mysql_fetch_array ($res))
																	{
																		// So it exists. Is there enough time to join yet?
																		if ($grouprow['dif'] < $dur)
																			$send_err = "Deine Truppen sind nicht schnell genug, um an diesem Gruppenangriff teilzunehmen.";
																		else
																		{
																			// Yes, there is enough time. We set the duration to the time of the final event
																			$dur = $grouprow['dif'];
																		}
																	}
																	else
																		$send_err = "Diese Einladung zum Gruppenangriff existiert nicht oder nicht mehr.";
																}
															}
															else
																$send_err = "Es ist ein interner Fehler aufgetreten.";
														}

														// Calculate how much this action will cost the player
														$gold_cost = ceil ($total_units / 50 * $cost_fac * ($dur / 3600) * WORLD_UNIT_SPEED);
														$gold_cost *= $me->hero->troop_send_costs;

													}
												}
											}
										}
									}
								}
							}
						}
						else
							$send_err = "Dort ist keine Stadt!";
					}
				}
				else
				{
					if (isset ($_REQUEST['dname']))
					{
						$send_err = "Stadtnamen-Suche noch nicht implementiert!";
					}
					else
						$send_err = "Bitte Ziel eingeben!";
				}
			}

			if (!isset ($send_err))
			{
				if ($stage == 1)
				{
					// Display all info again
					$info_str = "<form action=\"".$_SERVER['PHP_SELF']."\" method=\"POST\"><table class=\"border\">"; //<tr id=\"rundrum\"><th colspan=\"4\">";
					// $info_str .= $what.$targetvname.", Spieler ".$targetuser."</th></tr>";
					$info_str .= "<tr><th>&nbsp;</th><th id=rundrum>Einheit</th><th id=rundrum>Geschwindigkeit</th><th id=rundrum>Anzahl</th></tr>\n";

					if ($type == SPY)
					{
						$id = $spy_byrace[$me->race];
						$info_str .= "<tr id=\"rundrum\"><td id=rundrum><a href=\"hilfe.php?up=".$id."\" title=\"Hilfe\"><img src=\"gfx/u/".$id.".gif\"></a></td><td id=rundrum>".$unitmap[$id]."</td>";
						$info_str .= "<td id=rundrum>".(int) ($unit_speed[$id] * WORLD_UNIT_SPEED)."</td><td id=rundrum>".$u[$id]."<input type=\"hidden\" name=\"u[".$id."]\" value=\"".$u[$id]."\"></td></tr>";
					}
					else
					{
						$capacity = 0;
						foreach ($u as $id=>$amount)
						{
							// if ($type == SUPPORT || $type == RETURNING || $type == MOVE || $id != $spy_byrace[$me->race])
							{
								if ((int)$amount > 0)
								{
									if ($id == 1000)
									{
										if (isset ($_REQUEST['c']))
											$info_str .= "<tr id=\"rundrum\"><td id=rundrum><img src=\"gfx/u/1000.gif\"></td><td id=rundrum>".$ownerusername."</td>";
										else
											$info_str .= "<tr id=\"rundrum\"><td id=rundrum><img src=\"gfx/u/1000.gif\"></td><td id=rundrum>".$me->user."</td>";
										$info_str .= "<td id=rundrum>".(int) ($unit_speed[$id] * WORLD_UNIT_SPEED)."</td><td id=rundrum>1<input type=\"hidden\" name=\"u[".$id."]\" value=\"".min (1, $u[$id])."\"></td></tr>";
										$hero_cometh = true;	// Better set it twice eh :)
										$capacity += 50;
									}
									else
									{
										$info_str .= "<tr id=\"rundrum\"><td id=rundrum><a href=\"hilfe.php?up=".$id."\" title=\"Hilfe\"><img src=\"gfx/u/".$id.".gif\"></a></td><td id=rundrum>".$unitmap[$id]."</td>";
										$info_str .= "<td id=rundrum>".(int) ($unit_speed[$id] * WORLD_UNIT_SPEED)."<input type=\"hidden\" name=\"u[".$id."]\" value=\"".(int)$u[$id]."\"></td><td id=rundrum>".(int)$amount."</td></tr>";
										$capacity += $capacitymap[$id] * (int)$amount;
									}
								}
							}
						}
					}
					if ($commander_needed)
						$info_str .= "<tr><td colspan=\"4\"><b>Gesamttragekapazit&auml;t: ".($capacity)."</td></tr>";
					$info_str .= "</table><br>";

					if ($gold_cost > $me->activevillage->ress[4])
					{
						$info_str .= '<p>Diese Aktion w&uuml;rde dich <span id="bug">'.(int)$gold_cost.'</span>&nbsp;<img src="styles/'.$_SESSION['theme'].'/gold.gif" alt="Gold" width="18" title="Gold"> kosten, so viel hast du nicht. Probiers doch mal mit weniger Truppen oder l&ouml;se den Bausparvertrag auf.</p>';

						$info_str .= "<input type=\"button\" value=\"Verdammt, zur&uuml;ck\" onclick=\"javascript:history.back()\">\n";
					}
					else
					{
						$time_arrival = date ("H:i:s", time () + $dur);

						$info_str .= '<span class="info">Es wird '.external_calcdur ($dur).' dauern, bis die Einheiten ankommen, das wäre um <span id="itimer1">'.$time_arrival.'</span>. Die Aktion wird dich '.(int)$gold_cost.'&nbsp;<img src="styles/'.$_SESSION['theme'].'/gold.gif" width="18" alt="Gold" title="Gold" height="16"> kosten.</span></p>';

						if (($type == GROUPATTACK) || ($type == GROUPATTACK_PART))
							$info_str .= "<p><b>Gruppenangriffe k&ouml;nnen nicht abgebrochen werden.</b></p>";

						$info_str .= "Sollen deine Truppen wirklich losgesendet werden?<br><br>";
						$info_str .= "<input type=\"hidden\" name=\"f\" value=\"3\">";

						if (isset ($lastrow))
							$info_str .= "<input type=\"hidden\" name=\"c\" value=\"".$troopid."\">";
						else
							$info_str .= "<input type=\"hidden\" name=\"x\" value=\"".$x."\"><input type=\"hidden\" name=\"y\" value=\"".$y."\">\n";

						if (isset ($groupattack_id))
							$info_str .= "<input type=\"hidden\" name=\"grattid\" value=\"".$groupattack_id."\">";

						$info_str .= "<input type=\"hidden\" name=\"stage\" value=\"2\"><input type=\"hidden\" name=\"sendtroops[".$type."]\" value=\"".$_REQUEST['sendtroops']."\">";
						$info_str .= "<input type=\"submit\" name=\"send\" value=\"Absenden!\">&nbsp;";
						$info_str .= "<input type=\"button\" value=\"Ne, Zur&uuml;ck\" onclick=\"javascript:history.back()\">\n";
						$info_str .= "</form>\n";
					}
				}

				if ($stage == 2)
				{
					if (!$me->activevillage->can_spend (0, 0, 0, $gold_cost))
					// if ($gold_cost > $me->activevillage->ress[4])
						$send_err = "Nicht gen&uuml;gend Gold vorhanden.";
					else
					{
						// log_debug ("all_gone ".$all_gone.", type ".$type.", troopid ".$troopid);
						if ($all_gone && $type == RETURNING && isset ($troopid))
						{
							$all_gone_done = true;
							$query = "update armies set flag=".$type.", location=".$targetvill." where troopid=".$troopid;

							if (!mysql_query ($query))
							{
								$send_err = "Leider ist ein Datenbank-Fehler aufgetreten. :(";
								log_err ("Cannot update army when sending troops home. Query: ".$query.", error".mysql_error());
							}
						}
						else
						{
							// When moving troops, the rules are a bit different. To correctly calculate food in the
							// destination village, we swap location and villageid, i.e. the troops are already fed by
							// the destination village
							if ($type == MOVE)
								$query = "insert into armies (uid, villageid, flag, location) values (".$fromuid.", ".$targetvill.", ".$type.", ".$fromvill.")";
							else
								$query = "insert into armies (uid, villageid, flag, location) values (".$fromuid.", ".$fromvill.", ".$type.", ".$targetvill.")";

							if (!mysql_query ($query))
							{
								$send_err = "Leider ist ein Datenbank-Fehler aufgetreten. :(";
								log_err ("Cannot insert new army when sending troops. Query: ".$query.", error".mysql_error());
							}
							else
							{
								$troopid = mysql_insert_id ();
								$query = "insert into troops values ";

								foreach ($u as $idx => $this_unit)
								{
									if ($this_unit > 0)
									{
										if (!isset ($query_suffix))
											$query_suffix = "(".$troopid.", ".(int)$idx.", ".(int)$this_unit.")";
										else
											$query_suffix .= ",(".$troopid.", ".(int)$idx.", ".(int)$this_unit.")";
									}
								}

								if (!mysql_query ($query.$query_suffix))
								{
									$send_err = "Leider ist ein Datenbank-Fehler aufgetreten. :(";
									log_err ("Cannot insert new troops when sending troops. Query: ".$query.$query_suffix.", error".$mysql_error());
								}
							}
						}
					}

					if (!isset ($send_err))
					{
						if (isset ($hero_cometh) && ($hero_cometh == true))
						{
							if ($type == RETURNING)
								$me->hero->location = $fromvill;
							else
								$me->hero->location = $targetvill;
							$me->hero->troopid = $troopid;
							$me->hero->needs_updating = true;
							log_debug ("Setting hero location to ".$targetvill." and troopid to ".$troopid);
						}

						if ($type == GROUPATTACK)
						{
							// First acquire a group attack id
							$query = "insert into groupatts values (NULL, ".$targetvill.", addtime(now(), sec_to_time(".$dur.")))";

							if (!mysql_query ($query))
							{
								$send_err = "Leider ist ein Datenbank-Fehler aufgetreten. :(";
								log_err ("Cannot insert groupatts entry. Query: ".$query.", ".mysql_error ());
							}
							else
								$groupattack_id = mysql_insert_id ();
						}

						if (!isset ($send_err) && (($type == GROUPATTACK) || ($type == GROUPATTACK_PART)))
						{
							// A group attack first needs an entry in groupattacks - surprise
							$query = "insert into groupatt_members (grattid, troopid,type,uid,from_village,home_duration) values (".$groupattack_id.", ".$troopid.", ".$type.", ".$fromuid.", ".$fromvill.", ".$dur.")";

							if (!mysql_query ($query))
							{
								$send_err = "Leider ist ein Datenbank-Fehler aufgetreten. :(";
								log_err ("Cannot insert groupatts entry. Query: ".$query.", ".mysql_error ());
							}
						}
						else
							$groupattack_id = 0;

						if ($groupattack_id && ($type == GROUPATTACK_PART))
						{
							$query = "delete from groupatt_invites where uid=".$me->uid." and grattid=".$groupattack_id;

							if (!mysql_query ($query))
								log_err ("Cannot delete group attack invitation after sending troops. Query: ".$query.", ".mysql_error ());
						}

						if (!isset ($send_err))
						{
							// This is stupid, but we definitely want to avoid adding another row to the DB. So
							// we abuse the score (!) column for storing the grattid
							$query = "insert into event (uid1, village1, uid2, village2, timestamp, type, param, param2, flag, score) values (".$fromuid.", ".$fromvill.", ".$targetuid.", ".$targetvill.", addtime(now(), sec_to_time(".$dur.")), ".$type.", ".$troopid.", ".$dur.", ".$allflag.", ".$groupattack_id.")";

							if (!@mysql_query ($query))
							{
								$send_err = "Leider ist ein Datenbank-Fehler aufgetreten. :(";
								log_err ("Cannot insert troop send event: ".$query.", error: ".mysql_error ());
							}
							else
							{
								$redirect_page="einheiten.php?f=2";
								$eid = mysql_insert_id ();
								$query = "insert into eventlog (eid, uid1, village1, uid2, village2, fired, happened, type, param, param2, state) values (".$eid.", ".$fromuid.", ".$fromvill.", ".$targetuid.", ".$targetvill.", NULL, addtime(now(), sec_to_time(".$dur.")), ".$type.", ".$troopid.", ".$dur.", 0)";

								if (!@mysql_query ($query))
									log_err ("Cannot log event ".$query.", ".mysql_error());
							}

							if (!isset ($send_err) && !isset ($all_gone_done))
							{
								// Now subtract these units from the troop at home
								unset ($query);

								foreach ($u as $unit_id => $amount)
								{
									if ($amount > 0)
									{
										if (!isset ($query))
											$query = "(".$home_troopid.", ".(int)$unit_id.", ".($units_here[$unit_id] - $amount).")";
										else
											$query .= ", (".$home_troopid.", ".(int)$unit_id.", ".($units_here[$unit_id] - $amount).")";
									}
								}
								$query = "replace into troops values ".$query;

								if (!(mysql_query ($query)))
								{
									unset ($redirect_page);
									$send_err = "Leider ist ein Datenbank-Fehler aufgetreten. :(";
									log_err ("Cannot subtract troops at home after sending troops. Query: ".$query.", ".mysql_error());
								}

								//$me->activevillage->ress[4] -= $gold_cost;
								$me->activevillage->spend (0, 0, 0, $gold_cost);
								// Adding a siege event is different than other attack types
								// It sets flags in the target village
								if ($type == SIEGE)
								{
									$query = "update village set out_expansion=out_expansion-1 where villageid=".$me->activevillageid;
									if (!mysql_query ($query))
									{
										log_err ("Cannot reduce outpost expansion slots when building. Query: ".$query.", ".mysql_error ());
									}
									$me->activevillage->outpost_expansion--;
								}
							}
						}
					}
				}
			}

		}
	}
	else
		$send_err = "Es wurden nicht genügend Einheiten ausgewählt!";
  }
  if (isset ($redirect_page))
	echo '<script>window.location = "einheiten.php?f=2"; </script>';

require_once ("einheiten-schicken.php");


?>