Exemple #1
0
function UpdateUnionTime($union_id, $end, $fleet_id, $force_set = false)
{
    global $db_prefix;
    $result = EnumUnionFleets($union_id);
    $rows = dbrows($result);
    while ($rows--) {
        $fleet_obj = dbarray($result);
        if ($fleet_obj['fleet_id'] == $fleet_id) {
            continue;
        }
        $queue = GetFleetQueue($fleet_obj['fleet_id']);
        $union_time = $queue['end'];
        $queue_id = $queue['task_id'];
        if ($end > $union_time || $force_set) {
            $union_time = $end;
            $query = "UPDATE " . $db_prefix . "queue SET end = {$end} WHERE task_id = {$queue_id}";
            dbquery($query);
        }
    }
    return $union_time;
}
function PhalanxEventList($planet_id)
{
    $planet = GetPlanet($planet_id);
    $user = LoadUser($planet['owner_id']);
    $fleetmap = array(202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215);
    $result = EnumPlanetFleets($planet_id);
    $rows = dbrows($result);
    $task = array();
    $tasknum = 0;
    $unions = array();
    while ($rows--) {
        $fleet_obj = dbarray($result);
        $queue = GetFleetQueue($fleet_obj['fleet_id']);
        // Союзные флоты собираются отдельно
        if ($fleet_obj['union_id'] > 0 && $fleet_obj['target_planet'] == $planet_id && !$unions[$fleet_obj['union_id']]) {
            $task[$tasknum]['end_time'] = $queue['end'];
            // Флоты
            $acs_result = EnumUnionFleets($fleet_obj['union_id']);
            $task[$tasknum]['fleets'] = $acs_rows = dbrows($acs_result);
            $f = 0;
            while ($acs_rows--) {
                $fleet_obj = dbarray($acs_result);
                $task[$tasknum]['fleet'][$f] = array();
                foreach ($fleetmap as $id => $gid) {
                    $task[$tasknum]['fleet'][$f][$gid] = $fleet_obj["ship{$gid}"];
                }
                $task[$tasknum]['fleet'][$f]['owner_id'] = $fleet_obj['owner_id'];
                $task[$tasknum]['fleet'][$f]['origin_id'] = $fleet_obj['start_planet'];
                $task[$tasknum]['fleet'][$f]['target_id'] = $fleet_obj['target_planet'];
                $task[$tasknum]['fleet'][$f]['mission'] = GetMission($fleet_obj);
                $task[$tasknum]['fleet'][$f]['dir'] = 1;
                // на планету
                $f++;
            }
            $unions[$fleet_obj['union_id']] = 1;
            $tasknum++;
            continue;
        }
        if ($fleet_obj['union_id'] > 0 && $fleet_obj['target_planet'] == $planet_id && $fleet_obj['mission'] != 21) {
            continue;
        }
        // Не показывать отправление и возврат Оставить.
        if ($fleet_obj['mission'] == 104) {
            continue;
        }
        if ($fleet_obj['mission'] == 4 && $fleet_obj['start_planet'] == $planet_id) {
            continue;
        }
        // Не показывать возвращающиеся с целевой планеты флоты.
        if ($fleet_obj['mission'] > 100 && $fleet_obj['mission'] < 200 && $fleet_obj['target_planet'] == $planet_id) {
            continue;
        }
        // Время прибытия
        if ($fleet_obj['mission'] < 100 && $fleet_obj['start_planet'] == $planet_id) {
            if ($fleet_obj['mission'] != 15) {
                $task[$tasknum]['end_time'] = $queue['end'] + $fleet_obj['flight_time'];
            } else {
                $task[$tasknum]['end_time'] = $queue['end'];
            }
        } else {
            $task[$tasknum]['end_time'] = $queue['end'];
        }
        // Флот
        $task[$tasknum]['fleets'] = 1;
        $task[$tasknum]['fleet'][0] = array();
        foreach ($fleetmap as $i => $gid) {
            $task[$tasknum]['fleet'][0][$gid] = $fleet_obj["ship{$gid}"];
        }
        $task[$tasknum]['fleet'][0]['owner_id'] = $fleet_obj['owner_id'];
        $task[$tasknum]['fleet'][0]['origin_id'] = $fleet_obj['start_planet'];
        $task[$tasknum]['fleet'][0]['target_id'] = $fleet_obj['target_planet'];
        $task[$tasknum]['fleet'][0]['mission'] = GetMission($fleet_obj);
        if (GetMission($fleet_obj) == 15) {
            if ($fleet_obj['mission'] < 100) {
                $task[$tasknum]['fleet'][0]['dir'] = 1;
            } else {
                if ($fleet_obj['mission'] < 200) {
                    $task[$tasknum]['fleet'][0]['dir'] = 0;
                } else {
                    $task[$tasknum]['fleet'][0]['dir'] = 2;
                }
            }
        } else {
            if (GetMission($fleet_obj) == 5) {
                if ($fleet_obj['mission'] < 100) {
                    $task[$tasknum]['fleet'][0]['dir'] = 1;
                } else {
                    if ($fleet_obj['mission'] < 200) {
                        $task[$tasknum]['fleet'][0]['dir'] = 0;
                    } else {
                        $task[$tasknum]['fleet'][0]['dir'] = 2;
                    }
                }
            } else {
                if ($fleet_obj['target_planet'] == $planet_id) {
                    $task[$tasknum]['fleet'][0]['dir'] = 1;
                } else {
                    $task[$tasknum]['fleet'][0]['dir'] = 0;
                }
                // возврат
            }
        }
        if ($fleet_obj['mission'] == 20) {
            $task[$tasknum]['fleet'][0]['ipm_amount'] = $fleet_obj['ipm_amount'];
            $task[$tasknum]['fleet'][0]['ipm_target'] = $fleet_obj['ipm_target'];
        }
        $tasknum++;
        // Для убывающей экспедиции добавить псевдозадание удерживания.
        // Не показывать чужие флоты.
        if ($fleet_obj['mission'] == 15 && $fleet_obj['owner_id'] == $user['player_id']) {
            // Время отправления и прибытия
            $task[$tasknum]['end_time'] = $queue['end'] + $fleet_obj['deploy_time'];
            // Флот
            $task[$tasknum]['fleets'] = 1;
            $task[$tasknum]['fleet'][0] = array();
            foreach ($fleetmap as $i => $gid) {
                $task[$tasknum]['fleet'][0][$gid] = $fleet_obj["ship{$gid}"];
            }
            $task[$tasknum]['fleet'][0]['owner_id'] = $fleet_obj['owner_id'];
            $task[$tasknum]['fleet'][0]['origin_id'] = $fleet_obj['start_planet'];
            $task[$tasknum]['fleet'][0]['target_id'] = $fleet_obj['target_planet'];
            $task[$tasknum]['fleet'][0]['mission'] = GetMission($fleet_obj);
            $task[$tasknum]['fleet'][0]['dir'] = 2;
            $tasknum++;
        }
        // Для прибывающего задания Держаться добавить псевдозадание удерживания.
        if ($fleet_obj['mission'] == 5 && $fleet_obj['owner_id'] != $user['player_id']) {
            // Время отправления и прибытия
            $task[$tasknum]['end_time'] = $queue['end'] + $fleet_obj['deploy_time'];
            // Флот
            $task[$tasknum]['fleets'] = 1;
            $task[$tasknum]['fleet'][0] = array();
            foreach ($fleetmap as $i => $gid) {
                $task[$tasknum]['fleet'][0][$gid] = $fleet_obj["ship{$gid}"];
            }
            $task[$tasknum]['fleet'][0]['owner_id'] = $fleet_obj['owner_id'];
            $task[$tasknum]['fleet'][0]['origin_id'] = $fleet_obj['start_planet'];
            $task[$tasknum]['fleet'][0]['target_id'] = $fleet_obj['target_planet'];
            $task[$tasknum]['fleet'][0]['mission'] = GetMission($fleet_obj);
            $task[$tasknum]['fleet'][0]['dir'] = 2;
            $tasknum++;
        }
        // Для убывающих или удерживаемых экспедиций добавить псевдозадание возврата.
        if (($fleet_obj['mission'] == 15 || $fleet_obj['mission'] == 215) && $fleet_obj['owner_id'] == $user['player_id']) {
            // Время отправления и прибытия
            if ($fleet_obj['mission'] > 200) {
                $task[$tasknum]['end_time'] = $queue['end'] + $fleet_obj['deploy_time'];
            } else {
                $task[$tasknum]['end_time'] = $queue['end'] + $fleet_obj['deploy_time'] + $fleet_obj['flight_time'];
            }
            // Флот
            $task[$tasknum]['fleets'] = 1;
            $task[$tasknum]['fleet'][0] = array();
            foreach ($fleetmap as $i => $gid) {
                $task[$tasknum]['fleet'][0][$gid] = $fleet_obj["ship{$gid}"];
            }
            $task[$tasknum]['fleet'][0]['owner_id'] = $fleet_obj['owner_id'];
            $task[$tasknum]['fleet'][0]['origin_id'] = $fleet_obj['target_planet'];
            $task[$tasknum]['fleet'][0]['target_id'] = $fleet_obj['start_planet'];
            $task[$tasknum]['fleet'][0]['mission'] = GetMission($fleet_obj);
            $task[$tasknum]['fleet'][0]['dir'] = 0;
            $tasknum++;
        }
    }
    $anz = 0;
    if ($tasknum > 0) {
        sksort($task, 'end_time', true);
        // Сортировать по времени прибытия.
        $now = time();
        foreach ($task as $i => $t) {
            $seconds = max($t['end_time'] - $now, 0);
            if ($seconds <= 0) {
                continue;
            }
            if ($t['fleets'] > 1) {
                echo "<tr class=''>\n";
            } else {
                if ($t['direction'] == 1) {
                    echo "<tr class='flight'>\n";
                } else {
                    if ($t['direction'] == 0) {
                        echo "<tr class='return'>\n";
                    } else {
                        if ($t['direction'] == 2) {
                            echo "<tr class='holding'>\n";
                        }
                    }
                }
            }
            echo "<th><div id='bxx" . ($i + 1) . "' title='" . $seconds . "'star='" . $t['end_time'] . "'></div></th>\n";
            echo "<th colspan='3'>";
            for ($fl = 0; $fl < $t['fleets']; $fl++) {
                echo FleetSpan($t['fleet'][$fl]);
                if ($t['fleets'] > 1) {
                    echo "<br /><br />";
                }
            }
            echo "</th></tr>\n\n";
            $anz++;
        }
        if ($anz) {
            echo "<script language=javascript>anz=" . $anz . ";t();</script>\n\n";
        }
    }
}
function EventList()
{
    global $GlobalUser;
    $fleetmap = array(202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215);
    // Одиночные флоты
    $tasklist = EnumFleetQueue($GlobalUser['player_id']);
    $rows = dbrows($tasklist);
    $task = array();
    $tasknum = 0;
    while ($rows--) {
        $queue = dbarray($tasklist);
        // Время отправления и прибытия
        $task[$tasknum]['start_time'] = $queue['start'];
        $task[$tasknum]['end_time'] = $queue['end'];
        $fleet_obj = LoadFleet($queue['sub_id']);
        if ($fleet_obj['union_id'] > 0) {
            continue;
        }
        // Союзные флоты собираются отдельно
        // Флот
        $task[$tasknum]['fleets'] = 1;
        $task[$tasknum]['fleet'][0] = array();
        foreach ($fleetmap as $i => $gid) {
            $task[$tasknum]['fleet'][0][$gid] = $fleet_obj["ship{$gid}"];
        }
        $task[$tasknum]['fleet'][0]['owner_id'] = $fleet_obj['owner_id'];
        $task[$tasknum]['fleet'][0]['m'] = $fleet_obj['m'];
        $task[$tasknum]['fleet'][0]['k'] = $fleet_obj['k'];
        $task[$tasknum]['fleet'][0]['d'] = $fleet_obj['d'];
        if ($fleet_obj['mission'] < 100 || $fleet_obj['mission'] > 200) {
            $task[$tasknum]['fleet'][0]['origin_id'] = $fleet_obj['start_planet'];
            $task[$tasknum]['fleet'][0]['target_id'] = $fleet_obj['target_planet'];
        } else {
            $task[$tasknum]['fleet'][0]['origin_id'] = $fleet_obj['target_planet'];
            $task[$tasknum]['fleet'][0]['target_id'] = $fleet_obj['start_planet'];
        }
        $task[$tasknum]['fleet'][0]['mission'] = GetMission($fleet_obj);
        if ($fleet_obj['mission'] == 20) {
            $task[$tasknum]['fleet'][0]['ipm_amount'] = $fleet_obj['ipm_amount'];
            $task[$tasknum]['fleet'][0]['ipm_target'] = $fleet_obj['ipm_target'];
        }
        GetDirectionAssignment($fleet_obj, $task[$tasknum]['fleet'][0]['dir'], $task[$tasknum]['fleet'][0]['assign']);
        $tasknum++;
        // Для убывающей экспедиции или держаться добавить псевдозадание удерживания.
        // Не показывать чужие флоты.
        if (($fleet_obj['mission'] == 5 || $fleet_obj['mission'] == 15) && $fleet_obj['owner_id'] == $GlobalUser['player_id']) {
            // Время отправления и прибытия
            $task[$tasknum]['start_time'] = $queue['end'];
            $task[$tasknum]['end_time'] = $task[$tasknum]['start_time'] + $fleet_obj['deploy_time'];
            // Флот
            $task[$tasknum]['fleets'] = 1;
            $task[$tasknum]['fleet'][0] = array();
            foreach ($fleetmap as $i => $gid) {
                $task[$tasknum]['fleet'][0][$gid] = $fleet_obj["ship{$gid}"];
            }
            $task[$tasknum]['fleet'][0]['owner_id'] = $fleet_obj['owner_id'];
            $task[$tasknum]['fleet'][0]['m'] = $task[$tasknum]['fleet'][0]['k'] = $task[$tasknum]['fleet'][0]['d'] = 0;
            $task[$tasknum]['fleet'][0]['origin_id'] = $fleet_obj['start_planet'];
            $task[$tasknum]['fleet'][0]['target_id'] = $fleet_obj['target_planet'];
            $task[$tasknum]['fleet'][0]['mission'] = GetMission($fleet_obj);
            $task[$tasknum]['fleet'][0]['dir'] = 2;
            $task[$tasknum]['fleet'][0]['assign'] = 0;
            $tasknum++;
        }
        // Для прибывающего задания Держаться добавить псевдозадание удерживания.
        if ($fleet_obj['mission'] == 5 && $fleet_obj['owner_id'] != $GlobalUser['player_id']) {
            // Время отправления и прибытия
            $task[$tasknum]['start_time'] = $queue['end'];
            $task[$tasknum]['end_time'] = $task[$tasknum]['start_time'] + $fleet_obj['deploy_time'];
            // Флот
            $task[$tasknum]['fleets'] = 1;
            $task[$tasknum]['fleet'][0] = array();
            foreach ($fleetmap as $i => $gid) {
                $task[$tasknum]['fleet'][0][$gid] = $fleet_obj["ship{$gid}"];
            }
            $task[$tasknum]['fleet'][0]['owner_id'] = $fleet_obj['owner_id'];
            $task[$tasknum]['fleet'][0]['m'] = $task[$tasknum]['fleet'][0]['k'] = $task[$tasknum]['fleet'][0]['d'] = 0;
            $task[$tasknum]['fleet'][0]['origin_id'] = $fleet_obj['start_planet'];
            $task[$tasknum]['fleet'][0]['target_id'] = $fleet_obj['target_planet'];
            $task[$tasknum]['fleet'][0]['mission'] = GetMission($fleet_obj);
            $task[$tasknum]['fleet'][0]['dir'] = 2;
            $task[$tasknum]['fleet'][0]['assign'] = 2;
            $tasknum++;
        }
        // Для убывающих или удерживаемых флотов добавить псевдозадание возврата.
        // Не показывать возвраты чужих флотов, задание Оставить и Ракетную атаку.
        if (($fleet_obj['mission'] < 100 || $fleet_obj['mission'] > 200) && $fleet_obj['owner_id'] == $GlobalUser['player_id'] && $fleet_obj['mission'] != 4 && $fleet_obj['mission'] != 20) {
            // Время отправления и прибытия
            $task[$tasknum]['start_time'] = $queue['end'];
            $task[$tasknum]['end_time'] = 2 * $queue['end'] - $queue['start'];
            if (GetMission($fleet_obj) == 5 || GetMission($fleet_obj) == 15) {
                if ($fleet_obj['mission'] > 200) {
                    $task[$tasknum]['end_time'] = $task[$tasknum]['start_time'] + $fleet_obj['deploy_time'];
                } else {
                    $task[$tasknum]['end_time'] = $task[$tasknum]['start_time'] + $fleet_obj['deploy_time'] + $fleet_obj['flight_time'];
                }
            }
            // Флот
            $task[$tasknum]['fleets'] = 1;
            $task[$tasknum]['fleet'][0] = array();
            foreach ($fleetmap as $i => $gid) {
                $task[$tasknum]['fleet'][0][$gid] = $fleet_obj["ship{$gid}"];
            }
            $task[$tasknum]['fleet'][0]['owner_id'] = $fleet_obj['owner_id'];
            $task[$tasknum]['fleet'][0]['m'] = $task[$tasknum]['fleet'][0]['k'] = $task[$tasknum]['fleet'][0]['d'] = 0;
            $task[$tasknum]['fleet'][0]['origin_id'] = $fleet_obj['target_planet'];
            $task[$tasknum]['fleet'][0]['target_id'] = $fleet_obj['start_planet'];
            $task[$tasknum]['fleet'][0]['mission'] = GetMission($fleet_obj);
            $task[$tasknum]['fleet'][0]['dir'] = 1;
            $task[$tasknum]['fleet'][0]['assign'] = 0;
            $tasknum++;
        }
    }
    // Союзные флоты
    $unions = EnumUnion($GlobalUser['player_id']);
    foreach ($unions as $u => $union) {
        // Флоты
        $result = EnumUnionFleets($union['union_id']);
        $rows = dbrows($result);
        if ($rows > 0) {
            $task[$tasknum]['fleets'] = $rows;
            $f = 0;
            $tn = $tasknum;
            while ($rows--) {
                $fleet_obj = dbarray($result);
                $queue = GetFleetQueue($fleet_obj['fleet_id']);
                $task[$tn]['end_time'] = $queue['end'];
                // Для убывающих или удерживаемых флотов добавить псевдозадание возврата.
                // Не показывать возвраты чужих флотов и задание Оставить.
                if ($fleet_obj['mission'] < 100 && $fleet_obj['owner_id'] == $GlobalUser['player_id']) {
                    $tasknum++;
                    // Время отправления и прибытия
                    $task[$tasknum]['end_time'] = $queue['end'] + $fleet_obj['flight_time'];
                    // Флот
                    $task[$tasknum]['fleets'] = 1;
                    $task[$tasknum]['fleet'][0] = array();
                    foreach ($fleetmap as $i => $gid) {
                        $task[$tasknum]['fleet'][0][$gid] = $fleet_obj["ship{$gid}"];
                    }
                    $task[$tasknum]['fleet'][0]['owner_id'] = $fleet_obj['owner_id'];
                    $task[$tasknum]['fleet'][0]['m'] = $task[$tasknum]['fleet'][0]['k'] = $task[$tasknum]['fleet'][0]['d'] = 0;
                    $task[$tasknum]['fleet'][0]['origin_id'] = $fleet_obj['target_planet'];
                    $task[$tasknum]['fleet'][0]['target_id'] = $fleet_obj['start_planet'];
                    $task[$tasknum]['fleet'][0]['mission'] = GetMission($fleet_obj);
                    $task[$tasknum]['fleet'][0]['dir'] = 1;
                    $task[$tasknum]['fleet'][0]['assign'] = 0;
                }
                $task[$tn]['fleet'][$f] = array();
                foreach ($fleetmap as $id => $gid) {
                    $task[$tn]['fleet'][$f][$gid] = $fleet_obj["ship{$gid}"];
                }
                $task[$tn]['fleet'][$f]['owner_id'] = $fleet_obj['owner_id'];
                $task[$tn]['fleet'][$f]['m'] = $fleet_obj['m'];
                $task[$tn]['fleet'][$f]['k'] = $fleet_obj['k'];
                $task[$tn]['fleet'][$f]['d'] = $fleet_obj['d'];
                $task[$tn]['fleet'][$f]['origin_id'] = $fleet_obj['start_planet'];
                $task[$tn]['fleet'][$f]['target_id'] = $fleet_obj['target_planet'];
                $task[$tn]['fleet'][$f]['mission'] = GetMission($fleet_obj);
                GetDirectionAssignment($fleet_obj, $task[$tn]['fleet'][$f]['dir'], $task[$tn]['fleet'][$f]['assign']);
                $f++;
            }
            $tasknum++;
        }
    }
    $anz = 0;
    if ($tasknum > 0) {
        sksort($task, 'end_time', true);
        // Сортировать по времени прибытия.
        $now = time();
        foreach ($task as $i => $t) {
            $seconds = max($t['end_time'] - $now, 0);
            if ($seconds <= 0) {
                continue;
            }
            if ($t['fleets'] > 1) {
                echo "<tr class=''>\n";
            } else {
                if ($t['dir'] == 0) {
                    echo "<tr class='flight'>\n";
                } else {
                    if ($t['dir'] == 1) {
                        echo "<tr class='return'>\n";
                    } else {
                        if ($t['dir'] == 2) {
                            echo "<tr class='holding'>\n";
                        }
                    }
                }
            }
            echo "<th><div id='bxx" . ($i + 1) . "' title='" . $seconds . "'star='" . $t['end_time'] . "'></div></th>\n";
            echo "<th colspan='3'>";
            for ($fl = 0; $fl < $t['fleets']; $fl++) {
                echo FleetSpan($t['fleet'][$fl]);
                if ($t['fleets'] > 1) {
                    echo "<br /><br />";
                }
            }
            echo "</th></tr>\n\n";
            $anz++;
        }
        if ($anz) {
            echo "<script language=javascript>anz=" . $anz . ";t();</script>\n\n";
        }
    }
}
 // Совместная атака
 if ($origin_user['ally_id'] == $target_user['ally_id'] && $origin_user['ally_id'] > 0 || IsBuddy($origin_user['player_id'], $target_user['player_id'])) {
     $BlockAttack = 0;
 }
 if (key_exists('union2', $_POST)) {
     $union_id = floor(intval($_POST['union2']));
 } else {
     $union_id = 0;
 }
 if ($unitab['acs'] == 0) {
     $union_id = 0;
 }
 $union = LoadUnion($union_id);
 $head_queue = GetFleetQueue($union['fleet_id']);
 $acs_flighttime = $head_queue['end'] - time();
 $enum_result = EnumUnionFleets($union_id);
 $acs_fleets = dbrows($enum_result);
 if (!IsPlayerInUnion($GlobalUser['player_id'], $union) || $union == null) {
     FleetError("Вы не приглашены в этот альянс");
 } else {
     if ($target['owner_id'] == $origin['owner_id']) {
         FleetError("Невозможно напасть на собственную планету!");
     } else {
         if (IsPlayerNewbie($target['owner_id']) || IsPlayerStrong($target['owner_id'])) {
             FleetError("Планета находится под защитой для новичков!");
         } else {
             if ($flighttime > $acs_flighttime * 1.3) {
                 FleetError("Вы слишком медленны, чтобы присоединиться к этому флоту");
             } else {
                 if ($BlockAttack) {
                     FleetError("Запрет на атаки");
function StartBattle($fleet_id, $planet_id, $when)
{
    global $db_prefix;
    global $GlobalUni;
    $fleetmap = array(202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215);
    $defmap = array(401, 402, 403, 404, 405, 406, 407, 408);
    $a_result = array(0 => "combatreport_ididattack_iwon", 1 => "combatreport_ididattack_ilost", 2 => "combatreport_ididattack_draw");
    $d_result = array(1 => "combatreport_igotattacked_iwon", 0 => "combatreport_igotattacked_ilost", 2 => "combatreport_igotattacked_draw");
    global $db_host, $db_user, $db_pass, $db_name, $db_prefix;
    $a = array();
    $d = array();
    $unitab = LoadUniverse();
    $fid = $unitab['fid'];
    $did = $unitab['did'];
    $rf = $unitab['rapid'];
    $f = LoadFleet($fleet_id);
    // *** Сгенерировать исходные данные
    // Список атакующих
    $anum = 0;
    if ($f['union_id'] == 0) {
        $a[0] = LoadUser($f['owner_id']);
        $a[0]['fleet'] = array();
        foreach ($fleetmap as $i => $gid) {
            $a[0]['fleet'][$gid] = abs($f["ship{$gid}"]);
        }
        $start_planet = GetPlanet($f['start_planet']);
        $a[0]['g'] = $start_planet['g'];
        $a[0]['s'] = $start_planet['s'];
        $a[0]['p'] = $start_planet['p'];
        $a[0]['id'] = $fleet_id;
        $a[0]['points'] = $a[0]['fpoints'] = 0;
        $anum++;
    } else {
        $result = EnumUnionFleets($f['union_id']);
        $rows = dbrows($result);
        while ($rows--) {
            $fleet_obj = dbarray($result);
            $a[$anum] = LoadUser($fleet_obj['owner_id']);
            $a[$anum]['fleet'] = array();
            foreach ($fleetmap as $i => $gid) {
                $a[$anum]['fleet'][$gid] = abs($fleet_obj["ship{$gid}"]);
            }
            $start_planet = GetPlanet($fleet_obj['start_planet']);
            $a[$anum]['g'] = $start_planet['g'];
            $a[$anum]['s'] = $start_planet['s'];
            $a[$anum]['p'] = $start_planet['p'];
            $a[$anum]['id'] = $fleet_obj['fleet_id'];
            $a[$anum]['points'] = $a[$anum]['fpoints'] = 0;
            $anum++;
        }
    }
    // Список обороняющихся
    $dnum = 0;
    $p = GetPlanet($planet_id);
    $d[0] = LoadUser($p['owner_id']);
    $d[0]['fleet'] = array();
    $d[0]['defense'] = array();
    foreach ($fleetmap as $i => $gid) {
        $d[0]['fleet'][$gid] = abs($p["f{$gid}"]);
    }
    foreach ($defmap as $i => $gid) {
        $d[0]['defense'][$gid] = abs($p["d{$gid}"]);
    }
    $d[0]['g'] = $p['g'];
    $d[0]['s'] = $p['s'];
    $d[0]['p'] = $p['p'];
    $d[0]['id'] = $planet_id;
    $d[0]['points'] = $d[0]['fpoints'] = 0;
    $dnum++;
    // Флоты на удержании
    $result = GetHoldingFleets($planet_id);
    $rows = dbrows($result);
    while ($rows--) {
        $fleet_obj = dbarray($result);
        $d[$dnum] = LoadUser($fleet_obj['owner_id']);
        $d[$dnum]['fleet'] = array();
        $d[$dnum]['defense'] = array();
        foreach ($fleetmap as $i => $gid) {
            $d[$dnum]['fleet'][$gid] = abs($fleet_obj["ship{$gid}"]);
        }
        foreach ($defmap as $i => $gid) {
            $d[$dnum]['defense'][$gid] = 0;
        }
        $start_planet = GetPlanet($fleet_obj['start_planet']);
        $d[$dnum]['g'] = $start_planet['g'];
        $d[$dnum]['s'] = $start_planet['s'];
        $d[$dnum]['p'] = $start_planet['p'];
        $d[$dnum]['id'] = $fleet_obj['fleet_id'];
        $d[$dnum]['points'] = $d[$dnum]['fpoints'] = 0;
        $dnum++;
    }
    $source .= "Rapidfire = {$rf}\n";
    $source .= "FID = {$fid}\n";
    $source .= "DID = {$did}\n";
    $source .= "Attackers = " . $anum . "\n";
    $source .= "Defenders = " . $dnum . "\n";
    foreach ($a as $num => $attacker) {
        $source .= "Attacker" . $num . " = (<" . $attacker['oname'] . "> ";
        $source .= $attacker['id'] . " ";
        $source .= $attacker['g'] . " " . $attacker['s'] . " " . $attacker['p'] . " ";
        $source .= $attacker['r109'] . " " . $attacker['r110'] . " " . $attacker['r111'] . " ";
        foreach ($fleetmap as $i => $gid) {
            $source .= $attacker['fleet'][$gid] . " ";
        }
        $source .= ")\n";
    }
    foreach ($d as $num => $defender) {
        $source .= "Defender" . $num . " = (<" . $defender['oname'] . "> ";
        $source .= $defender['id'] . " ";
        $source .= $defender['g'] . " " . $defender['s'] . " " . $defender['p'] . " ";
        $source .= $defender['r109'] . " " . $defender['r110'] . " " . $defender['r111'] . " ";
        foreach ($fleetmap as $i => $gid) {
            $source .= $defender['fleet'][$gid] . " ";
        }
        foreach ($defmap as $i => $gid) {
            $source .= $defender['defense'][$gid] . " ";
        }
        $source .= ")\n";
    }
    $battle = array(null, $source, "", "", $when);
    $battle_id = AddDBRow($battle, "battledata");
    $bf = fopen("battledata/battle_" . $battle_id . ".txt", "w");
    fwrite($bf, $source);
    fclose($bf);
    // *** Передать данные боевому движку
    $arg = "\"battle_id={$battle_id}\"";
    system($unitab['battle_engine'] . " {$arg}");
    // *** Обработать выходные данные
    $battleres = file_get_contents("battleresult/battle_" . $battle_id . ".txt");
    $res = unserialize($battleres);
    // Определить исход битвы.
    if ($res['result'] === "awon") {
        $battle_result = 0;
    } else {
        if ($res['result'] === "dwon") {
            $battle_result = 1;
        } else {
            $battle_result = 2;
        }
    }
    // Восстановить оборону
    $repaired = RepairDefense($d, $res, $unitab['defrepair'], $unitab['defrepair_delta']);
    // Рассчитать общие потери (учитывать дейтерий и восстановленную оборону)
    $aloss = $dloss = 0;
    $loss = CalcLosses($a, $d, $res, $repaired);
    $a = $loss['a'];
    $d = $loss['d'];
    $aloss = $loss['aloss'];
    $dloss = $loss['dloss'];
    // Захватить ресурсы
    $cm = $ck = $cd = 0;
    if ($battle_result == 0) {
        $sum_cargo = CargoSummaryLastRound($a, $res);
        $captured = Plunder($sum_cargo, $p['m'], $p['k'], $p['d']);
        $cm = $captured['cm'];
        $ck = $captured['ck'];
        $cd = $captured['cd'];
    }
    // Создать поле обломков.
    $debris_id = CreateDebris($p['g'], $p['s'], $p['p'], $p['owner_id']);
    AddDebris($debris_id, $res['dm'], $res['dk']);
    // Создать луну
    $mooncreated = false;
    $moonchance = min(floor(($res['dm'] + $res['dk']) / 100000), 20);
    if (PlanetHasMoon($planet_id) || $p['type'] == 0 || $p['type'] == 10003) {
        $moonchance = 0;
    }
    if (mt_rand(1, 100) <= $moonchance) {
        CreatePlanet($p['g'], $p['s'], $p['p'], $p['owner_id'], 0, 1, $moonchance);
        $mooncreated = true;
    }
    // Обновить активность на планете.
    $queue = GetFleetQueue($fleet_id);
    UpdatePlanetActivity($planet_id, $queue['end']);
    // Сгенерировать боевой доклад.
    loca_add("battlereport", $GlobalUni['lang']);
    loca_add("technames", $GlobalUni['lang']);
    $text = BattleReport($res, $when, $aloss, $dloss, $cm, $ck, $cd, $moonchance, $mooncreated, $repaired);
    // Разослать сообщения
    $mailbox = array();
    foreach ($d as $i => $user) {
        if ($mailbox[$user['player_id']] == true) {
            continue;
        }
        $bericht = SendMessage($user['player_id'], "Командование флотом", "Боевой доклад", $text, 6, $when);
        MarkMessage($user['player_id'], $bericht);
        $subj = "<a href=\"#\" onclick=\"fenster(\\'index.php?page=bericht&session={PUBLIC_SESSION}&bericht={$bericht}\\', \\'Bericht_Kampf\\');\" ><span class=\"" . $d_result[$battle_result] . "\">Боевой доклад [" . $p['g'] . ":" . $p['s'] . ":" . $p['p'] . "] (V:" . nicenum($dloss) . ",A:" . nicenum($aloss) . ")</span></a>";
        SendMessage($user['player_id'], "Командование флотом", $subj, "", 2, $when);
        $mailbox[$user['player_id']] = true;
    }
    // Обновить лог боевого доклада
    $subj = "<a href=\"#\" onclick=\"fenster(\\'index.php?page=admin&session={PUBLIC_SESSION}&mode=BattleReport&bericht={$battle_id}\\', \\'Bericht_Kampf\\');\" ><span class=\"" . $a_result[$battle_result] . "\">Боевой доклад [" . $p['g'] . ":" . $p['s'] . ":" . $p['p'] . "] (V:" . nicenum($dloss) . ",A:" . nicenum($aloss) . ")</span></a>";
    $query = "UPDATE " . $db_prefix . "battledata SET title = '" . $subj . "', report = '" . $text . "' WHERE battle_id = {$battle_id};";
    dbquery($query);
    // Если флот уничтожен за 1 или 2 раунда - не показывать лог боя для атакующих.
    if (count($res['rounds']) <= 2 && $battle_result == 1) {
        $text = "Контакт с флотом потерян. <br> Это означает, что его уничтожили первым же залпом <!--A:{$aloss},W:{$dloss}-->";
    }
    foreach ($a as $i => $user) {
        if ($mailbox[$user['player_id']] == true) {
            continue;
        }
        $bericht = SendMessage($user['player_id'], "Командование флотом", "Боевой доклад", $text, 6, $when);
        MarkMessage($user['player_id'], $bericht);
        $subj = "<a href=\"#\" onclick=\"fenster(\\'index.php?page=bericht&session={PUBLIC_SESSION}&bericht={$bericht}\\', \\'Bericht_Kampf\\');\" ><span class=\"" . $a_result[$battle_result] . "\">Боевой доклад [" . $p['g'] . ":" . $p['s'] . ":" . $p['p'] . "] (V:" . nicenum($dloss) . ",A:" . nicenum($aloss) . ")</span></a>";
        SendMessage($user['player_id'], "Командование флотом", $subj, "", 2, $when);
        $mailbox[$user['player_id']] = true;
    }
    // Почистить старые боевые доклады
    $ago = $when - 2 * 7 * 24 * 60 * 60;
    $query = "DELETE FROM " . $db_prefix . "battledata WHERE date < {$ago};";
    dbquery($query);
    // Модифицировать флоты и планету в соответствии с потерями и захваченными ресурсами
    WritebackBattleResults($a, $d, $res, $repaired, $cm, $ck, $cd, $sum_cargo);
    // Изменить статистику игроков
    foreach ($a as $i => $user) {
        AdjustStats($user['player_id'], $user['points'], $user['fpoints'], 0, '-');
    }
    foreach ($d as $i => $user) {
        AdjustStats($user['player_id'], $user['points'], $user['fpoints'], 0, '-');
    }
    RecalcRanks();
    // Чистим промежуточные данные боевого движка
    unlink("battledata/battle_" . $battle_id . ".txt");
    unlink("battleresult/battle_" . $battle_id . ".txt");
    return $battle_result;
}