function _action_main()
 {
     if ($this->n_fleets > 1) {
         $this->deactivate(35);
         $this->report('Auctioned move ' . $this->move['move_id'] . ' has ' . $this->n_fleets . ' fleets');
         return MV_EXEC_ERROR;
     }
     $sql = 'SELECT s.ship_id,
                    st.name, st.ship_torso, st.race
             FROM (ships s)
             INNER JOIN ship_templates st ON st.id = s.template_id
             WHERE fleet_id IN (' . $this->fleet_ids_str . ')';
     if (($q_aship = $this->db->query($sql)) === false) {
         return $this->log(MV_M_DATABASE, 'Could not query ships data! SKIP');
     }
     $n_aships = $this->db->num_rows($q_aship);
     if ($n_aships != 1) {
         $this->deactivate(35);
         $this->report('Auctioned move ' . $this->move['move_id'] . ' has ' . $n_aships . ' ships');
         return MV_EXEC_ERROR;
     }
     $aship = $this->db->fetchrow($q_aship);
     $sql = 'UPDATE ships
             SET fleet_id = -' . $this->move['dest'] . ',
                 user_id = ' . $this->dest['user_id'] . ',
                 ship_untouchable = 0
             WHERE fleet_id IN (' . $this->fleet_ids_str . ')';
     if (!$this->db->query($sql)) {
         return $this->log(MV_M_DATABASE, 'Could not update ships user data! SKIP');
     }
     $sql = 'DELETE FROM ship_fleets
             WHERE fleet_id IN (' . $this->fleet_ids_str . ')';
     if (!$this->db->query($sql)) {
         return $this->log(MV_M_DATABASE, 'Could not delete fleets data! SKIP');
     }
     $log_data = array(33, $this->move['user_id'], $this->move['start'], $this->start['planet_name'], $this->start['user_id'], $this->move['dest'], $this->dest['planet_name'], $this->dest['user_id'], $aship['ship_id'], $aship['name'], $aship['ship_torso'], $aship['race']);
     // #############################################################################
     // 01/04/08 - AC: Retrieve player language
     switch ($this->dest['language']) {
         case 'GER':
             $log_title = 'Ersteigertes Schiff von ' . $this->move['user_name'] . ' angekommen';
             break;
         case 'ITA':
             $log_title = 'Ersteigertes nave di ' . $this->move['user_name'] . ' arrivata';
             break;
         default:
             $log_title = 'Ersteigertes ship of ' . $this->move['user_name'] . ' arrived';
             break;
     }
     add_logbook_entry($this->dest['user_id'], LOGBOOK_TACTICAL, $log_title, $log_data);
     return MV_EXEC_OK;
 }
 function _action_main()
 {
     // #############################################################################
     // Data from the attacker
     $sql = 'SELECT ' . $this->get_combat_query_fleet_columns() . ', f.resource_4, f.unit_1, f.unit_2, f.unit_3, f.unit_4
     FROM (ship_fleets f)
     INNER JOIN user u ON u.user_id = f.user_id
     WHERE f.fleet_id IN (' . $this->fleet_ids_str . ')';
     if (($atk_fleets = $this->db->queryrowset($sql)) === false) {
         return $this->log(MV_M_DATABASE, 'Could not query attackers fleets data! SKIP');
     }
     /* 01/07/08 -AC: I need to move this query here, in order to correctly report attacker
      *               losses in case he lost the battle.
      */
     $sql = 'SELECT ss.fleet_id,
            SUM(ss.unit_1 - st.min_unit_1) AS troop_1,
            SUM(ss.unit_2 - st.min_unit_2) AS troop_2,
            SUM(ss.unit_3 - st.min_unit_3) AS troop_3,
            SUM(ss.unit_4 - st.min_unit_4) AS troop_4
     FROM ships ss, ship_templates st
     WHERE ss.template_id = st.id
     AND ss.fleet_id IN (' . $this->fleet_ids_str . ')
     GROUP BY ss.fleet_id';
     if (($atk_crews = $this->db->queryrowset($sql)) === false) {
         return $this->log(MV_M_DATABASE, 'Could not query attacking fleet data! SKIP');
     }
     // #############################################################################
     // Data from the defender
     $user_id = $this->dest['user_id'];
     $planetary_attack = true;
     // The course could be optimized, but it should be possible
     // compatibility to provide much action_51.php maintained
     $cur_user = array('user_id' => $user_id, 'user_name' => $this->dest['user_name'], 'user_race' => $this->dest['user_race'], 'user_planets' => $this->dest['user_planets'], 'user_alliance' => $this->dest['user_alliance']);
     $sql = 'SELECT DISTINCT f.user_id,
            u.user_alliance,
            ud.ud_id, ud.accepted,
            ad.ad_id, ad.type, ad.status
     FROM (ship_fleets f)
     INNER JOIN user u ON u.user_id = f.user_id
     LEFT JOIN user_diplomacy ud ON ( ( ud.user1_id = ' . $user_id . ' AND ud.user2_id = f.user_id ) OR ( ud.user1_id = f.user_id AND ud.user2_id = ' . $user_id . ' ) )
     LEFT JOIN alliance_diplomacy ad ON ( ( ad.alliance1_id = ' . $cur_user['user_alliance'] . ' AND ad.alliance2_id = u.user_alliance) OR ( ad.alliance1_id = u.user_alliance AND ad.alliance2_id = ' . $cur_user['user_alliance'] . ' ) )
     WHERE f.planet_id = ' . $this->move['dest'] . ' AND
           f.user_id <> ' . $user_id . ' AND
           f.user_id <> ' . $this->move['user_id'] . ' AND
           f.alert_phase >= ' . ALERT_PHASE_YELLOW;
     if (!($q_st_uid = $this->db->query($sql))) {
         return $this->log(MV_M_DATABASE, 'Could not query stationated fleets user data! SKIP');
     }
     $st_user = array();
     while ($st_uid = $this->db->fetchrow($q_st_uid)) {
         $allied = false;
         if ($st_uid['user_alliance'] == $this->dest['user_alliance']) {
             $allied = true;
         }
         if (!empty($st_uid['ud_id'])) {
             if ($st_uid['accepted'] == 1) {
                 $allied = true;
             }
         }
         if (!empty($st_uid['ad_id'])) {
             if ($st_uid['type'] == ALLIANCE_DIPLOMACY_PACT && $st_uid['status'] == 0) {
                 $allied = true;
             }
         }
         if ($allied) {
             $st_user[] = $st_uid['user_id'];
         }
     }
     $n_st_user = count($st_user);
     if ($n_st_user > 0) {
         $sql = 'SELECT ' . $this->get_combat_query_fleet_columns() . '
          FROM (ship_fleets f)
          INNER JOIN user u ON u.user_id = f.user_id
          WHERE f.planet_id = ' . $this->move['dest'] . ' AND
                (
                  (
                    f.user_id = ' . $user_id . '
                  )
                  OR
                  (
                    f.user_id IN (' . implode(',', $st_user) . ') AND
                    f.alert_phase >= ' . ALERT_PHASE_YELLOW . '
                  )
                )';
     } else {
         $sql = 'SELECT ' . $this->get_combat_query_fleet_columns() . '
          FROM (ship_fleets f)
          INNER JOIN user u ON u.user_id = f.user_id
          WHERE f.planet_id = ' . $this->move['dest'] . ' AND
                f.user_id = ' . $user_id;
     }
     if (($dfd_fleets = $this->db->queryrowset($sql)) === false) {
         return $this->log(MV_M_DATABASE, 'Could not query defenders fleets data! SKIP');
     }
     $dfd_fleet_ids = array();
     foreach ($dfd_fleets as $i => $cur_fleet) {
         $dfd_fleet_ids[] = $cur_fleet['fleet_id'];
     }
     $dfd_fleet_ids_str = implode(',', $dfd_fleet_ids);
     if ($this->do_ship_combat($this->fleet_ids_str, $dfd_fleet_ids_str, MV_COMBAT_LEVEL_PLANETARY) == MV_EXEC_ERROR) {
         $this->log(MV_M_DATABASE, 'Move Action 55: Something went wrong with this fight!');
         return MV_EXEC_ERROR;
     }
     // #############################################################################
     // If the attacker has won attempt to start takeover
     // #############################################################################
     // 03/04/08 - AC: Retrieve player language
     switch ($this->dest['language']) {
         case 'GER':
             $dfd_title = 'Angriff auf ' . $this->dest['planet_name'];
             break;
         case 'ITA':
             $dfd_title = 'Attacco su ' . $this->dest['planet_name'];
             break;
         default:
             $dfd_title = 'Attack on ' . $this->dest['planet_name'];
             break;
     }
     $action_status = 0;
     /* 11/07/08 - AC: Initialize here arrays atk/dfd_losses */
     $atk_losses = array(0, 0, 0, 0, 0);
     $dfd_losses = array(0, 0, 0, 0, 0);
     if ($this->cmb[MV_CMB_WINNER] == MV_CMB_ATTACKER) {
         if (empty($this->action_data[0])) {
             return $this->log('Moves', 'action_55: Could not find required action_data entry [0]! SKIP');
         }
         $ship_id = (int) $this->action_data[0];
         // We make it quite safe here, to see whether the
         // ship is
         $sql = 'SELECT s.ship_id, s.user_id, s.unit_1, s.unit_2, s.unit_3, s.unit_4,
                st.ship_torso, st.race, st.min_unit_1, st.min_unit_2, st.min_unit_3, st.min_unit_4,
                f.fleet_id, f.move_id, f.n_ships
         FROM (ships s)
         INNER JOIN ship_templates st ON st.id = s.template_id
         INNER JOIN ship_fleets f ON f.fleet_id = s.fleet_id
         WHERE s.ship_id = ' . $ship_id;
         if (($cship = $this->db->queryrow($sql)) === false) {
             return $this->log(MV_M_DATABASE, 'Could not query cship data! SKIP');
         }
         $cship_exists = true;
         if (empty($cship['ship_id'])) {
             $cship_exists = false;
         } elseif ($cship['user_id'] != $this->move['user_id']) {
             $cship_exists = false;
         } elseif ($cship['ship_torso'] != SHIP_TYPE_COLO) {
             $cship_exists = false;
         } elseif ($cship['move_id'] != $this->mid) {
             $cship_exists = false;
         }
         if ($cship_exists) {
             $atk_units = array($cship['unit_1'] - $cship['min_unit_1'], $cship['unit_2'] - $cship['min_unit_2'], $cship['unit_3'] - $cship['min_unit_3'], $cship['unit_4'] - $cship['min_unit_4'], 0);
             // 20/06/08 - AC: Keep out workers from battle!
             for ($i = 0; $i < count($atk_fleets); ++$i) {
                 $atk_units[0] += $atk_fleets[$i]['unit_1'];
                 $atk_units[1] += $atk_fleets[$i]['unit_2'];
                 $atk_units[2] += $atk_fleets[$i]['unit_3'];
                 $atk_units[3] += $atk_fleets[$i]['unit_4'];
                 //$atk_units[4] += $atk_fleets[$i]['resource_4']; <-- What the hell is this field?? No workers in the battle!
                 // 23/06/08 - AC: Store the space occupied by workers
                 $worker_per_fleets[$atk_fleets[$i]['fleet_id']] = $atk_fleets[$i]['resource_4'];
             }
             // 090408 DC:  ------ Let those f*****g soldiers on ships do their job!!!!
             for ($i = 0; $i < count($atk_crews); ++$i) {
                 $atk_units[0] += $atk_crews[$i]['troop_1'];
                 $atk_units[1] += $atk_crews[$i]['troop_2'];
                 $atk_units[2] += $atk_crews[$i]['troop_3'];
                 $atk_units[3] += $atk_crews[$i]['troop_4'];
             }
             // 090409 DC:  ------
             $dfd_units = array($this->dest['unit_1'], $this->dest['unit_2'], $this->dest['unit_3'], $this->dest['unit_4'], $this->dest['resource_4']);
             // Are there some defenders?
             if (array_sum($dfd_units) > 0) {
                 $ucmb = UnitFight($atk_units, $this->move['user_race'], $dfd_units, $this->dest['user_race'], $this->mid);
                 $n_atk_alive = array_sum($ucmb[0]);
                 $atk_alive = $ucmb[0];
                 $dfd_alive = $ucmb[1];
             } else {
                 $n_atk_alive = 1;
                 $atk_alive = $atk_units;
                 $dfd_alive = array(0, 0, 0, 0, 0);
             }
             // 01/07/08 - AC: Count losses for each part
             for ($i = 0; $i < 5; ++$i) {
                 $atk_losses[$i] = $atk_units[$i] - $atk_alive[$i];
                 $dfd_losses[$i] = $dfd_units[$i] - $dfd_alive[$i];
             }
             // If there are no more attackers, the defender
             // always won even if the defending had no units
             if ($n_atk_alive == 0) {
                 // In order to eliminate the troops of the aggressor, simply reset all transporters
                 // 21/06/08 - AC: Keep out workers from battle!
                 $sql = 'UPDATE ship_fleets
                 SET unit_1 = 0,
                     unit_2 = 0,
                     unit_3 = 0,
                     unit_4 = 0
                 WHERE fleet_id IN (' . $this->fleet_ids_str . ')';
                 if (!$this->db->query($sql)) {
                     return $this->log(MV_M_DATABASE, 'Could not update ship fleets unit transport data! SKIP');
                 }
                 // Simply update the defender troops
                 $sql = 'UPDATE planets
                 SET unit_1 = ' . $ucmb[1][0] . ',
                     unit_2 = ' . $ucmb[1][1] . ',
                     unit_3 = ' . $ucmb[1][2] . ',
                     unit_4 = ' . $ucmb[1][3] . ',
                     resource_4 = ' . $ucmb[1][4] . '
                 WHERE planet_id = ' . $this->move['dest'];
                 if (!$this->db->query($sql)) {
                     return $this->log(MV_M_DATABASE, 'Could not update dest planet units data! SKIP');
                 }
                 // 090408 DC:  ------ Finally the f*****g soldiers have done their job!!!!
                 $this->log(MV_M_NOTICE, 'Update ships with the minimum troops value');
                 $sql = 'UPDATE ships ss, ship_templates st
                 SET ss.unit_1 = st.min_unit_1,
                     ss.unit_2 = st.min_unit_2,
                     ss.unit_3 = st.min_unit_3,
                     ss.unit_4 = st.min_unit_4
                 WHERE ss.template_id = st.id
             AND ss.fleet_id IN (' . $this->fleet_ids_str . ')';
                 if (!$this->db->query($sql)) {
                     return $this->log(MV_M_DATABASE, 'Could not update attacking ships! SKIP');
                 }
                 // 090408 DC:  ------
                 $action_status = -1;
                 // #############################################################################
                 // 03/04/08 - AC: Retrieve player language
                 switch ($this->move['language']) {
                     case 'GER':
                         $atk_title = 'Angriff auf ' . $this->dest['planet_name'] . ' teilweise erfolgreich';
                         break;
                     case 'ITA':
                         $atk_title = 'Attacco su ' . $this->dest['planet_name'] . ' parzialmente riuscito';
                         break;
                     default:
                         $atk_title = 'Attack on ' . $this->dest['planet_name'] . ' partially successful';
                         break;
                 }
             } else {
                 account_log($this->move['user_id'], $this->dest['user_id'], 4);
                 // Export a ruler switch
                 // We need the number of planets, which owns the colonizing
                 // (we want planet_owner_enum degree of certainty)
                 $sql = 'SELECT COUNT(planet_id) AS n_planets
                 FROM planets
                 WHERE planet_owner = ' . $this->move['user_id'];
                 if (($pcount = $this->db->queryrow($sql)) === false) {
                     $this->log(MV_M_DATABASE, 'Could not query planets count data! CONTINUE AND USE INSTABLE VALUE');
                     $n_planets = $this->move['user_planets'];
                 } else {
                     $n_planets = $pcount['n_planets'];
                 }
                 // We accommodate as much troops, as on the colony ship were, on the planet
                 $planet_units = array(0, 0, 0, 0);
                 // 21/06/08 - AC: Check available space on target planet
                 $sql = 'SELECT max_units FROM planets WHERE planet_id = ' . $this->move['dest'];
                 if (($plspace = $this->db->queryrow($sql)) === false) {
                     $this->log(MV_M_DATABASE, 'Could not query planet max units data! CONTINUE AND USE INSTABLE VALUE');
                     $plspace['max_units'] = 1300;
                     // Minimum size available
                 }
                 if ($atk_alive[0] * 2 + $atk_alive[1] * 3 + $atk_alive[2] * 4 + $atk_alive[3] * 4 > $plspace['max_units']) {
                     $this->log(MV_M_NOTICE, 'Alive units exceed planet maximum units, we need to recall aboard the surplus');
                     // AC: Recall aboard the surplus troops
                     $i = 0;
                     while ($n_atk_alive) {
                         if ($planet_units[0] * 2 + $planet_units[1] * 3 + $planet_units[2] * 4 + $planet_units[3] * 4 >= $plspace['max_units']) {
                             break;
                         }
                         if ($atk_alive[$i] > 0) {
                             $planet_units[$i]++;
                             $atk_alive[$i]--;
                             $n_atk_alive--;
                         } else {
                             $i++;
                         }
                     }
                     $this->log(MV_M_NOTICE, 'Troops that will return aboard: Lev1 ' . $atk_alive[0] . ' Lev2 ' . $atk_alive[1] . ' Lev3 ' . $atk_alive[2] . ' Lev4 ' . $atk_alive[3]);
                     // We pick ALL transporter of the fleets and then distribute
                     $sql = 'SELECT s.ship_id, s.fleet_id
                     FROM (ships s)
                     INNER JOIN (ship_templates st) ON s.template_id = st.id
                     WHERE s.fleet_id IN (' . $this->fleet_ids_str . ') AND
                           st.ship_torso = ' . SHIP_TYPE_TRANSPORTER;
                     if (!($q_ftrans = $this->db->query($sql))) {
                         $this->log(MV_M_DATABASE, 'Could not query fleets transporter data! CONTINUE');
                     }
                     // 27/10/08 - AC: First of all, loads all available transports
                     $space_per_fleets = array();
                     while ($_ship = $this->db->fetchrow($q_ftrans)) {
                         if (!isset($space_per_fleets[$_ship['fleet_id']])) {
                             $space_per_fleets[$_ship['fleet_id']] = $worker_per_fleets[$_ship['fleet_id']] * -1;
                         }
                         $space_per_fleets[$_ship['fleet_id']] += MAX_TRANSPORT_UNITS;
                     }
                     foreach ($space_per_fleets as $fleet_id => $free_space) {
                         if ($free_space == 0) {
                             continue;
                         }
                         $still_free = $free_space;
                         $new_load = array(0, 0, 0, 0);
                         for ($i = 0; $i < 4; ++$i) {
                             if ($atk_alive[$i] > 0) {
                                 $new_load[$i] = $atk_alive[$i] > $still_free ? $still_free : $atk_alive[$i];
                                 $atk_alive[$i] -= $new_load[$i];
                                 $still_free -= $new_load[$i];
                             }
                             if ($still_free == 0) {
                                 break;
                             }
                         }
                         $sql = 'UPDATE ship_fleets
                         SET unit_1 = ' . $new_load[0] . ',
                             unit_2 = ' . $new_load[1] . ',
                             unit_3 = ' . $new_load[2] . ',
                             unit_4 = ' . $new_load[3] . '
                         WHERE fleet_id = ' . $fleet_id;
                         if (!$this->db->query($sql)) {
                             $this->log(MV_M_DATABASE, 'Could not update fleets units data! CONTINUE');
                         }
                     }
                     // 27/10/08- AC: If there are still some extra troops on ground
                     $n_atk_still_to_board = array_sum($atk_alive);
                     if ($n_atk_still_to_board > 0) {
                         $this->log(MV_M_NOTICE, 'There are still: Lev1 ' . $atk_alive[0] . ' Lev2 ' . $atk_alive[1] . ' Lev3 ' . $atk_alive[2] . ' Lev4 ' . $atk_alive[3] . ' troops to embark!');
                         // Extra troops didn't really leave the ships so we have to remove the losses
                         $sql = 'SELECT ss.ship_id,
                                st.min_unit_1, st.max_unit_1,
                                st.min_unit_2, st.max_unit_2,
                                st.min_unit_3, st.max_unit_3,
                                st.min_unit_4, st.max_unit_4
                          FROM ships ss, ship_templates st
                          WHERE ss.template_id = st.id AND
                                ss.fleet_id IN (' . $this->fleet_ids_str . ')';
                         if (!($q_ships = $this->db->query($sql))) {
                             $this->log(MV_M_DATABASE, 'Could not query fleets ships data! CONTINUE');
                         }
                         // Distribute troops on available ships
                         while ($ship = $this->db->fetchrow($q_ships)) {
                             $new_crew = array(0, 0, 0, 0);
                             // For each type of troops
                             for ($i = 0; $i < 4; ++$i) {
                                 $j = $i + 1;
                                 // Are there still some troops?
                                 if ($atk_alive[$i] > 0) {
                                     $new_crew[$i] = $atk_alive[$i] > $ship['max_unit_' . $j] ? $ship['max_unit_' . $j] : $atk_alive[$i];
                                     $atk_alive[$i] -= $new_crew[$i];
                                 } else {
                                     $new_crew[$i] = $ship['min_unit_' . $j];
                                 }
                                 $n_atk_still_to_board -= $new_crew[$i];
                             }
                             // Update ship's crew
                             $sql = 'UPDATE ships
                             SET unit_1 = ' . $new_crew[0] . ',
                                 unit_2 = ' . $new_crew[1] . ',
                                 unit_3 = ' . $new_crew[2] . ',
                                 unit_4 = ' . $new_crew[3] . '
                             WHERE ship_id =' . $ship['ship_id'];
                             if (!$this->db->query($sql)) {
                                 $this->log(MV_M_DATABASE, 'Could not update ship crew data! CONTINUE');
                             }
                             // If we have finished boarding phase, we are ready to takeoff ;)
                             if ($n_atk_still_to_board == 0) {
                                 break;
                             }
                         }
                     }
                 } else {
                     for ($i = 0; $i <= 3; ++$i) {
                         $planet_units[$i] += $atk_alive[$i];
                     }
                     // 28/06/08 - AC: Snort! Delete landed troops!
                     $sql = 'UPDATE ship_fleets
                     SET unit_1 = 0,
                         unit_2 = 0,
                         unit_3 = 0,
                         unit_4 = 0
                     WHERE fleet_id IN (' . $this->fleet_ids_str . ')';
                     if (!$this->db->query($sql)) {
                         return $this->log(MV_M_DATABASE, 'Could not update ship fleets unit transport data! SKIP');
                     }
                     // 27/10/08 - AC: Delete also extra troops on ships...
                     $sql = 'UPDATE ships ss, ship_templates st
                     SET ss.unit_1 = st.min_unit_1,
                         ss.unit_2 = st.min_unit_2,
                         ss.unit_3 = st.min_unit_3,
                         ss.unit_4 = st.min_unit_4
                     WHERE ss.template_id = st.id AND
                           ss.fleet_id IN (' . $this->fleet_ids_str . ')';
                     if (!$this->db->query($sql)) {
                         return $this->log(MV_M_DATABASE, 'Could not update attacking ships to minimum crew! SKIP');
                     }
                 }
                 $this->log(MV_M_NOTICE, 'Troops that will remain on the planet: Lev1 ' . $planet_units[0] . ' Lev2 ' . $planet_units[1] . ' Lev3 ' . $planet_units[2] . ' Lev4 ' . $planet_units[3]);
                 $sql = 'DELETE FROM scheduler_instbuild
                 WHERE planet_id = ' . $this->move['dest'];
                 if (!$this->db->query($sql)) {
                     $this->log(MV_M_DATABASE, 'Could not delete scheduler instbuild data! CONTINUE');
                 }
                 $sql = 'DELETE FROM scheduler_research
                 WHERE planet_id = ' . $this->move['dest'];
                 if (!$this->db->query($sql)) {
                     $this->log(MV_M_DATABASE, 'Could not delete scheduler research data! CONTINUE');
                 }
                 $sql = 'DELETE FROM scheduler_resourcetrade
                 WHERE planet = ' . $this->move['dest'];
                 if (!$this->db->query($sql)) {
                     $this->log(MV_M_DATABASE, 'Could not delete resource data! CONTINUE');
                 }
                 $sql = 'DELETE FROM scheduler_shipbuild
                 WHERE planet_id = ' . $this->move['dest'];
                 if (!$this->db->query($sql)) {
                     $this->log(MV_M_DATABASE, 'Could not delete shipbuild data! CONTINUE');
                 }
                 global $NUM_BUILDING, $MAX_BUILDING_LVL;
                 // As someone yes number == max_index sets
                 $n_buildings = $NUM_BUILDING + 1;
                 $building_levels = array();
                 $building_damage = 0.01 * mt_rand(40, 60);
                 // Set new home world
                 if ($this->move['dest'] == $this->dest['user_capital']) {
                     for ($i = 0; $i < $n_buildings; ++$i) {
                         $j = $i + 1;
                         $building_levels[$i] = (int) ($this->dest['building_' . $j] > $MAX_BUILDING_LVL[0][$i]) ? $MAX_BUILDING_LVL[0][$i] : round($this->dest['building_' . $j] * $building_damage, 0);
                     }
                     if ($this->dest['user_planets'] == 1) {
                         // #############################################################################
                         // 03/04/08 - AC: Retrieve player language
                         switch ($this->dest['language']) {
                             case 'GER':
                                 $msg_title = 'Verlust aller deiner Planeten';
                                 $msg_body = 'Da du alle deine Planeten verloren hast, wurde f&uuml;r dich ein neuer Planet an einer zuf&uuml;ligen Stelle der Galaxie erstellt.';
                                 break;
                             case 'ITA':
                                 $msg_title = 'Perdita di tutti i pianeti';
                                 $msg_body = 'Dato che hai perduto tutti i pianeti ne &egrave; stato creato uno nuovo nella galassia.';
                                 break;
                             default:
                                 $msg_title = 'Loss of all your planets';
                                 $msg_body = 'Since you lost all your planets a new one have been created in the body of the galaxy.';
                                 break;
                         }
                         SystemMessage($this->dest['user_id'], $msg_title, $msg_body);
                     } else {
                         if (!$this->db->query('SET @i=0')) {
                             return $this->log(MV_M_DATABASE, 'Could not set sql iterator variable for planet owner enum! SKIP');
                         }
                         $sql = 'UPDATE planets
                         SET planet_owner_enum = (@i := (@i + 1))-1
                         WHERE planet_owner = ' . $this->dest['user_id'] . '
                         ORDER BY planet_owned_date ASC, planet_id ASC';
                         if (!$this->db->query($sql)) {
                             return $this->log(MV_M_DATABASE, 'Could not update planet owner enum data! SKIP');
                         }
                         $sql = 'SELECT planet_id
                         FROM planets
                         WHERE planet_owner = ' . $this->dest['user_id'] . '
                         ORDER BY planet_owner_enum ASC
                         LIMIT 1';
                         if (($first_planet = $this->db->queryrow($sql)) === false) {
                             return $this->log(MV_M_DATABASE, 'Could not query first planet data! SKIP');
                         }
                         $sql = 'UPDATE user
                         SET last_active = ' . time() . ',
                             last_ip = "0.0.0.0",
                             user_capital = ' . $first_planet['planet_id'] . ',
                             pending_capital_choice = 1
                         WHERE user_id = ' . $this->dest['user_id'];
                         if (!$this->db->query($sql)) {
                             return $this->log(MV_M_DATABASE, 'Could not update user capital data! SKIP');
                         }
                     }
                 } else {
                     for ($i = 0; $i < $n_buildings; ++$i) {
                         $building_levels[$i] = round($this->dest['building_' . ($i + 1)] * $building_damage, 0);
                     }
                 }
                 $sql = 'DELETE FROM resource_trade
                 WHERE planet = ' . $this->move['dest'];
                 if (!$this->db->query($sql)) {
                     $this->log(MV_M_DATABASE, 'Could not delete resource trade data! CONTINUE');
                 }
                 $sql = 'SELECT ship_id
                 FROM ship_trade
                 WHERE scheduler_processed = 0 AND
                       planet = ' . $this->move['dest'];
                 if (!($q_shipt = $this->db->query($sql))) {
                     $this->log(MV_M_DATABASE, 'Could not query ship trade data! CONTINUE');
                 } else {
                     $ship_ids = array();
                     while ($_ship = $this->db->fetchrow($q_shipt)) {
                         $ship_ids[] = $_ship['ship_id'];
                     }
                     if (count($ship_ids) > 0) {
                         $sql = 'UPDATE ships
                         SET ship_untouchable = 0
                         WHERE ship_id IN (' . implode(',', $ship_ids) . ')';
                         if (!$this->db->query($sql)) {
                             $this->log(MV_M_DATABASE, 'Could not update ships untouchable data! CONTINUE');
                         }
                     }
                 }
                 $sql = 'DELETE FROM ship_trade
                 WHERE scheduler_processed = 0 AND
                       planet = ' . $this->move['dest'];
                 if (!$this->db->query($sql)) {
                     $this->log(MV_M_DATABASE, 'Could not delete ship trade data! CONTINUE');
                 }
                 $sql = 'UPDATE planets
                 SET planet_owner = ' . $this->move['user_id'] . ',
                     planet_owned_date = ' . time() . ',
                     planet_owner_enum = ' . ($n_planets - 1) . ',
                     best_mood = 0,
                     best_mood_user = 0,
                     planet_available_points = ' . $this->get_structure_points($this->move['user_id'], $this->move['dest']) . ',
                     resource_4 = 0,
                     recompute_static = 1,
                     building_1 = ' . $building_levels[0] . ',
                     building_2 = ' . $building_levels[1] . ',
                     building_3 = ' . $building_levels[2] . ',
                     building_4 = ' . $building_levels[3] . ',
                     building_5 = ' . $building_levels[4] . ',
                     building_6 = ' . $building_levels[5] . ',
                     building_7 = ' . $building_levels[6] . ',
                     building_8 = ' . $building_levels[7] . ',
                     building_9 = ' . $building_levels[8] . ',
                     building_10 = ' . $building_levels[9] . ',
                     building_11 = ' . $building_levels[10] . ',
                     building_12 = ' . $building_levels[11] . ',
                     building_13 = ' . $building_levels[12] . ',
                     unit_1 = ' . $planet_units[0] . ',
                     unit_2 = ' . $planet_units[1] . ',
                     unit_3 = ' . $planet_units[2] . ',
                     unit_4 = ' . $planet_units[3] . ',
                     unit_5 = 0,
                     unit_6 = 0,
                     workermine_1 = 100,
                     workermine_2 = 100,
                     workermine_3 = 100,
                     catresearch_1 = 0,
                     catresearch_2 = 0,
                     catresearch_3 = 0,
                     catresearch_4 = 0,
                     catresearch_5 = 0,
                     catresearch_6 = 0,
                     catresearch_7 = 0,
                     catresearch_8 = 0,
                     catresearch_9 = 0,
                     catresearch_10 = 0,
                     unittrainid_1 = 0,
                     unittrainid_2 = 0,
                     unittrainid_3 = 0,
                     unittrainid_4 = 0,
                     unittrainid_5 = 0,
                     unittrainid_6 = 0,
                     unittrainid_7 = 0,
                     unittrainid_8 = 0,
                     unittrainid_9 = 0,
                     unittrainid_10 = 0,
                     unittrainnumber_1 = 0,
                     unittrainnumber_2 = 0,
                     unittrainnumber_3 = 0,
                     unittrainnumber_4 = 0,
                     unittrainnumber_5 = 0,
                     unittrainnumber_6 = 0,
                     unittrainnumber_7 = 0,
                     unittrainnumber_8 = 0,
                     unittrainnumber_9 = 0,
                     unittrainnumber_10 = 0,
                     unittrainnumberleft_1 = 0,
                     unittrainnumberleft_2 = 0,
                     unittrainnumberleft_3 = 0,
                     unittrainnumberleft_4 = 0,
                     unittrainnumberleft_5 = 0,
                     unittrainnumberleft_6 = 0,
                     unittrainnumberleft_7 = 0,
                     unittrainnumberleft_8 = 0,
                     unittrainnumberleft_9 = 0,
                     unittrainnumberleft_10 = 0,
                     unittrain_actual = 0,
                     unittrainid_nexttime=0,
                     planet_insurrection_time=0,
                     planet_surrender=0
                 WHERE planet_id = ' . $this->move['dest'];
                 //$this->log('SQL Debug', ''.$sql.'');
                 if (!$this->db->query($sql)) {
                     return $this->log(MV_M_DATABASE, 'Could not update planets data! SKIP');
                 }
                 // DC ---- History record in planet_details, with label '26'
                 $sql = 'INSERT INTO planet_details (planet_id, user_id, alliance_id, source_uid, source_aid, timestamp, log_code, defeat_uid, defeat_aid)
                 VALUES (' . $this->move['dest'] . ', ' . $this->move['user_id'] . ', ' . $this->move['user_alliance'] . ', ' . $this->move['user_id'] . ', ' . $this->move['user_alliance'] . ', ' . time() . ', 26,' . $this->dest['user_id'] . ', ' . $this->dest['user_alliance'] . ')';
                 if (!$this->db->query($sql)) {
                     $this->log(MV_M_DATABASE, 'Could not update planet details data! CONTINUE');
                 }
                 // If the attack was on a settlers planet, we get rid of the moods data!
                 if ($this->dest['user_id'] == INDEPENDENT_USERID) {
                     $this->log(MV_M_NOTICE, 'Colony: Settlers taken over!!! They gonna be no more...');
                     $sql = 'SELECT user_id, user_name, language FROM settlers_relations
                                                         INNER JOIN user USING user_id
                     WHERE planet_id = ' . $this->move['dest'] . ' AND user_id NOT = ' . $this->move['user_id'] . '
                     GROUP BY user_id';
                     if ($res = $this->db->queryrowset($sql)) {
                         foreach ($res as $res_item) {
                             $log_data = array($this->move['dest'], $this->dest['planet_name'], 0, '', 105, $res_item['user_name']);
                             switch ($res_item['language']) {
                                 case 'GER':
                                     $log_title = 'Automatic distress message from ';
                                     break;
                                 case 'ITA':
                                     $log_title = 'Richiesta automatica di soccorso dalla colonia ';
                                     break;
                                 default:
                                     $log_title = 'Automatic distress message from ';
                                     break;
                             }
                             add_logbook_entry($res_item['user_id'], LOGBOOK_SETTLERS, $log_title . $this->dest['planet_name'], $log_data);
                         }
                     }
                     $sql = 'DELETE FROM settlers_relations WHERE planet_id = ' . $this->dest['planet_id'];
                     if (!$this->db->query($sql)) {
                         $this->log(MV_M_DATABASE, 'Could not delete settlers moods! CONTINUE!');
                     }
                     $sql = 'SELECT planet_id FROM settlers_relations WHERE user_id = ' . $this->move['user_id'] . ' GROUP BY planet_id';
                     if ($res = $this->db->queryrowset($sql)) {
                         foreach ($res as $res_item) {
                             // Clear all + logs on the planet
                             $sql = 'DELETE FROM settlers_relations
                             WHERE user_id = ' . $this->move['user_id'] . '
                             AND planet_id = ' . $res_item['planet_id'] . '
                             AND log_code IN ("2", "3", "4")';
                             if (!$this->db->query($sql)) {
                                 $this->log(MV_M_DATABASE, 'Could not delete settlers relations data! ' . $sql . ' CONTINUE');
                             }
                             $sql = 'INSERT INTO settlers_relations SET planet_id = ' . $res_item['planet_id'] . ',
                                                                user_id = ' . $this->move['user_id'] . ',
                                                                timestamp = ' . time() . ', log_code = 12,
                                                                mood_modifier = -50';
                             $this->db->query($sql);
                             $this->check_best_mood($res_item['planet_id'], false);
                         }
                     }
                 }
                 // DC ----
                 $this->log('Update Planetdata', 'Limited resources');
                 //Concept of vessels destroyed by hostile takeover.
                 //Version 0.2b by Mojo1987 - Calculation adjusted
                 $this->log('Ship destruction', 'Begin ships deletion');
                 $sql = 'SELECT s.ship_id FROM (ships s) WHERE s.fleet_id = -' . $this->move['dest'] . '';
                 if (!($del_ship = $this->db->query($sql))) {
                     $this->log('Errors with ships get', 'Could not query planets ships! CONTINUE - ' . $sql . '');
                 }
                 while ($ship_wahl = $this->db->fetchrow($del_ship)) {
                     $zufall = mt_rand(6, 18);
                     if ($zufall >= 8) {
                         $sql = 'DELETE FROM ships WHERE ship_id = ' . $ship_wahl['ship_id'] . '';
                         if (!$this->db->query($sql)) {
                             $this->log('Error with ship deletion', 'Could not query deleted ship! CONTINUE');
                         } else {
                             $this->log('Ships removed', 'Ship_ID: ' . $ship_wahl['ship_id'] . ' Random number: ' . $zufall . ' <b>SUCCESS!</b>');
                         }
                     }
                 }
                 $this->log('Ship destruction', 'Deletion ended');
                 if (!$this->db->query('SET @i=0')) {
                     return $this->log(MV_M_DATABASE, 'Could not set sql iterator variable for planet owner enum (the invading player)! SKIP');
                 }
                 $sql = 'UPDATE planets
                 SET planet_owner_enum = (@i := (@i + 1))-1
                 WHERE planet_owner = ' . $this->move['user_id'] . '
                 ORDER BY planet_owned_date ASC, planet_id ASC';
                 if (!$this->db->query($sql)) {
                     return $this->log(MV_M_DATABASE, 'Could not update planet owner enum data (the invading player)! SKIP');
                 }
                 $sql = 'UPDATE ships
                 SET user_id = ' . $this->move['user_id'] . '
                 WHERE fleet_id = -' . $this->move['dest'];
                 if (!$this->db->query($sql)) {
                     return $this->log(MV_M_DATABASE, 'Could not update ships location data! SKIP');
                 }
                 if ($this->dest['user_id'] == BORG_USERID) {
                     if ((int) $this->move['user_alliance'] != 0) {
                         $sql = 'UPDATE alliance
                         SET borg_invade = borg_invade + 1
                         WHERE alliance_id = ' . $this->move['user_alliance'];
                         if (!$this->db->query($sql)) {
                             $this->log(MV_M_DATABASE, 'Could not update user alliance Borg honor data! CONTINUE');
                         }
                     }
                     $num_item = $this->dest['planet_type'] == "m" || $this->dest['planet_type'] == "o" || $this->dest['planet_type'] == "y" || $this->dest['planet_type'] == "x" || $this->dest['planet_type'] == "f" || $this->dest['planet_type'] == "g" ? 2 : 1;
                     send_premonition_to_user($this->move['user_id'], $num_item);
                     $sql = 'SELECT threat_level FROM borg_target WHERE user_id = ' . $this->move['user_id'];
                     $bot_target_data = $this->db->query($sql);
                     $already_acquired = $this->db->num_rows($bot_target_data);
                     if ($already_acquired < 1) {
                         $honor_prize = $this->dest['planet_type'] == "m" || $this->dest['planet_type'] == "o" || $this->dest['planet_type'] == "y" || $this->dest['planet_type'] == "x" || $this->dest['planet_type'] == "f" || $this->dest['planet_type'] == "g" ? 40 : 15;
                         $sql = 'INSERT INTO borg_target (user_id, planets_taken, battle_win) VALUES (' . $this->move['user_id'] . ', 1, 1)';
                         $this->db->query($sql);
                     } else {
                         $honor_bonus_data = $this->db->fetchrow($bot_target_data);
                         // Keep values align with those present in in borg.php
                         if ($honor_bonus_data['threat_level'] > 1400.0) {
                             $honor_bonus = 5.0;
                         } elseif ($honor_bonus_data['threat_level'] > 950.0) {
                             $honor_bonus = 3.0;
                         } elseif ($honor_bonus_data['threat_level'] > 450.0) {
                             $honor_bonus = 2.0;
                         } elseif ($honor_bonus_data['threat_level'] > 200.0) {
                             $honor_bonus = 1.5;
                         } else {
                             $honor_bonus = 1.0;
                         }
                         $honor_prize = ($this->dest['planet_type'] == "m" || $this->dest['planet_type'] == "n" || $this->dest['planet_type'] == "y" || $this->dest['planet_type'] == "e" || $this->dest['planet_type'] == "f" || $this->dest['planet_type'] == "g" ? 40 : 15) * $honor_bonus;
                         $sql = 'UPDATE borg_target SET planets_taken = planets_taken + 1, battle_win = battle_win +1 WHERE user_id = ' . $this->move['user_id'];
                         $this->db->query($sql);
                     }
                     $sql = 'UPDATE user SET user_honor = user_honor + ' . $honor_prize . ' WHERE user_id = ' . $this->move['user_id'];
                     if (!$this->db->query($sql)) {
                         $this->log(MV_M_DATABASE, 'Could not update user honor data! CONTINUE');
                     }
                     if (isset($this->move['user_alliance']) && !empty($this->move['user_alliance'])) {
                         $sql = 'UPDATE alliance SET alliance_honor = alliance_honor + ' . $honor_prize . ' WHERE alliance_id = ' . $this->move['user_alliance'];
                         if (!$this->db->query($sql)) {
                             $this->log(MV_M_DATABASE, 'Could not update alliance honor data! CONTINUE');
                         }
                     }
                     // #############################################################################
                     // 03/04/08 - AC: Retrieve player language
                     switch ($this->move['language']) {
                         case 'GER':
                             $msg_title = 'Verdienst im Kampf gegen die Borg';
                             $msg_text = 'F&uuml;e gerade erbrachten Verdienst gegen die neue Invasion des Borg-Kollektives befinden sich im Anflug auf euren Heimatplaneten ein speziell f&ouml;sen Kampf entwickeltes Schiff. Versucht nicht die enthaltene Technologie zu verstehen, sie wurde wirkungsvoll gegen euch abgeschirmt - nutzt sie stattdessen in eurem weiteren Kampf!';
                             break;
                         case 'ITA':
                             $msg_title = 'Merito in battaglia contro i Borg';
                             $msg_text = 'Proprio per rendere merito contro la nuova invasione del collettivo Borg si trova in approccio al tuo pianeta madre una nave appositamente progettata per combatterli. Non provare a capire la tecnologia inclusa, &egrave; stata efficacemente schermata contro di te - utilizzala invece ulteriormente nella tua lotta!';
                             break;
                         default:
                             $msg_title = 'Merit in the battle against the Borg';
                             $msg_text = 'For precisely rendered merit against the new invasion of the Borg Collective are located in the approach to your home planet fuse fight a specially designed ship. Do not try to understand the included technology, it was effectively shielded against you - instead uses it further in your fight!';
                             break;
                     }
                     $sql = 'INSERT INTO message (sender, receiver, subject, text, time)
                     VALUES (' . FUTURE_HUMANS_UID . ', ' . $this->move['user_id'] . ', "' . $msg_title . '", "' . $msg_text . '", ' . time() . ')';
                     if (!$this->db->query($sql)) {
                         $this->log(MV_M_DATABASE, 'Could not send message');
                     }
                 }
                 $action_status = 1;
                 // #############################################################################
                 // 03/04/08 - AC: Retrieve player language
                 switch ($this->move['language']) {
                     case 'GER':
                         $atk_title = 'Angriff auf ' . $this->dest['planet_name'] . ' erfolgreich';
                         break;
                     case 'ITA':
                         $atk_title = 'Attacco su ' . $this->dest['planet_name'] . ' riuscito';
                         break;
                     default:
                         $atk_title = 'Attack on ' . $this->dest['planet_name'] . ' successful';
                         break;
                 }
             }
             $sql = 'DELETE FROM ships
             WHERE ship_id = ' . $ship_id;
             if (!$this->db->query($sql)) {
                 return $this->log(MV_M_DATABASE, 'Could not delete ships data! SKIP');
             }
             if ($cship['n_ships'] == 1) {
                 $sql = 'DELETE FROM ship_fleets
                 WHERE fleet_id = ' . $cship['fleet_id'];
             } else {
                 $sql = 'UPDATE ship_fleets
                 SET n_ships = n_ships - 1
                 WHERE fleet_id = ' . $cship['fleet_id'];
             }
             if (!$this->db->query($sql)) {
                 $this->log(MV_M_DATABASE, 'Could not update/delete cships fleet data! CONTINUE');
             }
         } else {
             $action_status = -2;
             // #############################################################################
             // 03/04/08 - AC: Retrieve player language
             switch ($this->move['language']) {
                 case 'GER':
                     $atk_title = 'Angriff auf ' . $this->dest['planet_name'] . ' teilweise erfolgreich';
                     break;
                 case 'ITA':
                     $atk_title = 'Attacco su ' . $this->dest['planet_name'] . ' parzialmente riuscito';
                     break;
                 default:
                     $atk_title = 'Attack on ' . $this->dest['planet_name'] . ' partially successful';
                     break;
             }
         }
         $sql = 'UPDATE ship_fleets
         SET planet_id = ' . $this->move['dest'] . ',
             move_id = 0
         WHERE fleet_id IN (' . $this->fleet_ids_str . ')';
         if (!$this->db->query($sql)) {
             // Here one could also report and then go on
             return $this->log(MV_M_DATABASE, 'Could not update fleets location data! SKIP');
         }
     } else {
         // #############################################################################
         // 03/04/08 - AC: Retrieve player language
         switch ($this->move['language']) {
             case 'GER':
                 $atk_title = 'Angriff auf ' . $this->dest['planet_name'] . ' fehlgeschlagen';
                 break;
             case 'ITA':
                 $atk_title = 'Attacco su ' . $this->dest['planet_name'] . ' fallito';
                 break;
             default:
                 $atk_title = 'Attack on ' . $this->dest['planet_name'] . ' failed';
                 break;
         }
         // 01/07/08 - The attacker has lost the fleets
         for ($i = 0; $i < count($atk_fleets); ++$i) {
             $atk_losses[0] += $atk_fleets[$i]['unit_1'];
             $atk_losses[1] += $atk_fleets[$i]['unit_2'];
             $atk_losses[2] += $atk_fleets[$i]['unit_3'];
             $atk_losses[3] += $atk_fleets[$i]['unit_4'];
             $atk_losses[4] += $atk_fleets[$i]['resource_4'];
         }
         for ($i = 0; $i < count($atk_crews); ++$i) {
             $atk_losses[0] += $atk_crews[$i]['troop_1'];
             $atk_losses[1] += $atk_crews[$i]['troop_2'];
             $atk_losses[2] += $atk_crews[$i]['troop_3'];
             $atk_losses[3] += $atk_crews[$i]['troop_4'];
         }
     }
     // #############################################################################
     // Write logbook
     $log1_data = array(55, $this->move['user_id'], $this->move['dest'], $this->dest['planet_name'], $this->dest['user_id'], 0, 0, 0, MV_CMB_ATTACKER, $this->cmb[MV_CMB_WINNER] == MV_CMB_ATTACKER ? 1 : 0, 0, 0, $atk_fleets, $dfd_fleets);
     $log2_data = array(55, $this->move['user_id'], $this->move['dest'], $this->dest['planet_name'], $this->dest['user_id'], 0, 0, 0, MV_CMB_DEFENDER, $this->cmb[MV_CMB_WINNER] == MV_CMB_DEFENDER ? 1 : 0, 0, 0, $atk_fleets, $dfd_fleets);
     $log1_data[17] = $log2_data[17] = $action_status;
     $log1_data[20] = $this->dest['user_race'];
     $log2_data[20] = $this->move['user_race'];
     for ($i = 0; $i < 5; ++$i) {
         $log1_data[18][$i] = $log2_data[19][$i] = $atk_losses[$i];
         $log1_data[19][$i] = $log2_data[18][$i] = $dfd_losses[$i];
     }
     //$log1_data[19][4] = $log2_data[18][4] = (int)$dfd_losses[4]; already done by for above...
     $log2_data[14] = $this->cmb[MV_CMB_KILLS_PLANETARY];
     $log1_data[10] = $this->cmb[MV_CMB_KILLS_EXT];
     $log2_data[10] = $this->cmb[MV_CMB_KILLS_EXT];
     add_logbook_entry($this->move['user_id'], LOGBOOK_TACTICAL, $atk_title, $log1_data);
     add_logbook_entry($this->dest['user_id'], LOGBOOK_TACTICAL, $dfd_title, $log2_data);
     if ($n_st_user > 0) {
         $log2_data[2] = $this->move['start'];
         $log2_data[3] = $this->dest['planet_name'];
         $log2_data[4] = $user_id;
         $log2_data[5] = 0;
         $log2_data[6] = 0;
         $log2_data[7] = 0;
         $log2_data[16] = 1;
         for ($i = 0; $i < $n_st_user; ++$i) {
             // #############################################################################
             // 24/06/08 - AC: Retrieve player language
             $log_title = 'One of your allies defended ' . $this->dest['planet_name'];
             $sql = 'SELECT language FROM user WHERE user_id = ' . $st_user[$i];
             if (!($lang = $this->db->queryrow($sql))) {
                 $this->log(MV_M_DATABASE, 'Could not retrieve player language');
             } else {
                 switch ($lang['language']) {
                     case 'GER':
                         $log_title = 'Verb&uuml;ndeten bei ' . $this->dest['planet_name'] . ' verteidigt';
                         break;
                     case 'ITA':
                         $log_title = 'Difesa alleata presso ' . $this->dest['planet_name'];
                         break;
                 }
             }
             add_logbook_entry($st_user[$i], LOGBOOK_TACTICAL, $log_title, $log2_data);
         }
     }
     return MV_EXEC_OK;
 }
    function _action_main()
    {
        // #############################################################################
        // Data from the attacker
        /*        
        $sql = 'SELECT '.$this->get_combat_query_fleet_columns().', f.resource_4, f.unit_1, f.unit_2, f.unit_3, f.unit_4
               FROM (ship_fleets f)
               INNER JOIN user u ON u.user_id = f.user_id
               INNER JOIN ships ON ships
               WHERE f.fleet_id IN ('.$this->fleet_ids_str.')';
        */
        $sql = 'SELECT ' . $this->get_combat_query_fleet_columns() . ',
		SUM(s.unit_1 - st.min_unit_1) AS unit_1,
                SUM(s.unit_2 - st.min_unit_2) AS unit_2,
                SUM(s.unit_3 - st.min_unit_3) AS unit_3,
                SUM(s.unit_4 - st.min_unit_4) AS unit_4
        FROM (ship_fleets f)
        INNER JOIN user u ON u.user_id = f.user_id
        INNER JOIN ships s USING (fleet_id)
        INNER JOIN ship_templates st ON s.template_id = st.id
        WHERE f.fleet_id IN (' . $this->fleet_ids_str . ')';
        if (($atk_fleets = $this->db->queryrowset($sql)) === false) {
            return $this->log(MV_M_DATABASE, 'Could not query attackers fleets data! SKIP');
        }
        // #############################################################################
        // Data from the defender
        $sql = 'SELECT DISTINCT f.user_id,
               u.user_alliance,
               ud.ud_id, ud.accepted,
               ad.ad_id, ad.type, ad.status
        FROM (ship_fleets f)
        INNER JOIN user u ON u.user_id = f.user_id
        LEFT JOIN user_diplomacy ud ON ( ( ud.user1_id = ' . $this->dest['user_id'] . ' AND ud.user2_id = f.user_id ) OR ( ud.user1_id = f.user_id AND ud.user2_id = ' . $this->dest['user_id'] . ' ) )
        LEFT JOIN alliance_diplomacy ad ON ( ( ad.alliance1_id = ' . $this->dest['user_alliance'] . ' AND ad.alliance2_id = u.user_alliance) OR ( ad.alliance1_id = u.user_alliance AND ad.alliance2_id = ' . $this->dest['user_alliance'] . ' ) )
        WHERE f.planet_id = ' . $this->move['dest'] . ' AND
              f.user_id <> ' . $this->dest['user_id'] . ' AND
              f.user_id <> ' . $this->move['user_id'] . ' AND
              f.alert_phase >= ' . ALERT_PHASE_YELLOW;
        if (!($q_st_uid = $this->db->query($sql))) {
            return $this->log(MV_M_DATABASE, 'Could not query stationated fleets user data! SKIP');
        }
        $st_user = array();
        while ($st_uid = $this->db->fetchrow($q_st_uid)) {
            $allied = false;
            if ($st_uid['user_alliance'] == $this->dest['user_alliance']) {
                $allied = true;
            }
            if (!empty($st_uid['ud_id'])) {
                if ($st_uid['accepted'] == 1) {
                    $allied = true;
                }
            }
            if (!empty($st_uid['ad_id'])) {
                if ($st_uid['type'] == ALLIANCE_DIPLOMACY_PACT && $st_uid['status'] == 0) {
                    $allied = true;
                }
            }
            if ($allied) {
                $st_user[] = $st_uid['user_id'];
            }
        }
        $n_st_user = count($st_user);
        if ($n_st_user > 0) {
            $sql = 'SELECT ' . $this->get_combat_query_fleet_columns() . '
             FROM (ship_fleets f)
             INNER JOIN user u ON u.user_id = f.user_id
             WHERE f.planet_id = ' . $this->move['dest'] . ' AND
                   (
                     (
                       f.user_id = ' . $this->dest['user_id'] . '
                     )
                     OR
                     (
                       f.user_id IN (' . implode(',', $st_user) . ') AND
                       f.alert_phase >= ' . ALERT_PHASE_YELLOW . '
                     )
                   )';
        } else {
            $sql = 'SELECT ' . $this->get_combat_query_fleet_columns() . '
             FROM (ship_fleets f)
             INNER JOIN user u ON u.user_id = f.user_id
             WHERE f.planet_id = ' . $this->move['dest'] . ' AND
                   f.user_id = ' . $this->dest['user_id'];
        }
        if (($dfd_fleets = $this->db->queryrowset($sql)) === false) {
            return $this->log(MV_M_DATABASE, 'Could not query defenders fleets data! SKIP');
        }
        $dfd_fleet_ids = array();
        foreach ($dfd_fleets as $i => $cur_fleet) {
            $dfd_fleet_ids[] = $cur_fleet['fleet_id'];
        }
        $dfd_fleet_ids_str = implode(',', $dfd_fleet_ids);
        if ($this->do_ship_combat($this->fleet_ids_str, $dfd_fleet_ids_str, MV_COMBAT_LEVEL_PLANETARY) == MV_EXEC_ERROR) {
            $this->log(MV_M_DATABASE, 'Move Action 46: Something went wrong with this fight!');
            return MV_EXEC_ERROR;
        }
        // #############################################################################
        // If the attacker has won attempt to start takeover
        // #############################################################################
        // 03/04/08 - AC: Retrieve player language
        switch ($this->dest['language']) {
            case 'GER':
                $dfd_title = 'Angriff der Borg auf ' . $this->dest['planet_name'];
                break;
            case 'ITA':
                $dfd_title = 'Attacco Borg su ' . $this->dest['planet_name'];
                break;
            default:
                $dfd_title = 'Borg attack on ' . $this->dest['planet_name'];
                break;
        }
        $action_status = 0;
        /* 11/07/08 - AC: Initialize here arrays atk/dfd_losses */
        $atk_losses = array(0, 0, 0, 0, 0);
        $dfd_losses = array(0, 0, 0, 0, 0);
        if ($this->cmb[MV_CMB_WINNER] == MV_CMB_ATTACKER) {
            $atk_units = array(0, 0, 0, 0, 0);
            // 20/06/08 - AC: Borg as no "workers"
            for ($i = 0; $i < count($atk_fleets); ++$i) {
                $atk_units[0] += $atk_fleets[$i]['unit_1'];
                $atk_units[1] += $atk_fleets[$i]['unit_2'];
                $atk_units[2] += $atk_fleets[$i]['unit_3'];
                $atk_units[3] += $atk_fleets[$i]['unit_4'];
            }
            $dfd_units = array($this->dest['unit_1'], $this->dest['unit_2'], $this->dest['unit_3'], $this->dest['unit_4'], $this->dest['resource_4']);
            // Are there some defenders?
            if (array_sum($dfd_units) > 0) {
                $ucmb = UnitFight($atk_units, $this->move['user_race'], $dfd_units, $this->dest['user_race'], $this->mid);
                $n_atk_alive = array_sum($ucmb[0]);
                $atk_alive = $ucmb[0];
                $dfd_alive = $ucmb[1];
            } else {
                $n_atk_alive = 1;
                $atk_alive = $atk_units;
                $dfd_alive = array(0, 0, 0, 0, 0);
            }
            // 01/07/08 - AC: Count losses for each part
            for ($i = 0; $i < 5; ++$i) {
                $atk_losses[$i] = $atk_units[$i] - $atk_alive[$i];
                $dfd_losses[$i] = $dfd_units[$i] - $dfd_alive[$i];
            }
            // If there are no more attackers, the defender
            // always won even if the defending had no units
            if ($n_atk_alive == 0) {
                // In order to eliminate the troops of the aggressor, simply reset all transporters
                // 21/06/08 - AC: Keep out workers from battle!
                $sql = 'UPDATE ships
                INNER JOIN ship_templates ON ships.template_id = ship_templates.id
                        SET unit_1 = ship_templates.min_unit_1,
                        unit_2 = ship_templates.min_unit_2,
                        unit_3 = ship_templates.min_unit_3,
                        unit_4 = ship_templates.min_unit_4
                WHERE fleet_id IN (' . $this->fleet_ids_str . ')';
                if (!$this->db->query($sql)) {
                    return $this->log(MV_M_DATABASE, 'Could not update ship fleets unit transport data! SKIP');
                }
                // Simply update the defender troops
                $sql = 'UPDATE planets
                SET unit_1 = ' . $ucmb[1][0] . ',
                    unit_2 = ' . $ucmb[1][1] . ',
                    unit_3 = ' . $ucmb[1][2] . ',
                    unit_4 = ' . $ucmb[1][3] . ',
                    resource_4 = ' . $ucmb[1][4] . '
                WHERE planet_id = ' . $this->move['dest'];
                if (!$this->db->query($sql)) {
                    return $this->log(MV_M_DATABASE, 'Could not update dest planet units data! SKIP');
                }
                $action_status = -1;
                // #############################################################################
                // 03/04/08 - AC: Retrieve player language
                switch ($this->move['language']) {
                    case 'GER':
                        $atk_title = 'Angriff auf ' . $this->dest['planet_name'] . ' teilweise erfolgreich';
                        break;
                    case 'ITA':
                        $atk_title = 'Attacco su ' . $this->dest['planet_name'] . ' parzialmente riuscito';
                        break;
                    default:
                        $atk_title = 'Attack on ' . $this->dest['planet_name'] . ' partially successful';
                        break;
                }
            } else {
                account_log($this->move['user_id'], $this->dest['user_id'], 4);
                // Export a ruler switch
                // We need the number of planets, which owns the colonizing
                // (we want planet_owner_enum degree of certainty)
                $sql = 'SELECT COUNT(planet_id) AS n_planets
                FROM planets
                WHERE planet_owner = ' . $this->move['user_id'];
                if (($pcount = $this->db->queryrow($sql)) === false) {
                    $this->log(MV_M_DATABASE, 'Could not query planets count data! CONTINUE AND USE INSTABLE VALUE');
                    $n_planets = $this->move['user_planets'];
                } else {
                    $n_planets = $pcount['n_planets'];
                }
                // We accommodate as much troops, as on the colony ship were, on the planet
                $planet_units = array(0, 0, 0, 0);
                // 25/06/08 - AC: Check available space on target planet
                $sql = 'SELECT max_units FROM planets WHERE planet_id = ' . $this->move['dest'];
                if (($plspace = $this->db->queryrow($sql)) === false) {
                    $this->log(MV_M_DATABASE, 'Could not query planet max units data! CONTINUE AND USE INSTABLE VALUE');
                    $plspace['max_units'] = 1300;
                    // Minimum size available
                }
                if ($atk_alive[0] * 2 + $atk_alive[1] * 3 + $atk_alive[2] * 4 + $atk_alive[3] * 4 > $plspace['max_units']) {
                    $this->log(MV_M_NOTICE, 'Alive units exceed planet maximum units, we need to recall aboard the surplus');
                    // AC: Recall aboard the surplus troops
                    $i = 0;
                    while ($n_atk_alive) {
                        if ($planet_units[0] * 2 + $planet_units[1] * 3 + $planet_units[2] * 4 + $planet_units[3] * 4 >= $plspace['max_units']) {
                            break;
                        }
                        if ($atk_alive[$i] > 0) {
                            $planet_units[$i]++;
                            $atk_alive[$i]--;
                            $n_atk_alive--;
                        } else {
                            $i++;
                        }
                    }
                    // Borg doesn't have cargo, simply use the Cube
                    /*
                                $sql = 'UPDATE ship_fleets
                           SET unit_1 = '.$atk_alive[0].',
                               unit_2 = '.$atk_alive[1].',
                               unit_3 = '.$atk_alive[2].',
                               unit_4 = '.$atk_alive[3].'
                           WHERE fleet_id = '.$this->fleet_ids_str;
                    
                                if(!$this->db->query($sql)) {
                       $this->log(MV_M_DATABASE, 'Could not update fleets units data! CONTINUE');
                                }
                    * 
                    */
                } else {
                    for ($i = 0; $i <= 3; ++$i) {
                        $planet_units[$i] += $atk_alive[$i];
                    }
                    /*
                                $sql = 'UPDATE ship_fleets
                           SET unit_1 = 0,
                               unit_2 = 0,
                               unit_3 = 0,
                               unit_4 = 0
                           WHERE fleet_id IN ('.$this->fleet_ids_str.')';
                    
                                if(!$this->db->query($sql)) {
                       return $this->log(MV_M_DATABASE, 'Could not update ship fleets unit transport data! SKIP');
                                }
                    * 
                    */
                }
                $sql = 'DELETE FROM scheduler_instbuild
                WHERE planet_id = ' . $this->move['dest'];
                if (!$this->db->query($sql)) {
                    $this->log(MV_M_DATABASE, 'Could not delete scheduler instbuild data! CONTINUE');
                }
                $sql = 'DELETE FROM scheduler_research
                WHERE planet_id = ' . $this->move['dest'];
                if (!$this->db->query($sql)) {
                    $this->log(MV_M_DATABASE, 'Could not delete scheduler research data! CONTINUE');
                }
                global $NUM_BUILDING, $MAX_BUILDING_LVL;
                // As someone yes number == max_index sets
                $n_buildings = $NUM_BUILDING + 1;
                $building_levels = array();
                $building_damage = 0.01 * mt_rand(40, 60);
                // Set new home world
                if ($this->move['dest'] == $this->dest['user_capital']) {
                    for ($i = 0; $i < $n_buildings; ++$i) {
                        $j = $i + 1;
                        $building_levels[$i] = (int) ($this->dest['building_' . $j] > $MAX_BUILDING_LVL[0][$i]) ? $MAX_BUILDING_LVL[0][$i] : round($this->dest['building_' . $j] * $building_damage, 0);
                    }
                    if ($this->dest['user_planets'] == 1) {
                        // #############################################################################
                        // 03/04/08 - AC: Retrieve player language
                        switch ($this->dest['language']) {
                            case 'GER':
                                $msg_title = 'Verlust aller deiner Planeten';
                                $msg_body = 'Da du alle deine Planeten verloren hast, wurde f&uuml;r dich ein neuer Planet an einer zuf&uuml;ligen Stelle der Galaxie erstellt.';
                                break;
                            case 'ITA':
                                $msg_title = 'Perdita di tutti i pianeti';
                                $msg_body = 'Dato che hai perduto tutti i pianeti ne &egrave; stato creato uno nuovo nella galassia.';
                                break;
                            default:
                                $msg_title = 'Loss of all your planets';
                                $msg_body = 'Since you lost all your planets a new one have been created in the body of the galaxy.';
                                break;
                        }
                        SystemMessage($this->dest['user_id'], $msg_title, $msg_body);
                    } else {
                        if (!$this->db->query('SET @i=0')) {
                            return $this->log(MV_M_DATABASE, 'Could not set sql iterator variable for planet owner enum! SKIP');
                        }
                        $sql = 'UPDATE planets
                        SET planet_owner_enum = (@i := (@i + 1))-1
                        WHERE planet_owner = ' . $this->dest['user_id'] . '
                        ORDER BY planet_owned_date ASC, planet_id ASC';
                        if (!$this->db->query($sql)) {
                            return $this->log(MV_M_DATABASE, 'Could not update planet owner enum data! SKIP');
                        }
                        $sql = 'SELECT planet_id
                        FROM planets
                        WHERE planet_owner = ' . $this->dest['user_id'] . '
                        ORDER BY planet_owner_enum ASC
                        LIMIT 1';
                        if (($first_planet = $this->db->queryrow($sql)) === false) {
                            return $this->log(MV_M_DATABASE, 'Could not query first planet data! SKIP');
                        }
                        $sql = 'UPDATE user
                        SET last_active = ' . time() . ',
                            last_ip = "0.0.0.0",
                            user_capital = ' . $first_planet['planet_id'] . ',
                            pending_capital_choice = 1
                        WHERE user_id = ' . $this->dest['user_id'];
                        if (!$this->db->query($sql)) {
                            return $this->log(MV_M_DATABASE, 'Could not update user capital data! SKIP');
                        }
                    }
                } else {
                    for ($i = 0; $i < $n_buildings; ++$i) {
                        $building_levels[$i] = round($this->dest['building_' . ($i + 1)] * $building_damage, 0);
                    }
                }
                $sql = 'DELETE FROM resource_trade
                WHERE planet = ' . $this->move['dest'];
                if (!$this->db->query($sql)) {
                    $this->log(MV_M_DATABASE, 'Could not delete resource trade data! CONTINUE');
                }
                $sql = 'SELECT ship_id
                FROM ship_trade
                WHERE scheduler_processed = 0 AND
                      planet = ' . $this->move['dest'];
                if (!($q_shipt = $this->db->query($sql))) {
                    $this->log(MV_M_DATABASE, 'Could not query ship trade data! CONTINUE');
                } else {
                    $ship_ids = array();
                    while ($_ship = $this->db->fetchrow($q_shipt)) {
                        $ship_ids[] = $_ship['ship_id'];
                    }
                    if (count($ship_ids) > 0) {
                        $sql = 'UPDATE ships
                        SET ship_untouchable = 0
                        WHERE ship_id IN (' . implode(',', $ship_ids) . ')';
                        if (!$this->db->query($sql)) {
                            $this->log(MV_M_DATABASE, 'Could not update ships untouchable data! CONTINUE');
                        }
                    }
                }
                $sql = 'DELETE FROM ship_trade
                WHERE scheduler_processed = 0 AND
                      planet = ' . $this->move['dest'];
                if (!$this->db->query($sql)) {
                    $this->log(MV_M_DATABASE, 'Could not delete ship trade data! CONTINUE');
                }
                $sql = 'DELETE FROM scheduler_shipbuild WHERE planet_id = ' . $this->move['dest'];
                if (!$this->db->query($sql)) {
                    $this->log(MV_M_DATABASE, 'Could not delete ship building queue! CONTINUE');
                }
                if ($this->dest['planet_type'] == "m" || $this->dest['planet_type'] == "o" || $this->dest['planet_type'] == "p" || $this->dest['planet_type'] == "x" || $this->dest['planet_type'] == "y" || $this->dest['planet_type'] == "f" || $this->dest['planet_type'] == "g") {
                    $def_tech_lev = 9;
                } else {
                    $def_tech_lev = 6;
                }
                $sql = 'UPDATE planets
                SET planet_owner = ' . $this->move['user_id'] . ',
                    planet_name = "Unimatrix #' . $this->move['dest'] . '",
                    best_mood = 0,
                    best_mood_user = 0,
                    planet_owned_date = ' . time() . ',
                    planet_owner_enum = ' . ($n_planets - 1) . ',
                    resource_4 = ' . $ucmb[1][4] . ',
                    planet_next_attack = 0,
                    planet_attack_ships = 0,
                    planet_attack_type = 0,
                    research_3 = ' . $def_tech_lev . ',
                    research_4 = ' . $def_tech_lev . ',
                    research_5 = ' . $def_tech_lev . ',
                    recompute_static = 1,
                    building_1 = 9,
                    building_2 = ' . $building_levels[1] . ',
                    building_3 = ' . $building_levels[2] . ',
                    building_4 = ' . $building_levels[3] . ',
                    building_5 = 9,
                    building_6 = 9,
                    building_7 = ' . $building_levels[6] . ',
                    building_8 = ' . $building_levels[7] . ',
                    building_9 = ' . $building_levels[8] . ',
                    building_10 = ' . $building_levels[9] . ',
                    building_11 = ' . $building_levels[10] . ',
                    building_12 = ' . $building_levels[11] . ',
                    building_13 = ' . $building_levels[12] . ',
                    unit_1 = ' . $planet_units[0] . ',
                    unit_2 = ' . $planet_units[1] . ',
                    unit_3 = ' . $planet_units[2] . ',
                    unit_4 = ' . $planet_units[3] . ',
                    unit_5 = 0,
                    unit_6 = 0,
                    workermine_1 = 100,
                    workermine_2 = 100,
                    workermine_3 = 100,
                    catresearch_1 = 0,
                    catresearch_2 = 0,
                    catresearch_3 = 0,
                    catresearch_4 = 0,
                    catresearch_5 = 0,
                    catresearch_6 = 0,
                    catresearch_7 = 0,
                    catresearch_8 = 0,
                    catresearch_9 = 0,
                    catresearch_10 = 0,
                    unittrainid_1 = 0, unittrainid_2 = 0, unittrainid_3 = 0, unittrainid_4 = 0, unittrainid_5 = 0, unittrainid_6 = 0, unittrainid_7 = 0, unittrainid_8 = 0, unittrainid_9 = 0, unittrainid_10 = 0, 
                    unittrainnumber_1 = 0, unittrainnumber_2 = 0, unittrainnumber_3 = 0, unittrainnumber_4 = 0, unittrainnumber_5 = 0, unittrainnumber_6 = 0, unittrainnumber_7 = 0, unittrainnumber_8 = 0, unittrainnumber_9 = 0, unittrainnumber_10 = 0, 
                    unittrainnumberleft_1 = 0, unittrainnumberleft_2 = 0, unittrainnumberleft_3 = 0, unittrainnumberleft_4 = 0, unittrainnumberleft_5 = 0, unittrainnumberleft_6 = 0, unittrainnumberleft_7 = 0, unittrainnumberleft_8 = 0, unittrainnumberleft_9 = 0, unittrainnumberleft_10 = 0, 
                    unittrainendless_1 = 0, unittrainendless_2 = 0, unittrainendless_3 = 0, unittrainendless_4 = 0, unittrainendless_5 = 0, unittrainendless_6 = 0, unittrainendless_7 = 0, unittrainendless_8 = 0, unittrainendless_9 = 0, unittrainendless_10 = 0, 
                    unittrain_actual = 0,
                    unittrainid_nexttime=0,
                    planet_insurrection_time=0
                WHERE planet_id = ' . $this->move['dest'];
                if (!$this->db->query($sql)) {
                    return $this->log(MV_M_DATABASE, 'Could not update planets data! SKIP');
                }
                // DC >>>> Historycal record in planet_details, with label '29'
                $sql = 'INSERT INTO planet_details (planet_id, user_id, alliance_id, source_uid, source_aid, timestamp, log_code, defeat_uid, defeat_aid)
                VALUES (' . $this->move['dest'] . ', 0, 0, 0, 0, ' . time() . ', 29,' . $this->dest['user_id'] . ', ' . $this->dest['user_alliance'] . ')';
                if (!$this->db->query($sql)) {
                    $this->log(MV_M_DATABASE, 'Could not update planet details data! CONTINUE');
                }
                // DC <<<<
                // DC >>>> Update borg_target table; the $this->dest['user_id'] entry may not exists, so do not check error
                $sql = 'UPDATE borg_target SET battle_lost = battle_lost + 1,
                                       planets_back = planets_back + 1,
                                       under_attack = under_attack - 1
                WHERE user_id = ' . $this->dest['user_id'];
                $this->db->query($sql);
                // DC <<<<
                // DC >>>>
                $sql = 'DELETE FROM borg_npc_target WHERE planet_id = ' . $this->move['dest'];
                $this->db->query($sql);
                $sql = 'UPDATE scheduler_shipmovement SET action_code = 11
                WHERE action_code = 46 AND move_id <> ' . $this->mid . '
                AND move_status = 0 AND user_id = ' . BORG_USERID . ' AND dest = ' . $this->move['dest'];
                $this->db->query($sql);
                // DC <<<<
                // DC >>>> Settlers management
                if ($this->dest['user_id'] == INDEPENDENT_USERID) {
                    $sql = 'SELECT sr.user_id, u.language FROM settlers_relations sr
                    LEFT JOIN user u ON u.user_id = sr.user_id
                    WHERE planet_id = ' . $this->move['dest'] . ' GROUP BY sr.user_id';
                    if ($m_u_q = $this->db->queryrowset($sql)) {
                        foreach ($m_u_q as $m_u) {
                            $log_data = array($this->move['dest'], $this->dest['planet_name'], 0, '', 103);
                            switch ($m_u['language']) {
                                case 'GER':
                                    $log_title = 'Automatic distress message from ';
                                    break;
                                case 'ITA':
                                    $log_title = 'Richiesta automatica di soccorso dalla colonia ';
                                    break;
                                default:
                                    $log_title = 'Automatic distress message from ';
                                    break;
                            }
                            add_logbook_entry($m_u['user_id'], LOGBOOK_SETTLERS, $log_title . $this->dest['planet_name'], $log_data);
                        }
                        $sql = 'DELETE FROM settlers_relations WHERE planet_id = ' . $this->move['dest'];
                        $this->db->query($sql);
                    }
                }
                // DC <<<< Settlers management
                if (!$this->db->query('SET @i=0')) {
                    return $this->log(MV_M_DATABASE, 'Could not set sql iterator variable for planet owner enum (the invading player)! SKIP');
                }
                $sql = 'UPDATE planets
                SET planet_owner_enum = (@i := (@i + 1))-1
                WHERE planet_owner = ' . $this->move['user_id'] . '
                ORDER BY planet_owned_date ASC, planet_id ASC';
                if (!$this->db->query($sql)) {
                    return $this->log(MV_M_DATABASE, 'Could not update planet owner enum data (the invading player)! SKIP');
                }
                $sql = 'UPDATE ships
                SET user_id = ' . $this->move['user_id'] . '
                WHERE fleet_id = -' . $this->move['dest'];
                if (!$this->db->query($sql)) {
                    return $this->log(MV_M_DATABASE, 'Could not update ships location data! SKIP');
                }
                $action_status = 1;
                // #############################################################################
                // 03/04/08 - AC: Retrieve player language
                switch ($this->move['language']) {
                    case 'GER':
                        $atk_title = 'Angriff auf ' . $this->dest['planet_name'] . ' erfolgreich';
                        break;
                    case 'ITA':
                        $atk_title = 'Attacco su ' . $this->dest['planet_name'] . ' riuscito';
                        break;
                    default:
                        $atk_title = 'Attack on ' . $this->dest['planet_name'] . ' successful';
                        break;
                }
            }
            // DC >>>>
            if ($this->dest['user_id'] == INDEPENDENT_USERID) {
                $sql = 'SELECT sr.user_id, u.language FROM settlers_relations sr
                LEFT JOIN user u ON u.user_id = sr.user_id
                WHERE planet_id = ' . $this->move['dest'] . ' GROUP BY sr.user_id';
                if ($m_u_q = $this->db->queryrowset($sql)) {
                    foreach ($m_u_q as $m_u) {
                        $log_data = array($this->move['dest'], $this->dest['planet_name'], 0, '', 104);
                        switch ($m_u['language']) {
                            case 'GER':
                                $log_title = 'Distress call from ';
                                break;
                            case 'ITA':
                                $log_title = 'Richiesta di soccorso dalla colonia ';
                                break;
                            default:
                                $log_title = 'Distress call from ';
                                break;
                        }
                        add_logbook_entry($m_u['user_id'], LOGBOOK_SETTLERS, $log_title . $this->dest['planet_name'], $log_data);
                    }
                }
            }
            // DC <<<<
            $sql = 'UPDATE ship_fleets
            SET planet_id = ' . $this->move['dest'] . ',
                move_id = 0
            WHERE fleet_id IN (' . $this->fleet_ids_str . ')';
            if (!$this->db->query($sql)) {
                // Here one could also report and then go on
                return $this->log(MV_M_DATABASE, 'Could not update fleets location data! SKIP');
            }
        } else {
            // #############################################################################
            // 03/04/08 - AC: Retrieve player language
            switch ($this->move['language']) {
                case 'GER':
                    $atk_title = 'Angriff auf ' . $this->dest['planet_name'] . ' fehlgeschlagen';
                    break;
                case 'ITA':
                    $atk_title = 'Attacco su ' . $this->dest['planet_name'] . ' fallito';
                    break;
                default:
                    $atk_title = 'Attack on ' . $this->dest['planet_name'] . ' failed';
                    break;
            }
            // DC >>>> Begin Borg Adaption Phase!!!
            $adaption_chance_array = array('no_event' => 90, 'adapt_PRI' => 13, 'adapt_SEC' => 12, 'adapt_SHI' => 7, 'adapt_ARM' => 9, 'adapt_REA' => 4, 'adapt_RED' => 5, 'adapt_AGI' => 3, 'adapt_ROF' => 4, 'adapt_ROF2' => 2);
            $adaption_array = array();
            foreach ($adaption_chance_array as $event => $probability) {
                for ($i = 0; $i < $probability; ++$i) {
                    $adaption_array[] = $event;
                }
            }
            $adaption_event = $adaption_array[array_rand($adaption_array)];
            if ($adaption_event == 'no_event') {
                $this->log(MV_M_NOTICE, 'Borg Adaption Phase not occured this time.');
            } else {
                $this->log(MV_M_NOTICE, 'Borg Adaption Phase begin NOW.');
                $borg_bot = $this->db->queryrow('SELECT ship_template2 FROM borg_bot WHERE id = 1');
                $borgcube_tp = $this->db->queryrow('SELECT * FROM ship_templates WHERE owner = ' . BORG_USERID . ' AND id = ' . $borg_bot['ship_template2']);
                $newvalue1 = $borgcube_tp['value_1'];
                $newvalue2 = $borgcube_tp['value_2'];
                $newvalue4 = $borgcube_tp['value_4'];
                $newvalue5 = $borgcube_tp['value_5'];
                $newvalue6 = $borgcube_tp['value_6'];
                $newvalue7 = $borgcube_tp['value_7'];
                $newvalue8 = $borgcube_tp['value_8'];
                $newrof = $borgcube_tp['rof'];
                $newrof2 = $borgcube_tp['rof2'];
                switch ($adaption_event) {
                    case 'adapt_PRI':
                        $newvalue1 = $newvalue1 * 1.015;
                        $this->log(MV_M_NOTICE, 'Borg Primary Attack Value ++.');
                        break;
                    case 'adapt_SEC':
                        $newvalue2 = $newvalue2 * 1.015;
                        $this->log(MV_M_NOTICE, 'Borg Secondary Attack Value ++.');
                        break;
                    case 'adapt_SHI':
                        $newvalue4 = $newvalue4 * 1.025;
                        $this->log(MV_M_NOTICE, 'Borg Armor Value ++.');
                        break;
                    case 'adapt_ARM':
                        $newvalue5 = $newvalue5 * 1.02;
                        $this->log(MV_M_NOTICE, 'Borg Shield Value ++.');
                        break;
                    case 'adapt_REA':
                        $newvalue6 = $newvalue6 + 1;
                        $this->log(MV_M_NOTICE, 'Borg Reaction Value ++.');
                        break;
                    case 'adapt_RED':
                        $newvalue7 = $newvalue7 + 1;
                        $this->log(MV_M_NOTICE, 'Borg Readiness Value ++.');
                        break;
                    case 'adapt_AGI':
                        $newvalue8 = $newvalue8 + 1;
                        $this->log(MV_M_NOTICE, 'Borg Agility Value ++.');
                        break;
                    case 'adapt_ROF':
                        $newrof = $newrof + 1;
                        $this->log(MV_M_NOTICE, '+++ Borg ROF Value +++.');
                        break;
                    case 'adapt_ROF2':
                        $newrof2 = $newrof2 + 1;
                        $this->log(MV_M_NOTICE, '+++ Borg ROF2 Value +++.');
                        break;
                }
                $oldversion = 0;
                sscanf($borgcube_tp['name'], "Adapted Cube#%u", $oldversion);
                $sql = 'INSERT INTO ship_templates (owner, timestamp, name, description, race, ship_torso, ship_class,
                                                component_1, component_2, component_3, component_4, component_5,
                                                component_6, component_7, component_8, component_9, component_10,
                                                value_1, value_2, value_3, value_4, value_5,
                                                value_6, value_7, value_8, value_9, value_10,
                                                value_11, value_12, value_13, value_14, value_15,
                                                resource_1, resource_2, resource_3, resource_4, unit_5, unit_6,
                                                min_unit_1, min_unit_2, min_unit_3, min_unit_4,
                                                max_unit_1, max_unit_2, max_unit_3, max_unit_4,
                                                buildtime, rof, rof2, max_torp)
                VALUES ("' . $borgcube_tp['owner'] . '","' . time() . '","Adapted Cube#' . ($oldversion + 1) . '","Assimilation ship","' . $borgcube_tp['race'] . '",9,3,
                            -1,-1,-1,-1,-1,
                            -1,-1,-1,-1,-1,
                            "' . $newvalue1 . '","' . $newvalue2 . '","140","' . $newvalue4 . '","' . $newvalue5 . '",
                            "' . $newvalue6 . '","' . $newvalue7 . '","' . $newvalue8 . '","50","10",
                            "42","0","300","300","0",
                            "500000","500000","500000","50000","39","16",
                            "294","0","0","6",
                            "9294","6000","3000","6",
                            0, ' . $newrof . ', ' . $newrof2 . ', 1000)';
                $this->db->query($sql);
                $newtpid = $this->db->insert_id();
                $this->db->query('UPDATE borg_bot SET ship_template2 = ' . $newtpid . ' WHERE id = 1 ');
                $this->log(MV_M_NOTICE, 'Borg Adaption Phase ends NOW.');
            }
            // DC <<<< End Borg Adaption Phase
            // DC >>>> Settlers management
            if ($this->dest['user_id'] == INDEPENDENT_USERID) {
                // Check for defenders
                if ($n_st_user > 0) {
                    $sql = 'SELECT user_id from borg_target WHERE user_id IN (' . implode(",", $st_user) . ')';
                    if (!($def_q = $this->db->query($sql))) {
                        $this->log(MV_M_DATABASE, 'Could not query borg_target data! ' . $sql);
                    }
                    $num_row = $this->db->num_rows($def_q);
                    if ($num_row > 0) {
                        // Update priority of this planet!!!
                        $sql = 'UPDATE borg_npc_target SET priority = priority + ' . 10 * $num_row . ' WHERE planet_id = ' . $this->move['dest'];
                        if (!$this->db->query($sql)) {
                            $this->log(MV_M_DATABASE, 'Could not update borg_npc_target data! ' . $sql);
                        }
                        $def_i_q = $this->db->fetchrowset($def_q);
                        foreach ($def_i_q as $item_def_q) {
                            $sql = 'UPDATE borg_target SET battle_win = battle_win + 1 WHERE user_id = ' . $item_def_q['user_id'];
                            if (!$this->db->query($sql)) {
                                $this->log(MV_M_DATABASE, 'Could not update borg_target data! ' . $sql);
                            }
                        }
                    }
                }
                $sql = 'UPDATE borg_npc_target SET tries = tries + 1,
                                           live_attack = live_attack - 1 
                WHERE planet_id = ' . $this->move['dest'];
                $this->db->query($sql);
                $sql = 'SELECT sr.user_id, u.language FROM settlers_relations sr
                LEFT JOIN user u ON u.user_id = sr.user_id
                WHERE planet_id = ' . $this->move['dest'] . ' GROUP BY sr.user_id';
                if ($m_u_q = $this->db->queryrowset($sql)) {
                    foreach ($m_u_q as $m_u) {
                        $log_data = array($this->move['dest'], $this->dest['planet_name'], 0, '', 104);
                        switch ($m_u['language']) {
                            case 'GER':
                                $log_title = 'Distress call from ';
                                break;
                            case 'ITA':
                                $log_title = 'Richiesta di soccorso dalla colonia ';
                                break;
                            default:
                                $log_title = 'Distress call from ';
                                break;
                        }
                        add_logbook_entry($m_u['user_id'], LOGBOOK_SETTLERS, $log_title . $this->dest['planet_name'], $log_data);
                    }
                }
            }
            // DC <<<< Settlers management
            // 01/07/08 - The attacker has lost the fleets
            for ($i = 0; $i < count($atk_fleets); ++$i) {
                $atk_losses[0] += $atk_fleets[$i]['unit_1'];
                $atk_losses[1] += $atk_fleets[$i]['unit_2'];
                $atk_losses[2] += $atk_fleets[$i]['unit_3'];
                $atk_losses[3] += $atk_fleets[$i]['unit_4'];
                $atk_losses[4] += $atk_fleets[$i]['resource_4'];
            }
        }
        // #############################################################################
        // Write logbook
        $log1_data = array(46, $this->move['user_id'], $this->move['start'], $this->start['planet_name'], $this->start['user_id'], $this->move['dest'], $this->dest['planet_name'], $this->dest['user_id'], MV_CMB_ATTACKER, $this->cmb[MV_CMB_WINNER] == MV_CMB_ATTACKER ? 1 : 0, 0, 0, $atk_fleets, $dfd_fleets);
        $log2_data = array(46, $this->move['user_id'], $this->move['start'], $this->start['planet_name'], $this->start['user_id'], $this->move['dest'], $this->dest['planet_name'], $this->dest['user_id'], MV_CMB_DEFENDER, $this->cmb[MV_CMB_WINNER] == MV_CMB_DEFENDER ? 1 : 0, 0, 0, $atk_fleets, $dfd_fleets);
        $log1_data[17] = $log2_data[17] = $action_status;
        $log1_data[20] = $this->dest['user_race'];
        $log2_data[20] = $this->move['user_race'];
        for ($i = 0; $i < 5; ++$i) {
            $log1_data[18][$i] = $log2_data[19][$i] = $atk_losses[$i];
            $log1_data[19][$i] = $log2_data[18][$i] = $dfd_losses[$i];
        }
        //$log1_data[19][4] = $log2_data[18][4] = (int)$dfd_losses[4]; already done by for above...
        $log2_data[14] = $this->cmb[MV_CMB_KILLS_PLANETARY];
        $log1_data[10] = $this->cmb[MV_CMB_KILLS_EXT];
        $log2_data[10] = $this->cmb[MV_CMB_KILLS_EXT];
        add_logbook_entry($this->move['user_id'], LOGBOOK_TACTICAL, $atk_title, $log1_data);
        add_logbook_entry($this->dest['user_id'], LOGBOOK_TACTICAL, $dfd_title, $log2_data);
        if ($n_st_user > 0) {
            $log2_data[2] = $this->move['dest'];
            $log2_data[3] = $this->dest['planet_name'];
            $log2_data[4] = $this->dest['user_id'];
            $log2_data[5] = 0;
            $log2_data[6] = 0;
            $log2_data[7] = 0;
            $log2_data[16] = 1;
            for ($i = 0; $i < $n_st_user; ++$i) {
                // #############################################################################
                // 03/04/08 - AC: Retrieve player language
                $log_title = 'One of your allies defended ' . $this->dest['planet_name'];
                $sql = 'SELECT language FROM user WHERE user_id = ' . $st_user[$i];
                if (!($lang = $this->db->queryrow($sql))) {
                    $this->log(MV_M_DATABASE, 'Could not retrieve player language');
                } else {
                    switch ($lang['language']) {
                        case 'GER':
                            $log_title = 'Verb&uuml;ndeten bei ' . $this->dest['planet_name'] . ' verteidigt';
                            break;
                        case 'ENG':
                            $log_title = 'Joined the defenders of the ' . $this->dest['planet_name'] . ' planet';
                            break;
                        case 'ITA':
                            $log_title = 'Difesa alleata presso ' . $this->dest['planet_name'];
                            break;
                    }
                }
                add_logbook_entry($st_user[$i], LOGBOOK_TACTICAL, $log_title, $log2_data);
            }
        }
        return MV_EXEC_OK;
    }
 function _action_main()
 {
     global $PLANETS_DATA, $RACE_DATA, $TECH_DATA, $TECH_NAME, $MAX_RESEARCH_LVL, $ACTUAL_TICK, $cfg_data;
     // #############################################################################
     // Away Team Missions!!!
     //
     // Beam us down! Energy!
     //
     //#############################################################################
     $tech_reward = array(5, 7, 7, 7, 10, 10, 10, 12, 12);
     // cache_mood è un array che raccoglie tutte le modifiche da apportare alla settlers_relations e viene svuotata alla fine
     // e inizializziamolo sto array, sennò php scassa le balle...
     $cache_mood = array(3 => 0, 4 => 0, 5 => 0, 6 => 0, 7 => 0, 8 => 0, 10 => 0, 11 => 0, 12 => 0, 13 => 0, 14 => 0, 15 => 0, 16 => 0, 17 => 0, 18 => 0, 19 => 0, 20 => 0, 21 => 0, 22 => 0, 23 => 0, 24 => 0, 25 => 0, 26 => 0, 27 => 0);
     $cache_event_sql = array();
     // $decrease_founder è un flag che ci dice, a fine missione, se dobbiamo abbassare il mood del Founder
     $decrease_founder = 0;
     $is_first_contact = false;
     $is_diplo_speech = false;
     $sql = 'SELECT s.ship_name, s.experience, s.awayteam, s.ship_id,
                     s.unit_1, s.unit_2, s.unit_3, s.unit_4,
                     t.name, t.min_unit_1, t.min_unit_2, t.min_unit_3, t.min_unit_4,
                     t.max_unit_1, t.max_unit_2, t.max_unit_3, t.max_unit_4
                     FROM ship_fleets f
                     LEFT JOIN ships s ON s.fleet_id = f.fleet_id
                     LEFT JOIN ship_templates t ON t.id = s.template_id
             WHERE f.fleet_id IN (' . $this->fleet_ids_str . ')';
     if (($ship_details = $this->db->queryrow($sql)) == false) {
         $this->log(MV_M_DATABASE, 'Could not read ship name! CONTINUE');
         $name_of_ship = '<i>Sconosciuto</i>';
     } else {
         if (!empty($ship_details['ship_name'])) {
             $name_of_ship = '<b>' . $ship_details['ship_name'] . '</b>';
         } else {
             $name_of_ship = '<b><i>&#171;' . $ship_details['name'] . '&#187;</i></b>';
         }
     }
     // Check Action Code
     if (!isset($this->action_data[0])) {
         // first item tell us the kind of mission we are going to do
         $this->log(MV_M_DATABASE, 'action_27: Could not find required action_data entry [0]! FORCED TO ZERO');
         $this->action_data[0] = 0;
     }
     if ($this->action_data[0] == 3 && !isset($this->action_data[1])) {
         // second item tell us more on the mission target
         // for tech mission:
         // - 0 = research_1 (higher rooms for ppl on planet, higher labourer rate)
         // - 1 = research_2 (higher labourer rate, will not be implemented)
         // - 2 = research_3 (better defense protection)
         // - 3 = research_4 (optimization of accademy, shipyards)
         // - 4 = research_5 (higher mines output)
         $this->log(MV_M_NOTICE, 'action_27: Could not find mission parameters [1]! FORCED TO -1');
         $this->action_data[1] = -1;
     }
     /**
      * Check planet's mood.
      */
     $sql = 'SELECT log_code FROM settlers_relations WHERE log_code IN (1, 2) AND planet_id = ' . $this->move['dest'] . ' AND user_id = ' . $this->move['user_id'];
     $log_query = $this->db->query($sql);
     $log_rows = $this->db->num_rows($log_query);
     if ($log_rows > 0) {
         $log_list = $this->db->fetchrowset($log_query);
         foreach ($log_list as $log_item) {
             switch ($log_item['log_code']) {
                 case 1:
                     $is_first_contact = true;
                     break;
                 case 2:
                     $is_diplo_speech = true;
                     break;
             }
         }
     }
     // Player mood
     $sql = 'SELECT SUM(mood_modifier) AS mood_user
             FROM settlers_relations
             WHERE planet_id = ' . $this->move['dest'] . ' AND
                   user_id = ' . $this->move['user_id'];
     if (($mood_user = $this->db->queryrow($sql)) === false) {
         return $this->log(MV_M_DATABASE, 'Could not read planet data! SKIP');
     }
     $mood['user'] = $mood_user['mood_user'];
     $mood['value'] = (!empty($mood['race']) ? $mood['race'] : 0) + (!empty($mood['alliance']) ? $mood['alliance'] : 0) + (!empty($mood['user']) ? $mood['user'] : 0);
     // Event check section
     // EVENT TABLE FORMAT
     // planet_id
     // user_id
     // event_code                                   < il codice ci dice anche se un evento è VISIBILE o NON VISIBILE
     // timestamp                                    < data e ora inizio evento
     // tick                                         < TICK inizio evento
     // awayteamship_id                              < id della nave che ha sbarcato la squadra
     // awayteam_startlevel                          < livello iniziale della squadra
     // unit_1                                       <
     // unit_2                                       <
     // unit_3                                       <
     // unit_4                                       <
     // awayteam_alive                               < 0 = la squadra è persa, 1 = la squadra è viva e recuperabile
     // event_status                                 < 0 = evento non più attivo, 1 = evento attivo
     // event_result                                 < 0 = evento concluso negativamente (bloccato), 1 = evento concluso positivamente
     // count_ok                                   <-----
     // count_crit_ok                              <   contatori usati per il calcolo dell'exp guadagnata al momento del recupero
     // count_ko                                   <
     // count_crit_ko                              <------
     $sql = 'SELECT * FROM settlers_events WHERE planet_id = ' . $this->move['dest'] . ' AND event_status = 1 ORDER BY timestamp ASC, event_code ASC';
     $ev_query = $this->db->query($sql);
     $ev_num = $this->db->num_rows($ev_query);
     if ($ev_num > 0) {
         $ev_list = $this->db->fetchrowset($ev_query);
         // Scansione della lista eventi, ordinati per cronologico e event_code. Eventi con codice basso sono prioritari e possono bloccare
         // la scansione della lista e l'esecuzione della mossa
         $halt_mission = FALSE;
         $res = $this->fetch_founder_mood($this->move['dest']);
         foreach ($ev_list as $event_row) {
             $new_event_code = $event_row['event_code'];
             $new_event_status = $event_row['event_status'];
             $new_event_result = $event_row['event_result'];
             $new_count_ok = $event_row['count_ok'];
             $new_count_ko = $event_row['count_ko'];
             $new_count_crit_ok = $event_row['count_crit_ok'];
             $new_count_crit_ko = $event_row['count_crit_ko'];
             $event_delete = FALSE;
             $changed = FALSE;
             switch ($event_row['event_code']) {
                 case '100':
                     // Terreno di Caccia - NASCOSTO. Si aggiorna il codice evento sul db e si esegue il codice 101
                     if ($event_row['user_id'] == $this->move['user_id']) {
                         break;
                     }
                     $new_event_code = '101';
                     $sql = 'UPDATE settlers_events SET event_code = ' . $new_event_code . ' WHERE planet_id = ' . $this->move['dest'] . ' AND event_code = ' . $event_row['event_code'] . ' AND user_id = ' . $event_row['user_id'];
                     if (!$this->db->query($sql)) {
                         return $this->log(MV_M_DATABASE, 'Could not update ship AT level!!! ' . $sql);
                     }
                 case '101':
                     // Terreno di Caccia - Può bloccare la missione - NON usa l'array cache_mood e scrive direttamente
                     if ($event_row['user_id'] == $this->move['user_id']) {
                         break;
                     }
                     if ($this->action_data[0] == 5) {
                         break;
                     }
                     $critical_test = rand(0, 10000);
                     $test_value = $ship_details['awayteam'] - $event_row['awayteam_startlevel'];
                     $log_data1 = array($this->move['dest'], $this->dest['planet_name'], $event_row['awayteamship_id'], 'N/A', 107, 0);
                     $log_title1 = 'Rapporto dei cacciatori su ' . $this->dest['planet_name'];
                     $log_data2 = array($this->move['dest'], $this->dest['planet_name'], $ship_details['ship_id'], $name_of_ship, 106, 0);
                     if ($test_value > 0) {
                         $critical_ko_chance = intval(7500 - 180 * ($ship_details['awayteam'] - $event_row['awayteam_startlevel']));
                         if ($critical_test > $critical_ko_chance) {
                             // La missione NEUTRALIZZA il TdC
                             $log_title2 = 'La tua missione su ' . $this->dest['planet_name'] . ' ha subito un agguato!';
                             $log_data1[5] = $log_data2[5] = -2;
                             $event_delete = TRUE;
                             $sql = 'UPDATE ships SET awayteam = 1, awayteamplanet_id = 0 WHERE ship_id = ' . $event_row['awayteamship_id'];
                             if (!$this->db->query($sql)) {
                                 return $this->log(MV_M_DATABASE, 'Could not update ship AT level!!! ' . $sql);
                             }
                         } else {
                             // La missione NON SUPERA il Terreno di Caccia
                             $changed = TRUE;
                             $log_title2 = 'La tua missione su ' . $this->dest['planet_name'] . ' &egrave; fallita!';
                             $this->do_simple_relation($event_row['user_id'], $event_row['planet_id'], LC_REL_PREDAT, 5);
                             $this->do_simple_relation($this->move['user_id'], $event_row['planet_id'], LC_REL_PREY, -5);
                             $new_count_ok += 1;
                             $halt_mission = TRUE;
                         }
                     } else {
                         $changed = TRUE;
                         $log_title2 = 'La tua missione su ' . $this->dest['planet_name'] . ' &egrave; fallita!';
                         // La missione NON SUPERA il Terreno di Caccia e viene uccisa!
                         $this->do_simple_relation($event_row['user_id'], $event_row['planet_id'], LC_REL_PREDAT, 10);
                         $this->do_simple_relation($this->move['user_id'], $event_row['planet_id'], LC_REL_PREY, -10);
                         $sql = 'UPDATE ships SET unit_1 = ' . $ship_details['min_unit_1'] . ', unit_2 = ' . $ship_details['min_unit_2'] . ', unit_3 = ' . $ship_details['min_unit_3'] . ', unit_4 = ' . $ship_details['min_unit_4'] . ', awayteam = 1 WHERE ship_id = ' . $ship_details['ship_id'];
                         if (!$this->db->query($sql)) {
                             return $this->log(MV_M_DATABASE, 'Could not create new settlers relations! SKIP!!!');
                         }
                         $log_data1[5] = $log_data2[5] = 1;
                         $new_count_crit_ok += 1;
                         $halt_mission = TRUE;
                     }
                     add_logbook_entry($event_row['user_id'], LOGBOOK_SETTLERS, $log_title1, $log_data1);
                     add_logbook_entry($this->move['user_id'], LOGBOOK_SETTLERS, $log_title2, $log_data2);
                     break;
                 case '102':
                     // Razziatori in attesa NASCOSTO
                     if ($event_row['user_id'] == $this->move['user_id']) {
                         break;
                     }
                     if ($this->action_data[0] != 3) {
                         break;
                     }
                     // Rimane nascosto finché non arriva una missione di supporto
                     $new_event_code = '103';
                     $sql = 'UPDATE settlers_events SET event_code = ' . $new_event_code . ' WHERE planet_id = ' . $this->move['dest'] . ' AND event_code = ' . $event_row['event_code'] . ' AND user_id = ' . $event_row['user_id'];
                     if (!$this->db->query($sql)) {
                         return $this->log(MV_M_DATABASE, 'Could not update ship AT level!!! ' . $sql);
                     }
                 case '103':
                     // Razziatori in attesa. Può bloccare la missione - NON usa l'array cache_mood e scrive direttamente
                     // Attende lo sbarco a terra di altre squadre nel tentativo di sottrarre la nave al proprietario
                     if ($event_row['user_id'] == $this->move['user_id']) {
                         break;
                     }
                     if ($this->action_data[0] == 5) {
                         break;
                     }
                     $check = rand(0, 1000);
                     $log_data1 = array($this->move['dest'], $this->dest['planet_name'], $event_row['awayteamship_id'], 'N/A', 109, 0);
                     $log_title1 = 'Rapporto della squadra su ' . $this->dest['planet_name'];
                     $log_data2 = array($this->move['dest'], $this->dest['planet_name'], $ship_details['ship_id'], $name_of_ship, 108, 0);
                     $test_value = $event_row['awayteam_startlevel'] - $ship_details['awayteam'];
                     if ($test_value > 0) {
                         $success_test = $test_value * 1.334 * 10;
                         if ($success_test > $check) {
                             // Successo CRITICO! La nave avversaria viene CATTURATA
                             $log_title2 = 'La tua missione su ' . $this->dest['planet_name'] . ' &egrave; fallita!';
                             $this->do_simple_relation($event_row['user_id'], $event_row['planet_id'], LC_REL_PREDAT, 10);
                             $this->do_simple_relation($this->move['user_id'], $event_row['planet_id'], LC_REL_PREY, -10);
                             $newatlevel = $event_row['awayteam_startlevel'] + $event_row['count_ok'] * 2.0 + 15.0;
                             $sql = 'UPDATE ships SET unit_1 = ' . $event_row['unit_1'] . ', unit_2 = ' . $event_row['unit_2'] . ', unit_3 = ' . $event_row['unit_3'] . ', unit_4 = ' . $event_row['unit_4'] . ',
                                                      awayteam = ' . $newatlevel . ', user_id = ' . $event_row['user_id'] . ', awayteamplanet_id = 0 WHERE ship_id = ' . $ship_details['ship_id'];
                             if (!$this->db->query($sql)) {
                                 return $this->log(MV_M_DATABASE, 'Could not update captured ship data! SKIP!!! ' . $sql);
                             }
                             $sql = 'UPDATE ship_fleets SET user_id = ' . $event_row['user_id'] . ', fleet_name = "Catturata" WHERE fleet_id = ' . $ship_details['fleet_id'];
                             if (!$this->db->query($sql)) {
                                 return $this->log(MV_M_DATABASE, 'Could not update captured fleet data! SKIP!!! ' . $sql);
                             }
                             $sql = 'UPDATE ships SET awayteam = 1, awayteamplanet_id = 0 WHERE ship_id = ' . $event_row['awayteamship_id'];
                             if (!$this->db->query($sql)) {
                                 return $this->log(MV_M_DATABASE, 'Could not update ship AT level!!! ' . $sql);
                             }
                             $log_data1[5] = $log_data2[5] = 1;
                             $event_delete = TRUE;
                             $halt_mission = TRUE;
                         } else {
                             // Successo! La squadra avversaria è battuta e viene respinta
                             $log_title2 = 'La tua missione su ' . $this->dest['planet_name'] . ' &egrave; fallita!';
                             $this->do_simple_relation($event_row['user_id'], $event_row['planet_id'], LC_REL_PREDAT, 5);
                             $this->do_simple_relation($this->move['user_id'], $event_row['planet_id'], LC_REL_PREY, -5);
                             $changed = TRUE;
                             $new_count_ok += 1;
                             $halt_mission = TRUE;
                         }
                     } else {
                         $failure_test = -1 * ($test_value * 1.334 * 10);
                         if ($failure_test > $check) {
                             // Fallimento CRITICO! I razziatori vengono UCCISI!
                             $log_title2 = 'La tua missione su ' . $this->dest['planet_name'] . ' ha subito un agguato!';
                             $log_data1[5] = $log_data2[5] = -2;
                             $event_delete = TRUE;
                             $sql = 'UPDATE ships SET awayteam = 1, awayteamplanet_id = 0 WHERE ship_id = ' . $event_row['awayteamship_id'];
                             if (!$this->db->query($sql)) {
                                 return $this->log(MV_M_DATABASE, 'Could not update ship AT level!!! ' . $sql);
                             }
                         } else {
                             // Fallimento!!! I razziatori non riescono a battere la squadra.
                             $log_title2 = 'La tua missione su ' . $this->dest['planet_name'] . ' ha subito un agguato!';
                             $log_data1[5] = $log_data2[5] = -1;
                             $changed = TRUE;
                             $new_count_ko += 1;
                         }
                     }
                     break;
                 case '120':
                     // Presidio Federale.
                     if ($this->action_data[0] != 3 && $this->action_data[0] != 4) {
                         break;
                     }
                     $new_count_ok += 1;
                     $new_event_result = 1;
                     $changed = TRUE;
                     $cache_mood[LC_REL_MULTIC] += $res[1] == $this->move['user_id'] ? 2 : 4;
                     break;
                 case '121':
                     // Presidio Romulano.
                     if ($this->action_data[0] != 3) {
                         break;
                     }
                     if ($res[1] == $this->move['user_id']) {
                         $cache_mood[LC_REL_TSUPER] += 3;
                         $new_count_ok += 1;
                         $new_event_result = 1;
                         $changed = TRUE;
                     }
                     break;
                 case '122':
                     // Presidio Klingon.
                     if ($this->action_data[0] != 3 && $this->action_data[0] != 4) {
                         break;
                     }
                     if ($res[1] == $this->move['user_id']) {
                         switch ($this->action_data[0]) {
                             case 3:
                                 $cache_mood[LC_REL_CHAMPN] += 4;
                                 break;
                             case 4:
                                 $cache_mood[LC_REL_DEFNDR] += 8;
                                 break;
                         }
                         $new_count_ok += 1;
                         $new_event_result = 1;
                         $changed = TRUE;
                         break;
                     }
                     if ($ship_details['awayteam'] > $event_row['awayteam_startlevel']) {
                         $cache_mood[LC_REL_CHAMPN] += 4;
                         $new_count_ko += 1;
                         $changed = TRUE;
                     }
                     break;
                 case '123':
                     // Presidio Cardassiano
                     if ($this->action_data[0] != 3 && $this->action_data[0] != 4) {
                         break;
                     }
                     if ($res[1] == $this->move['user_id']) {
                         switch ($this->action_data[0]) {
                             case 3:
                                 $cache_mood[LC_REL_INNVTR] += 2;
                                 break;
                             case 4:
                                 $cache_mood[LC_REL_INNVTR] += 3;
                                 break;
                         }
                         $new_count_ok += 1;
                         $new_event_result = 1;
                         $changed = TRUE;
                         break;
                     }
                     if ($event_row['awayteam_startlevel'] > $ship_details['awayteam']) {
                         $cache_mood[LC_REL_STRNGR] -= 5;
                         $new_count_crit_ok += 1;
                         $new_event_result = 1;
                         $changed = TRUE;
                     } else {
                         $cache_mood[LC_REL_INNVTR] += 5;
                         $new_count_ko += 1;
                         $changed = TRUE;
                     }
                     break;
                 case '124':
                     // Presidio Dominion
                     if ($this->action_data[0] != 3 && $this->action_data[0] != 4) {
                         break;
                     }
                     if ($res[1] == $this->move['user_id']) {
                         $cache_mood[LC_REL_WORSHP] += 2;
                         $new_count_ok += 1;
                         $new_event_result = 1;
                         $changed = TRUE;
                         break;
                     }
                     if ($ship_details['awayteam'] > $event_row['awayteam_startlevel']) {
                         $cache_mood[LC_REL_OPPSTR] += 5;
                         $new_count_ko += 1;
                         $changed = TRUE;
                     }
                     break;
                 case '130':
                     // Pluralismo
                     if ($this->action_data[0] != 3) {
                         break;
                     }
                     $sql = 'SELECT COUNT(log_code) AS speech_count FROM settlers_relations WHERE user_id <> ' . $res[1] . ' AND planet_id = ' . $this->move['dest'] . ' AND log_code = ' . LC_DIPLO_SPEECH;
                     $r1 = $this->db->queryrow($sql);
                     if ($res[1] == $this->move['user_id'] && $r1['speech_count'] > 0) {
                         $tech_data = $this->action_data[1];
                         switch ($tech_data) {
                             case 0:
                                 $cache_mood[LC_SUP_TECH] -= 1 * min($r1['speech_count'], 3);
                                 break;
                             case 1:
                                 $cache_mood[LC_SUP_MEDI] -= 1 * min($r1['speech_count'], 3);
                                 break;
                             case 2:
                                 $cache_mood[LC_SUP_DFNS] -= 1 * min($r1['speech_count'], 3);
                                 break;
                             case 3:
                                 $cache_mood[LC_SUP_AUTO] -= 1 * min($r1['speech_count'], 3);
                                 break;
                             case 4:
                                 $cache_mood[LC_SUP_MINE] -= 1 * min($r1['speech_count'], 3);
                                 break;
                         }
                         $new_count_crit_ok += 1;
                         $new_event_result = 1;
                         $changed = TRUE;
                         break;
                     }
                     if ($event_row['user_id'] == $this->move['user_id']) {
                         // $decrease_founder += 3;
                         $new_count_ok += 1;
                         $new_event_result = 1;
                         $changed = TRUE;
                     }
                     $cache_mood[LC_REL_PLURLS] += 3;
                     break;
                 case '131':
                     // Orgoglio del Pretore
                     if ($this->action_data[0] != 3) {
                         break;
                     }
                     if ($event_row['user_id'] == $this->move['user_id']) {
                         // $decrease_founder += 3;
                         $cache_mood[LC_REL_PRESTG] += 4;
                         $new_count_ok += 1;
                         $new_event_result = 1;
                         $changed = TRUE;
                         break;
                     }
                     if ($res[1] == $this->move['user_id']) {
                         $sql = 'SELECT research_' . ($this->action_data[1] + 1) . ' AS tech_level FROM planets p INNER JOIN user u ON u.user_capital = p.planet_id WHERE user_id = ' . $res[1];
                         $r1 = $this->db->queryrow($sql);
                         $sql = 'SELECT research_' . ($this->action_data[1] + 1) . ' AS tech_level FROM planets p INNER JOIN user u ON u.user_capital = p.planet_id WHERE user_id = ' . $event_row['user_id'];
                         $r2 = $this->db->queryrow($sql);
                         if (empty($r1['tech_level']) || empty($r2['tech_level']) || $r1['tech_level'] > $r2['tech_level']) {
                             // $decrease_founder += 3;
                             $cache_mood[LC_REL_PRESTG] += 5;
                             $new_count_ko += 1;
                             $changed = TRUE;
                         } else {
                             // $decrease_founder += 5;
                             $this->do_simple_relation($event_row['user_id'], $event_row['planet_id'], LC_REL_PRESTG, 5);
                             $new_count_crit_ok += 1;
                             $changed = TRUE;
                         }
                     }
                     break;
                 case '132':
                     // Addestramento Autodifesa
                     if ($this->action_data[0] != 4) {
                         break;
                     }
                     if ($event_row['user_id'] == $this->move['user_id']) {
                         // $decrease_founder += 8;
                         $cache_mood[LC_REL_DEFNDR] += 8;
                         $new_count_ok += 1;
                         $new_event_result = 1;
                         $changed = TRUE;
                     }
                     break;
                 case '133':
                     // Propaganda Sovversiva
                     if ($this->action_data[0] != 3 && $this->action_data[0] != 4) {
                         break;
                     }
                     if ($res[1] == $this->move['user_id'] && $event_row['awayteam_startlevel'] > $ship_details['awayteam']) {
                         $this->do_simple_relation($event_row['user_id'], $event_row['planet_id'], LC_REL_LIBERT, 5);
                         $cache_mood[LC_REL_EXPLOI] -= 3;
                         $new_count_crit_ok += 1;
                         $new_event_result = 1;
                         $changed = TRUE;
                     }
                     if ($event_row['user_id'] == $this->move['user_id']) {
                         // $decrease_founder += 2;
                         $cache_mood[LC_REL_LEADER] += 4;
                         $new_count_ok += 1;
                         $new_event_result = 1;
                         $changed = TRUE;
                     }
                     break;
                 case '134':
                     // Denunciare Incompetenza
                     if ($this->action_data[0] != 3 && $this->action_data[0] != 4) {
                         break;
                     }
                     if ($res[1] == $this->move['user_id'] && $event_row['awayteam_startlevel'] > $ship_details['awayteam']) {
                         $this->do_simple_relation($event_row['user_id'], $event_row['planet_id'], LC_REL_CMPTNT, 5);
                         $cache_mood[LC_REL_UNABLE] -= 3;
                         $new_count_crit_ok += 1;
                         $new_event_result = 1;
                         $changed = TRUE;
                     }
                     if ($event_row['user_id'] == $this->move['user_id']) {
                         // $decrease_founder += 2;
                         $cache_mood[LC_REL_MECENA] += 4;
                         $new_count_ok += 1;
                         $new_event_result = 1;
                         $changed = TRUE;
                     }
                     break;
             }
             if ($event_delete) {
                 $sql = 'DELETE FROM settlers_events WHERE planet_id = ' . $this->move['dest'] . ' AND event_code = ' . $event_row['event_code'] . ' AND user_id = ' . $event_row['user_id'];
                 $this->db->query($sql);
                 $changed = false;
             }
             if ($changed) {
                 $cache_event_sql[] = 'UPDATE settlers_events SET event_code = ' . $new_event_code . ', event_status = ' . $new_event_status . ', event_result = ' . $new_event_result . ',
                                                    count_ok = ' . $new_count_ok . ', count_ko = ' . $new_count_ko . ', count_crit_ok = ' . $new_count_crit_ok . ', count_crit_ko = ' . $new_count_crit_ko . '
                                WHERE planet_id = ' . $this->move['dest'] . ' AND event_code = ' . $event_row['event_code'] . ' AND user_id = ' . $event_row['user_id'];
             }
             if ($halt_mission) {
                 if (count($cache_event_sql) > 0) {
                     foreach ($cache_event_sql as $cached_query) {
                         if (!$this->db->query($cached_query)) {
                             return $this->log(MV_M_DATABASE, 'Could not update event data. SKIP!!! ' . $cached_query);
                         }
                     }
                 }
                 $this->action_data[0] = 99;
                 break;
             }
         }
         // if($decrease_founder > 0) $this->update_founder_mood($this->move['dest'], $decrease_founder);
     }
     // Diplo Section
     // In this section, good things happens
     switch ($this->action_data[0]) {
         /**
          * First contact mission.
          */
         case 0:
             switch ($this->move['language']) {
                 case 'GER':
                     $f_c_title = 'First contact on ';
                     $f_c_fail = ' failed';
                     $f_c_success = ' done';
                     break;
                 case 'ITA':
                     $f_c_title = 'Primo contatto su ';
                     $f_c_fail = ' fallito';
                     $f_c_success = ' avvenuto';
                     break;
                 default:
                     $f_c_title = 'First contact on ';
                     $f_c_fail = ' failed';
                     $f_c_success = ' done';
                     break;
             }
             $log_data = array(27, $this->move['user_id'], $this->move['start'], $this->start['planet_name'], $this->start['user_id'], $this->move['dest'], $this->dest['planet_name'], $this->dest['user_id'], 0);
             $log_data[8] = array('mission_type' => 0, 'mission_result' => 0);
             if ($is_first_contact) {
                 // Invalid move.
                 $log_data[8]['mission_result'] = -1;
                 add_logbook_entry($this->move['user_id'], LOGBOOK_TACTICAL_2, $f_c_title . $this->dest['planet_name'] . $f_c_fail, $log_data);
             } else {
                 if ($mood['value'] >= 0) {
                     // Mission successfully
                     // Insert First Contact record, log_code = 1
                     // If the player is President or Diplomatic, add alliance mood value
                     if (isset($this->move['user_alliance']) && !empty($this->move['user_alliance']) && $this->move['user_alliance_status'] > 2) {
                         $sql = 'INSERT INTO settlers_relations
                                 SET planet_id = ' . $this->move['dest'] . ',
                                     race_id = ' . $this->move['user_race'] . ',
                                     user_id = ' . $this->move['user_id'] . ',
                                     alliance_id = ' . $this->move['user_alliance'] . ',
                                     timestamp = ' . time() . ',
                                     log_code = ' . LC_FIRST_CONTACT . ',
                                     mood_modifier = 20';
                         if (!$this->db->query($sql)) {
                             return $this->log(MV_M_DATABASE, 'Could not create new settlers relations! SKIP!!!');
                         }
                     } else {
                         $sql = 'INSERT INTO settlers_relations
                                 SET planet_id = ' . $this->move['dest'] . ',
                                     race_id = ' . $this->move['user_race'] . ',
                                     user_id = ' . $this->move['user_id'] . ',
                                     timestamp = ' . time() . ',
                                     log_code = ' . LC_FIRST_CONTACT . ',
                                     mood_modifier = 10';
                         if (!$this->db->query($sql)) {
                             return $this->log(MV_M_DATABASE, 'Could not create new settlers relations! SKIP!!!');
                         }
                     }
                     // Calculate Exp of the mission
                     if ($ship_details['experience'] < 75) {
                         $actual_exp = $ship_details['experience'];
                         $exp = 2.7 / ((double) $actual_exp * 0.0635) + 1.5;
                         $sql = 'UPDATE ships SET experience = experience+' . $exp . ' WHERE ship_id = ' . $ship_details['ship_id'];
                         if (!$this->db->query($sql)) {
                             return $this->log(MV_M_DATABASE, 'Could not update ship exp! SKIP');
                         }
                     }
                     $awayteamlvl = round($ship_details['awayteam'], 0);
                     $exp_award = round(2.56 / $awayteamlvl, 3);
                     $ship_details['awayteam'] += $exp_award;
                     $sql = 'UPDATE ships SET awayteam = ' . $ship_details['awayteam'] . ' WHERE ship_id = ' . $ship_details['ship_id'];
                     if (!$this->db->query($sql)) {
                         return $this->log(MV_M_DATABASE, 'Could not update ship exp! SKIP');
                     }
                     $log_data[8]['mission_result'] = 1;
                     add_logbook_entry($this->move['user_id'], LOGBOOK_TACTICAL_2, $f_c_title . $this->dest['planet_name'] . $f_c_success, $log_data);
                 } else {
                     // Mission failed!
                     $log_data[8]['mission_result'] = -2;
                     add_logbook_entry($this->move['user_id'], LOGBOOK_TACTICAL_2, $f_c_title . $this->dest['planet_name'] . $f_c_fail, $log_data);
                 }
             }
             break;
             /**
              * Reconnaissance mission.
              */
         /**
          * Reconnaissance mission.
          */
         case 1:
             switch ($this->move['language']) {
                 case 'GER':
                     $f_c_title = 'Recon mission on ';
                     $f_c_fail = ' failed';
                     $f_c_success = ' done';
                     break;
                 case 'ITA':
                     $f_c_title = 'Ricognizione su ';
                     $f_c_fail = ' fallita';
                     $f_c_success = ' terminata';
                     break;
                 default:
                     $f_c_title = 'Recon mission on ';
                     $f_c_fail = ' failed';
                     $f_c_success = ' done';
                     break;
             }
             $log_data = array($this->move['dest'], $this->dest['planet_name'], $ship_details['ship_id'], $name_of_ship, 1, 0);
             // Mood Section
             $index = 0;
             $sql = 'SELECT sr.user_id, u.user_name, u.user_alliance, u.user_race, SUM(mood_modifier) as mood_value
                     FROM (settlers_relations sr)
                     LEFT JOIN (user u) ON sr.user_id = u.user_id
                     WHERE sr.user_id != ' . $this->move['user_id'] . ' AND
                           sr.planet_id = ' . $this->move['dest'] . '
                           GROUP BY sr.user_id ORDER BY mood_value
                     LIMIT 0,10';
             $user_mood_query = $this->db->query($sql);
             $user_mood_data = array();
             while ($user_mood_item = $this->db->fetchrow($user_mood_query)) {
                 $user_mood_data[$index] = $user_mood_item;
                 $index++;
             }
             $log_data[5] = array();
             $log_data[6] = array();
             $log_data[5]['user_mood'] = $mood['user'];
             $log_data[5]['toptenlist'] = $user_mood_data;
             // Tech section
             // We will display info on the tech we can teach to the planet, accordingly with RACE_DATA table, element 29
             $sql = 'SELECT MAX(research_1) as rescap1, MAX(research_2) as rescap2, MAX(research_3) as rescap3,
                          MAX(research_4) as rescap4, MAX(research_5) as rescap5
                   FROM planets WHERE planet_owner = ' . $this->move['user_id'];
             $rc_q = $this->db->queryrow($sql);
             if ($RACE_DATA[$this->move['user_race']][29][0]) {
                 $sql = 'SELECT research_start, research_finish
                         FROM scheduler_research WHERE planet_id = ' . $this->move['dest'] . '
                         AND player_id = ' . INDEPENDENT_USERID . ' AND research_id = 0';
                 $q_time = $this->db->queryrow($sql);
                 if (isset($q_time['research_finish']) && !empty($q_time['research_finish'])) {
                     $actual_lvl = $this->dest['research_1'] + 1;
                     if ($actual_lvl < 9 && $this->dest['research_1'] < $rc_q['rescap1']) {
                         $log_data[6]['research_1'] = true;
                         $log_data[6]['time_1'] = format_time(($q_time['research_finish'] - $ACTUAL_TICK) * TICK_DURATION);
                     }
                 } else {
                     if ($this->dest['research_1'] < 9 && $this->dest['research_1'] < $rc_q['rescap1']) {
                         $log_data[6]['research_1'] = true;
                     }
                 }
             }
             /*
                             if($this->dest['research_1'] < 9 && $RACE_DATA[$this->move['user_race']][29][0] && $this->dest['research_1'] < $rc_q['rescap1'])
                             {
                $log_data[6]['research_1'] = true;
                $sql = 'SELECT research_start, research_finish
                        FROM scheduler_research WHERE planet_id = '.$this->move['dest'].'
                        AND player_id = '.INDEPENDENT_USERID.' AND research_id = 0';
                if($q_time = $this->db->queryrow($sql))
                {
                    $log_data[6]['time_1'] = format_time(($q_time['research_finish'] - $ACTUAL_TICK)*TICK_DURATION);
                }
                             }
             * 
             */
             if ($RACE_DATA[$this->move['user_race']][29][1]) {
                 $sql = 'SELECT research_start, research_finish
                         FROM scheduler_research WHERE planet_id = ' . $this->move['dest'] . '
                         AND player_id = ' . INDEPENDENT_USERID . ' AND research_id = 1';
                 $q_time = $this->db->queryrow($sql);
                 if (isset($q_time['research_finish']) && !empty($q_time['research_finish'])) {
                     $actual_lvl = $this->dest['research_2'] + 1;
                     if ($actual_lvl < 9 && $this->dest['research_2'] < $rc_q['rescap2']) {
                         $log_data[6]['research_2'] = true;
                         $log_data[6]['time_2'] = format_time(($q_time['research_finish'] - $ACTUAL_TICK) * TICK_DURATION);
                     }
                 } else {
                     if ($this->dest['research_2'] < 9 && $this->dest['research_2'] < $rc_q['rescap2']) {
                         $log_data[6]['research_2'] = true;
                     }
                 }
             }
             if ($RACE_DATA[$this->move['user_race']][29][2]) {
                 $sql = 'SELECT research_start, research_finish
                         FROM scheduler_research WHERE planet_id = ' . $this->move['dest'] . '
                         AND player_id = ' . INDEPENDENT_USERID . ' AND research_id = 2';
                 $q_time = $this->db->queryrow($sql);
                 if (isset($q_time['research_finish']) && !empty($q_time['research_finish'])) {
                     $actual_lvl = $this->dest['research_3'] + 1;
                     if ($actual_lvl < 9 && $this->dest['research_3'] < $rc_q['rescap3']) {
                         $log_data[6]['research_3'] = true;
                         $log_data[6]['time_3'] = format_time(($q_time['research_finish'] - $ACTUAL_TICK) * TICK_DURATION);
                     }
                 } else {
                     if ($this->dest['research_3'] < 9 && $this->dest['research_3'] < $rc_q['rescap3']) {
                         $log_data[6]['research_3'] = true;
                     }
                 }
             }
             if ($RACE_DATA[$this->move['user_race']][29][3]) {
                 $sql = 'SELECT research_start, research_finish
                         FROM scheduler_research WHERE planet_id = ' . $this->move['dest'] . '
                         AND player_id = ' . INDEPENDENT_USERID . ' AND research_id = 3';
                 $q_time = $this->db->queryrow($sql);
                 if (isset($q_time['research_finish']) && !empty($q_time['research_finish'])) {
                     $actual_lvl = $this->dest['research_4'] + 1;
                     if ($actual_lvl < 9 && $this->dest['research_4'] < $rc_q['rescap4']) {
                         $log_data[6]['research_4'] = true;
                         $log_data[6]['time_4'] = format_time(($q_time['research_finish'] - $ACTUAL_TICK) * TICK_DURATION);
                     }
                 } else {
                     if ($this->dest['research_4'] < 9 && $this->dest['research_4'] < $rc_q['rescap4']) {
                         $log_data[6]['research_4'] = true;
                     }
                 }
             }
             if ($RACE_DATA[$this->move['user_race']][29][4]) {
                 $sql = 'SELECT research_start, research_finish
                         FROM scheduler_research WHERE planet_id = ' . $this->move['dest'] . '
                         AND player_id = ' . INDEPENDENT_USERID . ' AND research_id = 4';
                 $q_time = $this->db->queryrow($sql);
                 if (isset($q_time['research_finish']) && !empty($q_time['research_finish'])) {
                     $actual_lvl = $this->dest['research_5'] + 1;
                     if ($actual_lvl < 9 && $this->dest['research_5'] < $rc_q['rescap5']) {
                         $log_data[6]['research_5'] = true;
                         $log_data[6]['time_5'] = format_time(($q_time['research_finish'] - $ACTUAL_TICK) * TICK_DURATION);
                     }
                 } else {
                     if ($this->dest['research_5'] < 9 && $this->dest['research_5'] < $rc_q['rescap5']) {
                         $log_data[6]['research_5'] = true;
                     }
                 }
             }
             add_logbook_entry($this->move['user_id'], LOGBOOK_SETTLERS, $f_c_title . $this->dest['planet_name'] . $f_c_success, $log_data);
             break;
             /**
              * Diplomatic Agreement.
              */
         /**
          * Diplomatic Agreement.
          */
         case 2:
             switch ($this->move['language']) {
                 case 'GER':
                     $f_c_title = 'Diplo Speech on ';
                     $f_c_fail = ' failed';
                     $f_c_success = ' done';
                     break;
                 case 'ITA':
                     $f_c_title = 'Trattative Diplomatiche su ';
                     $f_c_fail = ' fallite';
                     $f_c_success = ' concluse';
                     break;
                 default:
                     $f_c_title = 'Diplo Speech on ';
                     $f_c_fail = ' failed';
                     $f_c_success = ' done';
                     break;
             }
             $log_data = array($this->move['dest'], $this->dest['planet_name'], $ship_details['ship_id'], $name_of_ship, 2, 0);
             if ($mood['value'] < 1) {
                 // Invalid move.
                 $log_title = $f_c_title . $this->dest['planet_name'] . $f_c_fail;
                 $log_data[5] = -1;
                 add_logbook_entry($this->move['user_id'], LOGBOOK_SETTLERS, $log_title, $log_data);
             } else {
                 // Check whether an agreement is still valid
                 $sql = 'SELECT log_code, mood_modifier
                         FROM settlers_relations
                         WHERE planet_id = ' . $this->move['dest'] . ' AND
                               user_id = ' . $this->move['user_id'] . ' AND
                               log_code = ' . LC_DIPLO_SPEECH;
                 if (($_qd = $this->db->queryrow($sql)) === false) {
                     return $this->log(MV_M_DATABASE, 'Could not read planet data! SKIP');
                 }
                 if (!empty($_qd['log_code']) && $_qd['log_code'] == LC_DIPLO_SPEECH && $_qd['mood_modifier'] > 0) {
                     // There's already a valid agreement, invalid move
                     $log_title = $f_c_title . $this->dest['planet_name'] . $f_c_fail;
                     $log_data[5] = -2;
                     add_logbook_entry($this->move['user_id'], LOGBOOK_SETTLERS, $log_title, $log_data);
                 } else {
                     $speech_value = 40;
                     $sql = 'SELECT threat_level FROM borg_target WHERE user_id = ' . $this->move['user_id'];
                     $bot_target_data = $this->db->query($sql);
                     $already_acquired = $this->db->num_rows($bot_target_data);
                     if ($already_acquired > 0) {
                         $honor_bonus_data = $this->db->fetchrow($bot_target_data);
                         // REMEMBER to keep this aligned with those present in borg.php!!
                         if ($honor_bonus_data['threat_level'] > 1400.0) {
                             $speech_value += 50;
                         } elseif ($honor_bonus_data['threat_level'] > 950.0) {
                             $speech_value += 35;
                         } elseif ($honor_bonus_data['threat_level'] > 450.0) {
                             $speech_value += 25;
                         } elseif ($honor_bonus_data['threat_level'] > 200.0) {
                             $speech_value += 15;
                         } else {
                             $speech_value += 10;
                         }
                     }
                     $sql = 'INSERT INTO settlers_relations
                             SET planet_id = ' . $this->move['dest'] . ',
                                 race_id = ' . $this->move['user_race'] . ',
                                 user_id = ' . $this->move['user_id'] . ',
                                 timestamp = ' . time() . ',
                                 log_code = ' . LC_DIPLO_SPEECH . ',
                                 mood_modifier = ' . $speech_value;
                     if (!$this->db->query($sql)) {
                         return $this->log(MV_M_DATABASE, 'Could not create new settlers relations! SKIP!!!');
                     }
                     // Calculate Exp of the mission
                     if ($ship_details['experience'] < 99) {
                         $actual_exp = $ship_details['experience'];
                         $exp = 2.9 / ((double) $actual_exp * 0.0635) + 2.5;
                         $sql = 'UPDATE ships SET experience = experience+' . $exp . ' WHERE ship_id = ' . $ship_details['ship_id'];
                         if (!$this->db->query($sql)) {
                             return $this->log(MV_M_DATABASE, 'Could not update ship exp! SKIP');
                         }
                     }
                     $awayteamlvl = round($ship_details['awayteam'], 0);
                     $exp_award = round(2.34 / $awayteamlvl, 3);
                     $ship_details['awayteam'] += $exp_award;
                     $sql = 'UPDATE ships SET awayteam = ' . $ship_details['awayteam'] . ' WHERE ship_id = ' . $ship_details['ship_id'];
                     if (!$this->db->query($sql)) {
                         return $this->log(MV_M_DATABASE, 'Could not update ship exp! SKIP');
                     }
                     $log_title = $f_c_title . $this->dest['planet_name'] . $f_c_success;
                     $log_data[6] = $speech_value;
                     add_logbook_entry($this->move['user_id'], LOGBOOK_SETTLERS, $log_title, $log_data);
                 }
             }
             break;
             /**
              * Tech Help
              */
         /**
          * Tech Help
          */
         case 3:
             switch ($this->move['language']) {
                 case 'GER':
                     $f_c_title = 'Tech Support on ';
                     $f_c_fail = ' failed';
                     $f_c_success = ' succesful';
                     break;
                 case 'ITA':
                     $f_c_title = 'Supporto tecnologico su ';
                     $f_c_fail = ' non fornito';
                     $f_c_success = ' fornito con successo';
                     break;
                 default:
                     $f_c_title = 'Tech Support on ';
                     $f_c_fail = ' failed';
                     $f_c_success = ' succesful';
                     break;
             }
             $log_data = array($this->move['dest'], $this->dest['planet_name'], $ship_details['ship_id'], $name_of_ship, 3, 0);
             if ($this->action_data[1] < 0) {
                 // Mission parameter invalid. Exit.
                 $log_title = $f_c_title . $this->dest['planet_name'] . $f_c_fail;
                 $log_data[5] = -1;
                 add_logbook_entry($this->move['user_id'], LOGBOOK_SETTLERS, $log_title, $log_data);
             }
             // A Treaty must exists on planet for this move to work
             if (!$is_diplo_speech) {
                 $log_title = $f_c_title . $this->dest['planet_name'] . $f_c_fail;
                 $log_data[5] = -5;
                 add_logbook_entry($this->move['user_id'], LOGBOOK_SETTLERS, $log_title, $log_data);
             }
             $tech_data = $this->action_data[1];
             if (!$RACE_DATA[$this->move['user_race']][$tech_data]) {
                 $log_title = $f_c_title . $this->dest['planet_name'] . $f_c_fail;
                 $log_data[5] = -6;
                 add_logbook_entry($this->move['user_id'], LOGBOOK_SETTLERS, $log_title, $log_data);
             }
             switch ($tech_data) {
                 case 0:
                     $_log_code = LC_SUP_TECH;
                     switch ($this->move['language']) {
                         case 'GER':
                             $log_data[7] = '<b>Environmental modification</b>';
                             break;
                         case 'ITA':
                             $log_data[7] = '<b>Modifica ambientale</b>';
                             break;
                         default:
                             $log_data[7] = '<b>Environmental modification</b>';
                             break;
                     }
                     break;
                 case 1:
                     $_log_code = LC_SUP_MEDI;
                     switch ($this->move['language']) {
                         case 'GER':
                             $log_data[7] = '<b>Medical research</b>';
                             break;
                         case 'ITA':
                             $log_data[7] = '<b>Ricerca medica</b>';
                             break;
                         default:
                             $log_data[7] = '<b>Medical research</b>';
                             break;
                     }
                     break;
                 case 2:
                     $_log_code = LC_SUP_DFNS;
                     switch ($this->move['language']) {
                         case 'GER':
                             $log_data[7] = '<b>Defenses upgrade</b>';
                             break;
                         case 'ITA':
                             $log_data[7] = '<b>Aggiornamento difese</b>';
                             break;
                         default:
                             $log_data[7] = '<b>Defenses upgrade</b>';
                             break;
                     }
                     break;
                 case 3:
                     $_log_code = LC_SUP_AUTO;
                     switch ($this->move['language']) {
                         case 'GER':
                             $log_data[7] = '<b>Automation</b>';
                             break;
                         case 'ITA':
                             $log_data[7] = '<b>Automazione</b>';
                             break;
                         default:
                             $log_data[7] = '<b>Automation</b>';
                             break;
                     }
                     break;
                 case 4:
                     $_log_code = LC_SUP_MINE;
                     switch ($this->move['language']) {
                         case 'GER':
                             $log_data[7] = '<b>Mining</b>';
                             break;
                         case 'ITA':
                             $log_data[7] = '<b>Estrazione</b>';
                             break;
                         default:
                             $log_data[7] = '<b>Mining</b>';
                             break;
                     }
                     break;
             }
             // Let's check if planet reached maximum research
             if ($this->dest['research_' . ($tech_data + 1)] >= 9) {
                 //Research cannot go tooo far!!! Exit.
                 $log_title = $f_c_title . $this->dest['planet_name'] . $f_c_fail;
                 $log_data[5] = -2;
                 add_logbook_entry($this->move['user_id'], LOGBOOK_SETTLERS, $log_title, $log_data);
             } else {
                 // Let's check if we can afford to supply this tech
                 $sql = 'SELECT MAX(research_' . ($tech_data + 1) . ') as rescap FROM planets WHERE planet_owner = ' . $this->move['user_id'];
                 $rc_q = $this->db->queryrow($sql);
                 if (!isset($rc_q['rescap']) || $rc_q['rescap'] <= $this->dest['research_' . ($tech_data + 1)]) {
                     // We can't do this!!!
                     $log_title = $f_c_title . $this->dest['planet_name'] . $f_c_fail;
                     $log_data[5] = -3;
                     add_logbook_entry($this->move['user_id'], LOGBOOK_SETTLERS, $log_title, $log_data);
                 }
             }
             // Let's check if someone else is already doing this mission.
             $sql = 'SELECT COUNT(*) as counter 
                     FROM scheduler_research WHERE planet_id = ' . $this->move['dest'] . '
                     AND research_id = ' . $tech_data;
             $c_q = $this->db->queryrow($sql);
             if (isset($c_q['counter']) && $c_q['counter'] > 0) {
                 // The research is already undergoing!!!
                 $log_title = $f_c_title . $this->dest['planet_name'] . $f_c_fail;
                 $log_data[5] = -4;
                 add_logbook_entry($this->move['user_id'], LOGBOOK_SETTLERS, $log_title, $log_data);
                 // refound the resources!
             }
             if ($log_data[5] == 0) {
                 // ALL GREEN: LET'S DO THIS
                 // Code taken from modules/researchlabs.php
                 $time = 0;
                 $time = $TECH_DATA[$tech_data][3] + pow($this->dest['research_' . ($tech_data + 1)], $TECH_DATA[$tech_data][4]);
                 $time *= $RACE_DATA[13][4];
                 // Settlers Race is 13
                 $time /= 100;
                 $time *= 100 - 2 * ($this->dest['research_4'] * $RACE_DATA[13][20]);
                 // Settlers Race is 13
                 if ($time < 1) {
                     $time = 1;
                 }
                 $time = round($time, 0);
                 $sql = 'INSERT INTO scheduler_research (research_id,planet_id,player_id,research_finish,research_start)
                         VALUES ("' . $tech_data . '","' . $this->move['dest'] . '","' . INDEPENDENT_USERID . '","' . ($ACTUAL_TICK + $time) . '","' . $ACTUAL_TICK . '")';
                 if (!$this->db->query($sql)) {
                     return $this->log(MV_M_DATABASE, 'Could not write research record for settlers research! SKIP!!!');
                 }
                 $log_data[8] = format_time($time * TICK_DURATION);
                 // Tech Rewards. Create a LC_TECH_SUPPORT/LC_DEF_SUPPORT entry on settlers_relations or upgrade it
                 $tech_value = $tech_reward[$this->dest['research_' . ($tech_data + 1)]];
                 // Calculate Exp of the mission
                 if ($ship_details['experience'] < 99) {
                     $actual_exp = $ship_details['experience'];
                     $exp = 2.9 / ((double) $actual_exp * 0.0635) + 2.5;
                     $sql = 'UPDATE ships SET experience = experience+' . $exp . ' WHERE ship_id = ' . $ship_details['ship_id'];
                     if (!$this->db->query($sql)) {
                         return $this->log(MV_M_DATABASE, 'Could not update ship exp! SKIP');
                     }
                 }
                 $awayteamlvl = round($ship_details['awayteam'], 0);
                 $exp_award = round(6.75 / $awayteamlvl, 3);
                 $ship_details['awayteam'] += $exp_award;
                 $sql = 'UPDATE ships SET awayteam = ' . $ship_details['awayteam'] . ' WHERE ship_id = ' . $ship_details['ship_id'];
                 if (!$this->db->query($sql)) {
                     return $this->log(MV_M_DATABASE, 'Could not update ship exp! SKIP');
                 }
                 $log_title = $f_c_title . $this->dest['planet_name'] . $f_c_success;
                 $log_data[6] = $tech_value;
                 $this->do_simple_relation($this->move['user_id'], $this->move['dest'], $_log_code, $tech_value);
                 // if($decrease_founder != 0) $this->update_founder_mood($this->move['dest'], $decrease_founder);
                 if (count($cache_event_sql)) {
                     foreach ($cache_event_sql as $cached_query) {
                         $this->db->query($cached_query);
                     }
                 }
                 foreach ($cache_mood as $key => $cache_mood_modifier) {
                     if ($cache_mood_modifier != 0) {
                         $this->do_simple_relation($this->move['user_id'], $this->move['dest'], $key, $cache_mood_modifier);
                         $log_data[9][] = $this->get_mood_text_string($key, $cache_mood_modifier);
                     }
                 }
                 add_logbook_entry($this->move['user_id'], LOGBOOK_SETTLERS, $log_title, $log_data);
             }
             break;
             /**
              * Orbital Defense Help
              */
         /**
          * Orbital Defense Help
          */
         case 4:
             switch ($this->move['language']) {
                 case 'GER':
                     $f_c_title = 'Orbital defense building on ';
                     $f_c_fail = ' not done';
                     $f_c_success = ' done';
                     break;
                 case 'ITA':
                     $f_c_title = 'Costruzione difese orbitali su ';
                     $f_c_fail = ' non ultimata';
                     $f_c_success = ' ultimata';
                     break;
                 default:
                     $f_c_title = 'Orbital defense building on ';
                     $f_c_fail = ' not done';
                     $f_c_success = ' done';
                     break;
             }
             $log_data = array($this->move['dest'], $this->dest['planet_name'], $ship_details['ship_id'], $name_of_ship, 4, 0);
             $sql = 'SELECT COUNT(*) as conto FROM settlers_relations WHERE planet_id = ' . $this->move['dest'] . ' AND user_id = ' . $this->move['user_id'] . ' AND log_code = ' . LC_DIPLO_SPEECH;
             if (!$is_diplo_speech) {
                 // A Treaty must exists on planet for this move to work
                 $log_title = $f_c_title . $this->dest['planet_name'] . $f_c_fail;
                 $log_data[5] = -2;
                 add_logbook_entry($this->move['user_id'], LOGBOOK_SETTLERS, $log_title, $log_data);
             }
             $sql = 'SELECT fleet_id FROM ship_fleets WHERE fleet_name = "Orbital' . $this->move['dest'] . '"';
             $od_q = $this->db->queryrow($sql);
             if (isset($od_q['fleet_id']) && !empty($od_q['fleet_id'])) {
                 $sql = 'SELECT COUNT(*) AS counter FROM ships WHERE fleet_id = ' . $od_q['fleet_id'];
                 $orbital_check = $this->db->queryrow($sql);
                 $orbital_counter = $orbital_check['counter'];
                 if ($orbital_counter >= STL_MAX_ORBITAL) {
                     $log_title = $f_c_title . $this->dest['planet_name'] . $f_c_fail;
                     $log_data[5] = -1;
                     add_logbook_entry($this->move['user_id'], LOGBOOK_SETTLERS, $log_title, $log_data);
                 }
             } else {
                 $orbital_counter = 0;
             }
             if ($log_data[5] == 0) {
                 $sql = 'SELECT value_5, value_9, rof, max_torp FROM `ship_templates`
                         WHERE `id` = ' . $cfg_data['settler_tmp_4'];
                 if (($stpl = $this->db->queryrow($sql)) === false) {
                     return $this->log(MV_M_DATABASE, '<b>Error:</b> Could not query settlers ship template data');
                 }
                 if ($orbital_counter > 1 && $orbital_counter < STL_MAX_ORBITAL) {
                     $fleet_id = $od_q['fleet_id'];
                     $orbital_to_made = min(STL_MAX_ORBITAL - $orbital_counter, 10);
                 } else {
                     // Orbital defence fleet not exists. Let's create this.
                     $sql = 'INSERT INTO ship_fleets (fleet_name, user_id, planet_id,
                                                      alert_phase, move_id, n_ships)
                             VALUES ("Orbital' . $this->move['dest'] . '", ' . INDEPENDENT_USERID . ', ' . $this->move['dest'] . ',
                                     ' . ALERT_PHASE_GREEN . ', 0, 10)';
                     $this->db->query($sql);
                     $fleet_id = $this->db->insert_id();
                     $orbital_to_made = 10;
                 }
                 $sql = 'INSERT INTO ships (fleet_id, user_id, template_id,
                                            experience, hitpoints, construction_time,
                                            torp, rof, last_refit_time)
                         VALUES (' . $fleet_id . ', ' . INDEPENDENT_USERID . ', ' . $cfg_data['settler_tmp_4'] . ',
                                 ' . $stpl['value_9'] . ', ' . $stpl['value_5'] . ', ' . time() . ',
                                 ' . $stpl['max_torp'] . ', ' . $stpl['rof'] . ', ' . time() . ')';
                 $tally = 0;
                 while ($tally < $orbital_to_made) {
                     if (!$this->db->query($sql)) {
                         return $this->log(MV_M_DATABASE, 'Error while adding an orbital cannon for Settlers ---> ' . $sql);
                     }
                     $tally++;
                 }
                 $log_title = $f_c_title . $this->dest['planet_name'] . $f_c_success;
                 if (count($cache_event_sql)) {
                     foreach ($cache_event_sql as $cached_query) {
                         $this->db->query($cached_query);
                     }
                 }
                 foreach ($cache_mood as $key => $cache_mood_modifier) {
                     if ($cache_mood_modifier != 0) {
                         $this->do_simple_relation($this->move['user_id'], $this->move['dest'], $key, $cache_mood_modifier);
                         $log_data[7][] = $this->get_mood_text_string($key, $cache_mood_modifier);
                     }
                 }
                 $log_data[6] = $tally;
                 add_logbook_entry($this->move['user_id'], LOGBOOK_SETTLERS, $log_title, $log_data);
                 // Calculate Exp of the mission
                 if ($ship_details['experience'] < 99) {
                     $actual_exp = $ship_details['experience'];
                     $exp = 2.9 / ((double) $actual_exp * 0.0635) + 2.5;
                     $sql = 'UPDATE ships SET experience = experience+' . $exp . ' WHERE ship_id = ' . $ship_details['ship_id'];
                     if (!$this->db->query($sql)) {
                         return $this->log(MV_M_DATABASE, 'Could not update ship exp! SKIP');
                     }
                 }
                 $awayteamlvl = round($ship_details['awayteam'], 0);
                 $exp_award = round(15.6 / $awayteamlvl, 3);
                 $ship_details['awayteam'] += $exp_award;
                 $sql = 'UPDATE ships SET awayteam = ' . $ship_details['awayteam'] . ' WHERE ship_id = ' . $ship_details['ship_id'];
                 if (!$this->db->query($sql)) {
                     return $this->log(MV_M_DATABASE, 'Could not update ship exp! SKIP');
                 }
             }
             break;
             /**
              * Rescue Mission
              */
         /**
          * Rescue Mission
          */
         case 5:
             $mission_exp = array(100 => 0, 101 => 80.0, 120 => 50.0, 121 => 50.0, 122 => 50.0, 123 => 50.0, 124 => 50.0, 130 => 70.0, 131 => 70.0, 132 => 70.0, 133 => 70.0, 134 => 70.0, 150 => 50.0);
             switch ($this->move['language']) {
                 case 'GER':
                     $f_c_title = 'Rescue mission on ';
                     $f_c_fail = ' not done';
                     $f_c_success = ' done';
                     break;
                 case 'ITA':
                     $f_c_title = 'Missione di recupero su ';
                     $f_c_fail = ' non ultimata';
                     $f_c_success = ' ultimata';
                     break;
                 default:
                     $f_c_title = 'Rescue mission on ';
                     $f_c_fail = ' not done';
                     $f_c_success = ' done';
                     break;
             }
             $log_data = array($this->move['dest'], $this->dest['planet_name'], $ship_details['ship_id'], $name_of_ship, 5, 0);
             // Cerchiamo la squadra a terra
             $sql = 'SELECT * from settlers_events WHERE planet_id = ' . $this->move['dest'] . ' AND user_id = ' . $this->move['user_id'];
             $rescue_data = $this->db->queryrow($sql);
             $crew_check = $ship_details['unit_1'] - $ship_details['min_unit_1'] + ($ship_details['unit_1'] - $ship_details['min_unit_1']) + ($ship_details['unit_1'] - $ship_details['min_unit_1']) + ($ship_details['unit_1'] - $ship_details['min_unit_1']);
             if ($crew_check > 0) {
                 $log_title = $f_c_title . $this->dest['planet_name'] . $f_c_fail;
                 $log_data[5] = -4;
                 add_logbook_entry($this->move['user_id'], LOGBOOK_SETTLERS, $log_title, $log_data);
             } elseif (!isset($rescue_data['event_code'])) {
                 $log_title = $f_c_title . $this->dest['planet_name'] . $f_c_fail;
                 $log_data[5] = -3;
                 add_logbook_entry($this->move['user_id'], LOGBOOK_SETTLERS, $log_title, $log_data);
             } elseif ($rescue_data['awayteam_alive'] == 0) {
                 $log_title = $f_c_title . $this->dest['planet_name'] . $f_c_fail;
                 $log_data[5] = -2;
                 add_logbook_entry($this->move['user_id'], LOGBOOK_SETTLERS, $log_title, $log_data);
                 $sql = 'UPDATE ships SET awayteam = 1, awayteamplanet_id = 0 WHERE ship_id = ' . $ship_details['ship_id'];
                 $this->db->query($sql);
             } elseif ($rescue_data['event_result'] == 0) {
                 $log_title = $f_c_title . $this->dest['planet_name'] . $f_c_success;
                 $log_data[5] = -1;
                 add_logbook_entry($this->move['user_id'], LOGBOOK_SETTLERS, $log_title, $log_data);
                 $new_unit_1 = min($ship_details['unit_1'] + $rescue_data['unit_1'], $ship_details['max_unit_1']);
                 $new_unit_2 = min($ship_details['unit_2'] + $rescue_data['unit_2'], $ship_details['max_unit_2']);
                 $new_unit_3 = min($ship_details['unit_3'] + $rescue_data['unit_3'], $ship_details['max_unit_3']);
                 $new_unit_4 = min($ship_details['unit_4'] + $rescue_data['unit_4'], $ship_details['max_unit_4']);
                 $sql = 'UPDATE ships SET awayteam = ' . $rescue_data['awayteam_startlevel'] . ', awayteamplanet_id = 0,
                                unit_1 = ' . $new_unit_1 . ', unit_2 = ' . $new_unit_2 . ', unit_3 = ' . $new_unit_3 . ' ,unit_4 = ' . $new_unit_4 . ' 
                         WHERE ship_id = ' . $ship_details['ship_id'];
                 if (!$this->db->query($sql)) {
                     return $this->log(MV_M_DATABASE, 'Could not update ship data! SQL DUMP 1: ' . $sql);
                 }
                 $sql = 'DELETE FROM settlers_events WHERE planet_id = ' . $this->move['dest'] . ' AND user_id = ' . $this->move['user_id'] . ' AND event_code = ' . $rescue_data['event_code'];
                 if (!$this->db->query($sql)) {
                     return $this->log(MV_M_DATABASE, 'Could not update settlers event data! SQL DUMP: ' . $sql);
                 }
             }
             // Preparazione Report e calcolo EXP
             if ($log_data[5] == 0) {
                 // Liberiamo la nave di partenza.
                 $sql = 'UPDATE ships SET awayteam = 1, awayteamplanet_id = 0 WHERE ship_id = ' . $rescue_data['awayteamship_id'];
                 $this->db->query($sql);
                 $this->log(MV_M_NOTICE, 'Liberando la nave di partenza dalla sua squadra: ' . $sql);
                 $new_unit_1 = min($ship_details['unit_1'] + $rescue_data['unit_1'], $ship_details['max_unit_1']);
                 $new_unit_2 = min($ship_details['unit_2'] + $rescue_data['unit_2'], $ship_details['max_unit_2']);
                 $new_unit_3 = min($ship_details['unit_3'] + $rescue_data['unit_3'], $ship_details['max_unit_3']);
                 $new_unit_4 = min($ship_details['unit_4'] + $rescue_data['unit_4'], $ship_details['max_unit_4']);
                 $base_exp = $mission_exp[$rescue_data['event_code']];
                 switch ($rescue_data['event_code']) {
                     case 150:
                         $base_exp = $base_exp + $rescue_data['count_ok'] * 30.0 + $rescue_data['count_crit_ok'] * 150.0;
                         break;
                     default:
                         $base_exp = $base_exp + $rescue_data['count_ok'] * 1.0 + $rescue_data['count_crit_ok'] * 10.0;
                 }
                 $awayteamlvl = round($rescue_data['awayteam_startlevel'], 0);
                 $exp_award = round($base_exp / $awayteamlvl, 3);
                 $sql = 'UPDATE ships SET awayteam = ' . ($rescue_data['awayteam_startlevel'] + $exp_award) . ', awayteamplanet_id = 0,
                                unit_1 = ' . $new_unit_1 . ', unit_2 = ' . $new_unit_2 . ', unit_3 = ' . $new_unit_3 . ' ,unit_4 = ' . $new_unit_4 . ' 
                         WHERE ship_id = ' . $ship_details['ship_id'];
                 if (!$this->db->query($sql)) {
                     return $this->log(MV_M_DATABASE, 'Could not update ship data! SQL DUMP 3: ' . $sql);
                 }
                 $sql = 'DELETE FROM settlers_events WHERE planet_id = ' . $this->move['dest'] . ' AND user_id = ' . $this->move['user_id'] . ' AND event_code = ' . $rescue_data['event_code'];
                 if (!$this->db->query($sql)) {
                     return $this->log(MV_M_DATABASE, 'Could not update settlers event data! SQL DUMP: ' . $sql);
                 }
                 $log_title = $f_c_title . $this->dest['planet_name'] . $f_c_success;
                 add_logbook_entry($this->move['user_id'], LOGBOOK_SETTLERS, $log_title, $log_data);
             }
             break;
             /**
              * Deploy mission
              */
         /**
          * Deploy mission
          */
         case 10:
             switch ($this->move['language']) {
                 case 'GER':
                     $f_c_title = 'AT deploy on ';
                     $f_c_fail = ' not done';
                     $f_c_success = ' done';
                     break;
                 case 'ITA':
                     $f_c_title = 'Sbarco della squadra su ';
                     $f_c_fail = ' non ultimato';
                     $f_c_success = ' ultimato';
                     break;
                 default:
                     $f_c_title = 'AT deploy on ';
                     $f_c_fail = ' not done';
                     $f_c_success = ' done';
                     break;
             }
             // Event codes
             $event_codes_table = array('0' => 100, '1' => 102, '10' => 120, '20' => 121, '30' => 122, '40' => 123, '50' => 124, '100' => 130, '110' => 131, '120' => 132, '130' => 133, '140' => 134, '150' => 150);
             $log_data = array($this->move['dest'], $this->dest['planet_name'], $ship_details['ship_id'], $name_of_ship, 10, 0);
             $e_c_i = $this->action_data[1];
             if ($ship_details['awayteam'] == 0) {
                 $log_title = $f_c_title . $this->dest['planet_name'] . $f_c_fail;
                 $log_data[5] = -5;
                 add_logbook_entry($this->move['user_id'], LOGBOOK_SETTLERS, $log_title, $log_data);
             } elseif (!isset($event_codes_table[$e_c_i])) {
                 $log_title = $f_c_title . $this->dest['planet_name'] . $f_c_fail;
                 $log_data[5] = -5;
                 add_logbook_entry($this->move['user_id'], LOGBOOK_SETTLERS, $log_title, $log_data);
             } elseif ($event_codes_table[$e_c_i] > 119 && !$is_diplo_speech) {
                 $log_title = $f_c_title . $this->dest['planet_name'] . $f_c_fail;
                 $log_data[5] = -7;
                 add_logbook_entry($this->move['user_id'], LOGBOOK_SETTLERS, $log_title, $log_data);
             } elseif ($event_codes_table[$e_c_i] == 150 && $RACE_DATA[$this->move['user_race']][30]) {
                 $log_title = $f_c_title . $this->dest['planet_name'] . $f_c_fail;
                 $log_data[5] = -5;
                 add_logbook_entry($this->move['user_id'], LOGBOOK_SETTLERS, $log_title, $log_data);
             } elseif ($event_codes_table[$e_c_i] == 150 && ($this->dest['planet_type'] != 'a' && $this->dest['planet_type'] != 'b' && $this->dest['planet_type'] != 'c' && $this->dest['planet_type'] != 'd' && $this->dest['planet_type'] != 'm' && $this->dest['planet_type'] != 'o' && $this->dest['planet_type'] != 'p')) {
                 $log_title = $f_c_title . $this->dest['planet_name'] . $f_c_fail;
                 $log_data[5] = -6;
                 add_logbook_entry($this->move['user_id'], LOGBOOK_SETTLERS, $log_title, $log_data);
             }
             $sql = 'SELECT user_id, mood_modifier FROM settlers_relations WHERE planet_id = ' . $this->move['dest'] . ' AND log_code = 30';
             $founder_q = $this->db->queryrow($sql);
             if (!isset($founder_q['user_id'])) {
                 $founder_q['user_id'] = 0;
                 $founder_q['mood_modifier'] = -1;
             }
             if ($event_codes_table[$e_c_i] >= 120 && $event_codes_table[$e_c_i] <= 124 && $this->move['user_id'] != $founder_q['user_id']) {
                 $log_title = $f_c_title . $this->dest['planet_name'] . $f_c_fail;
                 $log_data[5] = -4;
                 add_logbook_entry($this->move['user_id'], LOGBOOK_SETTLERS, $log_title, $log_data);
             } elseif ($event_codes_table[$e_c_i] >= 130 && $event_codes_table[$e_c_i] <= 134 && $this->move['user_id'] == $founder_q['user_id']) {
                 $log_title = $f_c_title . $this->dest['planet_name'] . $f_c_fail;
                 $log_data[5] = -3;
                 add_logbook_entry($this->move['user_id'], LOGBOOK_SETTLERS, $log_title, $log_data);
             } elseif ($founder_q['mood_modifier'] == -1 && ($event_codes_table[$e_c_i] >= 120 && $event_codes_table[$e_c_i] < 150)) {
                 $log_title = $f_c_title . $this->dest['planet_name'] . $f_c_fail;
                 $log_data[5] = -2;
                 add_logbook_entry($this->move['user_id'], LOGBOOK_SETTLERS, $log_title, $log_data);
             }
             $sql = 'SELECT COUNT(event_code) AS check_code FROM settlers_events WHERE planet_id = ' . $this->move['dest'] . ' AND user_id = ' . $this->move['user_id'];
             $mission_q = $this->db->queryrow($sql);
             if ($mission_q['check_code'] > 0) {
                 $log_title = $f_c_title . $this->dest['planet_name'] . $f_c_fail;
                 $log_data[5] = -1;
                 add_logbook_entry($this->move['user_id'], LOGBOOK_SETTLERS, $log_title, $log_data);
             }
             if ($log_data[5] == 0) {
                 $sql = 'INSERT INTO settlers_events
                                     (planet_id, user_id, event_code, timestamp, tick, awayteamship_id, awayteam_startlevel, unit_1, unit_2, unit_3, unit_4, awayteam_alive, event_status)
                             VALUES  (' . $this->move['dest'] . ', ' . $this->move['user_id'] . ', ' . $event_codes_table[$e_c_i] . ', ' . time() . ', ' . $ACTUAL_TICK . ', ' . $ship_details['ship_id'] . ', ' . $ship_details['awayteam'] . ',
                                      ' . ($ship_details['unit_1'] - $ship_details['min_unit_1']) . ', ' . ($ship_details['unit_2'] - $ship_details['min_unit_2']) . ', ' . ($ship_details['unit_3'] - $ship_details['min_unit_3']) . ', ' . ($ship_details['unit_4'] - $ship_details['min_unit_4']) . ', 1, 1)';
                 if (!$this->db->query($sql)) {
                     return $this->log(MV_M_DATABASE, 'Could not insert settlers event data! SKIP ' . $sql);
                 }
                 $sql = 'UPDATE ships SET awayteam = 0, awayteamplanet_id = ' . $this->move['dest'] . ', unit_1 = ' . $ship_details['min_unit_1'] . ', unit_2 = ' . $ship_details['min_unit_2'] . ', unit_3 = ' . $ship_details['min_unit_3'] . ', unit_4 = ' . $ship_details['min_unit_4'] . ' WHERE ship_id = ' . $ship_details['ship_id'];
                 $this->db->query($sql);
                 $log_title = $f_c_title . $this->dest['planet_name'] . $f_c_success;
                 add_logbook_entry($this->move['user_id'], LOGBOOK_SETTLERS, $log_title, $log_data);
             }
             break;
     }
     $old_besty = $this->check_best_mood($this->move['dest'], true);
     if ($old_besty > 0) {
         $log_data = array($this->move['dest'], $this->dest['planet_name'], 0, '', 100);
         switch ($this->move['language']) {
             case 'GER':
                 $log_title = 'Priority message from ';
                 break;
             case 'ITA':
                 $log_title = 'Comunicazione prioritaria dalla colonia ';
                 break;
             default:
                 $log_title = 'Priority message from ';
                 break;
         }
         add_logbook_entry($old_besty, LOGBOOK_SETTLERS, $log_title . $this->dest['planet_name'], $log_data);
         $this->db->query('UPDATE planets SET best_mood_planet = NULL WHERE planet_id = ' . $this->move['dest']);
     }
     $sql = 'UPDATE ship_fleets
             SET planet_id = ' . $this->move['dest'] . ',
                 move_id = 0
             WHERE fleet_id IN (' . $this->fleet_ids_str . ')';
     if (!$this->db->query($sql)) {
         return $this->log(MV_M_DATABASE, 'Could not update fleets data! SKIP');
     }
     return MV_EXEC_OK;
 }
 function _action_main()
 {
     // #############################################################################
     // Data of the attacker
     $sql = 'SELECT fleet_id
     FROM ship_fleets
     WHERE planet_id = ' . $this->move['dest'] . ' AND
           user_id = ' . $this->move['user_id'] . ' AND
           alert_phase >= ' . ALERT_PHASE_YELLOW;
     if (!($q_atk_st_fleets = $this->db->query($sql))) {
         return $this->log(MV_M_DATABASE, 'Could not query stationated attacker fleet data! SKIP');
     }
     $atk_fleet_ids_str = $this->fleet_ids_str;
     while ($_fleet = $this->db->fetchrow($q_atk_st_fleets)) {
         $atk_fleet_ids_str .= ',' . $_fleet['fleet_id'];
     }
     $sql = 'SELECT ' . $this->get_combat_query_fleet_columns() . '
     FROM (ship_fleets f)
     INNER JOIN user u ON u.user_id = f.user_id
     WHERE f.fleet_id IN (' . $atk_fleet_ids_str . ')';
     if (($atk_fleets = $this->db->queryrowset($sql)) === false) {
         return $this->log(MV_M_DATABASE, 'Could not query attackers fleets data! SKIP');
     }
     // #############################################################################
     // Data of the defender
     $sql = 'SELECT DISTINCT f.user_id,
            u.user_alliance,
            ud.ud_id, ud.accepted,
            ad.ad_id, ad.type, ad.status
     FROM (ship_fleets f)
     INNER JOIN user u ON u.user_id = f.user_id
     LEFT JOIN user_diplomacy ud ON ( ( ud.user1_id = ' . $this->dest['user_id'] . ' AND ud.user2_id = f.user_id ) OR ( ud.user1_id = f.user_id AND ud.user2_id = ' . $this->dest['user_id'] . ' ) )
     LEFT JOIN alliance_diplomacy ad ON ( ( ad.alliance1_id = ' . $this->dest['user_alliance'] . ' AND ad.alliance2_id = u.user_alliance) OR ( ad.alliance1_id = u.user_alliance AND ad.alliance2_id = ' . $this->dest['user_alliance'] . ' ) )
     WHERE f.planet_id = ' . $this->move['dest'] . ' AND
           f.user_id <> ' . $this->dest['user_id'] . ' AND
           f.user_id <> ' . $this->move['user_id'] . ' AND
           f.alert_phase >= ' . ALERT_PHASE_YELLOW;
     if (!($q_st_uid = $this->db->query($sql))) {
         return $this->log(MV_M_DATABASE, 'Could not query stationated fleets user data! SKIP');
     }
     $st_user = array();
     while ($st_uid = $this->db->fetchrow($q_st_uid)) {
         $allied = false;
         if ($st_uid['user_alliance'] == $this->dest['user_alliance']) {
             $allied = true;
         }
         if (!empty($st_uid['ud_id'])) {
             if ($st_uid['accepted'] == 1) {
                 $allied = true;
             }
         }
         if (!empty($st_uid['ad_id'])) {
             if ($st_uid['type'] == ALLIANCE_DIPLOMACY_PACT && $st_uid['status'] == 0) {
                 $allied = true;
             }
         }
         if ($allied) {
             $st_user[] = $st_uid['user_id'];
         }
     }
     $n_st_user = count($st_user);
     if ($n_st_user > 0) {
         $sql = 'SELECT  ' . $this->get_combat_query_fleet_columns() . '
          FROM (ship_fleets f)
          INNER JOIN user u ON u.user_id = f.user_id
          WHERE f.planet_id = ' . $this->move['dest'] . ' AND
               (
                  (
                    f.user_id = ' . $this->dest['user_id'] . '
                  )
                  OR
                  (
                    f.user_id IN (' . implode(',', $st_user) . ') AND
                    f.alert_phase >= ' . ALERT_PHASE_YELLOW . '
                  )
                )';
     } else {
         $sql = 'SELECT  ' . $this->get_combat_query_fleet_columns() . '
          FROM (ship_fleets f)
          INNER JOIN user u ON u.user_id = f.user_id
          WHERE f.planet_id = ' . $this->move['dest'] . ' AND
                f.user_id = ' . $this->dest['user_id'];
     }
     if (($dfd_fleets = $this->db->queryrowset($sql)) === false) {
         return $this->log(MV_M_DATABASE, 'Could not query defenders fleets data! SKIP');
     }
     $dfd_fleet_ids = array();
     foreach ($dfd_fleets as $i => $cur_fleet) {
         $dfd_fleet_ids[] = $cur_fleet['fleet_id'];
     }
     $dfd_fleet_ids_str = implode(',', $dfd_fleet_ids);
     if ($this->do_ship_combat($atk_fleet_ids_str, $dfd_fleet_ids_str, MV_COMBAT_LEVEL_ORBITAL) == MV_EXEC_ERROR) {
         $this->log(MV_M_DATABASE, 'Move Action 42: Something went wrong with this fight!');
         return MV_EXEC_ERROR;
     }
     // #############################################################################
     // Possibly return the remaining ships again to the attacker
     if ($this->cmb[MV_CMB_WINNER] == MV_CMB_ATTACKER) {
         $sql = 'SELECT COUNT(ship_id) AS n_ships
         FROM ships
         WHERE fleet_id IN (' . $this->fleet_ids_str . ')';
         if (($ships_alive = $this->db->queryrow($sql)) === false) {
             return $this->log(MV_M_DATABASE, 'Could not query ships count! SKIP');
         }
         $sql = 'INSERT INTO scheduler_shipmovement (user_id, move_status, move_exec_started, start, dest, total_distance, remaining_distance, tick_speed, move_begin, move_finish, n_ships, action_code, action_data)
         VALUES (' . $this->move['user_id'] . ', 0, 0, ' . $this->move['dest'] . ', ' . $this->move['start'] . ', ' . $this->move['total_distance'] . ', ' . $this->move['total_distance'] . ', ' . $this->move['tick_speed'] . ', ' . $this->CURRENT_TICK . ', ' . ($this->CURRENT_TICK + ($this->move['move_finish'] - $this->move['move_begin'])) . ', ' . $ships_alive['n_ships'] . ', 12, "' . serialize(42) . '")';
         if (!$this->db->query($sql)) {
             return $this->log(MV_M_DATABASE, 'Could not create new movement for return! SKIP');
         }
         $new_move_id = $this->db->insert_id();
         if (!$new_move_id) {
             return $this->log(MV_M_ERROR, 'Could not get new move id! SKIP');
         }
         $sql = 'UPDATE ship_fleets
         SET move_id = ' . $new_move_id . '
         WHERE fleet_id IN (' . $this->fleet_ids_str . ')';
         if (!$this->db->query($sql)) {
             return $this->log(MV_M_DATABASE, 'Could not update fleets movement data! SKIP');
         }
         // #############################################################################
         // 02/04/08 - AC: Retrieve player language
         switch ($this->move['language']) {
             case 'GER':
                 $atk_title = 'Angriff auf ' . $this->dest['planet_name'] . ' erfolgreich';
                 break;
             case 'ITA':
                 $atk_title = 'Attacco su ' . $this->dest['planet_name'] . ' riuscito';
                 break;
             default:
                 $atk_title = 'Attack on ' . $this->dest['planet_name'] . ' successful';
                 break;
         }
         switch ($this->dest['language']) {
             case 'GER':
                 $dfd_title = 'Schwerer Angriff auf ' . $this->dest['planet_name'];
                 break;
             case 'ITA':
                 $dfd_title = 'Attacco fatale su ' . $this->dest['planet_name'];
                 break;
             default:
                 $dfd_title = 'Fatal attack on ' . $this->dest['planet_name'];
                 break;
         }
     } else {
         // #############################################################################
         // 02/04/08 - AC: Retrieve player language
         switch ($this->move['language']) {
             case 'GER':
                 $atk_title = 'Angriff auf ' . $this->dest['planet_name'] . ' fehlgeschlagen';
                 break;
             case 'ITA':
                 $atk_title = 'Attacco su ' . $this->dest['planet_name'] . ' fallito';
                 break;
             default:
                 $atk_title = 'Attack on ' . $this->dest['planet_name'] . ' failed';
                 break;
         }
         switch ($this->dest['language']) {
             case 'GER':
                 $dfd_title = 'Verteidigung von ' . $this->dest['planet_name'] . ' erfolgreich';
                 break;
             case 'ITA':
                 $dfd_title = 'Difesa di ' . $this->dest['planet_name'] . ' riuscita';
                 break;
             default:
                 $dfd_title = 'Defence of ' . $this->dest['planet_name'] . ' successful';
                 break;
         }
     }
     // #############################################################################
     // Write logbook
     $log1_data = array(41, $this->move['user_id'], $this->move['start'], $this->start['planet_name'], $this->start['user_id'], $this->move['dest'], $this->dest['planet_name'], $this->dest['user_id'], MV_CMB_ATTACKER, $this->cmb[MV_CMB_WINNER] == MV_CMB_ATTACKER ? 1 : 0, 0, 0, $atk_fleets, $dfd_fleets);
     $log2_data = array(41, $this->move['user_id'], $this->move['start'], $this->start['planet_name'], $this->start['user_id'], $this->move['dest'], $this->dest['planet_name'], $this->dest['user_id'], MV_CMB_DEFENDER, $this->cmb[MV_CMB_WINNER] == MV_CMB_DEFENDER ? 1 : 0, 0, 0, $atk_fleets, $dfd_fleets, $this->cmb[MV_CMB_KILLS_PLANETARY]);
     $log1_data[10] = $this->cmb[MV_CMB_KILLS_EXT];
     $log2_data[10] = $this->cmb[MV_CMB_KILLS_EXT];
     add_logbook_entry($this->move['user_id'], LOGBOOK_TACTICAL_2, $atk_title, $log1_data);
     add_logbook_entry($this->dest['user_id'], LOGBOOK_TACTICAL_2, $dfd_title, $log2_data);
     if ($n_st_user > 0) {
         $log2_data[2] = $this->move['dest'];
         $log2_data[3] = $this->dest['planet_name'];
         $log2_data[4] = $this->dest['user_id'];
         $log2_data[5] = 0;
         $log2_data[6] = 0;
         $log2_data[7] = 0;
         $log2_data[16] = 1;
         for ($i = 0; $i < $n_st_user; ++$i) {
             // #############################################################################
             // 02/04/08 - AC: Retrieve player language
             $log_title = 'One of your allies defended ' . $this->dest['planet_name'];
             $sql = 'SELECT language FROM user WHERE user_id = ' . $st_user[$i];
             if (!($lang = $this->db->queryrow($sql))) {
                 $this->log(MV_M_DATABASE, 'Could not retrieve player language');
             } else {
                 switch ($lang['language']) {
                     case 'GER':
                         $log_title = 'Verb&uuml;ndeten bei ' . $this->dest['planet_name'] . ' verteidigt';
                         break;
                     case 'ITA':
                         $log_title = 'Difesa alleata presso ' . $this->dest['planet_name'];
                         break;
                 }
             }
             add_logbook_entry($st_user[$i], LOGBOOK_TACTICAL_2, $log_title, $log2_data);
         }
     }
     return MV_EXEC_OK;
 }
Exemple #6
0
 while (($user = $db->fetchrow($player_qry)) == true) {
     $sdl->log('1');
     $log_data = array('resource_1' => round($resource[0], 0), 'resource_2' => round($resource[1], 0), 'resource_3' => round($resource[2], 0));
     $sdl->log('2');
     /* 16/05/08 - AC: Add logbook title translation */
     $log_title = 'Ferengi Taxes';
     switch ($user['language']) {
         case 'GER':
             $log_title = 'Ferengisteuer';
             break;
         case 'ITA':
             $log_title = 'Tasse Ferengi';
             break;
     }
     /* */
     add_logbook_entry($user['user_id'], LOGBOOK_FERENGITAX, $log_title, $log_data);
     $sdl->log('3');
     $res = $resource[0] + $resource[1] + $resource[2];
     $ships = ceil($res / MAX_TRANSPORT_RESOURCES);
     if (1 == $user['planet_system']) {
         $distance = 6;
     } else {
         $distance = get_distance(array(5, 7), array($user['system_global_x'], $user['system_global_y']));
         $velocity = warpf(6);
         $distance = ceil($distance / $velocity / TICK_DURATION);
     }
     $db->query('INSERT INTO scheduler_resourcetrade (planet,resource_1,resource_2,resource_3,arrival_time) VALUES ("' . $user['user_capital'] . '","' . $resource[0] . '","' . $resource[1] . '","' . $resource[2] . '","' . ($ACTUAL_TICK + $distance) . '")');
     //send_fake_transporter(array(FERENGI_TRADESHIP_ID=>$ships), FERENGI_USERID,5 ,$user['user_capital']);
     $sdl->log('4: ' . $distance);
     $sdl->log('5');
     $sdl->log('Paid ' . $user['user_name'] . ' (' . $user['user_id'] . ')!');
 function _action_main()
 {
     if ($this->flags['combat_happened']) {
         $sql = 'UPDATE ship_fleets
                 SET planet_id = ' . $this->move['dest'] . ',
                     move_id = 0
                 WHERE fleet_id = ' . $this->fleet_ids[0];
         if (!$this->db->query($sql)) {
             return $this->log(MV_M_DATABASE, 'Could not update ships position data');
         }
         return MV_EXEC_OK;
     }
     if ($this->flags['free_dest_planet']) {
         $sql = 'UPDATE ship_fleets
                 SET planet_id = ' . $this->move['dest'] . ',
                     move_id = 0
                 WHERE fleet_id = ' . $this->fleet_ids[0];
         if (!$this->db->query($sql)) {
             return $this->log(MV_M_DATABASE, 'Could not update ships position data');
         }
         return MV_EXEC_OK;
     }
     $this->tr_data = $this->action_data;
     $this->tr_data[5] *= 2;
     if ($this->tr_data[5] < 0) {
         $this->tr_data[5] = -1;
     }
     // On which planet we are arrived?
     if ($this->move['dest'] == $this->tr_data[2]) {
         $this->actions =& $this->tr_data[4];
     } else {
         $this->actions =& $this->tr_data[3];
     }
     $this->log(MV_M_NOTICE, 'Buondi! Sono quello della flotta <b>' . $this->fleet_ids[0] . '</b> del Boss <b>' . $this->move['user_id'] . '</b>, in arrivo sul pianeta <b>' . $this->dest['planet_id'] . '</b> che appartiene a <b>' . $this->dest['user_id'] . '</b> per un trasporto.');
     $sql = 'SELECT resource_1, resource_2, resource_3, resource_4, unit_1, unit_2, unit_3, unit_4, unit_5, unit_6
             FROM ship_fleets
             WHERE fleet_id = ' . $this->fleet_ids[0];
     if (($this->fleet = $this->db->queryrow($sql)) === false) {
         return $this->log(MV_M_DATABASE, 'Could not query fleet data');
     }
     $sql = 'SELECT COUNT(s.ship_id) AS n_transporter
             FROM (ships s, ship_templates st)
             WHERE s.fleet_id = ' . $this->fleet_ids[0] . ' AND
                   st.id = s.template_id AND
                   st.ship_torso = ' . SHIP_TYPE_TRANSPORTER;
     if (($n_transporter = $this->db->queryrow($sql)) === false) {
         return $this->log(MV_M_DATABASE, 'Could not query n_transporter data');
     }
     $this->fleet['max_resources'] = $n_transporter['n_transporter'] * MAX_TRANSPORT_RESOURCES;
     $this->fleet['max_units'] = $n_transporter['n_transporter'] * MAX_TRANSPORT_UNITS;
     /* START OF RULE TO AVOID ROUTES BETWEEN SITTER AND SITTED */
     $route_blocked = false;
     $sql = 'SELECT user_sitting_id1, user_sitting_id2, user_sitting_id3,
                    user_sitting_id4, user_sitting_id5
             FROM user
             WHERE user_id = ' . $this->move['user_id'];
     if (($move_sitters = $this->db->queryrow($sql)) === false) {
         return $this->log(MV_M_DATABASE, 'Could not query sitters data of the move owner');
     }
     $sql = 'SELECT user_sitting_id1, user_sitting_id2, user_sitting_id3,
                    user_sitting_id4, user_sitting_id5
             FROM user
             WHERE user_id = ' . $this->dest['user_id'];
     if (($dest_sitters = $this->db->queryrow($sql)) === false) {
         return $this->log(MV_M_DATABASE, 'Could not query sitters data of the dest owner');
     }
     if ($move_sitters['user_sitting_id1'] == $this->dest['user_id'] || $move_sitters['user_sitting_id2'] == $this->dest['user_id'] || $move_sitters['user_sitting_id3'] == $this->dest['user_id'] || $move_sitters['user_sitting_id4'] == $this->dest['user_id'] || $move_sitters['user_sitting_id5'] == $this->dest['user_id']) {
         $route_blocked = true;
         $log_message = 'Trade route between sitter <b>' . $this->dest['user_id'] . '</b> and sitted <b>' . $this->move['user_id'] . '</b> are forbidden!!!';
     }
     if ($dest_sitters['user_sitting_id1'] == $this->move['user_id'] || $dest_sitters['user_sitting_id2'] == $this->move['user_id'] || $dest_sitters['user_sitting_id3'] == $this->move['user_id'] || $dest_sitters['user_sitting_id4'] == $this->move['user_id'] || $dest_sitters['user_sitting_id5'] == $this->move['user_id']) {
         $route_blocked = true;
         $log_message = 'Trade route between sitter <b>' . $this->move['user_id'] . '</b> and sitted <b>' . $this->dest['user_id'] . '</b> are forbidden!!!';
     }
     if ($route_blocked) {
         switch ($this->move['language']) {
             case 'GER':
                 $message = 'Hallo ' . $this->move['user_name'] . ',<br>Handelswege zwischen Sitter und sitted Konto sind verboten.<br>Diese Nachricht wurde automatisch generiert, Beschwerden beim STFC2-Team bringen nichts.<br>~ Sitting-Abuse-Automatik';
                 $title = 'Routesperre';
                 break;
             case 'ITA':
                 $message = 'Ciao ' . $this->move['user_name'] . ',<br>le rotte commerciali tra account sitter e sittato non sono ammesse.<br>Questo messaggio &egrave; stato generato automaticamente, lamentele al team di STFC2 sono inutili.<br>~ Sistema anti abuso sitting';
                 $title = 'Rotta bloccata';
                 break;
             default:
                 $message = 'Hello ' . $this->move['user_name'] . ',<br>trade routes between sitter and sitted account are forbidden.<br>This message is automatically generated complaints to the team STFC2 are useless.<br>~Sitting Abuse Prevention System';
                 $title = 'Route blocked';
                 break;
         }
     }
     /* END OF RULE TO AVOID ROUTES BETWEEN SITTER AND SITTED */
     /* START OF RULE TO AVOID ROUTES WITH SETTLERS */
     if ($this->dest['user_id'] == INDEPENDENT_USERID) {
         $route_blocked = true;
         switch ($this->move['language']) {
             case 'GER':
                 $message = 'Hallo ' . $this->move['user_name'] . ',<br>Handelswege mit Siedler sind verboten.<br>Diese Nachricht wurde automatisch generiert, Beschwerden beim STFC2-Team bringen nichts.<br>~ Siedler-Abuse-Automatik';
                 $title = 'Routesperre';
                 break;
             case 'ITA':
                 $message = 'Ciao ' . $this->move['user_name'] . ',<br>le rotte commerciali con i Coloni non sono ammesse.<br>Questo messaggio &egrave; stato generato automaticamente, lamentele al team di STFC2 sono inutili.<br>~ Sistema anti abuso Coloni';
                 $title = 'Rotta bloccata';
                 break;
             default:
                 $message = 'Hello ' . $this->move['user_name'] . ',<br>trade routes with Settlers are forbidden.<br>This message is automatically generated complaints to the team STFC2 are useless.<br>~Settlers Abuse Prevention System';
                 $title = 'Route blocked';
                 break;
         }
         $log_message = 'Trade route between user <b>' . $this->move['user_id'] . '</b> and Settlers are forbidden!!!';
     }
     /* END OF RULE TO AVOID ROUTES WITH SETTLERS */
     // Route not allowed: log it, inform the admin and deactivate
     if ($route_blocked) {
         $this->log(MV_M_NOTICE, $log_message);
         SystemMessage($this->move['user_id'], $title, $message);
         //Send a copy to the admin
         SystemMessage(10, $title, $message);
         // Deactivate the move
         $sql = 'UPDATE ship_fleets
             SET planet_id = ' . $this->move['dest'] . ',
             move_id = 0
             WHERE fleet_id IN (' . $this->fleet_ids_str . ')';
         if (!$this->db->query($sql)) {
             return $this->log(MV_M_DATABASE, 'Could not update fleets data! SKIP');
         }
         return MV_EXEC_OK;
     }
     $this->do_unloading();
     if ($this->move['user_id'] != $this->dest['user_id']) {
         $sql = 'SELECT ud.ud_id, a.alliance_id, ad.ad_id, ad.type, ad.status 
                 FROM (user u)
                 LEFT JOIN user_diplomacy ud ON ( ( ud.user1_id = ' . $this->move['user_id'] . ' AND ud.user2_id = ' . $this->dest['user_id'] . ' ) OR (ud.user1_id = ' . $this->dest['user_id'] . ' AND ud.user2_id = ' . $this->move['user_id'] . ' ) )
                 LEFT JOIN alliance a ON a.alliance_id = u.user_alliance
                 LEFT JOIN alliance_diplomacy ad ON ( ( ad.alliance1_id = ' . $this->move['user_alliance'] . ' AND ad.alliance2_id = a.alliance_id ) OR ( ad.alliance1_id = a.alliance_id AND ad.alliance2_id = ' . $this->move['user_alliance'] . ' ) )
                 WHERE u.user_id = ' . $this->dest['user_id'];
         if (($diplomacy = $this->db->queryrow($sql)) === false) {
             return $this->log(MV_M_DATABASE, 'Could not query diplomacy data');
         }
         $allied = false;
         // Players has a private pact?
         if (!empty($diplomacy['ud_id'])) {
             $allied = true;
         }
         // Players are in the same alliance?
         if ($diplomacy['alliance_id'] != 0 && $diplomacy['alliance_id'] == $this->move['user_alliance']) {
             $allied = true;
         }
         // Player's alliances are sharing a Cooperation pact?
         if (!empty($diplomacy['ad_id'])) {
             if ($diplomacy['type'] == 3) {
                 if ($diplomacy['status'] == 0) {
                     $allied = true;
                 }
             }
         }
     } else {
         $allied = true;
     }
     if ($allied && ($this->tr_data[5] < 0 || $this->tr_data[5] == 4)) {
         $this->do_loading();
     }
     $sql = 'UPDATE ship_fleets
             SET resource_1 = ' . $this->fleet['resource_1'] . ',
                 resource_2 = ' . $this->fleet['resource_2'] . ',
                 resource_3 = ' . $this->fleet['resource_3'] . ',
                 resource_4 = ' . $this->fleet['resource_4'] . ',
                 unit_1 = ' . $this->fleet['unit_1'] . ',
                 unit_2 = ' . $this->fleet['unit_2'] . ',
                 unit_3 = ' . $this->fleet['unit_3'] . ',
                 unit_4 = ' . $this->fleet['unit_4'] . ',
                 unit_5 = ' . $this->fleet['unit_5'] . ',
                 unit_6 = ' . $this->fleet['unit_6'] . '
             WHERE fleet_id = ' . $this->fleet_ids[0];
     if (!$this->db->query($sql)) {
         return $this->log(MV_M_DATABASE, 'Could not update ship fleets resource data');
     }
     $sql = 'UPDATE planets
             SET resource_1 = ' . $this->dest['resource_1'] . ',
                 resource_2 = ' . $this->dest['resource_2'] . ',
                 resource_3 = ' . $this->dest['resource_3'] . ',
                 resource_4 = ' . $this->dest['resource_4'] . ',
                 unit_1 = ' . $this->dest['unit_1'] . ',
                 unit_2 = ' . $this->dest['unit_2'] . ',
                 unit_3 = ' . $this->dest['unit_3'] . ',
                 unit_4 = ' . $this->dest['unit_4'] . ',
                 unit_5 = ' . $this->dest['unit_5'] . ',
                 unit_6 = ' . $this->dest['unit_6'] . '
             WHERE planet_id = ' . $this->dest['planet_id'];
     if (!$this->db->query($sql)) {
         return $this->log(MV_M_DATABASE, 'Could not update planets resource data');
     }
     // #############################################################################
     // Returns ships if requested
     if ($this->tr_data[5] < 0 || $this->tr_data[5] == 4) {
         $new_move_begin = $this->CURRENT_TICK;
         $new_move_finish = $this->move['move_finish'] - $this->move['move_begin'] + $this->CURRENT_TICK;
         $sql = 'UPDATE scheduler_shipmovement
                 SET start = ' . $this->move['dest'] . ',
                     dest = ' . $this->move['start'] . ',
                     move_begin = ' . $new_move_begin . ',
                     move_finish = ' . $new_move_finish . ',
                     remaining_distance = total_distance,
                     action_data = "' . serialize($this->tr_data) . '"
                 WHERE move_id = ' . $this->mid;
         if (!$this->db->query($sql)) {
             return $this->log(MV_M_DATABASE, 'Could not update move data! SKIP');
         }
         $this->flags['keep_move_alive'] = true;
     } else {
         $sql = 'UPDATE ship_fleets
             SET planet_id = ' . $this->move['dest'] . ',
             move_id = 0
             WHERE fleet_id IN (' . $this->fleet_ids_str . ')';
         if (!$this->db->query($sql)) {
             return $this->log(MV_M_DATABASE, 'Could not update fleets data! SKIP');
         }
     }
     // #############################################################################
     // Logbook entry
     $sql = 'SELECT st.name, st.ship_torso, st.race,
                    COUNT(s.ship_id) AS n_ships
             FROM ship_templates st, ship_fleets f, ships s
             WHERE f.fleet_id IN (' . $this->fleet_ids_str . ') AND
                   s.template_id = st.id AND
                   s.fleet_id = f.fleet_id
             GROUP BY st.id
             ORDER BY st.ship_torso ASC, st.race ASC';
     if (!($q_stpls = $this->db->query($sql))) {
         return $this->log(MV_M_DATABASE, 'Could not query ships templates data! SKIP');
     }
     $log_data = array(34, $this->move['user_id'], $this->move['start'], $this->start['planet_name'], $this->start['user_id'], $this->move['dest'], $this->dest['planet_name'], $this->dest['user_id'], array(), $this->unlwares, $this->lwares, $this->planet_overloaded);
     while ($stpl = $this->db->fetchrow($q_stpls)) {
         $log_data[8][] = array($stpl['name'], $stpl['ship_torso'], $stpl['race'], $stpl['n_ships']);
     }
     // #############################################################################
     // Retrieve player language
     switch ($this->move['language']) {
         case 'GER':
             $log_title1 = 'Transport bei ' . $this->dest['planet_name'] . ' durchgef&uuml;hrt';
             $log_title2 = 'Transport bei ' . $this->dest['planet_name'] . ' erhalten';
             break;
         case 'ITA':
             $log_title1 = 'Trasporto per ' . $this->dest['planet_name'] . ' compiuto';
             $log_title2 = 'Trasporto per ' . $this->dest['planet_name'] . ' ricevuto';
             break;
         default:
             $log_title1 = 'Transport for ' . $this->dest['planet_name'] . ' accomplished';
             $log_title2 = 'Transport for ' . $this->dest['planet_name'] . ' received';
             break;
     }
     // Add logbook entries only if players had activated them
     if ($this->action_data[6]) {
         add_logbook_entry($this->move['user_id'], LOGBOOK_TACTICAL, $log_title1, $log_data);
     }
     // Only one logbook if the owner of the planet is also the owner of the fleets
     if ($this->move['user_id'] != $this->dest['user_id']) {
         add_logbook_entry($this->dest['user_id'], LOGBOOK_TACTICAL, $log_title2, $log_data);
     }
     return MV_EXEC_OK;
 }
 function _action_main()
 {
     account_log($this->move['user_id'], $this->dest['user_id'], 1);
     // #############################################################################
     // Update ships
     $sql = 'UPDATE ships
             SET user_id = ' . $this->dest['user_id'] . '
             WHERE fleet_id IN (' . $this->fleet_ids_str . ')';
     if (!$this->db->query($sql)) {
         return $this->log(MV_M_DATABASE, 'Could not update ships user data! SKIP');
     }
     // #############################################################################
     // Update fleets
     $sql = 'UPDATE ship_fleets
             SET planet_id = ' . $this->move['dest'] . ',
                 move_id = 0,
                 user_id = ' . $this->dest['user_id'] . '
             WHERE fleet_id IN (' . $this->fleet_ids_str . ')';
     if (!$this->db->query($sql)) {
         return $this->log(MV_M_DATABASE, 'Could not update fleets data! SKIP');
     }
     // #############################################################################
     // Check debts
     $sql = 'SELECT id, resource_1, resource_2, resource_3, ship_id
             FROM bidding_owed
             WHERE user = '******'user_id'] . ' AND
                   receiver = ' . $this->dest['user_id'] . '
             ORDER BY id ASC';
     if (!($q_debts = $this->db->query($sql))) {
         return $this->log(MV_M_DATABASE, 'Could not query bidding owed data! SKIP');
     }
     $n_debts = $this->db->num_rows($q_debts);
     if ($n_debts > 0) {
         $sql = 'SELECT SUM(resource_1) AS n1, SUM(resource_2) AS n2, SUM(resource_3) AS n3
                 FROM ship_fleets
                 WHERE fleet_id IN (' . $this->fleet_ids_str . ')';
         if (($rfleets = $this->db->queryrow($sql)) === false) {
             return $this->log(MV_M_DATABASE, 'Could not query fleets resources data! SKIP');
         }
         $ships = array();
         $sql = 'SELECT ship_id
                 FROM ships
                 WHERE fleet_id IN (' . $this->fleet_ids_str . ')';
         if (!($q_ships = $this->db->query($sql))) {
             return $this->log(MV_M_DATABASE, 'Could not query ships id data! SKIP');
         }
         while ($_ship = $this->db->fetchrow($q_ships)) {
             $ships[$_ship['ship_id']] = true;
         }
         while ($debt = $this->db->fetchrow($q_debts)) {
             if ($debt['resource_1'] > 0) {
                 if ($debt['resource_1'] >= $rfleets['n1']) {
                     $debt['resource_1'] -= $rfleets['n1'];
                     $rfleets['n1'] = 0;
                 } else {
                     $rfleets['n1'] -= $debt['resource_1'];
                     $debt['resource_1'] = 0;
                 }
             }
             if ($debt['resource_2'] > 0) {
                 if ($debt['resource_2'] >= $rfleets['n2']) {
                     $debt['resource_2'] -= $rfleets['n2'];
                     $rfleets['n2'] = 0;
                 } else {
                     $rfleets['n2'] -= $debt['resource_2'];
                     $debt['resource_2'] = 0;
                 }
             }
             if ($debt['resource_3'] > 0) {
                 if ($debt['resource_3'] >= $rfleets['n3']) {
                     $debt['resource_3'] -= $rfleets['n3'];
                     $rfleets['n3'] = 0;
                 } else {
                     $rfleets['n3'] -= $debt['resource_3'];
                     $debt['resource_3'] = 0;
                 }
             }
             if ($debt['ship_id'] > 0) {
                 if (!empty($ships[$debt['ship_id']])) {
                     $debt['ship_id'] = 0;
                 }
             }
             if ($debt['resource_1'] <= 0 && $debt['resource_2'] <= 0 && $debt['resource_3'] <= 0 && $debt['ship_id'] <= 0) {
                 $sql = 'DELETE FROM bidding_owed
                         WHERE id = ' . $debt['id'];
                 if (!$this->db->query($sql)) {
                     return $this->log(MV_M_DATABASE, 'Could not delete bidding owed data! SKIP');
                 }
             } else {
                 $sql = 'UPDATE bidding_owed
                         SET resource_1 = ' . $debt['resource_1'] . ',
                             resource_2 = ' . $debt['resource_2'] . ',
                             resource_3 = ' . $debt['resource_3'] . ',
                             ship_id = ' . $debt['ship_id'] . '
                         WHERE id = ' . $debt['id'];
                 if (!$this->db->query($sql)) {
                     return $this->log(MV_M_DATABASE, 'Could not update bidding owed data! SKIP');
                 }
             }
         }
     }
     // #############################################################################
     // Write Logbook
     $sql = 'SELECT st.name, st.ship_torso, st.race,
                    COUNT(s.ship_id) AS n_ships
             FROM ship_templates st, ship_fleets f, ships s
             WHERE f.fleet_id IN (' . $this->fleet_ids_str . ') AND
                   s.template_id = st.id AND
                   s.fleet_id = f.fleet_id
             GROUP BY st.id
             ORDER BY st.ship_torso ASC, st.race ASC';
     if (!($q_stpls = $this->db->query($sql))) {
         $this->log(MV_M_DATABASE, 'Could not query ships templates data! ABORTED LOGBOOK');
     }
     $log_data = array(23, $this->move['user_id'], $this->move['start'], $this->start['planet_name'], $this->start['user_id'], $this->move['dest'], $this->dest['planet_name'], $this->dest['user_id'], array());
     while ($stpl = $this->db->fetchrow($q_stpls)) {
         $log_data[8][] = array($stpl['name'], $stpl['ship_torso'], $stpl['race'], $stpl['n_ships']);
     }
     // #############################################################################
     // 31/03/08 - AC: Retrieve player language
     switch ($this->move['language']) {
         case 'GER':
             $log_title1 = 'Flottenverband ' . $this->dest['user_name'] . ' übergeben';
             break;
         case 'ITA':
             $log_title1 = 'Associazione flotta consegnata a ' . $this->dest['user_name'];
             break;
         default:
             $log_title1 = 'Fleet association handed over to ' . $this->dest['user_name'];
             break;
     }
     switch ($this->dest['language']) {
         case 'GER':
             $log_title2 = 'Flottenverband von ' . $this->move['user_name'] . ' hat sich ergeben';
             break;
         case 'ITA':
             $log_title2 = 'Ricevuta associazione flotta di ' . $this->move['user_name'];
             break;
         default:
             $log_title2 = 'Fleet association of ' . $this->move['user_name'] . ' has revealed';
             break;
     }
     add_logbook_entry($this->move['user_id'], LOGBOOK_TACTICAL, $log_title1, $log_data);
     add_logbook_entry($this->dest['user_id'], LOGBOOK_TACTICAL, $log_title2, $log_data);
     return MV_EXEC_OK;
 }
        $sql = 'SELECT st.name, st.ship_torso, st.race,
                       COUNT(s.ship_id) AS n_ships
                FROM (ship_templates st, ship_fleets f, ships s)
                WHERE f.fleet_id IN (' . $fleet_ids_str . ') AND
                      s.template_id = st.id AND
                      s.fleet_id = f.fleet_id
                GROUP BY st.id
                ORDER BY st.ship_torso ASC, st.race ASC';
        if (!($q_stpls = $db->query($sql))) {
            message(DATABASE_ERROR, 'Could not query logbook data');
        }
        $log_data = array(23, $game->player['user_id'], $planet_id, $planet['planet_name'], $planet['user_id'], 0, 0, 0, array());
        while ($stpl = $db->fetchrow($q_stpls)) {
            $log_data[8][] = array($stpl['name'], $stpl['ship_torso'], $stpl['race'], $stpl['n_ships']);
        }
        add_logbook_entry($user_id, LOGBOOK_TACTICAL, constant($game->sprache("TEXT15")) . ' ' . $game->player['user_name'] . ' ' . constant($game->sprache("TEXT16")), $log_data);
        redirect('a=tactical_cartography&planet_id=' . encode_planet_id($planet_id));
        break;
    case 'surrender_setup':
        if ($game->player['user_id'] > 10) {
            message(NOTICE, constant($game->sprache("TEXT11")));
        }
        if ($atkptc_present) {
            message(NOTICE, constant($game->sprache("TEXT12")));
        }
        if ($other_party['user_id'] == $game->player['user_id']) {
            message(NOTICE, constant($game->sprache("TEXT13")));
        }
        $game->out('
<table class="style_outer" align="center" border="0" cellpadding="2" cellspacing="2" width="450">
  <tr>
Exemple #10
0
 function _main()
 {
     $start_processing_time = time() + microtime();
     // #############################################################################
     // On...
     $this->flags['is_orbital_move'] = $this->move['start'] == $this->move['dest'];
     $this->flags['is_friendly_action'] = in_array($this->move['action_code'], array(23, 31, 33));
     // #############################################################################
     // Security checks
     if (empty($this->mid)) {
         $this->deactivate(31);
         $this->report('Deactivated due to empty move data');
         return MV_EXEC_ERROR;
     }
     if ($this->move['move_begin'] == $this->move['move_finish']) {
         $this->deactivate(32);
         $this->report('Deactivated due to illegal arrival times');
         return MV_EXEC_ERROR;
     }
     // #############################################################################
     // If the move was already tried 3 times, cancel
     if ($this->move['move_exec_started'] >= 3) {
         $this->deactivate(33);
         $this->report('Deactivated due to execution limit');
         return MV_EXEC_ERROR;
     }
     // #############################################################################
     // Exec-Counter setup
     $sql = 'UPDATE scheduler_shipmovement
             SET move_exec_started = move_exec_started + 1
             WHERE move_id = ' . $this->mid;
     if (!$this->db->query($sql)) {
         return $this->log(MV_M_DATABASE, 'Could not update move exec started data! SKIP');
     }
     // #############################################################################
     // Data from the participating fleets
     $sql = 'SELECT fleet_id, fleet_name, n_ships
             FROM ship_fleets
             WHERE move_id = ' . $this->mid;
     if (!($q_fleets = $this->db->query($sql))) {
         return $this->log(MV_M_DATABASE, 'Could not query moves fleets data! SKIP');
     }
     while ($_fl = $this->db->fetchrow($q_fleets)) {
         $this->fleet_ids[] = $_fl['fleet_id'];
         $this->fleet_names[] = $_fl['fleet_name'];
         $this->n_ships[] = $_fl['n_ships'];
     }
     $this->n_fleets = count($this->fleet_ids);
     if ($this->n_fleets == 0) {
         $this->deactivate(34);
         $this->report('Deactivated due to missing fleets');
         return MV_EXEC_ERROR;
     }
     $this->fleet_ids_str = implode(',', $this->fleet_ids);
     // #############################################################################
     // action_data decode, if available
     if (!empty($this->move['action_data'])) {
         $this->action_data = (array) unserialize($this->move['action_data']);
     }
     // #############################################################################
     // Data of start planet
     $sql = 'SELECT p.*,
                    u.user_id, u.user_active, u.user_name, u.user_race, u.user_planets, u.user_alliance, u.user_capital
             FROM (planets p)
             LEFT JOIN user u ON u.user_id = p.planet_owner
             WHERE p.planet_id = ' . $this->move['start'];
     if (($this->start = $this->db->queryrow($sql)) === false) {
         return $this->log(MV_M_DATABASE, 'Could not query start planets data! SKIP');
     }
     settype($this->start['user_id'], 'int');
     // #############################################################################
     // Data of target planet
     if ($this->flags['is_orbital_move']) {
         $this->dest =& $this->start;
         /* 03/04/08 - AC: Hmmm, we need language settings here?
          * However set it to english.
          */
         $this->dest['language'] = 'ENG';
     } else {
         $sql = 'SELECT p.*,
                        u.user_id, u.user_active, u.user_name, u.user_race, u.user_planets, u.user_alliance, u.user_capital
                 FROM (planets p)
                 LEFT JOIN user u ON u.user_id = p.planet_owner
                 WHERE p.planet_id = ' . $this->move['dest'];
         if (($this->dest = $this->db->queryrow($sql)) === false) {
             return $this->log(MV_M_DATABASE, 'Could not query dest planets! SKIP');
         }
         settype($this->dest['user_id'], 'int');
         // #############################################################################
         /* 17/06/08 - AC: Load user language only if a player is present*/
         if ($this->dest['user_id'] != 0) {
             $sql = 'SELECT language FROM user WHERE user_id = ' . $this->dest['user_id'];
             if (!($lang = $this->db->queryrow($sql))) {
                 $this->log(MV_M_DATABASE, 'Could not retrieve player ' . $this->dest['user_id'] . ' (dest) language! SET to ENG');
                 $this->dest['language'] = 'ENG';
             } else {
                 $this->dest['language'] = $lang['language'];
             }
         } else {
             $this->dest['language'] = 'ENG';
         }
         // #############################################################################
         // Look for stationed fleets in AR
         $sql = 'SELECT DISTINCT f.user_id,
                        u.user_alliance,
                        ud.ud_id, ud.accepted,
                        ad.ad_id, ad.type, ad.status
                 FROM (ship_fleets f)
                 INNER JOIN user u ON u.user_id = f.user_id
                 LEFT JOIN user_diplomacy ud ON ( ( ud.user1_id = ' . $this->move['user_id'] . ' AND ud.user2_id = f.user_id ) OR ( ud.user1_id = f.user_id AND ud.user2_id = ' . $this->move['user_id'] . ' ) )
                 LEFT JOIN alliance_diplomacy ad ON ( ( ad.alliance1_id = ' . $this->move['user_alliance'] . ' AND ad.alliance2_id = u.user_alliance) OR ( ad.alliance1_id = u.user_alliance AND ad.alliance2_id = ' . $this->move['user_alliance'] . ' ) )
                 WHERE f.planet_id = ' . $this->move['dest'] . ' AND
                       f.user_id <> ' . $this->move['user_id'] . ' AND
                       f.alert_phase = ' . ALERT_PHASE_RED;
         //$this->log(MV_M_NOTICE,'AR-Fleet:<br>"'.$sql.'"<br>');
         if (!($q_ar_uid = $this->db->query($sql))) {
             return $this->log(MV_M_DATABASE, 'Could not query alert phase red user! SKIP');
         }
         $ar_user = array();
         while ($ar_uid = $this->db->fetchrow($q_ar_uid)) {
             //if( ($ar_uid['user_id'] == $this->dest['user_id']) && $is_friendly_action ) continue;
             // While checking for the same alliance, also check if THERE IS actually an alliance!
             if ($ar_uid['user_alliance'] != 0 && $ar_uid['user_alliance'] == $this->move['user_alliance']) {
                 continue;
             }
             if (!empty($ar_uid['ud_id'])) {
                 if ($ar_uid['accepted'] == 1) {
                     continue;
                 }
             }
             if (!empty($ar_uid['ad_id'])) {
                 if ($ar_uid['type'] == ALLIANCE_DIPLOMACY_PACT && $ar_uid['status'] == 0) {
                     continue;
                 }
             }
             $ar_user[] = $ar_uid['user_id'];
             $this->log(MV_M_NOTICE, 'AR-User ID is ' . $ar_uid['user_id']);
         }
         $this->db->free_result($q_ar_uid);
         $this->log(MV_M_NOTICE, 'AR-user(s): <b>' . count($ar_user) . '</b>');
         for ($i = 0; $i < count($ar_user); ++$i) {
             $this->log(MV_M_NOTICE, 'Entering AR-loop #' . $i);
             $sql = 'SELECT ' . $this->get_combat_query_fleet_columns() . '
                     FROM (ship_fleets f)
                     INNER JOIN user u ON u.user_id = f.user_id
                     WHERE f.planet_id = ' . $this->move['dest'] . ' AND
                           f.user_id = ' . $ar_user[$i] . ' AND
                           f.alert_phase = ' . ALERT_PHASE_RED;
             $this->log(MV_M_NOTICE, 'AR-query:<br>"' . $sql . '"<br>');
             if (($atk_fleets = $this->db->queryrowset($sql)) === false) {
                 return $this->log(MV_M_DATABASE, 'Could not query attacker fleets in AR! SKIP');
             }
             $atk_fleet_ids = array();
             foreach ($atk_fleets as $ihh => $cur_fleet) {
                 $atk_fleet_ids[] = $cur_fleet['fleet_id'];
             }
             $sql = 'SELECT ' . $this->get_combat_query_fleet_columns() . '
                     FROM (ship_fleets f)
                     INNER JOIN user u ON u.user_id = f.user_id
                     WHERE f.fleet_id IN (' . $this->fleet_ids_str . ')';
             if (($dfd_fleets = $this->db->queryrowset($sql)) === false) {
                 return $this->log(MV_M_DATABASE, 'Could not query defender fleets in AR! SKIP');
             }
             $this->log(MV_M_NOTICE, 'Doing combat in AR-loop #' . $i);
             $atk_fleet_ids_str = implode(',', $atk_fleet_ids);
             if ($this->do_ship_combat($atk_fleet_ids_str, $this->fleet_ids_str, MV_COMBAT_LEVEL_OUTER) == MV_EXEC_ERROR) {
                 $this->log(MV_M_CRITICAL, 'Move Direct: Something went wrong with this fight!');
                 return MV_EXEC_ERROR;
             }
             $this->log(MV_M_NOTICE, 'Combat done in AR-loop #' . $i);
             // If the attacker has won (the fleet AR)
             // the move can then be terminated immediately
             // Now ships can run from combat. We have to check if any ships fled the fight
             // before calling the move a "skipped action"
             if ($this->cmb[MV_CMB_WINNER] == MV_CMB_ATTACKER) {
                 $this->flags['skip_action'] = true;
                 $sql = 'SELECT COUNT(*) as ship_escaped FROM ships WHERE fleet_id IN (' . $this->fleet_ids_str . ')';
                 //  $this->log(MV_M_NOTICE, 'Active fleet lost the fight, we look for survivors with '.$sql);
                 $e_s_c = $this->db->queryrow($sql);
                 if (isset($e_s_c['ship_escaped']) && $e_s_c['ship_escaped'] > 0) {
                     //      $this->log(MV_M_NOTICE, 'Active fleet survived the fight, will bounce back');
                     // Update move data, setting up the bouncing back
                     // start -> dest, dest -> start
                     $sql = 'UPDATE scheduler_shipmovement SET start = ' . $this->move['dest'] . ', dest = ' . $this->move['start'] . ', 
                                     move_begin = ' . $this->CURRENT_TICK . ', move_finish = ' . ($this->CURRENT_TICK + ($this->move['move_finish'] - $this->move['move_begin'])) . ',
                                     action_code = 28, action_data = 0, n_ships = ' . $e_s_c['ship_escaped'] . ' WHERE move_id = ' . $this->move['move_id'];
                     if (!$this->db->query($sql)) {
                         $this->log(MV_M_DATABASE, 'Could not update move data with retreat order! ' . $sql);
                     }
                     $this->flags['keep_move_alive'] = true;
                 }
             }
             $log1_data = array(40, $this->move['user_id'], $this->move['start'], $this->start['planet_name'], $this->start['user_id'], $this->move['dest'], $this->dest['planet_name'], $this->dest['user_id'], MV_CMB_ATTACKER, $this->cmb[MV_CMB_WINNER] == MV_CMB_ATTACKER, 0, 0, $atk_fleets, $dfd_fleets, null, $ar_user[$i]);
             $log2_data = array(40, $this->move['user_id'], $this->move['start'], $this->start['planet_name'], $this->start['user_id'], $this->move['dest'], $this->dest['planet_name'], $this->dest['user_id'], MV_CMB_DEFENDER, $this->cmb[MV_CMB_WINNER] == MV_CMB_DEFENDER, 0, 0, $atk_fleets, $dfd_fleets, null, $ar_user[$i]);
             $log1_data[10] = $this->cmb[MV_CMB_KILLS_EXT];
             $log2_data[10] = $this->cmb[MV_CMB_KILLS_EXT];
             // #############################################################################
             // 03/04/08 - AC: Retrieve player language
             //  !! ACTUALLY WE ARE USING THE SAME LANGUAGE ALSO FOR ALLIES LOGBOOK ENTRY !!
             switch ($this->move['language']) {
                 case 'GER':
                     $log_title1 = 'AR-Flottenverband hat Schiffe bei ' . $this->dest['planet_name'] . ' angegriffen';
                     $log_title2 = 'Flottenverband wurde bei ' . $this->dest['planet_name'] . ' angegriffen';
                     break;
                 case 'ITA':
                     $log_title1 = 'Flotta in AR ha attaccato navi presso ' . $this->dest['planet_name'];
                     $log_title2 = 'Associazione flotta attaccata presso ' . $this->dest['planet_name'];
                     break;
                 default:
                     $log_title1 = 'AR fleet has attacked ships at ' . $this->dest['planet_name'];
                     $log_title2 = 'Fleet association was attacked at ' . $this->dest['planet_name'];
                     break;
             }
             add_logbook_entry($ar_user[$i], LOGBOOK_TACTICAL_2, $log_title1, $log1_data);
             add_logbook_entry($this->move['user_id'], LOGBOOK_TACTICAL_2, $log_title2, $log2_data);
             $this->flags['combat_happened'] = true;
             $this->log(MV_M_NOTICE, 'Leaving AR-loop #' . $i);
         }
         // #############################################################################
         // Look for stationed fleets in Yellow Alert!!!
         // Non è la migliore delle scelte perché aggiungiamo un secondo loop
         $sql = 'SELECT DISTINCT f.user_id,
                        u.user_alliance, u.user_name,
                        ud.ud_id, ud.accepted, u.language,
                        ad.ad_id, ad.type, ad.status
                 FROM (ship_fleets f)
                 INNER JOIN user u ON u.user_id = f.user_id
                 LEFT JOIN user_diplomacy ud ON ( ( ud.user1_id = ' . $this->move['user_id'] . ' AND ud.user2_id = f.user_id ) OR ( ud.user1_id = f.user_id AND ud.user2_id = ' . $this->move['user_id'] . ' ) )
                 LEFT JOIN alliance_diplomacy ad ON ( ( ad.alliance1_id = ' . $this->move['user_alliance'] . ' AND ad.alliance2_id = u.user_alliance) OR ( ad.alliance1_id = u.user_alliance AND ad.alliance2_id = ' . $this->move['user_alliance'] . ' ) )
                 WHERE f.planet_id = ' . $this->move['dest'] . ' AND
                       f.user_id <> ' . $this->move['user_id'] . ' AND
                       f.alert_phase = ' . ALERT_PHASE_YELLOW;
         $ay_query = $this->db->query($sql);
         $ay_n_user = $this->db->num_rows($ay_query);
         if ($ay_n_user > 0) {
             $ay_user = array();
             $ay_rows = $this->db->fetchrowset($ay_query);
             // Raccogliamo info sulla flotta IN ARRIVO (ossia quella legata alla mossa in elaborazione)
             // per averle già pronte per la scrittura dei log da mandare ai giocatori.
             // Utilizzo queryrowset perché, salvo cataclismi, la flotta in movimento HA una composizione coerente e leggibile.
             $sql = 'SELECT st.name, st.race, st.ship_torso, st.ship_class, COUNT(st.name) as n_ships 
                     FROM ship_templates st
                     INNER JOIN ships s ON s.template_id = st.id
                     INNER JOIN ship_fleets f ON f.fleet_id = s.fleet_id
                     WHERE f.fleet_id IN (' . $this->fleet_ids_str . ')
                     GROUP BY st.name
                     ORDER BY st.ship_class DESC, st.ship_torso DESC';
             $ay_ship_list = $this->db->queryrowset($sql);
             $ay_move_name = $this->db->queryrow('SELECT user_name FROM user WHERE user_id = ' . $this->move['user_id']);
             foreach ($ay_rows as $ay_uid) {
                 if ($ay_uid['user_alliance'] != 0 && $ay_uid['user_alliance'] == $this->move['user_alliance']) {
                     continue;
                 }
                 if (isset($ay_uid['ud_id']) && !empty($ay_uid['ud_id'])) {
                     if ($ay_uid['accepted'] == 1) {
                         continue;
                     }
                 }
                 if (isset($ay_uid['ad_id']) && !empty($ay_uid['ad_id'])) {
                     if ($ay_uid['type'] == ALLIANCE_DIPLOMACY_PACT && $ay_uid['status'] == 0) {
                         continue;
                     }
                 }
                 $ay_user[] = array($ay_uid['user_id'], $ay_uid['language']);
                 $this->log(MV_M_NOTICE, 'AY-User ID is ' . $ay_uid['user_id']);
             }
             $this->log(MV_M_NOTICE, 'AY-user(s): <b>' . count($ay_user) . '</b>');
             for ($i = 0; $i < count($ay_user); ++$i) {
                 $this->log(MV_M_NOTICE, 'Entering AY-loop #' . $i);
                 $sql = 'SELECT f.fleet_id, f.fleet_name
                         FROM (ship_fleets f)
                         INNER JOIN user u ON u.user_id = f.user_id
                          WHERE f.planet_id = ' . $this->move['dest'] . ' AND
                           f.user_id = ' . $ay_user[$i][0] . ' AND
                           f.alert_phase = ' . ALERT_PHASE_YELLOW;
                 $this->log(MV_M_NOTICE, 'AY-query:<br>"' . $sql . '"<br>');
                 if (($sgnl_fleets = $this->db->queryrowset($sql)) === false) {
                     return $this->log(MV_M_DATABASE, 'Could not query signaling fleets in AY! SKIP');
                 }
                 foreach ($sgnl_fleets as $ihh => $cur_fleet) {
                     $log_data[0] = 100;
                     // Codice mossa fasullo per far funzionare il logbook
                     $log_data[1] = $this->move['user_id'];
                     $log_data[2] = $this->move['start'];
                     $log_data[3] = $this->start['planet_name'];
                     $log_data[4] = $this->start['user_id'];
                     $log_data[5] = $this->move['dest'];
                     $log_data[6] = $this->dest['planet_name'];
                     $log_data[7] = $this->dest['user_id'];
                     $log_data[8] = $cur_fleet['fleet_id'];
                     $log_data[9] = $cur_fleet['fleet_name'];
                     $log_data[10] = array_sum($this->n_ships);
                     $log_data[11] = $ay_ship_list;
                     $log_data[12] = $ay_move_name['user_name'];
                     switch ($ay_user[$i][1]) {
                         case 'GER':
                             $log_title = 'AY-fleet reporting the arrival of a fleet on planet ' . $this->dest['planet_name'];
                             break;
                         case 'ITA':
                             $log_title = 'Flotta in AG comunica arrivo di navi sul pianeta ' . $this->dest['planet_name'];
                             break;
                         default:
                             $log_title = 'AY-fleet reporting the arrival of ships on planet ' . $this->dest['planet_name'];
                             break;
                     }
                     add_logbook_entry($ay_user[$i][0], LOGBOOK_TACTICAL_2, $log_title, $log_data);
                 }
             }
         }
     }
     // #############################################################################
     // Come through without mistakes?
     $this->flags['free_dest_planet'] = empty($this->dest['user_id']) ? true : false;
     if ($this->flags['skip_action']) {
         $this->log(MV_M_NOTICE, 'Skipped_action_main()');
     } else {
         if ($this->_action_main() != MV_EXEC_OK) {
             return $this->log(MV_M_ERROR, 'Could not exec successfully _action_main()! SKIP');
         } else {
             // DC ---- Here we go, first steps into "Fog of War"
             // DC ---- FoW 2.0 Beta - Ally Section
             if (!empty($this->move['user_alliance'])) {
                 $sql = 'SELECT alliance_id FROM starsystems_details WHERE system_id = ' . $this->dest['system_id'] . ' AND alliance_id = ' . $this->move['user_alliance'];
                 $_res = $this->db->queryrow($sql);
                 if (!isset($_res['alliance_id'])) {
                     $sql = 'INSERT INTO starsystems_details (system_id, alliance_id, timestamp)
                             VALUES (' . $this->dest['system_id'] . ', ' . $this->move['user_alliance'] . ', ' . time() . ')';
                     $this->db->query($sql);
                     // No error check plz.
                 }
             }
             // DC ---- FoW 2.0 Beta -- User Section
             $sql = 'SELECT user_id FROM starsystems_details WHERE system_id = ' . $this->dest['system_id'] . ' AND user_id = ' . $this->move['user_id'];
             $_res = $this->db->queryrow($sql);
             if (!isset($_res['user_id'])) {
                 $sql = 'INSERT INTO starsystems_details (system_id, user_id, timestamp)
                         VALUES (' . $this->dest['system_id'] . ', ' . $this->move['user_id'] . ', ' . time() . ')';
                 $this->db->query($sql);
                 // No error check plz.
             }
             // DC Now, if the planet is unsettled...
             if (empty($this->dest['user_id'])) {
                 // DC Maybe we did boldly go where nobody has boldly gone before?
                 $sql = 'SELECT COUNT(*) AS been_here FROM planet_details WHERE planet_id = ' . $this->dest['planet_id'] . ' AND user_id = ' . $this->move['user_id'] . ' AND log_code IN (1,2)';
                 if (!($_flag = $this->db->queryrow($sql))) {
                     $this->log(MV_M_DATABASE, 'Could not query planet details data! CONTINUE!');
                 }
                 if ($_flag['been_here'] == 0) {
                     // DC Yeah, we made it!
                     $sql = 'SELECT COUNT(*) AS first_here FROM planet_details WHERE planet_id = ' . $this->dest['planet_id'] . ' AND log_code = 1';
                     if (!($_flag = $this->db->queryrow($sql))) {
                         $this->log(MV_M_DATABASE, 'Could not query planet details data! CONTINUE!');
                     }
                     if ($_flag['first_here'] == 0) {
                         $sql = 'INSERT INTO planet_details (planet_id, system_id, user_id, alliance_id, source_uid, source_aid, timestamp, log_code)
                                 VALUES (' . $this->dest['planet_id'] . ', ' . $this->dest['system_id'] . ', ' . $this->move['user_id'] . ', ' . (!empty($this->move['user_alliance']) ? $this->move['user_alliance'] : 0) . ', ' . $this->move['user_id'] . ', ' . (!empty($this->move['user_alliance']) ? $this->move['user_alliance'] : 0) . ', ' . time() . ', 1)';
                         if (!$this->db->query($sql)) {
                             $this->log(MV_M_DATABASE, 'Could not insert new planet details data! CONTINUE!');
                         }
                     } else {
                         // DC Bad luck, we are seconds...
                         // DC AND NOW we need to check if we already placed our flag here...
                         $sql = 'INSERT INTO planet_details (planet_id, system_id, user_id, alliance_id, source_uid, source_aid, timestamp, log_code)
                                 VALUES (' . $this->dest['planet_id'] . ', ' . $this->dest['system_id'] . ', ' . $this->move['user_id'] . ', ' . (!empty($this->move['user_alliance']) ? $this->move['user_alliance'] : 0) . ', ' . $this->move['user_id'] . ', ' . (!empty($this->move['user_alliance']) ? $this->move['user_alliance'] : 0) . ', ' . time() . ', 2)';
                         if (!$this->db->query($sql)) {
                             $this->log(MV_M_DATABASE, 'Could not insert new planet details data! CONTINUE!');
                         }
                     }
                 }
             }
         }
     }
     // #############################################################################
     // Clean-Up
     $total_processing_time = round(time() + microtime() - $start_processing_time, 4);
     if ($this->flags['keep_move_alive']) {
         $sql = 'UPDATE scheduler_shipmovement
                 SET move_exec_started = 0
                 WHERE move_id = ' . $this->mid;
         if (!$this->db->query($sql)) {
             $this->log(MV_M_DATABASE, 'Could not update move exec started data to keep move alive! CONTINUE');
         }
         $this->log(MV_M_NOTICE, 'Action ' . $this->move['action_code'] . ' executed in ' . $total_processing_time . 's, but kept alive');
     } else {
         $sql = 'UPDATE scheduler_shipmovement
                 SET move_status = ' . ($this->flags['skip_action'] ? '12' : '11') . '
                 WHERE move_id = ' . $this->mid;
         if (!$this->db->query($sql)) {
             $this->log(MV_M_DATABASE, 'Could not update move status data! CONTINUE');
         }
         $this->log(MV_M_NOTICE, 'Action ' . $this->move['action_code'] . ' executed in ' . $total_processing_time . 's');
     }
     return MV_EXEC_OK;
 }
 function _action_main()
 {
     account_log($this->move['user_id'], $this->dest['user_id'], 0);
     // #############################################################################
     // Determine the total raw
     $sql = 'SELECT fleet_id,
                    resource_1, resource_2, resource_3, resource_4,
                    unit_1, unit_2, unit_3, unit_4, unit_5, unit_6
             FROM ship_fleets
             WHERE fleet_id IN (' . $this->fleet_ids_str . ')';
     if (($q_rfleets = $this->db->query($sql)) === false) {
         return $this->log(MV_M_DATABASE, 'Could not query fleets resources data! SKIP');
     }
     // #############################################################################
     // Transferred resources
     $wares_names = array('resource_1', 'resource_2', 'resource_3', 'resource_4', 'unit_1', 'unit_2', 'unit_3', 'unit_4', 'unit_5', 'unit_6');
     // $pwares -> Wares on the planet
     // $fwares -> Wares on the fleet
     // $twares -> transferred goods (needed for debt calculation)
     $pwares = $fwares = $twares = array();
     // Push check Var initialized
     $push = false;
     for ($i = 0; $i < count($wares_names); ++$i) {
         $pwares[$i] = (int) $this->dest[$wares_names[$i]];
         $twares[$i] = 0;
     }
     $planet_overloaded = false;
     while ($rfleet = $this->db->fetchrow($q_rfleets)) {
         $fleet_id = $rfleet['fleet_id'];
         $n_fwares = $rfleet['resource_1'] + $rfleet['resource_2'] + $rfleet['resource_3'] + $rfleet['resource_4'] + $rfleet['unit_1'] + $rfleet['unit_2'] + $rfleet['unit_3'] + $rfleet['unit_4'] + $rfleet['unit_5'] + $rfleet['unit_6'];
         if ($n_fwares == 0) {
             continue;
         }
         // Check try to push
         if ($this->move['user_id'] != $this->dest['user_id']) {
             $push = true;
             continue;
         }
         foreach ($pwares as $i => $p_value) {
             $value = $fwares[$i] = (int) $rfleet[$wares_names[$i]];
             if ($value == 0) {
                 continue;
             }
             if ($i == 3) {
                 if ($pwares[$i] + $value > $this->dest['max_worker']) {
                     $value = $this->dest['max_worker'] - $pwares[$i];
                     $planet_overloaded = true;
                 }
             } elseif ($i <= 2) {
                 if ($pwares[$i] + $value > $this->dest['max_resources']) {
                     $value = $this->dest['max_resources'] - $pwares[$i];
                     $planet_overloaded = true;
                 }
             } else {
                 if ($pwares[$i] + $value > $this->dest['max_units']) {
                     $value = $this->dest['max_units'] - $pwares[$i];
                     $planet_overloaded = true;
                 }
             }
             $fwares[$i] -= $value;
             $pwares[$i] += $value;
             $twares[$i] += $value;
         }
         $sql = 'UPDATE ship_fleets
                 SET resource_1 = ' . $fwares[0] . ',
                     resource_2 = ' . $fwares[1] . ',
                     resource_3 = ' . $fwares[2] . ',
                     resource_4 = ' . $fwares[3] . ',
                     unit_1 = ' . $fwares[4] . ',
                     unit_2 = ' . $fwares[5] . ',
                     unit_3 = ' . $fwares[6] . ',
                     unit_4 = ' . $fwares[7] . ',
                     unit_5 = ' . $fwares[8] . ',
                     unit_6 = ' . $fwares[9] . '
                 WHERE fleet_id = ' . $fleet_id;
         if (!$this->db->query($sql)) {
             return $this->log(MV_M_DATABASE, 'Could not update resource data of fleet #' . $fleet_id . '! SKIP');
         }
     }
     $sql = 'UPDATE planets
             SET resource_1 = ' . $pwares[0] . ',
                 resource_2 = ' . $pwares[1] . ',
                 resource_3 = ' . $pwares[2] . ',
                 resource_4 = ' . $pwares[3] . ',
                 unit_1 = ' . $pwares[4] . ',
                 unit_2 = ' . $pwares[5] . ',
                 unit_3 = ' . $pwares[6] . ',
                 unit_4 = ' . $pwares[7] . ',
                 unit_5 = ' . $pwares[8] . ',
                 unit_6 = ' . $pwares[9] . '
             WHERE planet_id = ' . $this->move['dest'];
     if (!$this->db->query($sql)) {
         return $this->log(MV_M_DATABASE, 'Could not update planets resource data! SKIP');
     }
     // Reworking of $ twares to the expected size of the debt calculation
     // (one might even rewrite, but why bother when it works...)
     $rfleets = array('n1' => $twares[0], 'n2' => $twares[1], 'n3' => $twares[2]);
     // #############################################################################
     // Check debts
     $sql = 'SELECT id, resource_1, resource_2, resource_3, ship_id
             FROM bidding_owed
             WHERE user = '******'user_id'] . ' AND
                   receiver = ' . $this->dest['user_id'] . '
             ORDER BY id ASC';
     if (!($q_debts = $this->db->query($sql))) {
         return $this->log(MV_M_DATABASE, 'Could not query bidding owed data! SKIP');
     }
     $n_debts = $this->db->num_rows($q_debts);
     if ($n_debts > 0) {
         while ($debt = $this->db->fetchrow($q_debts)) {
             if ($debt['resource_1'] > 0) {
                 if ($debt['resource_1'] >= $rfleets['n1']) {
                     $debt['resource_1'] -= $rfleets['n1'];
                     $rfleets['n1'] = 0;
                 } else {
                     $rfleets['n1'] -= $debt['resource_1'];
                     $debt['resource_1'] = 0;
                 }
             }
             if ($debt['resource_2'] > 0) {
                 if ($debt['resource_2'] >= $rfleets['n2']) {
                     $debt['resource_2'] -= $rfleets['n2'];
                     $rfleets['n2'] = 0;
                 } else {
                     $rfleets['n2'] -= $debt['resource_2'];
                     $debt['resource_2'] = 0;
                 }
             }
             if ($debt['resource_3'] > 0) {
                 if ($debt['resource_3'] >= $rfleets['n3']) {
                     $debt['resource_3'] -= $rfleets['n3'];
                     $rfleets['n3'] = 0;
                 } else {
                     $rfleets['n3'] -= $debt['resource_3'];
                     $debt['resource_3'] = 0;
                 }
             }
             if ($debt['resource_1'] <= 0 && $debt['resource_2'] <= 0 && $debt['resource_3'] <= 0 && $debt['ship_id'] <= 0) {
                 $sql = 'DELETE FROM bidding_owed
                         WHERE id = ' . $debt['id'];
                 if (!$this->db->query($sql)) {
                     return $this->log(MV_M_DATABASE, 'Could not delete bidding owed data! SKIP');
                 }
             } else {
                 $sql = 'UPDATE bidding_owed
                         SET resource_1 = ' . $debt['resource_1'] . ',
                             resource_2 = ' . $debt['resource_2'] . ',
                             resource_3 = ' . $debt['resource_3'] . '
                         WHERE id = ' . $debt['id'];
                 if (!$this->db->query($sql)) {
                     return $this->log(MV_M_DATABASE, 'Could not update bidding owed data! SKIP');
                 }
             }
         }
     }
     // #############################################################################
     // Ships return
     $sql = 'INSERT INTO scheduler_shipmovement (user_id, move_status, move_exec_started, start, dest, total_distance, remaining_distance, tick_speed, move_begin, move_finish, n_ships, action_code, action_data)
             VALUES (' . $this->move['user_id'] . ', 0, 0, ' . $this->move['dest'] . ', ' . $this->move['start'] . ', ' . $this->move['total_distance'] . ', ' . $this->move['total_distance'] . ', ' . $this->move['tick_speed'] . ', ' . $this->CURRENT_TICK . ', ' . ($this->CURRENT_TICK + ($this->move['move_finish'] - $this->move['move_begin'])) . ', ' . $this->move['n_ships'] . ', 12, "' . serialize(31) . '")';
     if (!$this->db->query($sql)) {
         return $this->log(MV_M_DATABASE, 'Could not create new movement for return! SKIP');
     }
     $new_move_id = $this->db->insert_id();
     if (!$new_move_id) {
         return $this->log(MV_M_ERROR, 'Could not get new move id! SKIP');
     }
     $sql = 'UPDATE ship_fleets
             SET move_id = ' . $new_move_id . '
             WHERE fleet_id IN (' . $this->fleet_ids_str . ')';
     if (!$this->db->query($sql)) {
         return $this->log(MV_M_DATABASE, 'Could not update fleets movement data! SKIP');
     }
     // #############################################################################
     // Create a logbook entry
     $sql = 'SELECT st.name, st.ship_torso, st.race,
                    COUNT(s.ship_id) AS n_ships
             FROM ship_templates st, ship_fleets f, ships s
             WHERE f.fleet_id IN (' . $this->fleet_ids_str . ') AND
                   s.template_id = st.id AND
                   s.fleet_id = f.fleet_id
             GROUP BY st.id
             ORDER BY st.ship_torso ASC, st.race ASC';
     if (!($q_stpls = $this->db->query($sql))) {
         return $this->log(MV_M_DATABASE, 'Could not query ships templates data! SKIP');
     }
     $log_data = array(31, $this->move['user_id'], $this->move['start'], $this->start['planet_name'], $this->start['user_id'], $this->move['dest'], $this->dest['planet_name'], $this->dest['user_id'], array(), $twares, $planet_overloaded, $push);
     while ($stpl = $this->db->fetchrow($q_stpls)) {
         $log_data[8][] = array($stpl['name'], $stpl['ship_torso'], $stpl['race'], $stpl['n_ships']);
     }
     // #############################################################################
     // 31/03/08 - AC: Retrieve player language
     switch ($this->move['language']) {
         case 'GER':
             $log_title1 = 'Transport bei ' . $this->dest['planet_name'] . ' nicht durchgeführt';
             $log_title3 = 'Transport bei ' . $this->dest['planet_name'] . ' durchgeführt';
             break;
         case 'ITA':
             $log_title1 = 'Trasporto per ' . $this->dest['planet_name'] . ' non compiuto';
             $log_title3 = 'Trasporto per ' . $this->dest['planet_name'] . ' compiuto';
             break;
         default:
             $log_title1 = 'Transport for ' . $this->dest['planet_name'] . ' not accomplished';
             $log_title3 = 'Transport for ' . $this->dest['planet_name'] . ' accomplished';
             break;
     }
     switch ($this->dest['language']) {
         case 'GER':
             $log_title2 = 'Transport bei ' . $this->dest['planet_name'] . ' konnte nicht abgeladen werden';
             $log_title4 = 'Transport bei ' . $this->dest['planet_name'] . ' erhalten';
             break;
         case 'ITA':
             $log_title2 = 'Trasporto per ' . $this->dest['planet_name'] . ' non scaricato';
             $log_title4 = 'Trasporto per ' . $this->dest['planet_name'] . ' ricevuto';
             break;
         default:
             $log_title2 = 'Transport for ' . $this->dest['planet_name'] . ' could not be unloaded';
             $log_title4 = 'Transport for ' . $this->dest['planet_name'] . ' received';
             break;
     }
     if ($push) {
         add_logbook_entry($this->move['user_id'], LOGBOOK_TACTICAL, $log_title1, $log_data);
         add_logbook_entry($this->dest['user_id'], LOGBOOK_TACTICAL, $log_title2, $log_data);
     } else {
         add_logbook_entry($this->move['user_id'], LOGBOOK_TACTICAL, $log_title3, $log_data);
         add_logbook_entry($this->dest['user_id'], LOGBOOK_TACTICAL, $log_title4, $log_data);
     }
     return MV_EXEC_OK;
 }
    function _action_main()
    {
        global $NUM_BUILDING, $RACE_DATA;
        // #############################################################################
        // Data from the attacker
        $sql = 'SELECT ' . $this->get_combat_query_fleet_columns() . '
		FROM (ship_fleets f)
		INNER JOIN user u ON u.user_id = f.user_id
		WHERE f.fleet_id IN (' . $this->fleet_ids_str . ')';
        if (($atk_fleets = $this->db->queryrowset($sql)) === false) {
            return $this->log(MV_M_DATABASE, 'Could not query attackers fleets data! SKIP');
        }
        // #############################################################################
        // Data from the defender
        $user_id = $this->dest['user_id'];
        $planetary_attack = true;
        // The course could be optimized, but it should be possible
        // compatibility to provide much action_51.php maintained
        $cur_user = array('user_id' => $user_id, 'user_name' => $this->dest['user_name'], 'user_race' => $this->dest['user_race'], 'user_planets' => $this->dest['user_planets'], 'user_alliance' => $this->dest['user_alliance']);
        // 21/06/08 - AC: Check if attacker and defender are NOT the same player!
        if ($this->move['user_id'] == $this->dest['user_id']) {
            $this->log(MV_M_NOTICE, 'Player #' . $this->move['user_id'] . ' has tried to bomb himself! SKIP');
            // Put ships in safe place
            $sql = 'UPDATE ship_fleets
            SET planet_id = ' . $this->move['dest'] . ',
                move_id = 0
            WHERE fleet_id IN (' . $this->fleet_ids_str . ')';
            if (!$this->db->query($sql)) {
                return $this->log(MV_M_DATABASE, 'Could not update fleets location data! SKIP');
            }
            return MV_EXEC_OK;
        }
        $sql = 'SELECT DISTINCT f.user_id,
               u.user_alliance,
               ud.ud_id, ud.accepted,
               ad.ad_id, ad.type, ad.status
        FROM (ship_fleets f)
        INNER JOIN (user u) ON u.user_id = f.user_id
        LEFT JOIN (user_diplomacy ud) ON ( ( ud.user1_id = ' . $user_id . ' AND ud.user2_id = f.user_id ) OR ( ud.user1_id = f.user_id AND ud.user2_id = ' . $user_id . ' ) )
        LEFT JOIN (alliance_diplomacy ad) ON ( ( ad.alliance1_id = ' . $cur_user['user_alliance'] . ' AND ad.alliance2_id = u.user_alliance) OR ( ad.alliance1_id = u.user_alliance AND ad.alliance2_id = ' . $cur_user['user_alliance'] . ' ) )
        WHERE f.planet_id = ' . $this->move['dest'] . ' AND
              f.user_id <> ' . $user_id . ' AND
              f.user_id <> ' . $this->move['user_id'] . ' AND
              f.alert_phase >= ' . ALERT_PHASE_YELLOW;
        if (!($q_st_uid = $this->db->query($sql))) {
            return $this->log(MV_M_DATABASE, 'Could not query stationated fleets user data! SKIP');
        }
        $st_user = array();
        while ($st_uid = $this->db->fetchrow($q_st_uid)) {
            $allied = false;
            if ($st_uid['user_alliance'] == $this->dest['user_alliance']) {
                $allied = true;
            }
            if (!empty($st_uid['ud_id'])) {
                if ($st_uid['accepted'] == 1) {
                    $allied = true;
                }
            }
            if (!empty($st_uid['ad_id'])) {
                if ($st_uid['type'] == ALLIANCE_DIPLOMACY_PACT && $st_uid['status'] == 0) {
                    $allied = true;
                }
            }
            if ($allied) {
                $st_user[] = $st_uid['user_id'];
            }
        }
        $n_st_user = count($st_user);
        if ($n_st_user > 0) {
            $sql = 'SELECT ' . $this->get_combat_query_fleet_columns() . '
             FROM (ship_fleets f)
             INNER JOIN user u ON u.user_id = f.user_id
             WHERE f.planet_id = ' . $this->move['dest'] . ' AND
                   (
                     (
                       f.user_id = ' . $user_id . '
                     )
                     OR
                     (
                       f.user_id IN (' . implode(',', $st_user) . ') AND
                       f.alert_phase >= ' . ALERT_PHASE_YELLOW . '
                     )
                   )';
        } else {
            $sql = 'SELECT ' . $this->get_combat_query_fleet_columns() . '
             FROM (ship_fleets f)
             INNER JOIN user u ON u.user_id = f.user_id
             WHERE f.planet_id = ' . $this->move['dest'] . ' AND
                   f.user_id = ' . $user_id;
        }
        if (($dfd_fleets = $this->db->queryrowset($sql)) === false) {
            return $this->log(MV_M_DATABASE, 'Could not query defenders fleets data! SKIP');
        }
        $dfd_fleet_ids = array();
        foreach ($dfd_fleets as $i => $cur_fleet) {
            $dfd_fleet_ids[] = $cur_fleet['fleet_id'];
        }
        $dfd_fleet_ids_str = implode(',', $dfd_fleet_ids);
        if ($this->do_ship_combat($this->fleet_ids_str, $dfd_fleet_ids_str, MV_COMBAT_LEVEL_PLANETARY) == MV_EXEC_ERROR) {
            $this->log(MV_M_DATABASE, 'Move Action 54: Something went wrong with this fight!');
            return MV_EXEC_ERROR;
        }
        // #############################################################################
        // If the attacker has won more bomb or is final
        // #############################################################################
        // 03/04/08 - AC: Retrieve player language
        switch ($this->dest['language']) {
            case 'GER':
                $dfd_title = 'Angriff auf ' . $this->dest['planet_name'];
                break;
            case 'ITA':
                $dfd_title = 'Attacco su ' . $this->dest['planet_name'];
                break;
            default:
                $dfd_title = 'Attack on ' . $this->dest['planet_name'];
                break;
        }
        $status_code = 0;
        if ($this->cmb[MV_CMB_WINNER] == MV_CMB_ATTACKER) {
            $n_buildings = $NUM_BUILDING;
            $n_building_lvls = 0;
            $i = 0;
            while ($i <= $n_buildings) {
                $n_building_lvls += (int) $this->dest['building_' . ++$i];
            }
            $bomb_i = !empty($this->action_data[1]) ? (int) $this->action_data[1] : 0;
            // 080408 DC: the oracle says....
            $this->log(MV_M_NOTICE, 'I read building_lvls = ' . $n_building_lvls . ' and bomb_i = ' . $bomb_i);
            //Special "Antiborg" ship
            $queryadd = '';
            if ($this->dest['user_id'] == BORG_USERID) {
                $sql = 'SELECT COUNT(ship_id) AS num FROM (ships s) WHERE s.template_id = 8 AND s.fleet_id IN (' . $this->fleet_ids_str . ')';
                if (($borgw = $this->db->queryrow($sql)) === false) {
                    return $this->log(MV_M_DATABASE, 'Could not query fleets planetary weapons data! SKIP');
                }
                if ($borgw['num'] > 0) {
                    $unitkill = array(min($this->dest['unit_1'], $borgw['num'] * rand(200, 400)), min($this->dest['unit_2'], $borgw['num'] * rand(100, 300)), min($this->dest['unit_3'], $borgw['num'] * rand(75, 200)), min($this->dest['unit_4'], $borgw['num'] * rand(50, 100)));
                    $queryadd = ' unit_1=unit_1-' . $unitkill[0] . ', 
                        unit_2=unit_2-' . $unitkill[1] . ', 
                        unit_3=unit_3-' . $unitkill[2] . ', 
                        unit_4=unit_4-' . $unitkill[3] . ', ';
                }
            }
            if ($n_building_lvls == 1 && $queryadd == '') {
                // Enough Bombed...
                $sql = 'UPDATE ship_fleets
                SET planet_id = ' . $this->move['dest'] . ',
                    move_id = 0
                WHERE fleet_id IN (' . $this->fleet_ids_str . ')';
                // 080408 DC: Atrocity & Genocide are not YET permitted
                $this->log(MV_M_NOTICE, 'Atrocity & Genocide not YET permitted, bombing will not be done.');
                if (!$this->db->query($sql)) {
                    return $this->log(MV_M_DATABASE, 'Could not update fleets location data! SKIP');
                }
                if ($bomb_i > 0) {
                    $status_code = -2;
                    // #############################################################################
                    // 03/04/08 - AC: Retrieve player language
                    switch ($this->move['language']) {
                        case 'GER':
                            $atk_title = 'Angriff auf ' . $this->dest['planet_name'] . ' beendet';
                            break;
                        case 'ITA':
                            $atk_title = 'Attacco su ' . $this->dest['planet_name'] . ' terminato';
                            break;
                        default:
                            $atk_title = 'Attack on ' . $this->dest['planet_name'] . ' ended';
                            break;
                    }
                } else {
                    $status_code - 1;
                    // #############################################################################
                    // 03/04/08 - AC: Retrieve player language
                    switch ($this->move['language']) {
                        case 'GER':
                            $atk_title = 'Angriff auf ' . $this->dest['planet_name'] . ' teilweise erfolgreich';
                            break;
                        case 'ITA':
                            $atk_title = 'Attacco su ' . $this->dest['planet_name'] . ' parzialmente riuscito';
                            break;
                        default:
                            $atk_title = 'Attack on ' . $this->dest['planet_name'] . ' partially successful';
                            break;
                    }
                }
            } else {
                $sql = 'SELECT SUM(st.value_3) AS sum_planetary_weapons
                FROM (ships s)
                INNER JOIN ship_templates st ON st.id = s.template_id
                WHERE s.fleet_id IN (' . $this->fleet_ids_str . ') AND s.torp >= 5';
                if (($plweapons = $this->db->queryrow($sql)) === false) {
                    return $this->log(MV_M_DATABASE, 'Could not query fleets planetary weapons data! SKIP');
                }
                // 190815 DC Yeah! We need moooar querieeees!!!
                $sql = 'SELECT COUNT(*) as c3 FROM (ships s) INNER JOIN (ship_templates st) ON st.id =s.template_id
                 WHERE s.fleet_id IN (' . $this->fleet_ids_str . ') AND s.torp >= 5 AND s.experience >= 70 AND st.ship_class = 3';
                if (($c3bonus = $this->db->queryrow($sql)) === false) {
                    return $this->log(MV_M_DATABASE, 'Could not query fleets planetary weapons data! SKIP');
                }
                $sql = 'SELECT COUNT(*) as c2 FROM (ships s) INNER JOIN (ship_templates st) ON st.id =s.template_id
                 WHERE s.fleet_id IN (' . $this->fleet_ids_str . ') AND s.torp >= 5 AND s.experience >= 100 AND st.ship_class = 2';
                if (($c2bonus = $this->db->queryrow($sql)) === false) {
                    return $this->log(MV_M_DATABASE, 'Could not query fleets planetary weapons data! SKIP');
                }
                $planetary_weapons = (int) $plweapons['sum_planetary_weapons'] + (int) ($c2bonus['c2'] * 10) + (int) ($c3bonus['c3'] * 50);
                if ($planetary_weapons == 0) {
                    $sql = 'UPDATE ship_fleets
                    SET planet_id = ' . $this->move['dest'] . ',
                        move_id = 0
                    WHERE fleet_id IN (' . $this->fleet_ids_str . ')';
                    if (!$this->db->query($sql)) {
                        return $this->log(MV_M_DATABASE, 'Could not update fleets location data! SKIP');
                    }
                    $status_code = -3;
                    // #############################################################################
                    // 03/04/08 - AC: Retrieve player language
                    switch ($this->move['language']) {
                        case 'GER':
                            $atk_title = 'Angriff auf ' . $this->dest['planet_name'] . ' teilweise erfolgreich';
                            break;
                        case 'ITA':
                            $atk_title = 'Attacco su ' . $this->dest['planet_name'] . ' parzialmente riuscito';
                            break;
                        default:
                            $atk_title = 'Attack on ' . $this->dest['planet_name'] . ' partially successful';
                            break;
                    }
                } else {
                    if (!isset($this->action_data[0])) {
                        return $this->log(MV_M_ERROR, 'action_54: Could not find required action_data parameter 0! SKIP');
                    }
                    // Updating torpedo stocks on ships
                    $sql = 'UPDATE ships SET torp = torp - 5 WHERE fleet_id IN (' . $this->fleet_ids_str . ') AND torp >= 5';
                    if (!$this->db->query($sql)) {
                        return $this->log(MV_M_DATABASE, 'Could not update torpedo data after attack! SKIP');
                    }
                    $focus = (int) $this->move['action_data'][0];
                    if ($focus < 0) {
                        $focus = 0;
                    }
                    if ($focus > 3) {
                        $focus = 3;
                    }
                    $new_dest = PlanetaryAttack($this->mid, $planetary_weapons, $this->dest, $focus, $RACE_DATA[$this->dest['user_race']][17]);
                    $sql = 'UPDATE planets
                    SET resource_4 = ' . $new_dest['resource_4'] . ',
                        building_1 = ' . $new_dest['building_1'] . ',
                        building_2 = ' . $new_dest['building_2'] . ',
                        building_3 = ' . $new_dest['building_3'] . ',
                        building_4 = ' . $new_dest['building_4'] . ',
                        building_5 = ' . $new_dest['building_5'] . ',
                        building_6 = ' . $new_dest['building_6'] . ',
                        building_7 = ' . $new_dest['building_7'] . ',
                        building_8 = ' . $new_dest['building_8'] . ',
                        building_9 = ' . $new_dest['building_9'] . ',
                        building_10 = 0,
                        building_11 = ' . $new_dest['building_11'] . ',
                        building_12 = ' . $new_dest['building_12'] . ',
                        building_13 = 0,
                        unit_1 = ' . $new_dest['unit_1'] . ',
                        unit_2 = ' . $new_dest['unit_2'] . ',
                        unit_3 = ' . $new_dest['unit_3'] . ',
                        unit_4 = ' . $new_dest['unit_4'] . ',
                        unit_5 = ' . $new_dest['unit_5'] . ',
                        unit_6 = ' . $new_dest['unit_6'] . ',
                        workermine_1 = ' . ($new_dest['building_2'] + 1) * 100 . ',
                        workermine_2 = ' . ($new_dest['building_3'] + 1) * 100 . ',
                        workermine_3 = ' . ($new_dest['building_4'] + 1) * 100 . ',
                        ' . $queryadd . '
                        recompute_static=1
                    WHERE planet_id = ' . $this->move['dest'];
                    if (!$this->db->query($sql)) {
                        return $this->log(MV_M_DATABASE, 'Could not update planets data after attack! SKIP');
                    }
                    $sql = 'UPDATE scheduler_shipmovement
                    SET move_begin = ' . $this->CURRENT_TICK . ',
                        move_finish = ' . ($this->CURRENT_TICK + 8) . ',
                        action_data = "' . serialize(array($focus, $bomb_i + 1)) . '"
                    WHERE move_id = ' . $this->mid;
                    if (!$this->db->query($sql)) {
                        return $this->log(MV_M_DATABASE, 'Could not update move data! SKIP');
                    }
                    $this->check_academy_status();
                    // Gonna check the academy queue after bombing
                    $this->check_shipyard_status();
                    // Gonna check the shipyard status after bombing
                    $this->check_spacedock_status();
                    // Gonna check the ships in spacedock after bombing
                    $status_code = $bomb_i > 0 ? 2 : 1;
                    // #############################################################################
                    // 03/04/08 - AC: Retrieve player language
                    switch ($this->move['language']) {
                        case 'GER':
                            $atk_title = 'Angriff auf ' . $this->dest['planet_name'] . ' erfolgreich';
                            break;
                        case 'ITA':
                            $atk_title = 'Attacco su ' . $this->dest['planet_name'] . ' riuscito';
                            break;
                        default:
                            $atk_title = 'Attack on ' . $this->dest['planet_name'] . ' successful';
                            break;
                    }
                    // If the attack was on a settlers planet, they will get a little mad!
                    if ($this->dest['user_id'] == INDEPENDENT_USERID) {
                        $this->log(MV_M_NOTICE, 'Colony: Settlers being attacked!!! They gonna be mad!');
                        $sql = 'DELETE FROM settlers_relations WHERE planet_id = ' . $this->move['dest'] . ' AND user_id = ' . $this->move['user_id'];
                        if (!$this->db->query($sql)) {
                            $this->log(MV_M_DATABASE, 'Could not update settlers moods! CONTINUE!');
                        }
                        if (!empty($this->move['user_alliance']) && $this->move['user_alliance_status'] > 2) {
                            $sql = 'INSERT INTO settlers_relations
                            SET planet_id = ' . $this->move['dest'] . ',
                                user_id = ' . $this->move['user_id'] . ',
                                alliance_id = ' . $this->move['user_alliance'] . ',
                                race_id = ' . $this->move['user_race'] . ',
                                timestamp = ' . time() . ',
                                log_code = 11,
                                mood_modifier = - 50';
                        } else {
                            $sql = 'INSERT INTO settlers_relations
                            SET planet_id = ' . $this->move['dest'] . ',
                                user_id = ' . $this->move['user_id'] . ',
                                race_id = ' . $this->move['user_race'] . ',
                                timestamp = ' . time() . ',
                                log_code = 11,
                                mood_modifier = - 50';
                        }
                        if (!$this->db->query($sql)) {
                            $this->log(MV_M_DATABASE, 'Could not update settlers moods! CONTINUE!');
                        }
                        $this->check_best_mood($this->move['dest'], false);
                    }
                    $this->flags['keep_move_alive'] = true;
                }
            }
        } else {
            // #############################################################################
            // 17/08/15 - Retreat Management
            $sql = 'SELECT COUNT(*) as ship_escaped FROM ships WHERE fleet_id IN (' . $this->fleet_ids_str . ')';
            $e_s_c = $this->db->queryrow($sql);
            if (isset($e_s_c['ship_escaped']) && $e_s_c['ship_escaped'] > 0) {
                $sql = 'SELECT system_id, planet_distance_id FROM planets WHERE planet_id = ' . $this->move['dest'];
                $e_s_s = $this->db->queryrow($sql);
                $sql = 'SELECT planet_id FROM planets WHERE system_id = ' . $e_s_s['system_id'] . ' AND planet_id <> ' . $this->move['dest'] . '
                       AND planet_distance_id > ' . $e_s_s['planet_distance_id'] . ' ORDER BY planet_distance_id ASC LIMIT 0,1';
                if (!($res = $this->db->query($sql))) {
                    return $this->log(MV_M_DATABASE, 'Could not read system data!!! SQL is ' . $sql);
                }
                $rows = $this->db->num_rows();
                if ($rows > 0) {
                    $escaperes = $this->db->fetchrow($res);
                    $newdest = $escaperes['planet_id'];
                } else {
                    $newdest = $this->move['dest'];
                }
                $sql = 'UPDATE scheduler_shipmovement SET start = ' . $this->move['dest'] . ', dest = ' . $newdest . ', move_begin = ' . $this->CURRENT_TICK . ', move_finish = ' . ($this->CURRENT_TICK + 4) . ',' . ' action_code = 28, action_data = 0, n_ships = ' . $e_s_c['ship_escaped'] . ' WHERE move_id = ' . $this->move['move_id'];
                if (!$this->db->query($sql)) {
                    return $this->log(MV_M_DATABASE, 'Could not update movement data!!! SQL is ' . $sql);
                }
                $this->flags['keep_move_alive'] = true;
            }
            // #############################################################################
            // 03/04/08 - AC: Retrieve player language
            switch ($this->move['language']) {
                case 'GER':
                    $atk_title = 'Angriff auf ' . $this->dest['planet_name'] . ' fehlgeschlagen';
                    break;
                case 'ITA':
                    $atk_title = 'Attacco su ' . $this->dest['planet_name'] . ' fallito';
                    break;
                default:
                    $atk_title = 'Attack on ' . $this->dest['planet_name'] . ' failed';
                    break;
            }
        }
        // #############################################################################
        // Write logbook
        $log1_data = array(54, $this->move['user_id'], $this->move['dest'], $this->dest['planet_name'], $this->dest['user_id'], 0, 0, 0, MV_CMB_ATTACKER, $this->cmb[MV_CMB_WINNER] == MV_CMB_ATTACKER ? 1 : 0, 0, 0, $atk_fleets, $dfd_fleets);
        $log2_data = array(54, $this->move['user_id'], $this->move['dest'], $this->dest['planet_name'], $this->dest['user_id'], 0, 0, 0, MV_CMB_DEFENDER, $this->cmb[MV_CMB_WINNER] == MV_CMB_DEFENDER ? 1 : 0, 0, 0, $atk_fleets, $dfd_fleets);
        $log1_data[10] = $this->cmb[MV_CMB_KILLS_EXT];
        $log2_data[10] = $this->cmb[MV_CMB_KILLS_EXT];
        $log2_data[14] = $this->cmb[MV_CMB_KILLS_PLANETARY];
        $log1_data[17] = $log2_data[17] = $status_code;
        if (!empty($new_dest)) {
            $log1_data[18] = $log2_data[18] = array($this->dest['resource_4'] - $new_dest['resource_4'], $this->dest['building_1'] - $new_dest['building_1'], $this->dest['building_2'] - $new_dest['building_2'], $this->dest['building_3'] - $new_dest['building_3'], $this->dest['building_4'] - $new_dest['building_4'], $this->dest['building_5'] - $new_dest['building_5'], $this->dest['building_6'] - $new_dest['building_6'], $this->dest['building_7'] - $new_dest['building_7'], $this->dest['building_8'] - $new_dest['building_8'], $this->dest['building_9'] - $new_dest['building_9'], 0, $this->dest['building_11'] - $new_dest['building_11'], $this->dest['building_12'] - $new_dest['building_12'], $this->dest['unit_1'] - $new_dest['unit_1'], $this->dest['unit_2'] - $new_dest['unit_2'], $this->dest['unit_3'] - $new_dest['unit_3'], $this->dest['unit_4'] - $new_dest['unit_4'], $this->dest['unit_5'] - $new_dest['unit_5'], $this->dest['unit_6'] - $new_dest['unit_6'], 0);
        }
        $log1_data[19] = $log2_data[19] = $this->dest['user_race'];
        if (isset($unitkill)) {
            $log1_data[20] = $log2_data[20] = $unitkill;
        }
        add_logbook_entry($this->move['user_id'], LOGBOOK_TACTICAL, $atk_title, $log1_data);
        add_logbook_entry($this->dest['user_id'], LOGBOOK_TACTICAL, $dfd_title, $log2_data);
        if ($n_st_user > 0) {
            $log2_data[2] = $this->move['start'];
            $log2_data[3] = $this->dest['planet_name'];
            $log2_data[4] = $user_id;
            $log2_data[5] = 0;
            $log2_data[6] = 0;
            $log2_data[7] = 0;
            $log2_data[16] = 1;
            for ($i = 0; $i < $n_st_user; ++$i) {
                // #############################################################################
                // 03/04/08 - AC: Retrieve player language
                $log_title = 'One of your allies defended ' . $this->dest['planet_name'];
                $sql = 'SELECT language FROM user WHERE user_id = ' . $st_user[$i];
                if (!($lang = $this->db->queryrow($sql))) {
                    $this->log(MV_M_DATABASE, 'Could not retrieve player language');
                } else {
                    switch ($lang['language']) {
                        case 'GER':
                            $log_title = 'Verb&uuml;ndeten bei ' . $this->dest['planet_name'] . ' verteidigt';
                            break;
                        case 'ITA':
                            $log_title = 'Difesa alleata presso ' . $this->dest['planet_name'];
                            break;
                    }
                }
                add_logbook_entry($st_user[$i], LOGBOOK_TACTICAL, $log_title, $log2_data);
            }
        }
        return MV_EXEC_OK;
    }
 function _action_main()
 {
     global $RACE_DATA;
     // #############################################################################
     // Prepare Logbook to be able to cancel at any time
     $log_data = array(24, $this->move['user_id'], $this->move['start'], $this->start['planet_name'], $this->start['user_id'], $this->move['dest'], $this->dest['planet_name'], $this->dest['user_id'], 0);
     // #############################################################################
     // 10/03/08 - AC: Retrieve player language
     switch ($this->move['language']) {
         case 'GER':
             $col_title = 'Kolonisation von ';
             $col_fail = ' fehlgeschlagen';
             $col_success = ' erfolgreich';
             $ter_title = 'Terraforming von ';
             $ter_fail = ' fehlgeschlagen';
             $ter_success = ' erfolgreich';
             break;
         case 'ITA':
             $col_title = 'Colonizzazione di ';
             $col_fail = ' fallita';
             $col_success = ' riuscita';
             $ter_title = 'Terraforming di ';
             $ter_fail = ' fallito';
             $ter_success = ' riuscito';
             break;
         default:
             $col_title = 'Colonization of ';
             $col_fail = ' failed';
             $col_success = ' successful';
             $ter_title = 'Terraforming of ';
             $ter_fail = ' failed';
             $ter_success = ' succeesful';
             break;
     }
     // #############################################################################
     // Args check
     if (!isset($this->action_data[1])) {
         $this->action_data[1] = false;
     }
     if (!isset($this->action_data[2])) {
         $this->action_data[2] = false;
     }
     // #############################################################################
     // Planets check
     if (!empty($this->dest['user_id'])) {
         $sql = 'UPDATE ship_fleets
                 SET planet_id = ' . $this->move['dest'] . ',
                     move_id = 0
                 WHERE fleet_id IN (' . $this->fleet_ids_str . ')';
         // Here there is a point at which I should be notified
         if (!$this->db->query($sql)) {
             return $this->log(MV_M_DATABASE, 'Could not update fleets location data! CONTINUE');
         }
         $log_data[8] = -1;
         add_logbook_entry($this->move['user_id'], LOGBOOK_TACTICAL, $col_title . $this->dest['planet_name'] . $col_fail, $log_data);
         return MV_EXEC_OK;
     }
     // #############################################################################
     // Colonization ship check
     if (empty($this->action_data[0])) {
         return $this->log(MV_M_ERROR, 'action_24: Could not find required action_data entry [0]! SKIP');
     }
     $ship_id = (int) $this->action_data[0];
     $sql = 'SELECT s.ship_id, s.user_id, s.unit_1, s.unit_2, s.unit_3, s.unit_4,
                    st.name, st.race, st.ship_torso, st.min_unit_1, st.min_unit_2, st.min_unit_3, st.min_unit_4,
                    f.fleet_id, f.move_id, f.n_ships
             FROM (ships s)
             INNER JOIN (ship_templates st) ON st.id = s.template_id
             INNER JOIN (ship_fleets f) ON f.fleet_id = s.fleet_id
             WHERE s.ship_id = ' . $ship_id;
     if (($cship = $this->db->queryrow($sql)) === false) {
         return $this->log(MV_M_DATABASE, 'Could not query cship data! SKIP');
     }
     $cship_exists = true;
     if (empty($cship['ship_id'])) {
         $cship_exists = false;
     } elseif ($cship['user_id'] != $this->move['user_id']) {
         $cship_exists = false;
     } elseif ($cship['ship_torso'] != SHIP_TYPE_COLO) {
         $cship_exists = false;
     } elseif ($cship['move_id'] != $this->mid) {
         $cship_exists = false;
     }
     if (!$cship_exists) {
         $sql = 'UPDATE ship_fleets
                 SET planet_id = ' . $this->move['dest'] . ',
                     move_id = 0
                 WHERE fleet_id IN (' . $this->fleet_ids_str . ')';
         // Here there is a point at which I should be notified
         if (!$this->db->query($sql)) {
             $this->log(MV_M_DATABASE, 'Could not update fleets location data! CONTINUE');
         }
         $log_data[8] = -2;
         add_logbook_entry($this->move['user_id'], LOGBOOK_TACTICAL, $col_title . $this->dest['planet_name'] . $col_fail, $log_data);
         return MV_EXEC_OK;
     }
     // #############################################################################
     // Terraforming planet!!!
     if ((bool) $this->action_data[1]) {
         // Pre-Terraforming Check
         $sql = 'SELECT resource_3 FROM ship_fleets WHERE fleet_id IN (' . $this->fleet_ids_str . ')';
         if (($dilicheck = $this->db->queryrow($sql)) === false) {
             $this->log(MV_M_DATABASE, 'Could not query fleets cargo data! Assumed zero.');
             $dilithium = 0;
         } else {
             $dilithium = $dilicheck['resource_3'];
         }
         if ($dilithium < 150000) {
             $log_data[8] = -3;
             add_logbook_entry($this->move['user_id'], LOGBOOK_TACTICAL, $ter_title . $this->dest['planet_name'] . $ter_fail, $log_data);
             return MV_EXEC_OK;
         }
         $check_clear = true;
         $sql = 'SELECT planet_type, planet_owner, planet_distance_id FROM planets WHERE planet_id = ' . $this->move['dest'];
         if (($_check = $this->db->queryrow($sql)) === false) {
             $this->log(MV_M_DATABASE, 'Could not query terraforming planet data! Assumed invalid.');
             $check_clear = false;
         } elseif ($_check['planet_owner'] != 0) {
             $check_clear = false;
         } elseif ($_check['planet_type'] != 'a' && $_check['planet_type'] != 'b' && $_check['planet_type'] != 'c' && $_check['planet_type'] != 'd') {
             $check_clear = false;
         }
         if (!$check_clear) {
             $log_data[8] = -4;
             add_logbook_entry($this->move['user_id'], LOGBOOK_TACTICAL, $ter_title . $this->dest['planet_name'] . $ter_fail, $log_data);
             return MV_EXEC_OK;
         }
         // Ok, it seems like all is GREEN, let's do it.
         switch ($_check['planet_distance_id']) {
             case 0:
             case 1:
                 $type_probabilities = array('k' => 35, 'e' => 13, 'f' => 13, 'g' => 13, 'n' => 10, 'l' => 8, 'x' => 5, 'y' => 3);
                 break;
             case 2:
             case 3:
                 $type_probabilities = array('l' => 8, 'e' => 20, 'f' => 20, 'g' => 20, 'n' >= 15, 'm' => 6, 'o' => 5, 'x' => 4, 'y' => 2);
                 break;
             case 4:
             case 5:
             case 6:
             case 7:
                 $type_probabilities = array('h' => 25, 'j' => 31, 'k' => 15, 'n' => 15, 'p' => 10, 'x' => 3, 'y' => 1);
                 break;
         }
         $type_array = array();
         foreach ($type_probabilities as $type => $probability) {
             for ($i = 0; $i < $probability; ++$i) {
                 $type_array[] = $type;
             }
         }
         $planet_type = $type_array[array_rand($type_array)];
         global $PLANETS_DATA;
         // Random variance of the constants basis of the planet
         $rateo_1 = round($PLANETS_DATA[$planet_type][0] + (200 - mt_rand(0, 350)) * 0.001, 2);
         if ($rateo_1 < 0.1) {
             $rateo_1 = 0.1;
         }
         $rateo_2 = round($PLANETS_DATA[$planet_type][1] + (200 - mt_rand(0, 350)) * 0.001, 2);
         if ($rateo_2 < 0.1) {
             $rateo_2 = 0.1;
         }
         $rateo_3 = round($PLANETS_DATA[$planet_type][2] + (200 - mt_rand(0, 350)) * 0.001, 2);
         if ($rateo_3 < 0.1) {
             $rateo_3 = 0.1;
         }
         $rateo_4 = $PLANETS_DATA[$planet_type][3] + 0.05;
         $sql = 'UPDATE planets SET
                        planet_type = "' . $planet_type . '",
                        rateo_1 = ' . $rateo_1 . ',
                        rateo_2 = ' . $rateo_2 . ',
                        rateo_3 = ' . $rateo_3 . ',
                        rateo_4 = ' . $rateo_4 . ',
                        recompute_static = 1
                 WHERE planet_id = ' . $this->move['dest'];
         if (!$this->db->query($sql)) {
             return $this->log(MV_M_DATABASE, 'Could not update planets data! SKIP');
         }
         $sql = 'DELETE FROM planet_details WHERE planet_id = ' . $this->move['dest'] . ' AND log_code = 100';
         if (!$this->db->query($sql)) {
             return $this->log(MV_M_DATABASE, 'Could not update planet details data! SKIP');
         }
         $sql = 'UPDATE ship_fleets
                 SET planet_id = ' . $this->move['dest'] . ',
                     move_id = 0,
                     resource_3 = resource_3 - 150000
                 WHERE fleet_id IN (' . $this->fleet_ids_str . ')';
         if (!$this->db->query($sql)) {
             return $this->log(MV_M_DATABASE, 'Could not update fleets data! SKIP');
         }
         $log_data[8] = 2;
         add_logbook_entry($this->move['user_id'], LOGBOOK_TACTICAL, $ter_title . $this->dest['planet_name'] . $ter_success, $log_data);
         // #############################################################################
         // Add History Record in planet details; log_code = 31
         $sql = 'INSERT INTO planet_details (planet_id, planet_type, user_id, alliance_id, source_uid, source_aid, timestamp, log_code)
                 VALUES (' . $this->move['dest'] . ', "' . $planet_type . '",' . $this->move['user_id'] . ', ' . $this->move['user_alliance'] . ', ' . $this->move['user_id'] . ', ' . $this->move['user_alliance'] . ', ' . time() . ', 31)';
         if (!$this->db->query($sql)) {
             $this->log(MV_M_DATABASE, 'Could not update planet details data!');
         }
         return MV_EXEC_OK;
     }
     // #############################################################################
     // Planet goes to Settlers Community!
     if ((bool) $this->action_data[2]) {
         // Target planet MUST BE unsettled!
         if (!empty($this->dest['planet_owner'])) {
             $log_data[8] = -4;
             add_logbook_entry($this->move['user_id'], LOGBOOK_TACTICAL, $ter_title . $this->dest['planet_name'] . $ter_fail, $log_data);
             return MV_EXEC_OK;
         }
         // How many planets Settlers already controls?
         $sql = 'SELECT COUNT(planet_id) AS n_planets FROM planets WHERE planet_owner = ' . INDEPENDENT_USERID;
         if (($pcount = $this->db->queryrow($sql)) === false) {
             $this->log(MV_M_DATABASE, 'Could not query planets count data! CONTINUE USING INSTABLE VALUE');
             $n_planets = $cur_move['user_planets'];
         } else {
             $n_planets = $pcount['n_planets'];
         }
         // All seems ok, let's clear all the queue on the planet
         $sql = 'DELETE FROM scheduler_instbuild WHERE planet_id = ' . $this->move['dest'];
         if (!$this->db->query($sql)) {
             $this->log(MV_M_DATABASE, 'Could not delete scheduler instbuild data! CONTINUE');
         }
         $sql = 'DELETE FROM scheduler_shipbuild WHERE planet_id = ' . $this->move['dest'];
         if (!$this->db->query($sql)) {
             $this->log('MySQL', 'Could not delete shipbuild data! CONTINUE');
         }
         $sql = 'DELETE FROM scheduler_research WHERE planet_id = ' . $this->move['dest'];
         if (!$this->db->query($sql)) {
             $this->log(MV_M_DATABASE, 'Could not delete scheduler research data! CONTINUE');
         }
         $sql = 'UPDATE planets
                 SET planet_owner = ' . INDEPENDENT_USERID . ',
                 planet_owned_date = ' . time() . ',
                 planet_owner_enum = ' . ($n_planets - 1 > 0 ? $n_planets - 1 : 0) . ',
                 planet_name = "Colony' . $this->move['dest'] . '",
                 npc_last_action = 0,
                 research_1 = 0,
                 research_2 = 0,
                 research_3 = 0,
                 research_4 = 0,
                 research_5 = 0,
                 resource_1 = 100,
                 resource_2 = 100,
                 resource_3 = 100,
                 resource_4 = 100,
                 recompute_static = 1,
                 building_1 = 1,
                 building_2 = 0,
                 building_3 = 0,
                 building_4 = 0,
                 building_5 = 0,
                 building_6 = 0,
                 building_7 = 0,
                 building_8 = 0,
                 building_9 = 0,
                 building_10 = 0,
                 building_11 = 0,
                 building_12 = 0,
                 building_13 = 0,
                 unit_1 = ' . ($cship['unit_1'] - $cship['min_unit_1'] + 50) . ',
                 unit_2 = ' . ($cship['unit_2'] - $cship['min_unit_2'] + 25) . ',
                 unit_3 = ' . ($cship['unit_3'] - $cship['min_unit_3']) . ',
                 unit_4 = ' . ($cship['unit_4'] - $cship['min_unit_4'] + 1) . ',
                 unit_5 = 0,
                 unit_6 = 0,
                 workermine_1 = 100,
                 workermine_2 = 100,
                 workermine_3 = 100,
                 catresearch_1 = 0,
                 catresearch_2 = 0,
                 catresearch_3 = 0,
                 catresearch_4 = 0,
                 catresearch_5 = 0,
                 catresearch_6 = 0,
                 catresearch_7 = 0,
                 catresearch_8 = 0,
                 catresearch_9 = 0,
                 catresearch_10 = 0,
                 unittrainid_1 = 0,
                 unittrainid_2 = 0,
                 unittrainid_3 = 0,
                 unittrainid_4 = 0,
                 unittrainid_5 = 0,
                 unittrainid_6 = 0,
                 unittrainid_7 = 0,
                 unittrainid_8 = 0,
                 unittrainid_9 = 0,
                 unittrainid_10 = 0,
                 unittrainnumber_1 = 0,
                 unittrainnumber_2 = 0,
                 unittrainnumber_3 = 0,
                 unittrainnumber_4 = 0,
                 unittrainnumber_5 = 0,
                 unittrainnumber_6 = 0,
                 unittrainnumber_7 = 0,
                 unittrainnumber_8 = 0,
                 unittrainnumber_9 = 0,
                 unittrainnumber_10 = 0,
                 unittrainnumberleft_1 = 0,
                 unittrainnumberleft_2 = 0,
                 unittrainnumberleft_3 = 0,
                 unittrainnumberleft_4 = 0,
                 unittrainnumberleft_5 = 0,
                 unittrainnumberleft_6 = 0,
                 unittrainnumberleft_7 = 0,
                 unittrainnumberleft_8 = 0,
                 unittrainnumberleft_9 = 0,
                 unittrainnumberleft_10 = 0,
                 unittrain_actual = 0,
                 unittrainid_nexttime=0,
                 planet_surrender=0
             WHERE planet_id = ' . $this->move['dest'];
         if (!$this->db->query($sql)) {
             return $this->log(MV_M_DATABASE, 'Could not update planets data! SKIP');
         }
         $sql = 'DELETE FROM ships WHERE fleet_id = -' . $this->move['dest'] . ' OR ship_id = ' . $ship_id;
         if (!$this->db->query($sql)) {
             return $this->log(MV_M_DATABASE, 'Could not delete ships data! SKIP');
         }
         if ($cship['n_ships'] == 1) {
             $sql = 'DELETE FROM ship_fleets WHERE fleet_id = ' . $cship['fleet_id'];
         } else {
             $sql = 'UPDATE ship_fleets SET n_ships = n_ships - 1 WHERE fleet_id = ' . $cship['fleet_id'];
         }
         if (!$this->db->query($sql)) {
             $this->log(MV_M_DATABASE, 'Could not update/delete cships fleet data! CONTINUE');
         }
         $sql = 'UPDATE ship_fleets SET planet_id = ' . $this->move['dest'] . ', move_id = 0 WHERE fleet_id IN (' . $this->fleet_ids_str . ')';
         if (!$this->db->query($sql)) {
             return $this->log(MV_M_DATABASE, 'Could not update fleets data! SKIP');
         }
         $log_data[8] = 1;
         $log_data[9] = $cship['name'];
         $log_data[10] = $cship['race'];
         add_logbook_entry($this->move['user_id'], LOGBOOK_TACTICAL, $col_title . $this->dest['planet_name'] . $col_success, $log_data);
         // #############################################################################
         // Add History Record in planet details; log_code = 32
         $sql = 'INSERT INTO planet_details (planet_id, user_id, alliance_id, source_uid, source_aid, timestamp, log_code)
                 VALUES (' . $this->move['dest'] . ', ' . $this->move['user_id'] . ', ' . $this->move['user_alliance'] . ', ' . $this->move['user_id'] . ', ' . $this->move['user_alliance'] . ', ' . time() . ', 32)';
         if (!$this->db->query($sql)) {
             $this->log(MV_M_DATABASE, 'Could not update planet details data!');
         }
         // #############################################################################
         // Mood Records. We have to add log_code 1,30
         if (isset($this->move['user_alliance']) && !empty($this->move['user_alliance']) && $this->move['user_alliance_status'] > 2) {
             // First Contact
             $sql = 'INSERT INTO settlers_relations SET planet_id = ' . $this->move['dest'] . ', race_id = ' . $this->move['user_race'] . ', user_id = ' . $this->move['user_id'] . ', alliance_id = ' . $this->move['user_alliance'] . ', timestamp = ' . time() . ', log_code = 1, mood_modifier = 20';
             if (!$this->db->query($sql)) {
                 return $this->log(MV_M_DATABASE, 'Could not create new settlers relations! SKIP!!!');
             }
             // Colo Founder, +1 to timestap to avoid duplicate key
             $sql = 'INSERT INTO settlers_relations SET planet_id = ' . $this->move['dest'] . ', user_id = ' . $this->move['user_id'] . ', alliance_id = ' . $this->move['user_alliance'] . ', race_id = ' . $this->move['user_race'] . ', timestamp = ' . (time() + 1) . ', log_code = 30, mood_modifier = 80';
             if (!$this->db->query($sql)) {
                 $this->log(MV_M_DATABASE, 'Could not update settlers moods! CONTINUE!');
             }
         } else {
             // First Contact
             $sql = 'INSERT INTO settlers_relations SET planet_id = ' . $this->move['dest'] . ', race_id = ' . $this->move['user_race'] . ', user_id = ' . $this->move['user_id'] . ', timestamp = ' . time() . ', log_code = 1, mood_modifier = 10';
             if (!$this->db->query($sql)) {
                 return $this->log(MV_M_DATABASE, 'Could not create new settlers relations! SKIP!!!');
             }
             // Colo Founder +1 to timestap to avoid duplicate key
             $sql = 'INSERT INTO settlers_relations SET planet_id = ' . $this->move['dest'] . ', user_id = ' . $this->move['user_id'] . ', race_id = ' . $this->move['user_race'] . ', timestamp = ' . (time() + 1) . ', log_code = 30, mood_modifier = 80';
             if (!$this->db->query($sql)) {
                 $this->log(MV_M_DATABASE, 'Could not update settlers moods! CONTINUE!');
             }
         }
         return MV_EXEC_OK;
     }
     // #############################################################################
     // We need the number of planets, which owns the colonizer
     // (we want to determine planet_owner_enum surely)
     $sql = 'SELECT COUNT(planet_id) AS n_planets
             FROM planets
             WHERE planet_owner = ' . $this->move['user_id'];
     if (($pcount = $this->db->queryrow($sql)) === false) {
         $this->log(MV_M_DATABASE, 'Could not query planets count data! CONTINUE USING INSTABLE VALUE');
         $n_planets = $cur_move['user_planets'];
     } else {
         $n_planets = $pcount['n_planets'];
     }
     if ($n_planets >= $RACE_DATA[$this->move['user_race']][31]) {
         $sql = 'UPDATE ship_fleets
                 SET planet_id = ' . $this->move['dest'] . ',
                     move_id = 0
                 WHERE fleet_id IN (' . $this->fleet_ids_str . ')';
         // Here there is a point at which I should be notified
         if (!$this->db->query($sql)) {
             return $this->log(MV_M_DATABASE, 'Could not update fleets location data! CONTINUE');
         }
         $log_data[8] = -3;
         add_logbook_entry($this->move['user_id'], LOGBOOK_TACTICAL, $col_title . $this->dest['planet_name'] . $col_fail, $log_data);
         return MV_EXEC_OK;
     }
     // #############################################################################
     // Colonization attempt
     $sql = 'DELETE FROM scheduler_instbuild
             WHERE planet_id = ' . $this->move['dest'];
     if (!$this->db->query($sql)) {
         $this->log(MV_M_DATABASE, 'Could not delete scheduler instbuild data! CONTINUE');
     }
     $sql = 'DELETE FROM scheduler_shipbuild
             WHERE planet_id = ' . $this->move['dest'];
     if (!$this->db->query($sql)) {
         $this->log('MySQL', 'Could not delete shipbuild data! CONTINUE');
     }
     $sql = 'DELETE FROM scheduler_research
             WHERE planet_id = ' . $this->move['dest'];
     if (!$this->db->query($sql)) {
         $this->log(MV_M_DATABASE, 'Could not delete scheduler research data! CONTINUE');
     }
     $structure_pts = $this->get_structure_points($this->move['user_id'], $this->move['dest']);
     $sql = 'UPDATE planets
             SET planet_owner = ' . $this->move['user_id'] . ',
                 planet_owned_date = ' . time() . ',
                 planet_owner_enum = ' . ($n_planets - 1) . ',
                 planet_available_points = ' . $structure_pts . ',
                 research_1 = 0,
                 research_2 = 0,
                 research_3 = 0,
                 research_4 = 0,
                 research_5 = 0,
                 resource_1 = 50,
                 resource_2 = 50,
                 resource_3 = 0,
                 resource_4 = 10,
                 recompute_static = 1,
                 building_1 = 1,
                 building_2 = 0,
                 building_3 = 0,
                 building_4 = 0,
                 building_5 = 0,
                 building_6 = 0,
                 building_7 = 0,
                 building_8 = 0,
                 building_9 = 0,
                 building_10 = 0,
                 building_11 = 0,
                 building_12 = 0,
                 building_13 = 0,
                 unit_1 = ' . ($cship['unit_1'] - $cship['min_unit_1']) . ',
                 unit_2 = ' . ($cship['unit_2'] - $cship['min_unit_2']) . ',
                 unit_3 = ' . ($cship['unit_3'] - $cship['min_unit_3']) . ',
                 unit_4 = ' . ($cship['unit_4'] - $cship['min_unit_4']) . ',
                 unit_5 = 0,
                 unit_6 = 0,
                 workermine_1 = 100,
                 workermine_2 = 100,
                 workermine_3 = 100,
                 catresearch_1 = 0,
                 catresearch_2 = 0,
                 catresearch_3 = 0,
                 catresearch_4 = 0,
                 catresearch_5 = 0,
                 catresearch_6 = 0,
                 catresearch_7 = 0,
                 catresearch_8 = 0,
                 catresearch_9 = 0,
                 catresearch_10 = 0,
                 unittrainid_1 = 0,
                 unittrainid_2 = 0,
                 unittrainid_3 = 0,
                 unittrainid_4 = 0,
                 unittrainid_5 = 0,
                 unittrainid_6 = 0,
                 unittrainid_7 = 0,
                 unittrainid_8 = 0,
                 unittrainid_9 = 0,
                 unittrainid_10 = 0,
                 unittrainnumber_1 = 0,
                 unittrainnumber_2 = 0,
                 unittrainnumber_3 = 0,
                 unittrainnumber_4 = 0,
                 unittrainnumber_5 = 0,
                 unittrainnumber_6 = 0,
                 unittrainnumber_7 = 0,
                 unittrainnumber_8 = 0,
                 unittrainnumber_9 = 0,
                 unittrainnumber_10 = 0,
                 unittrainnumberleft_1 = 0,
                 unittrainnumberleft_2 = 0,
                 unittrainnumberleft_3 = 0,
                 unittrainnumberleft_4 = 0,
                 unittrainnumberleft_5 = 0,
                 unittrainnumberleft_6 = 0,
                 unittrainnumberleft_7 = 0,
                 unittrainnumberleft_8 = 0,
                 unittrainnumberleft_9 = 0,
                 unittrainnumberleft_10 = 0,
                 unittrain_actual = 0,
                 unittrainid_nexttime=0,
                 planet_surrender=0
             WHERE planet_id = ' . $this->move['dest'];
     //$this->log('SQL Debug', ''.$sql.'');
     if (!$this->db->query($sql)) {
         return $this->log(MV_M_DATABASE, 'Could not update planets data! SKIP');
     }
     //Concept of vessels destroyed by hostile takeover.
     //Version 0.2b by Mojo1987 - Computation adapted
     $this->log(MV_M_NOTICE, 'Start ships deletion');
     $sql = 'SELECT s.ship_id FROM (ships s) WHERE s.fleet_id = -' . $this->move['dest'] . '';
     if (!($del_ship = $this->db->query($sql))) {
         $this->log(MV_M_DATABASE, 'Could not query planets ships! CONTINUE - ' . $sql . '');
     }
     while ($ship_wahl = $this->db->fetchrow($del_ship)) {
         $zufall = mt_rand(6, 18);
         if ($zufall >= 8) {
             $sql = 'DELETE FROM ships WHERE ship_id = ' . $ship_wahl['ship_id'] . '';
             if (!$this->db->query($sql)) {
                 $this->log(MV_M_DATABASE, 'Could not query deleted ship! CONTINUE');
             } else {
                 $this->log(MV_M_NOTICE, 'Ship_ID: ' . $ship_wahl['ship_id'] . ' Random number: ' . $zufall . ' <b> SUCCESS!</b>');
             }
         }
     }
     $this->log(MV_M_NOTICE, 'Delete terminated');
     $sql = 'DELETE FROM ships
             WHERE fleet_id = -' . $this->move['dest'] . ' OR
                   ship_id = ' . $ship_id;
     if (!$this->db->query($sql)) {
         return $this->log(MV_M_DATABASE, 'Could not delete ships data! SKIP');
     }
     if ($cship['n_ships'] == 1) {
         $sql = 'DELETE FROM ship_fleets
                 WHERE fleet_id = ' . $cship['fleet_id'];
     } else {
         $sql = 'UPDATE ship_fleets
                 SET n_ships = n_ships - 1
                 WHERE fleet_id = ' . $cship['fleet_id'];
     }
     if (!$this->db->query($sql)) {
         $this->log(MV_M_DATABASE, 'Could not update/delete cships fleet data! CONTINUE');
     }
     // #############################################################################
     // Fleets positioning
     $sql = 'UPDATE ship_fleets
             SET planet_id = ' . $this->move['dest'] . ',
                 move_id = 0
             WHERE fleet_id IN (' . $this->fleet_ids_str . ')';
     if (!$this->db->query($sql)) {
         return $this->log(MV_M_DATABASE, 'Could not update fleets data! SKIP');
     }
     // #############################################################################
     // Write Logbook
     $log_data[8] = 1;
     $log_data[9] = $cship['name'];
     $log_data[10] = $cship['race'];
     add_logbook_entry($this->move['user_id'], LOGBOOK_TACTICAL, $col_title . $this->dest['planet_name'] . $col_success, $log_data);
     // #############################################################################
     // Add History Record in planet details; log_code = 25
     $sql = 'INSERT INTO planet_details (planet_id, user_id, alliance_id, source_uid, source_aid, timestamp, log_code)
             VALUES (' . $this->move['dest'] . ', ' . $this->move['user_id'] . ', ' . $this->move['user_alliance'] . ', ' . $this->move['user_id'] . ', ' . $this->move['user_alliance'] . ', ' . time() . ', 25)';
     if (!$this->db->query($sql)) {
         $this->log(MV_M_DATABASE, 'Could not update planet details data!');
     }
     return MV_EXEC_OK;
 }
    function _action_main()
    {
        // #############################################################################
        // Data from the attacker
        /*
        $sql = 'SELECT fleet_id
                FROM ship_fleets
                WHERE planet_id = '.$this->move['dest'].' AND
                      user_id = '.$this->move['user_id'].' AND
                      alert_phase >= '.ALERT_PHASE_YELLOW;
        
        if(!$q_atk_st_fleets = $this->db->query($sql)) {
            return $this->log(MV_M_DATABASE, 'Could not query stationated attacker fleet data! SKIP');
        }
        
        $atk_fleet_ids_str = $this->fleet_ids_str;
        
        while($_fleet = $this->db->fetchrow($q_atk_st_fleets)) {
            $atk_fleet_ids_str .= ','.$_fleet['fleet_id'];
        }
        
        $sql = 'SELECT '.$this->get_combat_query_fleet_columns().'
        		FROM (ship_fleets f)
        		INNER JOIN user u ON u.user_id = f.user_id
        		WHERE f.fleet_id IN ('.$atk_fleet_ids_str.')';
        
        if(($atk_fleets = $this->db->queryrowset($sql)) === false) {
        	return $this->log(MV_M_DATABASE, 'Could not query attackers fleets data! SKIP');}
        */
        //move_finish
        $sql_user = '******' . $this->move['user_id'] . '';
        if (($user_attacker = $this->db->queryrow($sql_user)) === false) {
            return $this->log(MV_M_DATABASE, 'Could not obtain attacker alliance data! SKIP');
        }
        $sql_3 = 'SELECT DISTINCT f.user_id,f.fleet_id,ssm.dest,
               u.user_alliance,
               ud.ud_id, ud.accepted,
               ad.ad_id, ad.type, ad.status,ssm.move_id
        FROM (ship_fleets f)
        INNER JOIN user u ON u.user_id = f.user_id
        LEFT JOIN (scheduler_shipmovement ssm) ON ssm.move_id=f.move_id
        LEFT JOIN user_diplomacy ud ON ( ( ud.user1_id = ' . $this->move['user_id'] . ' AND ud.user2_id = f.user_id ) OR ( ud.user1_id = f.user_id AND ud.user2_id = ' . $this->move['user_id'] . ' ) )
        LEFT JOIN alliance_diplomacy ad ON ( ( ad.alliance1_id =' . $user_attacker['user_alliance'] . ' AND ad.alliance2_id = u.user_alliance) OR ( ad.alliance1_id = u.user_alliance AND ad.alliance2_id = ' . $user_attacker['user_alliance'] . ' ) ) 
        WHERE ssm.move_finish<=' . $this->move['move_finish'] . ' AND
              f.user_id <>' . $this->dest['user_id'] . ' AND
              ssm.move_status=0 AND ssm.action_code!=31 AND ssm.action_code!=33 AND ssm.action_code!=34 AND ssm.action_code!=14 AND ssm.action_code!=22 AND ssm.action_code!=23 AND
              f.move_id!=0 AND
              ssm.dest=' . $this->move['dest'] . ' AND
              f.user_id <> ' . $this->move['user_id'] . ' AND
              f.alert_phase >= ' . ALERT_PHASE_YELLOW;
        //$this->log(MV_M_NOTICE, $sql_3);
        if (!($l_st_uid = $this->db->query($sql_3))) {
            return $this->log(MV_M_DATABASE, 'Could not query stationated fleets user data! SKIP');
        }
        $at_user = array();
        while ($at_uid = $this->db->fetchrow($l_st_uid)) {
            $allied = false;
            if ($at_uid['user_alliance'] == $user_attacker['user_alliance']) {
                $allied = true;
            }
            if (!empty($at_uid['ud_id'])) {
                if ($at_uid['accepted'] == 1) {
                    $allied = true;
                }
            }
            if (!empty($at_uid['ad_id'])) {
                if ($at_uid['type'] == ALLIANCE_DIPLOMACY_PACT && $at_uid['status'] == 0) {
                    $allied = true;
                }
            }
            if ($allied) {
                $at_user[] = $at_uid['user_id'];
            }
        }
        $a_st_user = count($at_user);
        $this->log(MV_M_NOTICE, 'Allied in orbit: <b>' . $a_st_user . '</b> common assault');
        if ($a_st_user > 0) {
            $sql = 'SELECT ' . $this->get_combat_query_fleet_columns() . '
             FROM (ship_fleets f)
             INNER JOIN user u ON u.user_id = f.user_id
             LEFT JOIN (scheduler_shipmovement ssm) ON ssm.move_id=f.move_id
             WHERE ssm.dest=' . $this->move['dest'] . ' AND ssm.action_code!=31 AND ssm.action_code!=33 AND ssm.action_code!=34 AND ssm.action_code!=14 AND ssm.action_code!=22 AND ssm.action_code!=23 AND ssm.move_finish<=' . $this->move['move_finish'] . ' AND ssm.move_status=0 AND f.move_id!=0 AND
                   (
                     (
                       f.user_id = ' . $this->move['user_id'] . ' AND f.alert_phase >= ' . ALERT_PHASE_YELLOW . '
                     )
                     OR
                     (
                       f.user_id IN (' . implode(',', $at_user) . ') AND
                       f.alert_phase >= ' . ALERT_PHASE_YELLOW . '
                     )
                   ) ';
        } else {
            $sql = 'SELECT ' . $this->get_combat_query_fleet_columns() . '
		FROM (ship_fleets f)
		INNER JOIN user u ON u.user_id = f.user_id
		JOIN (scheduler_shipmovement ssm) ON ssm.user_id=f.user_id
		WHERE ssm.dest=' . $this->move['dest'] . ' AND ssm.action_code!=31 AND ssm.action_code!=33 AND ssm.action_code!=34 AND ssm.action_code!=14 AND ssm.action_code!=22 AND ssm.action_code!=23 AND ssm.move_finish<=' . $this->move['move_finish'] . ' AND ssm.move_status=0 AND f.move_id!=0 AND
		f.fleet_id IN (' . $this->fleet_ids_str . ')';
        }
        if (($atk_fleets = $this->db->queryrowset($sql)) === false) {
            return $this->log(MV_M_DATABASE, 'Could not query defenders fleets data! SKIP');
        }
        $atk_fleets_ids = array();
        $zahl = 0;
        foreach ($atk_fleets as $i => $cur_fleet) {
            $zahl++;
            $this->log(MV_M_NOTICE, '<b>Attacker:</b> fleet ID: <b>' . $cur_fleet['fleet_id'] . '</b> name: <b>' . $cur_fleet['fleet_name'] . '</b> ships: <b>' . $cur_fleet['n_ships'] . '</b>');
            $atk_fleets_ids[] = $cur_fleet['fleet_id'];
        }
        if ($zahl < 1) {
            return MV_EXEC_ERROR;
        }
        // #############################################################################
        // Data from the defender
        $sql = 'SELECT DISTINCT f.user_id,
               u.user_alliance,
               ud.ud_id, ud.accepted,
               ad.ad_id, ad.type, ad.status
        FROM (ship_fleets f)
        INNER JOIN (user u) ON u.user_id = f.user_id
        LEFT JOIN (user_diplomacy ud) ON ( ( ud.user1_id = ' . $this->dest['user_id'] . ' AND ud.user2_id = f.user_id ) OR ( ud.user1_id = f.user_id AND ud.user2_id = ' . $this->dest['user_id'] . ' ) )
        LEFT JOIN (alliance_diplomacy ad) ON ( ( ad.alliance1_id = ' . $this->dest['user_alliance'] . ' AND ad.alliance2_id = u.user_alliance) OR ( ad.alliance1_id = u.user_alliance AND ad.alliance2_id = ' . $this->dest['user_alliance'] . ' ) )
        WHERE f.planet_id = ' . $this->move['dest'] . ' AND
              f.user_id <> ' . $this->dest['user_id'] . ' AND
              f.user_id <> ' . $this->move['user_id'] . ' AND
              f.alert_phase >= ' . ALERT_PHASE_YELLOW;
        if (!($q_st_uid = $this->db->query($sql))) {
            return $this->log(MV_M_DATABASE, 'Could not query stationated fleets user data! SKIP');
        }
        $st_user = array();
        while ($st_uid = $this->db->fetchrow($q_st_uid)) {
            $allied = false;
            if ($st_uid['user_alliance'] == $this->dest['user_alliance']) {
                $allied = true;
            }
            if (!empty($st_uid['ud_id'])) {
                if ($st_uid['accepted'] == 1) {
                    $allied = true;
                }
            }
            if (!empty($st_uid['ad_id'])) {
                if ($st_uid['type'] == ALLIANCE_DIPLOMACY_PACT && $st_uid['status'] == 0) {
                    $allied = true;
                }
            }
            if ($allied) {
                $st_user[] = $st_uid['user_id'];
            }
        }
        $n_st_user = count($st_user);
        if ($n_st_user > 0) {
            $sql = 'SELECT  ' . $this->get_combat_query_fleet_columns() . '
             FROM (ship_fleets f)
             INNER JOIN (user u) ON u.user_id = f.user_id
             WHERE f.planet_id = ' . $this->move['dest'] . ' AND
                   (
                     (
                       f.user_id = ' . $this->dest['user_id'] . '
                     )
                     OR
                     (
                       f.user_id IN (' . implode(',', $st_user) . ') AND
                       f.alert_phase >= ' . ALERT_PHASE_YELLOW . '
                     )
                   )';
        } else {
            $sql = 'SELECT  ' . $this->get_combat_query_fleet_columns() . '
             FROM (ship_fleets f)
             INNER JOIN user u ON u.user_id = f.user_id
             WHERE f.planet_id = ' . $this->move['dest'] . ' AND
                   f.user_id = ' . $this->dest['user_id'];
        }
        if (($dfd_fleets = $this->db->queryrowset($sql)) === false) {
            return $this->log(MV_M_DATABASE, 'Could not query defenders fleets data! SKIP');
        }
        $dfd_fleet_ids = array();
        foreach ($dfd_fleets as $i => $cur_fleet) {
            $this->log(MV_M_NOTICE, '<b>Defender:</b> fleet ID: <b>' . $cur_fleet['fleet_id'] . '</b> name: <b>' . $cur_fleet['fleet_name'] . '</b> ships: <b>' . $cur_fleet['n_ships'] . '</b>');
            $dfd_fleet_ids[] = $cur_fleet['fleet_id'];
        }
        $atk_fleet_ids_str = implode(',', $atk_fleets_ids);
        $dfd_fleet_ids_str = implode(',', $dfd_fleet_ids);
        if ($this->do_ship_combat($atk_fleet_ids_str, $dfd_fleet_ids_str, MV_COMBAT_LEVEL_ORBITAL) == MV_EXEC_ERROR) {
            $this->log(MV_M_DATABASE, 'Move Action 41: Something went wrong with this fight!');
            return MV_EXEC_ERROR;
        }
        // #############################################################################
        // Possibly ubriggeblienen the ships of the attacker left in orbit
        if ($this->cmb[MV_CMB_WINNER] == MV_CMB_ATTACKER) {
            $sql = 'UPDATE ship_fleets
            SET planet_id = ' . $this->move['dest'] . ',
                move_id = 0
            WHERE fleet_id IN (' . $this->fleet_ids_str . ')';
            if (!$this->db->query($sql)) {
                return $this->log(MV_M_DATABASE, 'Could not update fleets location data! SKIP');
            }
            // #############################################################################
            // 02/04/08 - AC: Retrieve player language
            switch ($this->move['language']) {
                case 'GER':
                    $atk_title = 'Angriff auf ' . $this->dest['planet_name'] . ' erfolgreich';
                    break;
                case 'ITA':
                    $atk_title = 'Attacco su ' . $this->dest['planet_name'] . ' riuscito';
                    break;
                default:
                    $atk_title = 'Attack on ' . $this->dest['planet_name'] . ' successful';
                    break;
            }
            switch ($this->dest['language']) {
                case 'GER':
                    $dfd_title = 'Schwerer Angriff auf ' . $this->dest['planet_name'];
                    break;
                case 'ITA':
                    $dfd_title = 'Attacco fatale su ' . $this->dest['planet_name'];
                    break;
                default:
                    $dfd_title = 'Fatal attack on ' . $this->dest['planet_name'];
                    break;
            }
        } else {
            // #############################################################################
            // 02/04/08 - AC: Retrieve player language
            switch ($this->move['language']) {
                case 'GER':
                    $atk_title = 'Angriff auf ' . $this->dest['planet_name'] . ' fehlgeschlagen';
                    break;
                case 'ITA':
                    $atk_title = 'Attacco su ' . $this->dest['planet_name'] . ' fallito';
                    break;
                default:
                    $atk_title = 'Attack on ' . $this->dest['planet_name'] . ' failed';
                    break;
            }
            switch ($this->dest['language']) {
                case 'GER':
                    $dfd_title = 'Verteidigung von ' . $this->dest['planet_name'] . ' erfolgreich';
                    break;
                case 'ITA':
                    $dfd_title = 'Difesa di ' . $this->dest['planet_name'] . ' riuscita';
                    break;
                default:
                    $dfd_title = 'Defence of ' . $this->dest['planet_name'] . ' successful';
                    break;
            }
        }
        // #############################################################################
        // Write logbook
        $log1_data = array(41, $this->move['user_id'], $this->move['start'], $this->start['planet_name'], $this->start['user_id'], $this->move['dest'], $this->dest['planet_name'], $this->dest['user_id'], MV_CMB_ATTACKER, $this->cmb[MV_CMB_WINNER] == MV_CMB_ATTACKER ? 1 : 0, 0, 0, $atk_fleets, $dfd_fleets);
        $log2_data = array(41, $this->move['user_id'], $this->move['start'], $this->start['planet_name'], $this->start['user_id'], $this->move['dest'], $this->dest['planet_name'], $this->dest['user_id'], MV_CMB_DEFENDER, $this->cmb[MV_CMB_WINNER] == MV_CMB_DEFENDER ? 1 : 0, 0, 0, $atk_fleets, $dfd_fleets, $this->cmb[MV_CMB_KILLS_PLANETARY]);
        $log1_data[10] = $this->cmb[MV_CMB_KILLS_EXT];
        $log2_data[10] = $this->cmb[MV_CMB_KILLS_EXT];
        add_logbook_entry($this->move['user_id'], LOGBOOK_TACTICAL_2, $atk_title, $log1_data);
        add_logbook_entry($this->dest['user_id'], LOGBOOK_TACTICAL_2, $dfd_title, $log2_data);
        $log3_data = array(99, $this->move['user_id'], $this->move['start'], $this->start['planet_name'], $this->start['user_id'], $this->move['dest'], $this->dest['planet_name'], $this->dest['user_id'], MV_CMB_ATTACKER, $this->cmb[MV_CMB_WINNER] == MV_CMB_ATTACKER ? 1 : 0, 0, 0, $atk_fleets, $dfd_fleets);
        $log3_data[10] = $this->cmb[MV_CMB_KILLS_EXT];
        if ($a_st_user > 0) {
            $log3_data[2] = $this->move['dest'];
            $log3_data[3] = $this->dest['planet_name'];
            $log3_data[4] = $this->dest['user_id'];
            $log3_data[5] = 0;
            $log3_data[6] = 0;
            $log3_data[7] = 0;
            $log3_data[16] = 1;
            for ($i = 0; $i < $a_st_user; ++$i) {
                // #############################################################################
                // 02/04/08 - AC: Retrieve player language
                $log_title = 'One of your allies attacked ' . $this->dest['planet_name'];
                $sql = 'SELECT language FROM user WHERE user_id = ' . $at_user[$i];
                if (!($lang = $this->db->queryrow($sql))) {
                    $this->log(MV_M_DATABASE, 'Could not retrieve player language');
                } else {
                    switch ($lang['language']) {
                        case 'GER':
                            $log_title = 'Mit Verb&uuml;ndeten bei ' . $this->dest['planet_name'] . ' angegriffen';
                            break;
                        case 'ITA':
                            $log_title = 'Attacco alleato presso ' . $this->dest['planet_name'];
                            break;
                    }
                }
                add_logbook_entry($at_user[$i], LOGBOOK_TACTICAL_2, $log_title, $log3_data);
            }
        }
        if ($n_st_user > 0) {
            $log2_data[2] = $this->move['dest'];
            $log2_data[3] = $this->dest['planet_name'];
            $log2_data[4] = $this->dest['user_id'];
            $log2_data[5] = 0;
            $log2_data[6] = 0;
            $log2_data[7] = 0;
            $log2_data[16] = 1;
            for ($i = 0; $i < $n_st_user; ++$i) {
                // #############################################################################
                // 02/04/08 - AC: Retrieve player language
                $log_title = 'One of your allies defended ' . $this->dest['planet_name'];
                $sql = 'SELECT language FROM user WHERE user_id = ' . $st_user[$i];
                if (!($lang = $this->db->queryrow($sql))) {
                    $this->log(MV_M_DATABASE, 'Could not retrieve player language');
                } else {
                    switch ($lang['language']) {
                        case 'GER':
                            $log_title = 'Verb&uuml;ndeten bei ' . $this->dest['planet_name'] . ' verteidigt';
                            break;
                        case 'ITA':
                            $log_title = 'Difesa alleata presso ' . $this->dest['planet_name'];
                            break;
                    }
                }
                add_logbook_entry($st_user[$i], LOGBOOK_TACTICAL_2, $log_title, $log2_data);
            }
        }
        //
        if (!($aad = $this->db->query($sql_3))) {
            return $this->log(MV_M_DATABASE, 'Could not query stationated fleets user data! SKIP');
        }
        while ($aa_uid = $this->db->fetchrow($aad)) {
            $this->log(MV_M_NOTICE, '::::' . $aa_uid['move_id'] . 'Now we delete:' . $this->move['user_id'] . '<br>');
            if ($aa_uid['move_id'] != $this->move['user_id']) {
                /*  $sql = 'UPDATE scheduler_shipmovement
                    SET move_exec_started = move_exec_started + 1
                    WHERE move_id = '.$this->mid;*/
                /*   if(!$this->db->query($sql)) {
                         return $this->log(MV_M_DATABASE, 'Could not update move exec started data! SKIP');;
                     } */
                $sql = 'UPDATE ship_fleets
                SET planet_id = ' . $aa_uid['dest'] . ',
                    move_id = 0
                WHERE fleet_id =' . $aa_uid['fleet_id'];
                if (!$this->db->query($sql)) {
                    return $this->log(MV_M_DATABASE, 'Could not update fleets location data! SKIP');
                }
                $sql = 'UPDATE scheduler_shipmovement
                SET move_status = 11
                WHERE move_id = ' . $aa_uid['move_id'];
                if (!$this->db->query($sql)) {
                    $this->log(MV_M_DATABASE, 'Could not update move status data! CONTINUE');
                }
            }
        }
        return MV_EXEC_OK;
    }
 function _action_main()
 {
     // #############################################################################
     // Data of the scouts or the target planet
     // (resembles get_fleet_details())
     $sql = 'SELECT COUNT(s.ship_id) AS n_ships,
                    MAX(st.ship_torso) AS highest_torso,
                    SUM(st.value_11) AS sum_sensors,
                    SUM(st.value_12) AS sum_cloak,
             AVG(st.value_9) AS scoutxp
             FROM (ship_fleets f)
             INNER JOIN ships s ON s.fleet_id = f.fleet_id
             INNER JOIN ship_templates st ON st.id = s.template_id
             WHERE f.fleet_id IN (' . $this->fleet_ids_str . ')';
     if (($spy_fleet = $this->db->queryrow($sql)) === false) {
         return $this->log(MV_M_DATABASE, 'Could not query main spy fleets data! SKIP');
     }
     if ($spy_fleet['highest_torso'] != SHIP_TYPE_SCOUT) {
         $this->deactivate(35);
         $this->report('Spy fleet has no-scout torso withflying');
         return MV_EXEC_ERROR;
     }
     $dest_planet = get_friendly_orbit_fleets($this->move['dest'], $this->dest['user_id'], $this->dest['user_alliance']);
     // #############################################################################
     // Spy()
     $spy_result = Spy($spy_fleet['sum_sensors'], $spy_fleet['sum_cloak'], $spy_fleet['n_ships'], $dest_planet['sum_sensors'], $this->dest['building_7'], $spy_fleet['scoutxp']);
     $log2_data = array();
     if ($spy_result[0]) {
         // unsuccessful
         $sql = 'DELETE FROM ship_fleets
                 WHERE fleet_id IN (' . $this->fleet_ids_str . ')';
         if (!$this->db->query($sql)) {
             return $this->log(MV_M_DATABASE, 'Could not delete fleets data! SKIP');
         }
         $sql = 'DELETE FROM ships
                 WHERE fleet_id IN (' . $this->fleet_ids_str . ')';
         if (!$this->db->query($sql)) {
             $this->log(MV_M_DATABASE, 'Could not delete ships data! CONTINUE');
             $this->report('Could not delete ships data due spy mission');
         }
         $log1_data = $log2_data = array(22, $this->move['user_id'], $this->move['start'], $this->start['planet_name'], $this->start['user_id'], $this->move['dest'], $this->dest['planet_name'], $this->dest['user_id'], $spy_fleet['n_ships']);
     } else {
         // Calculate gained experience
         $difficult_rate = $dest_planet['sum_sensors'] + ($this->dest['building_7'] + 1) * 200;
         $exp = (double) $difficult_rate / 266 + 5.0;
         $sql = 'UPDATE ships SET experience = experience+' . $exp . '
                 WHERE fleet_id IN (' . $this->fleet_ids_str . ')';
         if (!$this->db->query($sql)) {
             $this->log(MV_M_DATABASE, 'Could not update fleet EXP! CONTINUE');
         }
         // Scouts returns
         $sql = 'INSERT INTO scheduler_shipmovement (user_id, move_status,
                     move_exec_started, start, dest, total_distance,
                     remaining_distance, tick_speed, move_begin, move_finish, n_ships,
                     action_code, action_data)
                 VALUES (' . $this->move['user_id'] . ', 0, 0,
                     ' . $this->move['dest'] . ', ' . $this->move['start'] . ',
                     ' . $this->move['total_distance'] . ', ' . $this->move['total_distance'] . ',
                     ' . $this->move['tick_speed'] . ', ' . $this->CURRENT_TICK . ',
                     ' . ($this->CURRENT_TICK + ($this->move['move_finish'] - $this->move['move_begin'])) . ',
                     ' . $this->move['n_ships'] . ', 12, "' . serialize(22) . '")';
         if (!$this->db->query($sql)) {
             return $this->log(MV_M_DATABASE, 'Could not create new movement for return! SKIP');
         }
         $new_move_id = $this->db->insert_id();
         if (!$new_move_id) {
             return $this->log(MV_M_ERROR, 'Could not get new move id! SKIP');
         }
         $sql = 'UPDATE ship_fleets
                 SET move_id = ' . $new_move_id . '
                 WHERE fleet_id IN (' . $this->fleet_ids_str . ')';
         if (!$this->db->query($sql)) {
             return $this->log(MV_M_DATABASE, 'Could not update fleets movement data! SKIP');
         }
         $log1_data = array(22, $this->move['user_id'], $this->move['start'], $this->start['planet_name'], $this->start['user_id'], $this->move['dest'], $this->dest['planet_name'], $this->dest['user_id'], $spy_fleet['n_ships'], $spy_result, $this->dest['user_race']);
     }
     $log1_data[9] = array($spy_result[0], array(), array(), array(), array(), array());
     for ($i = 0; $i < count($spy_result[1]); ++$i) {
         $log1_data[9][1][$spy_result[1][$i]] = $this->dest['resource_' . ($spy_result[1][$i] + 1)];
     }
     for ($i = 0; $i < count($spy_result[2]); ++$i) {
         if ($spy_result[2][$i] == 1) {
             $log1_data[9][2][$i] = $this->dest['unit_' . ($i + 1)];
         }
     }
     for ($i = 0; $i < count($spy_result[3]); ++$i) {
         $log1_data[9][3][$spy_result[3][$i]] = $this->dest['building_' . ($spy_result[3][$i] + 1)];
     }
     for ($i = 0; $i < count($spy_result[4]); ++$i) {
         $log1_data[9][4][$spy_result[4][$i]] = $this->dest['research_' . ($spy_result[4][$i] + 1)];
     }
     for ($i = 0; $i < count($spy_result[5]); ++$i) {
         $log1_data[9][5][$spy_result[5][$i]] = $this->dest['catresearch_' . ($spy_result[5][$i] + 1)];
     }
     $log1_data[10] = $this->dest['user_race'];
     // #############################################################################
     // 31/03/08 - AC: Retrieve player language
     switch ($this->move['language']) {
         case 'GER':
             $log_title = 'Spionagebericht von ';
             $log_success = ' ausspioniert';
             break;
         case 'ITA':
             $log_title = 'Report spionaggio di ';
             $log_success = ' spiato';
             break;
         default:
             $log_title = 'Spy report of ';
             $log_success = ' spied';
             break;
     }
     add_logbook_entry($this->move['user_id'], LOGBOOK_TACTICAL, $log_title . $this->dest['planet_name'], $log1_data);
     if (!empty($log2_data)) {
         add_logbook_entry($this->dest['user_id'], LOGBOOK_TACTICAL, $this->dest['planet_name'] . $log_success, $log2_data);
     }
     return MV_EXEC_OK;
 }
    function _action_main()
    {
        global $PLANETS_DATA;
        // #############################################################################
        // Survey Mission!!!
        //
        // Beam us down! Energy!
        //
        //#############################################################################
        $sql = 'SELECT s.ship_name, s.experience, s.ship_id, t.name FROM ship_fleets f
		               LEFT JOIN ships s ON s.fleet_id = f.fleet_id
		               LEFT JOIN ship_templates t ON t.id = s.template_id
		        WHERE f.fleet_id IN (' . $this->fleet_ids_str . ')';
        if (($ship_details = $this->db->queryrow($sql)) == false) {
            $this->log(MV_M_DATABASE, 'Could not read ship name! CONTINUE');
            $name_of_ship = '<i>Sconosciuto</i>';
        } else {
            if (!empty($ship_details['ship_name'])) {
                $name_of_ship = '<b>' . $ship_details['ship_name'] . '</b>';
            } else {
                $name_of_ship = '<b><i>&#171;' . $ship_details['name'] . '&#187;</i></b>';
            }
        }
        // Calcolo Exp per missione
        if ($ship_details['experience'] < 50) {
            $actual_exp = $ship_details['experience'];
            if ($actual_exp < 1) {
                $actual_exp = 1;
            }
            $exp = $actual_exp > 0 ? 2.5 / ((double) $actual_exp * 0.0635) + 0.6 : 40;
            $sql = 'UPDATE ships SET experience = experience+' . $exp . '
                    WHERE ship_id = ' . $ship_details['ship_id'];
            if (!$this->db->query($sql)) {
                $this->log(MV_M_DATABASE, 'Could not update ship exp! CONTINUE');
            }
        }
        $sql = 'SELECT ss.system_name, p.* FROM planets p LEFT JOIN starsystems ss ON p.system_id = ss.system_id WHERE planet_id = ' . $this->move['dest'];
        if (($survey_data = $this->db->queryrow($sql)) == false) {
            return $this->log(MV_M_DATABASE, 'Could not read planet data! SKIP');
        }
        $base_rateo_1_over = $PLANETS_DATA[$survey_data['planet_type']][0] + 0.12;
        $base_rateo_1_under = $PLANETS_DATA[$survey_data['planet_type']][0] - 0.05;
        $base_rateo_2_over = $PLANETS_DATA[$survey_data['planet_type']][1] + 0.1;
        $base_rateo_2_under = $PLANETS_DATA[$survey_data['planet_type']][1] - 0.05;
        $base_rateo_3_over = $PLANETS_DATA[$survey_data['planet_type']][2] + 0.08;
        $base_rateo_3_under = $PLANETS_DATA[$survey_data['planet_type']][2] - 0.05;
        $_survey1 = 1;
        if ($survey_data['rateo_1'] > $base_rateo_1_over) {
            $_survey1 = 2;
        }
        if ($survey_data['rateo_1'] < $base_rateo_1_under) {
            $_survey1 = 0;
        }
        $_survey2 = 1;
        if ($survey_data['rateo_2'] > $base_rateo_2_over) {
            $_survey2 = 2;
        }
        if ($survey_data['rateo_2'] < $base_rateo_2_under) {
            $_survey2 = 0;
        }
        $_survey3 = 1;
        if ($survey_data['rateo_3'] > $base_rateo_3_over) {
            $_survey3 = 2;
        }
        if ($survey_data['rateo_3'] < $base_rateo_3_under) {
            $_survey3 = 0;
        }
        // Update planet_details
        $sql = 'SELECT id from planet_details
                WHERE log_code = 100 AND planet_id = ' . $this->move['dest'] . ' AND user_id = ' . $this->move['user_id'];
        if (!($res = $this->db->queryrow($sql))) {
            // No old data present (I hope...), insert the data
            $sql = 'INSERT INTO planet_details (planet_id, user_id, alliance_id,
                                                source_uid, source_aid, timestamp,
                                                log_code, ship_name,
                                                survey_1, survey_2, survey_3)
                    VALUES (' . $this->move['dest'] . ', ' . $this->move['user_id'] . ', ' . $this->move['user_alliance'] . ',
                            ' . $this->move['user_id'] . ', ' . $this->move['user_alliance'] . ', ' . time() . ',
                            100,"' . $name_of_ship . '",
                            ' . $_survey1 . ', ' . $_survey2 . ', ' . $_survey3 . ')';
            if (!$this->db->query($sql)) {
                return $this->log(MV_M_DATABASE, 'Could not insert planet details data! SKIP');
            }
        } else {
            // Update data already present, avoid to fill table with row will never be read
            $sql = 'UPDATE planet_details
                    SET timestamp = ' . time() . ', 
                        ship_name = "' . $name_of_ship . '",
                        survey_1 = ' . $_survey1 . ',
                        survey_2 = ' . $_survey2 . ',
                        survey_3 = ' . $_survey3 . '
                    WHERE id = ' . $res['id'];
            if (!$this->db->query($sql)) {
                return $this->log(MV_M_DATABASE, 'Could not update planet details data! SKIP');
            }
        }
        // Inseriamo la notifica nel logbook
        $log_data = array(26, $this->move['user_id'], $this->move['start'], $this->start['planet_name'], $this->start['user_id'], $this->move['dest'], $this->dest['planet_name'], $this->dest['user_id'], 0);
        switch ($this->move['language']) {
            case 'GER':
                $log_title = 'Exploration of planet class ' . strtoupper($survey_data['planet_type']) . ', ' . $survey_data['system_name'];
                $log_msg1 = 'Forschungs-Verh&auml;ltnis vom Schiff';
                $log_msg2 = 'Geologische Erforschung- und Verwandt&uuml;bersichten zum Kategorienplaneten';
                break;
            case 'ITA':
                $log_title = 'Esplorazione pianeta classe ' . strtoupper($survey_data['planet_type']) . ', ' . $survey_data['system_name'];
                $log_msg1 = 'Rapporto esplorativo dalla nave';
                $log_msg2 = 'Esplorazione e rilevamenti geologici relativi al pianeta di classe';
                break;
            default:
                $log_title = 'Exploration of planet class ' . strtoupper($survey_data['planet_type']) . ', ' . $survey_data['system_name'];
                $log_msg1 = 'Exploratory relationship from the ship';
                $log_msg2 = 'Geologic exploration and relative surveys to the planet of class';
                break;
        }
        $log_data[8] = $log_msg1 . ' ' . $name_of_ship . '.';
        $log_data[9] = $log_msg2 . ' ' . strtoupper($survey_data['planet_type']) . ' <b>' . $this->dest['planet_name'] . '</b>:';
        $log_data[10] = date('d.m.y H:i', time());
        $log_data[11] = $_survey1;
        $log_data[12] = $_survey2;
        $log_data[13] = $_survey3;
        add_logbook_entry($this->move['user_id'], LOGBOOK_TACTICAL_2, $log_title, $log_data);
        $sql = 'UPDATE ship_fleets
		        SET planet_id = ' . $this->move['dest'] . ',
		            move_id = 0
		        WHERE fleet_id IN (' . $this->fleet_ids_str . ')';
        if (!$this->db->query($sql)) {
            return $this->log(MV_M_DATABASE, 'Could not update fleets data! SKIP');
        }
        return MV_EXEC_OK;
    }
Exemple #17
0
 public function Execute($debug = 0)
 {
     global $ACTUAL_TICK, $cfg_data;
     $starttime = microtime() + time();
     $this->sdl->log('<br><b>-------------------------------------------------------------</b><br>' . '<b>Starting Settlers Bot Scheduler at ' . date('d.m.y H:i:s', time()) . '</b>', TICK_LOG_FILE_NPC);
     // Update BOT user ID
     $this->bot['user_id'] = INDEPENDENT_USERID;
     // ########################################################################################
     // ########################################################################################
     // Messages answer
     $messages = array('Bot system.', 'Bot system.', 'Se desiderate avere contatti con noi, dovrete scendere direttamente su uno dei nostri pianeti.<br><br>A presto.');
     $titles = array('--', '--', 'Grazie per averci contattato.');
     $this->ReplyToUser($titles, $messages);
     // ########################################################################################
     // ########################################################################################
     // Read Logbook
     $this->ReadLogbook();
     // ########################################################################################
     // ########################################################################################
     // Ok, only three (3) Settlers' planets per run are going to wake up. More planets means more overhead.
     $this->sdl->start_job('Mayflower Planets Building Control', TICK_LOG_FILE_NPC);
     $sql = 'SELECT * FROM planets WHERE planet_owner = ' . INDEPENDENT_USERID . ' AND npc_last_action < ' . $ACTUAL_TICK . ' ORDER BY npc_last_action ASC LIMIT 0, 3';
     if (($setpoint = $this->db->query($sql)) === false) {
         $this->sdl->log('<b>Error:</b> Bot: Could not read planets DB', TICK_LOG_FILE_NPC);
     } else {
         $_already_done = false;
         while ($planet_to_serve = $this->db->fetchrow($setpoint)) {
             if ($planet_to_serve['building_1'] < 9) {
                 $sql = 'UPDATE planets SET building_1 = 9, npc_last_action = ' . $ACTUAL_TICK . ' WHERE planet_id = ' . $planet_to_serve['planet_id'];
                 $this->sdl->log('SQL 1.1 ' . $sql, TICK_LOG_FILE_NPC);
                 $this->db->query($sql);
                 continue;
             }
             if ($planet_to_serve['building_5'] < 9) {
                 $sql = 'UPDATE planets SET building_5 = 9, npc_last_action = ' . $ACTUAL_TICK . ' WHERE planet_id = ' . $planet_to_serve['planet_id'];
                 $this->sdl->log('SQL 1' . $sql, TICK_LOG_FILE_NPC);
                 $this->db->query($sql);
                 continue;
             }
             if ($planet_to_serve['building_2'] < 9) {
                 $sql = 'UPDATE planets SET building_2 = 9, npc_last_action = ' . $ACTUAL_TICK . ', recompute_static = 1 WHERE planet_id = ' . $planet_to_serve['planet_id'];
                 $this->sdl->log('SQL 1.2' . $sql, TICK_LOG_FILE_NPC);
                 $this->db->query($sql);
                 continue;
             }
             if ($planet_to_serve['building_3'] < 9) {
                 $sql = 'UPDATE planets SET building_3 = 9, npc_last_action = ' . $ACTUAL_TICK . ', recompute_static = 1 WHERE planet_id = ' . $planet_to_serve['planet_id'];
                 $this->sdl->log('SQL 1.3' . $sql, TICK_LOG_FILE_NPC);
                 $this->db->query($sql);
                 continue;
             }
             if ($planet_to_serve['building_4'] < 9) {
                 $sql = 'UPDATE planets SET building_4 = 9, npc_last_action = ' . $ACTUAL_TICK . ', recompute_static = 1 WHERE planet_id = ' . $planet_to_serve['planet_id'];
                 $this->sdl->log('SQL 1.4' . $sql, TICK_LOG_FILE_NPC);
                 $this->db->query($sql);
                 continue;
             }
             if ($planet_to_serve['building_12'] < 9) {
                 $sql = 'UPDATE planets SET building_12 = 9, npc_last_action = ' . $ACTUAL_TICK . ', recompute_static = 1 WHERE planet_id = ' . $planet_to_serve['planet_id'];
                 $this->sdl->log('SQL 1.12' . $sql, TICK_LOG_FILE_NPC);
                 $this->db->query($sql);
                 continue;
             }
             // At this point, having rebuilt HQ and mines, Settlers automatically gains level 9 Academy.
             if ($planet_to_serve['building_6'] < 9) {
                 $sql = 'UPDATE planets SET building_6 = 9, npc_last_action = ' . $ACTUAL_TICK . ', recompute_static = 1 WHERE planet_id = ' . $planet_to_serve['planet_id'];
                 $this->sdl->log('SQL 2' . $sql, TICK_LOG_FILE_NPC);
                 $this->db->query($sql);
                 continue;
             }
             // Now the Spacedock
             if ($planet_to_serve['building_7'] < 3) {
                 $sql = 'UPDATE planets SET building_7 = 3, npc_last_action = ' . $ACTUAL_TICK . ', recompute_static = 1 WHERE planet_id = ' . $planet_to_serve['planet_id'];
                 $this->sdl->log('SQL 3' . $sql, TICK_LOG_FILE_NPC);
                 $this->db->query($sql);
                 continue;
             }
             // Now the Spaceyard
             if ($planet_to_serve['building_8'] < 1) {
                 $sql = 'UPDATE planets SET building_8 = 1, npc_last_action = ' . $ACTUAL_TICK . ', recompute_static = 1 WHERE planet_id = ' . $planet_to_serve['planet_id'];
                 $this->sdl->log('SQL 4' . $sql, TICK_LOG_FILE_NPC);
                 $this->db->query($sql);
                 continue;
             }
             // Light orbital defense
             if ($planet_to_serve['building_10'] + $planet_to_serve['research_3'] < 14 + $planet_to_serve['research_3']) {
                 $sql = 'UPDATE planets SET building_10 = ' . (14 + $planet_to_serve['research_3']) . ', npc_last_action = ' . ($ACTUAL_TICK + 10) . ', recompute_static = 1 WHERE planet_id = ' . $planet_to_serve['planet_id'];
                 $this->sdl->log('SQL 5' . $sql, TICK_LOG_FILE_NPC);
                 $this->db->query($sql);
                 continue;
             }
             // Heavy orbital defense
             if ($planet_to_serve['building_13'] + $planet_to_serve['research_3'] < 14 + $planet_to_serve['research_3']) {
                 $sql = 'UPDATE planets SET building_13 = ' . (14 + $planet_to_serve['research_3']) . ', npc_last_action = ' . ($ACTUAL_TICK + 30) . ', recompute_static = 1 WHERE planet_id = ' . $planet_to_serve['planet_id'];
                 $this->sdl->log('SQL 6' . $sql, TICK_LOG_FILE_NPC);
                 $this->db->query($sql);
                 continue;
             }
             // Are there enough workers in the mines?
             if ($planet_to_serve['workermine_1'] < 1000 || $planet_to_serve['workermine_2'] < 1000 || $planet_to_serve['workermine_3'] < 1000) {
                 $sql = 'UPDATE planets SET workermine_1 = 1000, workermine_2 = 1000, workermine_3 = 1000, npc_last_action = ' . $ACTUAL_TICK . ', recompute_static = 1 WHERE planet_id = ' . $planet_to_serve['planet_id'];
                 $this->sdl->log('SQL 7' . $sql, TICK_LOG_FILE_NPC);
                 $this->db->query($sql);
                 continue;
             }
             // Are there enough security troops?
             $troops_check = $planet_to_serve['unit_1'] * 2 + $planet_to_serve['unit_2'] * 3 + $planet_to_serve['unit_3'] * 4 + $planet_to_serve['unit_4'] * 4;
             $troops_to_train = round(($planet_to_serve['min_security_troops'] - $troops_check) / 4);
             if ($troops_to_train > 0) {
                 $sql = 'UPDATE planets SET unit_3 = unit_3 + ' . $troops_to_train . ', npc_last_action = ' . $ACTUAL_TICK . ', recompute_static = 1 WHERE planet_id = ' . $planet_to_serve['planet_id'];
                 $this->sdl->log('SQL 7.1' . $sql, TICK_LOG_FILE_NPC);
                 $this->db->query($sql);
                 continue;
             }
             // Check for best mood!!!
             $newbest = false;
             $sql = 'SELECT user_id, SUM(mood_modifier) AS mood FROM settlers_relations
                     WHERE planet_id = ' . $planet_to_serve['planet_id'] . ' GROUP BY user_id ORDER BY timestamp ASC';
             $q_p_m = $this->db->queryrowset($sql);
             // $this->sdl->log('DEBUG CHECK MOOD A'.$planet_to_serve['best_mood'].' '.$planet_to_serve['best_mood_user'], TICK_LOG_FILE_NPC);
             $newbest = $best = $best_id = 0;
             foreach ($q_p_m as $q_m) {
                 if ($q_m['mood'] > $best) {
                     $newbest = true;
                     $best = $q_m['mood'];
                     $best_id = $q_m['user_id'];
                 }
             }
             if ($newbest) {
                 $sql = 'UPDATE planets
                         SET best_mood = ' . $best . ',
                         best_mood_user = '******'
                         WHERE planet_id = ' . $planet_to_serve['planet_id'];
                 $this->db->query($sql);
             }
             // $this->sdl->log('DEBUG CHECK MOOD B '.$best.' '.$best_id, TICK_LOG_FILE_NPC);
             if ($best_id != $planet_to_serve['best_mood_user']) {
                 $log_data = array($planet_to_serve['planet_id'], $planet_to_serve['planet_name'], 0, '', 100);
                 add_logbook_entry($planet_to_serve['best_mood_user'], LOGBOOK_SETTLERS, 'Comunicazione prioritaria dalla colonia ' . $planet_to_serve['planet_name'], $log_data);
                 $planet_to_serve['best_mood'] = $best;
                 $planet_to_serve['best_mood_user'] = $best_id;
                 $this->db->query('UPDATE planets SET best_mood_planet = NULL WHERE planet_id = ' . $planet_to_serve['planet_id']);
             }
             // Let's activate the Academy! Sadly, we have to set ALL the fields for clearing them
             if ($planet_to_serve['unittrain_actual'] == 0 && ($planet_to_serve['planet_type'] == 'g' || $planet_to_serve['planet_type'] == 'h' || $planet_to_serve['planet_type'] == 'm' || $planet_to_serve['planet_type'] == 'o' || $planet_to_serve['planet_type'] == 'p')) {
                 if ($troops_to_train < 1) {
                     $troops_to_train = 0;
                 }
                 $sql = 'UPDATE planets SET unittrainid_1 = 5, unittrainid_2 = 6,
                                unittrainid_3 = 0, unittrainid_4 = 0,
                                unittrainid_5 = 0, unittrainid_6 = 0,
                                unittrainid_7 = 0, unittrainid_8 = 0,
                                unittrainid_9 = 0, unittrainid_10 = 0,
                                unittrainnumber_1 = 3, unittrainnumber_2 = 1,
                                unittrainnumber_3 = 0, unittrainnumber_4 = 0,
                                unittrainnumber_5 = 0, unittrainnumber_6 = 0,
                                unittrainnumber_7 = 0, unittrainnumber_8 = 0,
                                unittrainnumber_9 = 0, unittrainnumber_10 = 0,
                                unittrainnumberleft_1 = 3, unittrainnumberleft_2 = 1,
                                unittrainnumberleft_3 = 0, unittrainnumberleft_4 = 0,
                                unittrainnumberleft_5 = 0, unittrainnumberleft_6 = 0,
                                unittrainnumberleft_7 = 0, unittrainnumberleft_8 = 0,
                                unittrainnumberleft_9 = 0, unittrainnumberleft_10 = 0,
                                unittrainendless_1 = 1, unittrainendless_2 = 1,
                                unittrainendless_3 = 0, unittrainendless_4 = 0,
                                unittrainendless_5 = 0, unittrainendless_6 = 0,
                                unittrainendless_7 = 0, unittrainendless_8 = 0,
                                unittrainendless_9 = 0, unittrainendless_10 = 0,
                                unittrain_actual = 1, unittrainid_nexttime = ' . ($ACTUAL_TICK + 2) . ',
                                npc_last_action = ' . $ACTUAL_TICK . '
                         WHERE planet_id = ' . $planet_to_serve['planet_id'];
                 $this->sdl->log('SQL A - 1A ' . $sql, TICK_LOG_FILE_NPC);
                 $this->db->query($sql);
                 continue;
             }
             if ($planet_to_serve['unittrain_actual'] == 0 && ($planet_to_serve['planet_type'] == 'a' || $planet_to_serve['planet_type'] == 'b' || $planet_to_serve['planet_type'] == 'c' || $planet_to_serve['planet_type'] == 'd' || $planet_to_serve['planet_type'] == 'n')) {
                 if ($troops_to_train < 1) {
                     $troops_to_train = 0;
                 }
                 $sql = 'UPDATE planets SET unittrainid_1 = 1, unittrainid_2 = 2,
                                unittrainid_3 = 0, unittrainid_4 = 0,
                                unittrainid_5 = 0, unittrainid_6 = 0,
                                unittrainid_7 = 0, unittrainid_8 = 0,
                                unittrainid_9 = 0, unittrainid_10 = 0,
                                unittrainnumber_1 = 2, unittrainnumber_2 = 1,
                                unittrainnumber_3 = 0, unittrainnumber_4 = 0,
                                unittrainnumber_5 = 0, unittrainnumber_6 = 0,
                                unittrainnumber_7 = 0, unittrainnumber_8 = 0,
                                unittrainnumber_9 = 0, unittrainnumber_10 = 0,
                                unittrainnumberleft_1 = 2, unittrainnumberleft_2 = 1,
                                unittrainnumberleft_3 = 0, unittrainnumberleft_4 = 0,
                                unittrainnumberleft_5 = 0, unittrainnumberleft_6 = 0,
                                unittrainnumberleft_7 = 0, unittrainnumberleft_8 = 0,
                                unittrainnumberleft_9 = 0, unittrainnumberleft_10 = 0,
                                unittrainendless_1 = 1, unittrainendless_2 = 1,
                                unittrainendless_3 = 0, unittrainendless_4 = 0,
                                unittrainendless_5 = 0, unittrainendless_6 = 0,
                                unittrainendless_7 = 0, unittrainendless_8 = 0,
                                unittrainendless_9 = 0, unittrainendless_10 = 0,
                                unittrain_actual = 1, unittrainid_nexttime = ' . ($ACTUAL_TICK + 2) . ',
                                npc_last_action = ' . $ACTUAL_TICK . '
                         WHERE planet_id = ' . $planet_to_serve['planet_id'];
                 $this->sdl->log('SQL A - 1B ' . $sql, TICK_LOG_FILE_NPC);
                 $this->db->query($sql);
                 continue;
             }
             // A - 6
             // Settlers get back a ship from unsuccesful auction.
             $sql = 'SELECT ship_id FROM FHB_warteschlange WHERE user_id = ' . INDEPENDENT_USERID . ' LIMIT 0,1';
             $notpayed = $this->db->queryrow($sql);
             if (isset($notpayed['ship_id']) && !empty($notpayed['ship_id'])) {
                 $sql = 'DELETE FROM FHB_warteschlange WHERE ship_id = ' . $notpayed['ship_id'];
                 $this->sdl->log('SQL A - 6A ' . $sql, TICK_LOG_FILE_NPC);
                 $this->db->query($sql);
                 $sql = 'UPDATE ships SET user_id = ' . INDEPENDENT_USERID . ', fleet_id = -' . $planet_to_serve['planet_id'] . ' WHERE ship_id = ' . $notpayed['ship_id'];
                 $this->sdl->log('SQL A - 6B ' . $sql, TICK_LOG_FILE_NPC);
                 $this->db->query($sql);
                 $sql = 'UPDATE planets SET npc_last_action = ' . ($ACTUAL_TICK + 20) . ' WHERE planet_id = ' . $planet_to_serve['planet_id'];
                 $this->sdl->log('SQL A - 6C ' . $sql, TICK_LOG_FILE_NPC);
                 $this->db->query($sql);
                 continue;
             }
             // A - 2
             // Huge rewrite!
             // If we have a ship in the spacedock, we can send it to the best friend of the planet or
             // make and auction.
             // The query is made on all the planets, in order to free the deleted players spacedocks
             // Search for the oldest ship present in the spacedock.
             $sql = 'SELECT * FROM ships LEFT JOIN ship_templates ON ships.template_id = ship_templates.id
                     WHERE fleet_id = -' . $planet_to_serve['planet_id'] . ' AND ship_untouchable = 0
                     ORDER BY construction_time ASC
                     LIMIT 0,1';
             /**************************************************************/
             /* AC: I think would be lighter for the DB to:                */
             /* - first retrieve the oldest ship                           */
             /* - then retrieve the resources needed by its template       */
             /* instead of joining the two tables ships and ship_templates */
             /**************************************************************/
             $t_q = $this->db->queryrow($sql);
             if (isset($t_q['ship_id']) && !empty($t_q['ship_id'])) {
                 $player_found = FALSE;
                 $setl_q = $this->db->queryrow($sql);
                 if ($planet_to_serve['best_mood'] >= 120) {
                     $player_chance = min(round(($planet_to_serve['best_mood'] - 120) / 4, 0) + 51, 96);
                     if ($player_chance > rand(0, 100)) {
                         $player_found = TRUE;
                     }
                 }
                 if ($player_found) {
                     // besty found. Make a fleet, put the ship into int, warn it about that.
                     // $sql = 'SELECT user_capital from user WHERE user_id = '.$planet_to_serve['best_mood_user'];
                     // $setl_bf = $this->db->queryrow($sql);
                     $sql = 'INSERT INTO ship_fleets (fleet_name, user_id, planet_id, move_id, n_ships)
                                  VALUES ("Reinforcement", ' . $planet_to_serve['best_mood_user'] . ', ' . $planet_to_serve['planet_id'] . ', 0, 1)';
                     $this->sdl->log('SQL A - 2.A1 ' . $sql, TICK_LOG_FILE_NPC);
                     $this->db->query($sql);
                     $fleet_id = $this->db->insert_id();
                     $sql = 'UPDATE ships SET user_id = ' . $planet_to_serve['best_mood_user'] . ', fleet_id = ' . $fleet_id . ' WHERE ship_id=' . $t_q['ship_id'];
                     $this->sdl->log('SQL A - 2.A2 ' . $sql, TICK_LOG_FILE_NPC);
                     $this->db->query($sql);
                     //Here we need multilanguage customization
                     $log_title = 'Nuova unit&agrave; disponibile dalla colonia indipendente ' . $planet_to_serve['planet_name'];
                     $log_data = array($planet_to_serve['planet_id'], $planet_to_serve['planet_name'], $t_q['ship_id'], $t_q['name'], 0, 0);
                     add_logbook_entry($planet_to_serve['best_mood_user'], LOGBOOK_SETTLERS, $log_title, $log_data);
                     $sql = 'UPDATE planets SET npc_last_action = ' . ($ACTUAL_TICK + 20) . ' WHERE planet_id = ' . $planet_to_serve['planet_id'];
                     $this->sdl->log('SQL A - 2.A5 ' . $sql, TICK_LOG_FILE_NPC);
                     $this->db->query($sql);
                     continue;
                 } else {
                     // No besty found; let's make an auction.
                     $_ress_1 = round($t_q['resource_1'] * 0.16);
                     $_ress_2 = round($t_q['resource_2'] * 0.16);
                     $_ress_3 = round($t_q['resource_3'] * 0.16);
                     $_ress_1_step = round($t_q['resource_1'] * 0.03);
                     $_ress_2_step = round($t_q['resource_2'] * 0.03);
                     $_ress_3_step = round($t_q['resource_3'] * 0.03);
                     $sql = 'INSERT INTO ship_trade (user,planet,start_time,end_time,ship_id,resource_1,resource_2,resource_3,unit_1,unit_2,unit_3,unit_4,unit_5,unit_6,add_resource_1,add_resource_2,add_resource_3,add_unit_1,add_unit_2,add_unit_3,add_unit_4,add_unit_5,add_unit_6,header,description,show_data,font_bold,font_colored,unowed_only)
                             VALUES   (' . INDEPENDENT_USERID . ',' . $planet_to_serve['planet_id'] . ',' . $ACTUAL_TICK . ',' . ($ACTUAL_TICK + 480) . ',' . $t_q['ship_id'] . ',' . $_ress_1 . ',' . $_ress_2 . ',' . $_ress_3 . ', 0, 0, 0, 0,' . $t_q['unit_5'] . ',' . $t_q['unit_6'] . ',' . $_ress_1_step . ',' . $_ress_2_step . ',' . $_ress_3_step . ',0,0,0,0,0,0,"' . $t_q['name'] . '","This is an automatic generated auction for a ship held by the Settlers Community!!!",2,1,1,0)';
                     $this->sdl->log('SQL A - 2.B1 ' . $sql, TICK_LOG_FILE_NPC);
                     $this->db->query($sql);
                     $sql = 'UPDATE ships SET ship_untouchable=1 WHERE ship_id=' . $t_q['ship_id'];
                     $this->db->query($sql);
                     // This update is marginal and it could be removed to decrease the server load
                     $sql = 'UPDATE user SET num_auctions=num_auctions+1 WHERE user_id=' . INDEPENDENT_USERID;
                     $this->db->query($sql);
                     $sql = 'UPDATE planets SET npc_last_action = ' . ($ACTUAL_TICK + 20) . ' WHERE planet_id = ' . $planet_to_serve['planet_id'];
                     $this->sdl->log('SQL A - 2.B2 ' . $sql, TICK_LOG_FILE_NPC);
                     $this->db->query($sql);
                     continue;
                 }
             }
             // A - 4
             // Troops sent to players / CC
             if ($planet_to_serve['planet_type'] == 'a' || $planet_to_serve['planet_type'] == 'b' || $planet_to_serve['planet_type'] == 'c' || $planet_to_serve['planet_type'] == 'd' || $planet_to_serve['planet_type'] == 'n') {
                 // Supplies first and second level troops
                 $_ress_4 = $_unit_1 = $_unit_2 = 0;
                 $_unit_1_cut = $_unit_2_cut = 0;
                 $_unit_trade = 0.2;
                 $troops_check = $planet_to_serve['unit_1'] * 2 + $planet_to_serve['unit_2'] * 3 + $planet_to_serve['unit_3'] * 4 + $planet_to_serve['unit_4'] * 4;
                 $security_check = $planet_to_serve['min_security_troops'] * 0.75;
                 if ($troops_check > $security_check) {
                     $_ress_4 = round(0.1 * $planet_to_serve['resource_4']);
                     $planet_to_serve['resource_4'] = $planet_to_serve['resource_4'] - $_ress_4;
                     $_unit_1 = round(0.3 * $planet_to_serve['unit_1']);
                     $planet_to_serve['unit_1'] = $planet_to_serve['unit_1'] - $_unit_1;
                     $_unit_2 = round(0.3 * $planet_to_serve['unit_2']);
                     $planet_to_serve['unit_2'] = $planet_to_serve['unit_2'] - $_unit_2;
                 }
                 if ($_ress_4 + $_unit_1 + $_unit_2 > 0) {
                     if ($planet_to_serve['best_mood'] >= 120) {
                         $_unit_1_cut = round($_unit_trade * $_unit_1);
                         $_unit_2_cut = round($_unit_trade * $_unit_2);
                         // $sql = 'UPDATE FHB_Handels_Lager SET unit_1=unit_1+'.$_unit_1_cut.', unit_2=unit_2+'.$_unit_2_cut.' WHERE id=1';
                         $avail_tick = mt_rand(23, 420);
                         $avail_tick = $avail_tick + $ACTUAL_TICK;
                         $sql = 'INSERT INTO `FHB_cache_trupp_trade` (`unit_1` , `unit_2` , tick ) VALUES (' . $_unit_1_cut . ', ' . $_unit_2_cut . ', ' . $avail_tick . ')';
                         $this->sdl->log('SQL A - 4.0.3.0' . $sql, TICK_LOG_FILE_NPC);
                         $this->db->query($sql);
                         // This is tricky!!!
                         // Il pianeta indicato in best_mood_planet potrebbe non appartenere più al giocatore, tuttavia
                         // in questo modo ci risparmiamo una lettura al DB
                         $log_title = 'Truppe in arrivo dalla colonia ' . $planet_to_serve['planet_name'];
                         $log_data = array($planet_to_serve['planet_id'], $planet_to_serve['planet_name'], 0, 0, 101, 0);
                         if (is_null($planet_to_serve['best_mood_planet'])) {
                             $sql = 'SELECT user_capital from user WHERE user_id = ' . $planet_to_serve['best_mood_user'];
                             $setl_bf = $this->db->queryrow($sql);
                             $target_planet = $setl_bf['user_capital'];
                         } else {
                             $target_planet = $planet_to_serve['best_mood_planet'];
                             $log_data[5] = 1;
                             $log_data[6] = $target_planet;
                             $sql = 'SELECT planet_name from planets WHERE planet_id = ' . $planet_to_serve['best_mood_planet'];
                             $setl_bfp = $this->db->queryrow($sql);
                             $log_data[7] = $setl_bfp['planet_name'];
                         }
                         $sql = 'INSERT INTO scheduler_resourcetrade (planet,resource_1,resource_2,resource_3,resource_4,unit_1,unit_2,unit_3,unit_4,unit_5,unit_6,arrival_time)
                             VALUES (' . $target_planet . ', 0, 0, 0, ' . $_ress_4 . ', ' . ($_unit_1 - $_unit_1_cut) . ', ' . ($_unit_2 - $_unit_2_cut) . ', 0, 0, 0, 0, ' . ($ACTUAL_TICK + 120) . ')';
                         $this->sdl->log('SQL A - 4.0.1' . $sql, TICK_LOG_FILE_NPC);
                         $this->db->query($sql);
                         $sql = 'UPDATE planets SET npc_last_action = ' . ($ACTUAL_TICK + 480) . ',
                                    resource_4 = ' . $planet_to_serve['resource_4'] . ',
                                    unit_1 = ' . $planet_to_serve['unit_1'] . ',
                                    unit_2 = ' . $planet_to_serve['unit_2'] . '
                                 WHERE planet_id = ' . $planet_to_serve['planet_id'];
                         $this->sdl->log('SQL A - 4.0.2' . $sql, TICK_LOG_FILE_NPC);
                         $this->db->query($sql);
                         $log_data[8]['unit_1'] = $_unit_1 - $_unit_1_cut;
                         $log_data[8]['unit_2'] = $_unit_2 - $_unit_2_cut;
                         $log_data[8]['ress_4'] = $_ress_4;
                         add_logbook_entry($planet_to_serve['best_mood_user'], LOGBOOK_SETTLERS, $log_title, $log_data);
                         continue;
                     } else {
                         // $sql = 'UPDATE FHB_Handels_Lager SET unit_1=unit_1+'.$_unit_1.', unit_2=unit_2+'.$_unit_2.' WHERE id=1';
                         $avail_tick = mt_rand(23, 420);
                         $avail_tick = $avail_tick + $ACTUAL_TICK;
                         $sql = 'INSERT INTO `FHB_cache_trupp_trade` (`unit_1` , `unit_2` , tick ) VALUES (' . $_unit_1 . ', ' . $_unit_2 . ', ' . $avail_tick . ')';
                         $this->sdl->log('SQL A - 4.1.1' . $sql, TICK_LOG_FILE_NPC);
                         $this->db->query($sql);
                         $sql = 'UPDATE planets SET npc_last_action = ' . ($ACTUAL_TICK + 480) . ',
                                    unit_1 = ' . $planet_to_serve['unit_1'] . ',
                                    unit_2 = ' . $planet_to_serve['unit_2'] . '
                                 WHERE planet_id = ' . $planet_to_serve['planet_id'];
                         $this->sdl->log('SQL A - 4.1.2' . $sql, TICK_LOG_FILE_NPC);
                         $this->db->query($sql);
                         continue;
                     }
                 }
             }
             if ($planet_to_serve['planet_type'] == 'm' || $planet_to_serve['planet_type'] == 'o' || $planet_to_serve['planet_type'] == 'p' || $planet_to_serve['planet_type'] == 'g' || $planet_to_serve['planet_type'] == 'h') {
                 // Supply workers and specs
                 $_ress_4 = $_unit_5 = $_unit_6 = 0;
                 $_unit_5_cut = $_unit_6_cut = 0;
                 $_unit_trade = 0.2;
                 $troops_check = $planet_to_serve['unit_1'] * 2 + $planet_to_serve['unit_2'] * 3 + $planet_to_serve['unit_3'] * 4 + $planet_to_serve['unit_4'] * 4;
                 $security_check = $planet_to_serve['min_security_troops'] * 0.75;
                 if ($troops_check > $security_check) {
                     $_ress_4 = round(0.1 * $planet_to_serve['resource_4']);
                     $planet_to_serve['resource_4'] = $planet_to_serve['resource_4'] - $_ress_4;
                     $_unit_5 = round(0.3 * $planet_to_serve['unit_5']);
                     $planet_to_serve['unit_5'] = $planet_to_serve['unit_5'] - $_unit_5;
                     $_unit_6 = round(0.3 * $planet_to_serve['unit_6']);
                     $planet_to_serve['unit_6'] = $planet_to_serve['unit_6'] - $_unit_6;
                 }
                 if ($_ress_4 + $_unit_5 + $_unit_6 > 0) {
                     if ($planet_to_serve['best_mood'] >= 120) {
                         $_unit_5_cut = round($_unit_trade * $_unit_5);
                         $_unit_6_cut = round($_unit_trade * $_unit_6);
                         // $sql = 'UPDATE FHB_Handels_Lager SET unit_5=unit_5+'.$_unit_5_cut.', unit_6=unit_6+'.$_unit_6_cut.' WHERE id=1';
                         $avail_tick = mt_rand(23, 420);
                         $avail_tick = $avail_tick + $ACTUAL_TICK;
                         $sql = 'INSERT INTO `FHB_cache_trupp_trade` (`unit_5` , `unit_6` , tick ) VALUES (' . $_unit_5_cut . ', ' . $_unit_6_cut . ', ' . $avail_tick . ')';
                         $this->sdl->log('SQL A - 4.0.3' . $sql, TICK_LOG_FILE_NPC);
                         $this->db->query($sql);
                         $log_title = 'Truppe in arrivo dalla colonia ' . $planet_to_serve['planet_name'];
                         $log_data = array($planet_to_serve['planet_id'], $planet_to_serve['planet_name'], 0, 0, 101, 0);
                         if (is_null($planet_to_serve['best_mood_planet'])) {
                             $sql = 'SELECT user_capital from user WHERE user_id = ' . $planet_to_serve['best_mood_user'];
                             $setl_bf = $this->db->queryrow($sql);
                             $target_planet = $setl_bf['user_capital'];
                         } else {
                             $target_planet = $planet_to_serve['best_mood_planet'];
                             $log_data[5] = 1;
                             $log_data[6] = $target_planet;
                             $sql = 'SELECT planet_name from planets WHERE planet_id = ' . $planet_to_serve['best_mood_planet'];
                             $setl_bfp = $this->db->queryrow($sql);
                             $log_data[7] = $setl_bfp['planet_name'];
                         }
                         $sql = 'INSERT INTO scheduler_resourcetrade (planet,resource_1,resource_2,resource_3,resource_4,unit_1,unit_2,unit_3,unit_4,unit_5,unit_6,arrival_time)
                             VALUES (' . $target_planet . ', 0, 0, 0, ' . $_ress_4 . ', 0, 0, 0, 0, ' . ($_unit_5 - $_unit_5_cut) . ', ' . ($_unit_6 - $_unit_6_cut) . ', ' . ($ACTUAL_TICK + 120) . ')';
                         $this->sdl->log('SQL A - 4.3.1' . $sql, TICK_LOG_FILE_NPC);
                         $this->db->query($sql);
                         $sql = 'UPDATE planets SET npc_last_action = ' . ($ACTUAL_TICK + 480) . ',
                                    resource_4 = ' . $planet_to_serve['resource_4'] . ',
                                    unit_5 = ' . $planet_to_serve['unit_5'] . ',
                                    unit_6 = ' . $planet_to_serve['unit_6'] . '
                                 WHERE planet_id = ' . $planet_to_serve['planet_id'];
                         $this->sdl->log('SQL A - 4.3.2' . $sql, TICK_LOG_FILE_NPC);
                         $this->db->query($sql);
                         $log_data[8]['unit_5'] = $_unit_5 - $_unit_5_cut;
                         $log_data[8]['unit_6'] = $_unit_6 - $_unit_6_cut;
                         $log_data[8]['ress_4'] = $_ress_4;
                         add_logbook_entry($planet_to_serve['best_mood_user'], LOGBOOK_SETTLERS, $log_title, $log_data);
                         continue;
                     } else {
                         // $sql = 'UPDATE FHB_Handels_Lager SET unit_5=unit_5+'.$_unit_5.', unit_6=unit_6+'.$_unit_6.' WHERE id=1';
                         $avail_tick = mt_rand(23, 420);
                         $avail_tick = $avail_tick + $ACTUAL_TICK;
                         $sql = 'INSERT INTO `FHB_cache_trupp_trade` (`unit_5` , `unit_6` , tick ) VALUES (' . $_unit_5 . ', ' . $_unit_6 . ', ' . $avail_tick . ')';
                         $this->sdl->log('SQL A - 4.4.1' . $sql, TICK_LOG_FILE_NPC);
                         $this->db->query($sql);
                         $sql = 'UPDATE planets SET npc_last_action = ' . ($ACTUAL_TICK + 480) . ',
                                    unit_5 = ' . $planet_to_serve['unit_5'] . ',
                                    unit_6 = ' . $planet_to_serve['unit_6'] . '
                                 WHERE planet_id = ' . $planet_to_serve['planet_id'];
                         $this->sdl->log('SQL A - 4.4.2' . $sql, TICK_LOG_FILE_NPC);
                         $this->db->query($sql);
                         continue;
                     }
                 }
             }
             // A - 4
             // Mining planets
             // We check the planet real production and get 55% of that
             // So the math is:  $_ress_X = 0.55*(add_X*20*24)
             if ($planet_to_serve['planet_type'] == 'j' || $planet_to_serve['planet_type'] == 's' || $planet_to_serve['planet_type'] == 'i' || $planet_to_serve['planet_type'] == 't' || $planet_to_serve['planet_type'] == 'x' || $planet_to_serve['planet_type'] == 'y') {
                 $_ress_1 = $_ress_2 = $_ress_3 = 0;
                 $_ress_1_cut = $_ress_2_cut = $_ress_3_cut = 0;
                 // Should we put this value in a define?
                 $_ress_rateo = 0.55;
                 // Trading Center cut is 27%
                 $_ress_trade = 0.27;
                 if ($planet_to_serve['planet_type'] == 'j') {
                     $_ress_1 = round($_ress_rateo * ($planet_to_serve['add_1'] * 20 * 24));
                     if ($_ress_1 < $planet_to_serve['resource_1']) {
                         $planet_to_serve['resource_1'] = $planet_to_serve['resource_1'] - $_ress_1;
                         $_ress_1_cut = round($_ress_trade * $_ress_1);
                     } else {
                         $_ress_1 = 0;
                     }
                 } elseif ($planet_to_serve['planet_type'] == 's' || $planet_to_serve['planet_type'] == 't') {
                     $_ress_2 = round($_ress_rateo * ($planet_to_serve['add_2'] * 20 * 24));
                     if ($_ress_2 < $planet_to_serve['resource_2']) {
                         $planet_to_serve['resource_2'] = $planet_to_serve['resource_2'] - $_ress_2;
                         $_ress_2_cut = round($_ress_trade * $_ress_2);
                     } else {
                         $_ress_2 = 0;
                     }
                 } elseif ($planet_to_serve['planet_type'] == 'i') {
                     $_ress_3 = round($_ress_rateo * ($planet_to_serve['add_3'] * 20 * 24));
                     if ($_ress_3 < $planet_to_serve['resource_3']) {
                         $planet_to_serve['resource_3'] = $planet_to_serve['resource_3'] - $_ress_3;
                         $_ress_3_cut = round($_ress_trade * $_ress_3);
                     } else {
                         $_ress_3 = 0;
                     }
                 } elseif ($planet_to_serve['planet_type'] == 'x' || $planet_to_serve['planet_type'] == 'y') {
                     $_ress_1 = round($_ress_rateo * ($planet_to_serve['add_1'] * 20 * 24));
                     if ($_ress_1 < $planet_to_serve['resource_1']) {
                         $planet_to_serve['resource_1'] = $planet_to_serve['resource_1'] - $_ress_1;
                         $_ress_1_cut = round($_ress_trade * $_ress_1);
                     } else {
                         $_ress_1 = 0;
                     }
                     $_ress_2 = round($_ress_rateo * ($planet_to_serve['add_2'] * 20 * 24));
                     if ($_ress_2 < $planet_to_serve['resource_2']) {
                         $planet_to_serve['resource_2'] = $planet_to_serve['resource_2'] - $_ress_2;
                         $_ress_2_cut = round($_ress_trade * $_ress_2);
                     } else {
                         $_ress_2 = 0;
                     }
                     $_ress_3 = round($_ress_rateo * ($planet_to_serve['add_3'] * 20 * 24));
                     if ($_ress_3 < $planet_to_serve['resource_3']) {
                         $planet_to_serve['resource_3'] = $planet_to_serve['resource_3'] - $_ress_3;
                         $_ress_3_cut = round($_ress_trade * $_ress_3);
                     } else {
                         $_ress_3 = 0;
                     }
                 }
                 if ($_ress_1 + $_ress_2 + $_ress_3 > 0) {
                     // Ships the cut to the tradecenter
                     $sql = 'UPDATE FHB_Handels_Lager SET ress_1=ress_1+' . $_ress_1_cut . ',ress_2=ress_2+' . $_ress_2_cut . ',ress_3=ress_3+' . $_ress_3_cut . ' WHERE id=1';
                     $this->sdl->log('SQL A - 4.7' . $sql, TICK_LOG_FILE_NPC);
                     $this->db->query($sql);
                     if ($planet_to_serve['best_mood'] >= 120) {
                         $log_title = 'Risorse in arrivo dalla colonia ' . $planet_to_serve['planet_name'];
                         $log_data = array($planet_to_serve['planet_id'], $planet_to_serve['planet_name'], 0, 0, 102, 0);
                         if (is_null($planet_to_serve['best_mood_planet'])) {
                             $sql = 'SELECT user_capital from user WHERE user_id = ' . $planet_to_serve['best_mood_user'];
                             $setl_bf = $this->db->queryrow($sql);
                             $target_planet = $setl_bf['user_capital'];
                         } else {
                             $target_planet = $planet_to_serve['best_mood_planet'];
                             $log_data[5] = 1;
                             $log_data[6] = $target_planet;
                             $sql = 'SELECT planet_name from planets WHERE planet_id = ' . $planet_to_serve['best_mood_planet'];
                             $setl_bfp = $this->db->queryrow($sql);
                             $log_data[7] = $setl_bfp['planet_name'];
                         }
                         $sql = 'INSERT INTO scheduler_resourcetrade (planet,resource_1,resource_2,resource_3,resource_4,unit_1,unit_2,unit_3,unit_4,unit_5,unit_6,arrival_time)
                                        VALUES (' . $target_planet . ', ' . ($_ress_1 - $_ress_1_cut) . ', ' . ($_ress_2 - $_ress_2_cut) . ', ' . ($_ress_3 - $_ress_3_cut) . ', 0, 0, 0, 0, 0, 0, 0, ' . ($ACTUAL_TICK + 120) . ')';
                         $this->sdl->log('SQL A - 4.5.1' . $sql, TICK_LOG_FILE_NPC);
                         $this->db->query($sql);
                         $sql = 'UPDATE planets SET npc_last_action = ' . ($ACTUAL_TICK + 480) . ',
                                     resource_1 = ' . $planet_to_serve['resource_1'] . ',
                                     resource_2 = ' . $planet_to_serve['resource_2'] . ',
                                     resource_3 = ' . $planet_to_serve['resource_3'] . '
                                 WHERE planet_id = ' . $planet_to_serve['planet_id'];
                         $this->sdl->log('SQL A - 4.5.2' . $sql, TICK_LOG_FILE_NPC);
                         $this->db->query($sql);
                         $log_data[8]['ress_1'] = $_ress_1 - $_ress_1_cut;
                         $log_data[8]['ress_2'] = $_ress_2 - $_ress_2_cut;
                         $log_data[8]['ress_3'] = $_ress_3 - $_ress_3_cut;
                         add_logbook_entry($planet_to_serve['best_mood_user'], LOGBOOK_SETTLERS, $log_title, $log_data);
                         continue;
                     } else {
                         $sql = 'UPDATE FHB_Handels_Lager SET ress_1=ress_1+' . $_ress_1 . ',ress_2=ress_2+' . $_ress_2 . ',ress_3=ress_3+' . $_ress_3 . ' WHERE id=1';
                         $this->sdl->log('SQL A - 4.6.1' . $sql, TICK_LOG_FILE_NPC);
                         $this->db->query($sql);
                         $sql = 'UPDATE planets SET npc_last_action = ' . ($ACTUAL_TICK + 480) . ',
                                     resource_1 = ' . $planet_to_serve['resource_1'] . ',
                                     resource_2 = ' . $planet_to_serve['resource_2'] . ',
                                     resource_3 = ' . $planet_to_serve['resource_3'] . '
                                 WHERE planet_id = ' . $planet_to_serve['planet_id'];
                         $this->sdl->log('SQL A - 4.6.2' . $sql, TICK_LOG_FILE_NPC);
                         $this->db->query($sql);
                         continue;
                     }
                 }
             }
             // A - 3
             // Let's build a ship!!! We could avoid the use of the scheduler, just to decrease the overhead...
             // In the definitive version, only certain planets should build ships.
             /*
             if($planet_to_serve['planet_type'] == 'h' || $planet_to_serve['planet_type'] == 'n')
             {
                 $sql = 'SELECT COUNT(*) as ship_queue FROM scheduler_shipbuild WHERE planet_id = '.$planet_to_serve['planet_id'];
                 $s_q = $this->db->queryrow($sql);
                 if($s_q['ship_queue'] == 0)
                 {
                     $_buildtime = 720; // Yep, no access to the DB, let's avoid it...
                     $sql = 'INSERT INTO scheduler_shipbuild SET ship_type = '.$cfg_data['settler_tmp_1'].', planet_id = '.$planet_to_serve['planet_id'].', start_build = '.$ACTUAL_TICK.', finish_build = '.($ACTUAL_TICK + $_buildtime).', unit_1 = 56, unit_2 = 0, unit_3 = 0, unit_4 = 1';
                     $this->sdl->log('SQL A - 3.1 '.$sql, TICK_LOG_FILE_NPC);
                     $this->db->query($sql);
                     $sql = 'UPDATE planets SET npc_last_action = '.($ACTUAL_TICK + 20).' WHERE planet_id = '.$planet_to_serve['planet_id'];
                     $this->sdl->log('SQL A - 3.2 '.$sql, TICK_LOG_FILE_NPC);
                     $this->db->query($sql);
                     continue;
                 }
             }
             */
             if ($planet_to_serve['planet_type'] == 'k' || $planet_to_serve['planet_type'] == 'l') {
                 // We build medium combat ships (hull 7)
                 $sql = 'SELECT COUNT(*) as ship_queue FROM scheduler_shipbuild WHERE planet_id = ' . $planet_to_serve['planet_id'];
                 $s_q = $this->db->queryrow($sql);
                 if ($s_q['ship_queue'] == 0) {
                     $_buildtime = 1440;
                     // Yep, no access to the DB, let's avoid it...
                     $sql = 'INSERT INTO scheduler_shipbuild SET ship_type = ' . $cfg_data['settler_tmp_2'] . ', planet_id = ' . $planet_to_serve['planet_id'] . ', start_build = ' . $ACTUAL_TICK . ', finish_build = ' . ($ACTUAL_TICK + $_buildtime) . ', unit_1 = 90, unit_2 = 30, unit_3 = 10, unit_4 = 1';
                     $this->sdl->log('SQL A - 3.1 ' . $sql, TICK_LOG_FILE_NPC);
                     $this->db->query($sql);
                     $sql = 'UPDATE planets SET npc_last_action = ' . ($ACTUAL_TICK + 20) . ' WHERE planet_id = ' . $planet_to_serve['planet_id'];
                     $this->sdl->log('SQL A - 3.2 ' . $sql, TICK_LOG_FILE_NPC);
                     $this->db->query($sql);
                     continue;
                 }
             }
             if ($planet_to_serve['planet_type'] == 'f' || $planet_to_serve['planet_type'] == 'e') {
                 $sql = 'SELECT COUNT(*) as ship_queue FROM scheduler_shipbuild WHERE planet_id = ' . $planet_to_serve['planet_id'];
                 $s_q = $this->db->queryrow($sql);
                 // We build combat ships (hull 10)!!!
                 if ($s_q['ship_queue'] == 0) {
                     $_buildtime = 2880;
                     // Yep, no access to the DB, let's avoid it...
                     $sql = 'INSERT INTO scheduler_shipbuild SET ship_type = ' . $cfg_data['settler_tmp_3'] . ', planet_id = ' . $planet_to_serve['planet_id'] . ', start_build = ' . $ACTUAL_TICK . ', finish_build = ' . ($ACTUAL_TICK + $_buildtime) . ', unit_1 = 200, unit_2 = 95, unit_3 = 65, unit_4 = 6';
                     $this->sdl->log('SQL A - 3.3 ' . $sql, TICK_LOG_FILE_NPC);
                     $this->db->query($sql);
                     $sql = 'UPDATE planets SET npc_last_action = ' . ($ACTUAL_TICK + 20) . ' WHERE planet_id = ' . $planet_to_serve['planet_id'];
                     $this->sdl->log('SQL A - 3.4 ' . $sql, TICK_LOG_FILE_NPC);
                     $this->db->query($sql);
                     continue;
                 }
             }
             // A - 5
             // Planetary Orbital Shield!!!!
             // Let's give Settlers something for self-defense against Borg and nasty players
             $sql = 'SELECT fleet_id FROM ship_fleets WHERE fleet_name = "Orbital' . $planet_to_serve['planet_id'] . '"';
             $od_q = $this->db->queryrow($sql);
             if (isset($od_q['fleet_id']) && !empty($od_q['fleet_id'])) {
                 $sql = 'SELECT COUNT(*) AS counter FROM ships WHERE fleet_id = ' . $od_q['fleet_id'];
                 $orbital_check = $this->db->queryrow($sql);
                 if ($orbital_check['counter'] < 50) {
                     //No access to DB, let's put the values right in, REMEMBER TO CHECK THE TEMPLATE IN THE DB WHEN EDITING THIS!!!
                     $sql = 'INSERT INTO ships (fleet_id, user_id, template_id, experience, hitpoints, construction_time, torp, rof, last_refit_time)
                             VALUES (' . $od_q['fleet_id'] . ', ' . INDEPENDENT_USERID . ', ' . $cfg_data['settler_tmp_4'] . ', 0, 100, ' . time() . ', 300, 5, ' . time() . ')';
                     $this->db->query($sql);
                     $sql = 'UPDATE planets SET npc_last_action = ' . ($ACTUAL_TICK + 160) . ' WHERE planet_id = ' . $planet_to_serve['planet_id'];
                     $this->sdl->log('SQL A - 5.1 ' . $sql, TICK_LOG_FILE_NPC);
                     $this->db->query($sql);
                     continue;
                 }
             } else {
                 // Orbital defence fleet not exists. Let's create this.
                 $sql = 'INSERT INTO ship_fleets (fleet_name, user_id, planet_id, alert_phase, move_id, n_ships)
                         VALUES ("Orbital' . $planet_to_serve['planet_id'] . '", ' . INDEPENDENT_USERID . ', ' . $planet_to_serve['planet_id'] . ', ' . ALERT_PHASE_GREEN . ', 0, 1)';
                 $this->db->query($sql);
                 $fleet_id = $this->db->insert_id();
                 $sql = 'INSERT INTO ships (fleet_id, user_id, template_id, experience, hitpoints, construction_time, torp, rof, last_refit_time)
                         VALUES (' . $fleet_id . ', ' . INDEPENDENT_USERID . ', ' . $cfg_data['settler_tmp_4'] . ', 0, 100, ' . time() . ', 300, 5, ' . time() . ')';
                 $this->db->query($sql);
                 $sql = 'UPDATE planets SET npc_last_action = ' . ($ACTUAL_TICK + 160) . ' WHERE planet_id = ' . $planet_to_serve['planet_id'];
                 $this->sdl->log('SQL A - 5.0 ' . $sql, TICK_LOG_FILE_NPC);
                 $this->db->query($sql);
                 continue;
             }
             $sql = 'UPDATE planets SET npc_last_action = ' . ($ACTUAL_TICK + 20) . ' WHERE planet_id = ' . $planet_to_serve['planet_id'];
             $this->sdl->log('SQL E ' . $sql, TICK_LOG_FILE_NPC);
             $this->db->query($sql);
         }
     }
     $this->sdl->finish_job('Mayflower Planets Building Control', TICK_LOG_FILE_NPC);
     // ########################################################################################
     // ########################################################################################
     // Auctions clean-up
     $this->sdl->start_job('Mayflower auctions clean-up', TICK_LOG_FILE_NPC);
     // Set to "every resources withdrawn" on Settler's paid auctions
     $sql = 'UPDATE schulden_table SET status=2
             WHERE user_ver = ' . INDEPENDENT_USERID . ' AND status = 1';
     if (!$this->db->query($sql)) {
         $this->sdl->log('<b>Error:</b> cannot update status to "resources withdrawn" for Settlers auctions', TICK_LOG_FILE_NPC);
     }
     $this->sdl->finish_job('Mayflower auctions clean-up', TICK_LOG_FILE_NPC);
     // ########################################################################################
     // ########################################################################################
     $this->sdl->log('<b>Finished Scheduler in <font color=#009900>' . round(microtime() + time() - $starttime, 4) . ' secs</font><br>Executed Queries: <font color=#ff0000>' . $this->db->i_query . '</font></b>', TICK_LOG_FILE_NPC);
 }
    function _action_main()
    {
        // #############################################################################
        // Data from the attacker
        $sql = 'SELECT ' . $this->get_combat_query_fleet_columns() . '
		FROM (ship_fleets f)
		INNER JOIN user u ON u.user_id = f.user_id
		WHERE f.fleet_id IN (' . $this->fleet_ids_str . ')';
        if (($atk_fleets = $this->db->queryrowset($sql)) === false) {
            return $this->log(MV_M_DATABASE, 'Could not query attackers fleets data! SKIP');
        }
        // #############################################################################
        // Data from the defender
        if (empty($this->action_data[0])) {
            return $this->log(MV_M_ERROR, 'action_51: Could not find required action_data entry [0]! SKIP');
        }
        $user_id = (int) $this->action_data[0];
        $planetary_attack = $user_id == $this->dest['user_id'] ? true : false;
        if ($planetary_attack) {
            $cur_user = array('user_id' => $user_id, 'user_name' => $this->dest['user_name'], 'user_race' => $this->dest['user_race'], 'user_planets' => $this->dest['user_planets'], 'user_alliance' => $this->dest['user_alliance']);
        } else {
            $sql = 'SELECT user_id, user_name, user_race, user_planets, user_alliance
            FROM user
            WHERE user_id = ' . $user_id;
            if (($cur_user = $this->db->queryrow($sql)) === false) {
                return $this->log(MV_M_DATABASE, 'Could not query attacked user data! SKIP');
            }
            if (empty($cur_user['user_id'])) {
                $this->log(MV_M_NOTICE, 'action_51: Could not find attacked user! FINISHED');
                $sql = 'UPDATE ship_fleets
                SET planet_id = ' . $this->move['dest'] . ',
                    move_id = 0
                WHERE fleet_id IN (' . $this->fleet_ids_str . ')';
                if (!$this->db->query($sql)) {
                    return $this->log(MV_M_DATABASE, 'Could not update fleets location data! SKIP');
                }
                return MV_EXEC_OK;
            }
        }
        $sql = 'SELECT DISTINCT f.user_id,
               u.user_alliance,
               ud.ud_id, ud.accepted,
               ad.ad_id, ad.type, ad.status
        FROM (ship_fleets f)
        INNER JOIN user u ON u.user_id = f.user_id
        LEFT JOIN user_diplomacy ud ON ( ( ud.user1_id = ' . $user_id . ' AND ud.user2_id = f.user_id ) OR ( ud.user1_id = f.user_id AND ud.user2_id = ' . $user_id . ' ) )
        LEFT JOIN alliance_diplomacy ad ON ( ( ad.alliance1_id = ' . $cur_user['user_alliance'] . ' AND ad.alliance2_id = u.user_alliance) OR ( ad.alliance1_id = u.user_alliance AND ad.alliance2_id = ' . $cur_user['user_alliance'] . ' ) )
        WHERE f.planet_id = ' . $this->move['start'] . ' AND
              f.user_id <> ' . $user_id . ' AND
              f.user_id <> ' . $this->move['user_id'] . ' AND
              f.alert_phase >= ' . ALERT_PHASE_YELLOW;
        //$this->log(MV_M_NOTICE,'Defenders Select:<br>"'.$sql.'"<br>');
        if (!($q_st_uid = $this->db->query($sql))) {
            return $this->log(MV_M_DATABASE, 'Could not query stationated fleets user data! SKIP');
        }
        $st_user = array();
        while ($st_uid = $this->db->fetchrow($q_st_uid)) {
            $allied = false;
            if ($st_uid['user_alliance'] == $cur_user['user_alliance']) {
                $allied = true;
            }
            if (!empty($st_uid['ud_id'])) {
                if ($st_uid['accepted'] == 1) {
                    $allied = true;
                }
            }
            if (!empty($st_uid['ad_id'])) {
                if ($st_uid['type'] == ALLIANCE_DIPLOMACY_PACT && $st_uid['status'] == 0) {
                    $allied = true;
                }
            }
            if ($allied) {
                $st_user[] = $st_uid['user_id'];
            }
        }
        $n_st_user = count($st_user);
        if ($n_st_user > 0) {
            $sql = 'SELECT ' . $this->get_combat_query_fleet_columns() . '
             FROM (ship_fleets f)
             INNER JOIN user u ON u.user_id = f.user_id
             WHERE f.planet_id = ' . $this->move['start'] . ' AND
			       (
                     (
                       f.user_id = ' . $user_id . '
                     )
                     OR
                     (
                       f.user_id IN (' . implode(',', $st_user) . ') AND
                       f.alert_phase >= ' . ALERT_PHASE_YELLOW . '
                     )
                   )';
        } else {
            $sql = 'SELECT ' . $this->get_combat_query_fleet_columns() . '
             FROM (ship_fleets f)
             INNER JOIN user u ON u.user_id = f.user_id
             WHERE f.planet_id = ' . $this->move['start'] . ' AND
                   f.user_id = ' . $user_id;
        }
        if (($dfd_fleets = $this->db->queryrowset($sql)) === false) {
            return $this->log(MV_M_DATABASE, 'Could not query defenders fleets data! SKIP');
        }
        $dfd_fleet_ids = array();
        foreach ($dfd_fleets as $i => $cur_fleet) {
            $dfd_fleet_ids[] = $cur_fleet['fleet_id'];
        }
        $dfd_fleet_ids_str = implode(',', $dfd_fleet_ids);
        if ($this->do_ship_combat($this->fleet_ids_str, $dfd_fleet_ids_str, $planetary_attack ? MV_COMBAT_LEVEL_ORBITAL : MV_COMBAT_LEVEL_OUTER) == MV_EXEC_ERROR) {
            $this->log(MV_M_DATABASE, 'Move Action 51: Something went wrong with this fight!');
            return MV_EXEC_ERROR;
        }
        // #############################################################################
        // The fleet possibly send into orbit
        // #############################################################################
        // 03/04/08 - AC: Retrieve player language
        $prep = $planetary_attack ? 'on' : 'at';
        $dfd_title = 'Attack ' . $prep . ' ' . $this->dest['planet_name'];
        $sql = 'SELECT language FROM user WHERE user_id = ' . $user_id;
        if (!($lang = $this->db->queryrow($sql))) {
            $this->log(MV_M_DATABASE, 'Could not retrieve player language');
        } else {
            switch ($lang['language']) {
                case 'GER':
                    $prep = $planetary_attack ? 'auf' : 'bei';
                    $dfd_title = 'Angriff ' . $prep . ' ' . $this->dest['planet_name'];
                    break;
                case 'ITA':
                    $prep = $planetary_attack ? 'su' : 'presso';
                    $dfd_title = 'Attacco ' . $prep . ' ' . $this->dest['planet_name'];
                    break;
            }
        }
        if ($this->cmb[MV_CMB_WINNER] == MV_CMB_ATTACKER) {
            // #############################################################################
            // 03/04/08 - AC: Retrieve player language
            switch ($this->move['language']) {
                case 'GER':
                    $prep = $planetary_attack ? 'auf' : 'bei';
                    $atk_title = 'Angriff ' . $prep . ' ' . $this->dest['planet_name'] . ' erfolgreich';
                    break;
                case 'ITA':
                    $prep = $planetary_attack ? 'su' : 'presso';
                    $atk_title = 'Attacco ' . $prep . ' ' . $this->dest['planet_name'] . ' riuscito';
                    break;
                default:
                    $prep = $planetary_attack ? 'on' : 'at';
                    $atk_title = 'Attack ' . $prep . ' ' . $this->dest['planet_name'] . ' successful';
                    break;
            }
            $sql = 'UPDATE ship_fleets
            SET planet_id = ' . $this->move['dest'] . ',
                move_id = 0
            WHERE fleet_id IN (' . $this->fleet_ids_str . ')';
            if (!$this->db->query($sql)) {
                // Here one could also report and then go on
                return $this->log(MV_M_DATABASE, 'Could not update fleets location data! SKIP');
            }
            // If the attack was on a settlers planet, they will get a little mad!
            if ($this->dest['user_id'] == INDEPENDENT_USERID) {
                $this->log(MV_M_NOTICE, 'Colony: Settlers being attacked!!! They gonna be mad!');
                $sql = 'DELETE FROM settlers_relations WHERE planet_id = ' . $this->move['dest'] . ' AND user_id = ' . $this->move['user_id'];
                if (!$this->db->query($sql)) {
                    $this->log(MV_M_DATABASE, 'Could not update settlers moods! CONTINUE!');
                }
                if (!empty($this->move['user_alliance']) && $this->move['user_alliance_status'] > 2) {
                    $sql = 'INSERT INTO settlers_relations
                    SET planet_id = ' . $this->move['dest'] . ',
                        user_id = ' . $this->move['user_id'] . ',
                        alliance_id = ' . $this->move['user_alliance'] . ',
                        race_id = ' . $this->move['user_race'] . ',
                        timestamp = ' . time() . ',
                        log_code = 10,
                        mood_modifier = - 20';
                } else {
                    $sql = 'INSERT INTO settlers_relations
                    SET planet_id = ' . $this->move['dest'] . ',
                        user_id = ' . $this->move['user_id'] . ',
                        race_id = ' . $this->move['user_race'] . ',
                        timestamp = ' . time() . ',
                        log_code = 10,
                        mood_modifier = - 20';
                }
                if (!$this->db->query($sql)) {
                    $this->log(MV_M_DATABASE, 'Could not update settlers moods! CONTINUE!');
                }
                $this->check_best_mood($this->move['dest'], false);
            }
        } else {
            // #############################################################################
            // 17/08/15 - Retreat Management
            $sql = 'SELECT COUNT(*) as ship_escaped FROM ships WHERE fleet_id IN (' . $this->fleet_ids_str . ')';
            $e_s_c = $this->db->queryrow($sql);
            if (isset($e_s_c['ship_escaped']) && $e_s_c['ship_escaped'] > 0) {
                $sql = 'SELECT system_id, planet_distance_id FROM planets WHERE planet_id = ' . $this->move['dest'];
                $e_s_s = $this->db->queryrow($sql);
                $sql = 'SELECT planet_id FROM planets WHERE system_id = ' . $e_s_s['system_id'] . ' AND planet_id <> ' . $this->move['dest'] . '
                       AND planet_distance_id > ' . $e_s_s['planet_distance_id'] . ' ORDER BY planet_distance_id ASC LIMIT 0,1';
                if (!($res = $this->db->query($sql))) {
                    return $this->log(MV_M_DATABASE, 'Could not read system data!!! SQL is ' . $sql);
                }
                $rows = $this->db->num_rows();
                if ($rows > 0) {
                    $escaperes = $this->db->fetchrow($res);
                    $newdest = $escaperes['planet_id'];
                } else {
                    $newdest = $this->move['dest'];
                }
                $sql = 'UPDATE scheduler_shipmovement SET start = ' . $this->move['dest'] . ', dest = ' . $newdest . ', move_begin = ' . $this->CURRENT_TICK . ', move_finish = ' . ($this->CURRENT_TICK + 4) . ',' . ' action_code = 28, action_data = 0, n_ships = ' . $e_s_c['ship_escaped'] . ' WHERE move_id = ' . $this->move['move_id'];
                if (!$this->db->query($sql)) {
                    return $this->log(MV_M_DATABASE, 'Could not update movement data!!! SQL is ' . $sql);
                }
                $this->flags['keep_move_alive'] = true;
            }
            // #############################################################################
            // 03/04/08 - AC: Retrieve player language
            switch ($this->move['language']) {
                case 'GER':
                    $prep = $planetary_attack ? 'auf' : 'bei';
                    $atk_title = 'Angriff ' . $prep . ' ' . $this->dest['planet_name'] . ' fehlgeschlagen';
                    break;
                case 'ITA':
                    $prep = $planetary_attack ? 'su' : 'presso';
                    $atk_title = 'Attacco su ' . $this->dest['planet_name'] . ' fallito';
                    break;
                default:
                    $prep = $planetary_attack ? 'on' : 'at';
                    $atk_title = 'Attack on ' . $this->dest['planet_name'] . ' failed';
                    break;
            }
        }
        // #############################################################################
        // Logbook write
        $log1_data = array(51, $this->move['user_id'], $this->move['dest'], $this->dest['planet_name'], $this->dest['user_id'], 0, 0, 0, MV_CMB_ATTACKER, $this->cmb[MV_CMB_WINNER] == MV_CMB_ATTACKER ? 1 : 0, 0, 0, $atk_fleets, $dfd_fleets);
        $log2_data = array(51, $this->move['user_id'], $this->move['dest'], $this->dest['planet_name'], $this->dest['user_id'], 0, 0, 0, MV_CMB_DEFENDER, $this->cmb[MV_CMB_WINNER] == MV_CMB_DEFENDER ? 1 : 0, 0, 0, $atk_fleets, $dfd_fleets);
        if ($planetary_attack) {
            $log2_data[14] = $this->cmb[MV_CMB_KILLS_PLANETARY];
        }
        $log1_data[10] = $this->cmb[MV_CMB_KILLS_EXT];
        $log2_data[10] = $this->cmb[MV_CMB_KILLS_EXT];
        add_logbook_entry($this->move['user_id'], LOGBOOK_TACTICAL_2, $atk_title, $log1_data);
        add_logbook_entry($user_id, LOGBOOK_TACTICAL_2, $dfd_title, $log2_data);
        if ($n_st_user > 0) {
            $log2_data[2] = $this->move['start'];
            $log2_data[3] = $this->dest['planet_name'];
            $log2_data[4] = $user_id;
            $log2_data[5] = 0;
            $log2_data[6] = 0;
            $log2_data[7] = 0;
            $log2_data[16] = 1;
            for ($i = 0; $i < $n_st_user; ++$i) {
                // #############################################################################
                // 03/04/08 - AC: Retrieve player language
                $log_title = 'One of your allies defended ' . $this->dest['planet_name'];
                $sql = 'SELECT language FROM user WHERE user_id = ' . $st_user[$i];
                if (!($lang = $this->db->queryrow($sql))) {
                    $this->log(MV_M_DATABASE, 'Could not retrieve player language');
                } else {
                    switch ($lang['language']) {
                        case 'GER':
                            $log_title = 'Verb&uuml;ndeten bei ' . $this->dest['planet_name'] . ' verteidigt';
                            break;
                        case 'ITA':
                            $log_title = 'Difesa alleata presso ' . $this->dest['planet_name'];
                            break;
                    }
                }
                add_logbook_entry($st_user[$i], LOGBOOK_TACTICAL, $log_title, $log2_data);
            }
        }
        return MV_EXEC_OK;
    }
Exemple #19
0
 public function Execute($debuggen = 0, $title = "", $type = 0, $color = "#ffffff")
 {
     global $sdl, $ACTUAL_TICK, $STARDATE;
     $starttime = microtime() + time();
     $debug_array_logen = 0;
     $debug_sql_logen = 0;
     /*if($debug_zu= $this->db->queryrow('SELECT debug,sql,array,style FROM FHB_debug LIMIT 0,1'))
       {
           if($debug_zu['debug']==0 || $debug_zu['debug']==1)$debuggen=$debug_zu['debug'];
           if($debug_zu['array']==0 || $debug_zu['array']==1)$debug_array_logen=$debug_zu['array'];
           if($debug_zu['style']==0 || $debug_zu['style']==1)$type=$debug_zu['style'];
           if($debug_zu['sql']==0 || $debug_zu['sql']==1)$debug_sql_logen=$debug_zu['sql'];
       }*/
     $this->sdl->log('<br><b>-------------------------------------------------------------</b><br>' . '<b>Starting Bot Scheduler at ' . date('d.m.y H:i:s', time()) . '</b>', TICK_LOG_FILE_NPC);
     // We need some info to allow the BOT to live
     $this->bot = $this->db->queryrow('SELECT * FROM FHB_Bot LIMIT 0,1');
     if ($this->bot) {
         $this->sdl->log("The conversation with Ramona begins, oh, it is not beautiful, and then, it has such a great personality", TICK_LOG_FILE_NPC);
     } else {
         $this->sdl->log('<b>Error:</b> No access to the bot table - ABORTED', TICK_LOG_FILE_NPC);
         return;
     }
     // ########################################################################################
     // ########################################################################################
     // Messages answer
     $messages = array('<center><b>Good morning</b></center><br><br>
         Your message to us has no effect. We handle everything properly and immediately at same.<br>
         If you think we need to blackmail us or put pressure or violence or other thoughts
         against us - forget it immediately.<br>
         Since we are what military defence is concerned, not something to admit, our weapons are loaded
         and our ships combat-ready.<br>If agression should take place, we will strike back with still stronger
         hardness.<br><br>
         If you wanted to say just hello, take that above as a warning. If you realize that our delivery
         system has problem, please report to the Galactic Administration
         (Administrators of the game to understand).
         <br><br>-----------------------------------<br>
         The Ferengi Trade Guild wish you a nice day<br>
         I.A. writer does not receive salary', '<center><b>Guten Tag</b></center><br><br>
         Ihre Nachricht an uns wird keine Wirkung erzielen. Wir bearbeiten alles Sachgem&auml;&beta; und gleich.<br>
         Wenn Sie meinen uns erpressen zu m&uuml;ssen, uns unter Druck zu setzen oder sonstige Gewaltgedanken
         gegen uns haben - vergessen Sie diese sofort wieder.<br>
         Da wir uns, was milit&auml;rische Verteidigung angeht, nicht auf irgendwas einlassen, sind unsere Waffen
         geladen und unsere Schiffe kampfbereit. Sollte Agression erfolgen, werden wir mit noch st&auml;rkerer
         H&auml;rte zur&uuml;ckschlagen.<br><br>
         Wenn Sie nur mal Hallo sagen wollten, nehmen Sie das oben als Warnung. Sollten Sie merken, dass
         unser Liefersystem Problem hat, melden Sie das bitte an die Galaktische Administration
         (Administratoren des Spiels f&uuml;r die die es nicht verstehen).
         <br><br>-----------------------------------<br>
         Noch einen schönen Tag w&uuml;nscht Ihnen die Ferengi Handelsgesselschaft<br>
         I.A. Schreiber der kein Gehalt bekommt', '<center><b>Buongiorno</b></center><br><br>
         il vostro messaggio non ha alcun effetto su di noi. Essi vengono tutti trattati appropriatamente ed
         immediatamente allo stesso modo.<br>
         Se state pensando di ricattarci, di fare pressione, di usare violenza o di compiere altre azioni ostili 
         contro di noi - scordatevelo immediatamente.<br>
         Conosciamo molto bene ci&ograve; che concerne la difesa militare, non &egrave; cosa da
         nascondere, quindi le nostre armi sono cariche e le nostre navi da combattimento pronte.<br>
         Se dovesse avvenire un&#146;aggressione, ci sar&agrave; una forte ritorsione con maggiore durezza.<br><br>
         Se volevate solo dire &quot;ciao&quot;, prendete questo come un avviso. Se invece avete riscontrato problemi con
         il nostro sistema di consegne, per favore riportatelo all&#146;Amministrazione
         Galattica (gli amministratori del gioco per intenderci).
         <br><br>-----------------------------------<br>
         La Gilda del Commercio Ferengi vi augura una buona giornata<br>
         Gli scrittori dell&#146;I.A. non sono pagati');
     $titles = array('<b>In reply to your letter</b>', '<b>Antwort auf ihr Schreiben</b>', '<b>Risposta alla sua lettera</b>');
     $this->ReplyToUser($titles, $messages);
     // ########################################################################################
     // ########################################################################################
     // Shiptrade Scheduler
     // So, in order, the troops will have to be paid really well, now it just needs to be made​safe, Tap
     $this->sdl->start_job('Shiptrade Scheduler', TICK_LOG_FILE_NPC);
     $sql = 'SELECT s.*,u.user_name,u.num_auctions,u.language,COUNT(b.id) AS num_bids FROM (ship_trade s)
             LEFT JOIN (user u) ON u.user_id=s.user
             LEFT JOIN (bidding b) ON b.trade_id=s.id
             WHERE s.scheduler_processed = 0 AND s.end_time <=' . $ACTUAL_TICK . ' GROUP BY s.id';
     if (($q_strade = $this->db->query($sql)) === false) {
         $this->sdl->log('<b>Error:</b> cannot query scheduler shiptrade data! - CONTINUED', TICK_LOG_FILE_NPC);
     } else {
         $n_shiptrades = 0;
         while ($tradedata = $this->db->fetchrow($q_strade)) {
             // Check if auction had no bids
             if ($tradedata['num_bids'] < 1) {
                 $this->sdl->log('<i>Notice:</i> shiptrade[' . $tradedata['id'] . '] had no bids', TICK_LOG_FILE_NPC);
                 // Vendor:
                 $log_data = array('player_name' => '', 'auction_id' => $tradedata['id'], 'auction_name' => $tradedata['header'], 'resource_1' => 0, 'resource_2' => 0, 'resource_3' => 0, 'unit_1' => 0, 'unit_2' => 0, 'unit_3' => 0, 'unit_4' => 0, 'unit_5' => 0, 'unit_6' => 0, 'ship_id' => $tradedata['ship_id']);
                 // Retrieve language of the vendor
                 switch ($tradedata['language']) {
                     case 'GER':
                         $log_title = 'Auktion benachrichtigung (Erfolgslos)';
                         break;
                     case 'ENG':
                         $log_title = 'Auction notification (no success)';
                         break;
                     case 'ITA':
                         $log_title = 'Notifica asta (non riuscita)';
                         break;
                     default:
                         $log_title = 'Auction notification (no success)';
                 }
                 if (!add_logbook_entry($tradedata['user'], LOGBOOK_AUCTION_VENDOR, $log_title, $log_data)) {
                     $this->sdl->log('<b>Error:</b> Logbook could not be written - ' . $tradedata['user'], TICK_LOG_FILE_NPC);
                 }
                 // Unlock the auctioned ship
                 if ($this->db->query('UPDATE ships SET ship_untouchable=0 WHERE ship_id=' . $tradedata['ship_id']) != true) {
                     $this->sdl->log('<b>CRITICAL ERROR</b>: shiptrade[' . $tradedata['id'] . ']: failed to free ship[' . $tradedata['ship_id'] . ']! - CONTINUED', TICK_LOG_FILE_NPC);
                 }
             } else {
                 $this->sdl->log('Trade id: ' . $tradedata['id'] . ' ended successfully', TICK_LOG_FILE_NPC);
                 // Retrieve higher bidder
                 $sql = 'SELECT b.*,u.user_id,u.user_name,u.language
                         FROM (bidding b) LEFT JOIN (user u) ON u.user_id=b.user
                         WHERE b.trade_id ="' . $tradedata['id'] . '"
                         ORDER BY b.max_bid DESC, b.id ASC LIMIT 1';
                 $purchaser = $this->db->queryrow($sql);
                 // Check if there was only one bid
                 if ($tradedata['num_bids'] < 2) {
                     // End price is simply the entry price
                     $end_price[0] = $tradedata['resource_1'];
                     $end_price[1] = $tradedata['resource_2'];
                     $end_price[2] = $tradedata['resource_3'];
                     $end_price[3] = $tradedata['unit_1'];
                     $end_price[4] = $tradedata['unit_2'];
                     $end_price[5] = $tradedata['unit_3'];
                     $end_price[6] = $tradedata['unit_4'];
                     $end_price[7] = $tradedata['unit_5'];
                     $end_price[8] = $tradedata['unit_6'];
                 } else {
                     $sql = 'SELECT max_bid FROM bidding
                             WHERE trade_id ="' . $tradedata['id'] . '"
                             ORDER BY max_bid DESC LIMIT 1,1';
                     $prelast_bid = $this->db->queryrow($sql);
                     $sql = 'SELECT max_bid FROM bidding
                             WHERE trade_id ="' . $tradedata['id'] . '"
                             ORDER BY max_bid DESC LIMIT 1';
                     $last_bid = $this->db->queryrow($sql);
                     $this->sdl->log('Last Bid: ' . $last_bid['max_bid'] . ' and Prelast Bid: ' . $prelast_bid['max_bid'], TICK_LOG_FILE_NPC);
                     // If last two bids are differents there isn't a tie then max_bid +1
                     if ($last_bid['max_bid'] != $prelast_bid['max_bid']) {
                         $prelast_bid['max_bid']++;
                     }
                     $end_price[0] = $tradedata['resource_1'] + $prelast_bid['max_bid'] * $tradedata['add_resource_1'];
                     $end_price[1] = $tradedata['resource_2'] + $prelast_bid['max_bid'] * $tradedata['add_resource_2'];
                     $end_price[2] = $tradedata['resource_3'] + $prelast_bid['max_bid'] * $tradedata['add_resource_3'];
                     $end_price[3] = $tradedata['unit_1'] + $prelast_bid['max_bid'] * $tradedata['add_unit_1'];
                     $end_price[4] = $tradedata['unit_2'] + $prelast_bid['max_bid'] * $tradedata['add_unit_2'];
                     $end_price[5] = $tradedata['unit_3'] + $prelast_bid['max_bid'] * $tradedata['add_unit_3'];
                     $end_price[6] = $tradedata['unit_4'] + $prelast_bid['max_bid'] * $tradedata['add_unit_4'];
                     $end_price[7] = $tradedata['unit_5'] + $prelast_bid['max_bid'] * $tradedata['add_unit_5'];
                     $end_price[8] = $tradedata['unit_6'] + $prelast_bid['max_bid'] * $tradedata['add_unit_6'];
                 }
                 // Vendor:
                 $log_data = array('player_name' => $purchaser['user_name'], 'player_id' => $purchaser['user_id'], 'auction_id' => $tradedata['id'], 'auction_name' => $tradedata['header'], 'resource_1' => $end_price[0], 'resource_2' => $end_price[1], 'resource_3' => $end_price[2], 'unit_1' => $end_price[3], 'unit_2' => $end_price[4], 'unit_3' => $end_price[5], 'unit_4' => $end_price[6], 'unit_5' => $end_price[7], 'unit_6' => $end_price[8], 'ship_id' => $tradedata['ship_id']);
                 // Retrieve language of the vendor
                 switch ($tradedata['language']) {
                     case 'GER':
                         $log_title = 'Auktion benachrichtigung (Verkauft)';
                         break;
                     case 'ENG':
                         $log_title = 'Auction notification (sold)';
                         break;
                     case 'ITA':
                         $log_title = 'Notifica asta (vendita)';
                         break;
                     default:
                         $log_title = 'Auction notification (sold)';
                 }
                 if (!add_logbook_entry($tradedata['user'], LOGBOOK_AUCTION_VENDOR, $log_title, $log_data)) {
                     $this->sdl->log('<b>Error:</b> Logbook could not be written - ' . $tradedata['user'], TICK_LOG_FILE_NPC);
                 }
                 // Purchaser:
                 $log_data = array('player_name' => $tradedata['user'], 'auction_id' => $tradedata['id'], 'auction_name' => $tradedata['header'], 'resource_1' => $end_price[0], 'resource_2' => $end_price[1], 'resource_3' => $end_price[2], 'unit_1' => $end_price[3], 'unit_2' => $end_price[4], 'unit_3' => $end_price[5], 'unit_4' => $end_price[6], 'unit_5' => $end_price[7], 'unit_6' => $end_price[8], 'ship_id' => $tradedata['ship_id']);
                 // Retireve language of the purchaser
                 switch ($purchaser['language']) {
                     case 'GER':
                         $log_title = 'Auktion benachrichtigung (Gekauft)';
                         break;
                     case 'ENG':
                         $log_title = 'Auction notification (bought)';
                         break;
                     case 'ITA':
                         $log_title = 'Notifica asta (acquisto)';
                         break;
                     default:
                         $log_title = 'Auction notification (bought)';
                 }
                 if (!add_logbook_entry($purchaser['user_id'], LOGBOOK_AUCTION_PURCHASER, $log_title, $log_data)) {
                     $this->sdl->log('<b>Error:</b> Logbook could not be written - ' . $purchaser['user_id'], TICK_LOG_FILE_NPC);
                 }
                 $this->sdl->log('Bidder ID: ' . $purchaser['user_id'] . ' and Seller ID: ' . $tradedata['user'], TICK_LOG_FILE_NPC);
                 // Insert payment request for purchase user
                 $sql = 'INSERT INTO schulden_table (user_ver,user_kauf,ship_id,
                                                     ress_1,ress_2,ress_3,
                                                     unit_1,unit_2,unit_3,
                                                     unit_4,unit_5,unit_6,
                                                     timestep,auktions_id)
                         VALUES (' . $tradedata['user'] . ',' . $purchaser['user_id'] . ',' . $tradedata['ship_id'] . ',
                                 ' . $end_price[0] . ',' . $end_price[1] . ',' . $end_price[2] . ',
                                 ' . $end_price[3] . ',' . $end_price[4] . ',' . $end_price[5] . ',
                                 ' . $end_price[6] . ',' . $end_price[7] . ',' . $end_price[8] . ',
                                 ' . $ACTUAL_TICK . ',' . $tradedata['id'] . ')';
                 if (!$this->db->query($sql)) {
                     $this->sdl->log('<b>CRITICAL ERROR:</b> debts were not saved: "' . $sql . '" -  CONTINUED', TICK_LOG_FILE_NPC);
                 } else {
                     $code = $this->db->insert_id();
                     $this->sdl->log('Payment request inserted [Code]: ' . $code, TICK_LOG_FILE_NPC);
                     // Create an account for vendor user
                     $sql = 'INSERT INTO treuhandkonto (code,timestep) VALUES (' . $code . ',' . $ACTUAL_TICK . ')';
                     if (!$this->db->query($sql)) {
                         $this->sdl->log('<b>CRITICAL ERROR:</b> cannot create auction trust account number: ' . $code . ' CONTINUED', TICK_LOG_FILE_NPC);
                     }
                     // Ship enters in the spacedock of the BOT
                     $spacedock = $this->bot['planet_id'] * -1;
                     $sql = 'UPDATE ships SET user_id="' . $this->bot['user_id'] . '",
                                              fleet_id="' . $spacedock . '"
                             WHERE ship_id="' . $tradedata['ship_id'] . '"';
                     if (!$this->db->query($sql)) {
                         $this->sdl->log('<b>CRITICAL ERROR:</b> cannot give the ship to Ramona - ' . $sql, TICK_LOG_FILE_NPC);
                     } else {
                         $this->sdl->log('Ramona got a ship (' . $spacedock . ')... shiptrade[' . $tradedata['id'] . '], processed sucessfully', TICK_LOG_FILE_NPC);
                     }
                 }
             }
             ++$n_shiptrades;
         }
         $sql = 'UPDATE ship_trade SET scheduler_processed=1
                 WHERE end_time <= ' . $ACTUAL_TICK . ' AND scheduler_processed=0
                 LIMIT ' . $n_shiptrades;
         if (!$this->db->query($sql)) {
             $this->sdl->log('<b>CRITICAL ERROR:</b> cannot update scheduler_shiptrade data - CONTINUED -' . $sql, TICK_LOG_FILE_NPC);
         }
         unset($tradedata);
     }
     $this->sdl->finish_job('Shiptrade Scheduler', TICK_LOG_FILE_NPC);
     // ########################################################################################
     // ########################################################################################
     // Trust accounts monitor
     $this->sdl->start_job('Trust accounts monitor', TICK_LOG_FILE_NPC);
     $paid_debts = 0;
     $debtors = 0;
     $fun_providers = 0;
     $messages = 0;
     $queued_ships = 0;
     $period = 20 * 24 * 6;
     // Payment deadline
     $period_h = 20 * 24 * 3;
     // Half of the previous value
     // Retrieve all debts still not solved
     $sql = 'SELECT * FROM schulden_table WHERE status=0';
     if (($trades = $this->db->query($sql)) === false) {
         $this->sdl->log('<b>Error:</b> cannot query scheduler shiptrade data! - SKIPPED', TICK_LOG_FILE_NPC);
     } else {
         $names = array('unit_1', 'unit_2', 'unit_3', 'unit_4', 'unit_5', 'unit_6', 'ress_1', 'ress_2', 'ress_3', 'id');
         $this->sdl->log('Examining debts....', TICK_LOG_FILE_NPC);
         while ($debt = $this->db->fetchrow($trades)) {
             // Retrieve vendor language for message localization
             $sql = 'SELECT language FROM user WHERE user_id=' . $debt['user_ver'];
             if (!($vendor = $this->db->queryrow($sql))) {
                 $this->sdl->log('<b>Error:</b> cannot read vendor user language!', TICK_LOG_FILE_NPC);
                 $vendor['language'] = 'ENG';
             }
             // Retrieve some info about the purchaser (debtor?)
             $sql = 'SELECT user_name,user_trade,language FROM user
                     WHERE user_id=' . $debt['user_kauf'];
             if (!($purchaser = $this->db->queryrow($sql))) {
                 $this->sdl->log('<b>Error:</b> cannot read purchaser data! - CONTINUED', TICK_LOG_FILE_NPC);
                 $purchaser['language'] = 'ENG';
             }
             // Retrieve trust account for the current auction
             $accounts = $this->db->query('SELECT *,code AS id FROM treuhandkonto WHERE code="' . $debt['id'] . '"');
             $num = $this->db->num_rows();
             if ($num > 1) {
                 $this->sdl->log('<b>PROGRAMMING ERROR:</b> apparently, there are more then one trust accounts on the same debts_table - SKIPPED', TICK_LOG_FILE_NPC);
             } else {
                 if ($num <= 0) {
                     $this->sdl->log('<b>BUG ERROR:</b> apparently, there is no trust account for the debts_table - SKIPPED', TICK_LOG_FILE_NPC);
                 } else {
                     if ($num == 1) {
                         $account = $this->db->fetchrow($accounts);
                         // Now we look whether everything were already paid
                         $debt_paid_off = true;
                         foreach ($names as $key) {
                             if ($debt[$key] != $account[$key]) {
                                 $debt_paid_off = false;
                             }
                         }
                         if (!$debt_paid_off) {
                             // Look if anyone has missed his trading
                             $this->sdl->log('Everything not paid: user #' . $debt['user_kauf'] . ' trust account  #' . $account['code'], TICK_LOG_FILE_NPC);
                             if ($account['timestep'] != $debt['timestep']) {
                                 $this->sdl->log('<b>Error:</b> user #' . $debt['user_kauf'] . ' debts and trust account ' . $debt['id'] . '/' . $account['code'] . ' have different time steps', TICK_LOG_FILE_NPC);
                             } else {
                                 // Check if there's still time to pay the debt and purchaser
                                 // has not been warned yet
                                 if ($account['timestep'] + $period_h <= $ACTUAL_TICK && $account['timestep'] + $period > $ACTUAL_TICK && $debt['mahnung'] == 0) {
                                     // Look who got new reminder
                                     $debtors++;
                                     // Here we should decide if we want to be more strict
                                     // and also smear players that paid after this warning.
                                     // NOTE: if so, we'll need to change < operator into <=
                                     // at lines 1073 and 1118 in job Users lock ahead.
                                     //$this->db->query('UPDATE user SET user_trade=user_trade+1 WHERE user_id="'.$debt['user_kauf'].'"');
                                     // Retrieve language of the purchaser
                                     switch ($purchaser['language']) {
                                         case 'GER':
                                             $text = '<center><b>Guten Tag</b></center>
                                         <br>
                                         Sie sind dabei die Frist zur Bezahlung zu &Uuml;berschreiten, f&uuml;r einen Handel
                                         den sie Abgeschlossen haben.<br>
                                         Hiermit werden sie ermahnt, sollten sie ihre Schulden nicht bezahlen
                                         werden entsprechende Ma&beta;nahmen eingeleitet.
                                         <br>--------------------------------------<br>
                                         Hochachtungsvoll Ferengi Handelsgilde';
                                             $title = '<b>Mahnung die Erste</b>';
                                             break;
                                         case 'ENG':
                                             $text = '<center><b>Good morning</b></center><br><br>
                                         You are about to exceed the time limit for payment, for a trade you have completed.
                                         Remember that appropriate measures will be take if you should not pay your debts.
                                         <br>--------------------------------------<br>
                                         Full respect from The Ferengi Trade Guild';
                                             $title = '<b>Warning</b>';
                                             break;
                                         case 'ITA':
                                             $text = '<center><b>Buongiorno</b></center><br><br>
                                         Il termine di pagamento per un commercio che avete concluso si sta avvicinando.<br>
                                         Si ricorda che saranno intraprese appropriate misure se non dovesse pagare i suoi debiti.
                                         <br>--------------------------------------<br>
                                         Massimo rispetto dalla Gilda del Commercio Ferengi';
                                             $title = '<b>Avvertimento</b>';
                                             break;
                                     }
                                     $this->MessageUser($this->bot['user_id'], $debt['user_kauf'], $title, $text);
                                     $messages++;
                                     // User gets warning
                                     $sql = 'UPDATE schulden_table SET mahnung=mahnung+1
                                     WHERE id="' . $account['code'] . '" AND user_ver="' . $debt['user_ver'] . '"';
                                     if (!$this->db->query($sql)) {
                                         $this->sdl->log('<b>Error:</b> cannot write user warning - CONTINUED', TICK_LOG_FILE_NPC);
                                     }
                                 }
                                 // If payment deadline is overdue
                                 if ($ACTUAL_TICK >= $period + $account['timestep']) {
                                     $fun_providers++;
                                     $queued_ships++;
                                     // Delete entries
                                     // AC: this query's pretty insane, id is unique, there's
                                     // no need to complicate the WHERE clause...
                                     $sql = 'DELETE FROM schulden_table
                                     WHERE user_ver="' . $debt['user_ver'] . '" AND
                                           user_kauf="' . $debt['user_kauf'] . '" AND
                                           id="' . $debt['id'] . '"';
                                     if (!$this->db->query($sql)) {
                                         $this->sdl->log('<b>Error:</b> cannot delete debts_table for auction #' . $debt['id'], TICK_LOG_FILE_NPC);
                                     }
                                     $sql = 'DELETE FROM treuhandkonto WHERE code="' . $debt['id'] . '"';
                                     if (!$this->db->query($sql)) {
                                         $this->sdl->log('<b>Error:</b> cannot delete trust account for auction #' . $debt['id'], TICK_LOG_FILE_NPC);
                                     }
                                     // Prepare to lock the user from the trade center
                                     $sql = 'INSERT INTO FHB_sperr_list VALUES(null,' . $debt['user_kauf'] . ',' . $ACTUAL_TICK . ')';
                                     if (!$this->db->query($sql)) {
                                         $this->sdl->log('<b>Error:</b> cannot insert user #' . $debt['user_kauf'] . ' in the blacklist', TICK_LOG_FILE_NPC);
                                     }
                                     // Here we should check if user_trade must be increased
                                     // by one or not.
                                     // $purchaser['user_trade']++;
                                     // Retrieve language of the purchaser
                                     switch ($purchaser['language']) {
                                         case 'GER':
                                             $text = '<center><b>Guten Tag</b></center><br><br>
                                         Sie haben die Frist zur Bezahlung ihrer Schulden Überschritten,
                                         damit wird der Handel R&uuml;ckg&auml;ngig gemacht. Sie erhalten daf&uuml;r einen
                                         Eintrag in das Schuldnerbuch.<br>
                                         Gesamt Eintr&auml;ge: ' . $purchaser['user_trade'] . '<br>
                                         Sollten sie weiter Auffallen wird das ernsthafte Konsequenzen f&uuml;r sie haben.<br>
                                         Dieser Beschluss ist G&uuml;ltig, sollten sie das Gef&uuml;hl haben ungerecht
                                         behandelt zu werden, können sie sich &uuml;ber den normalen Beschwerde Weg
                                         beschweren.<br>
                                         <br>--------------------------------------<br>
                                         Hochachtungsvoll Ferengi Handelsgilde';
                                             $title = '<b>Mahnung mit Folgen</b>';
                                             break;
                                         case 'ENG':
                                             $text = '<center><b>Good morning</b></center><br><br>
                                         You have crossed the term of the payment of your debts, thus the trade
                                         is reversed. You&#146;ll get for it an entry in the debtor&#146;s book.<br>
                                         Total entries: ' . $purchaser['user_trade'] . '<br>
                                         Attention, if you continue, there will be severe consequences for you.<br>
                                         This decision is important, if you should feel to be treated unfairly, you can
                                         appeal through the normal way of complain.<br>
                                         <br>--------------------------------------<br>
                                         Full respect from The Ferengi Trade Guild';
                                             $title = '<b>Reminder with consequences</b>';
                                             break;
                                         case 'ITA':
                                             $text = '<center><b>Buongiorno</b></center><br><br>
                                         Avete superato il termine ultimo per il pagamento dei vostri debiti, pertanto
                                         lo scambio sar&agrave; annullato. Per questo ricever&agrave; una nota nel libro
                                         dei debitori.<br>
                                         Totale voci: ' . $purchaser['user_trade'] . '<br>
                                         Attenzione, se persistete, ci saranno severe conseguenze per voi.<br>
                                         Questa decisione &egrave; importante, se doveste sentirvi trattati in modo sleale,
                                         potete appellarvi tramite la normale procedura di reclamo.<br>
                                         <br>--------------------------------------<br>
                                         Massimo rispetto dalla Gilda del Commercio Ferengi';
                                             $title = '<b>Avviso delle conseguenze</b>';
                                             break;
                                     }
                                     $this->MessageUser($this->bot['user_id'], $debt['user_kauf'], $title, $text);
                                     $messages++;
                                     $sql = 'INSERT INTO `FHB_warteschlange` VALUES (NULL,' . $debt['user_ver'] . ',' . $debt['ship_id'] . ')';
                                     if (!$this->db->query($sql)) {
                                         $this->sdl->log('<b>CRITICAL ERROR:</b> cannot put ship in the queue - CONTINUED' . $sql, TICK_LOG_FILE_NPC);
                                     }
                                     $this->sdl->log('User #' . $debt['user_ver'] . ' got his ship #' . $debt['ship_id'] . ' back', TICK_LOG_FILE_NPC);
                                     // Retrieve language of the vendor
                                     switch ($vendor['language']) {
                                         case 'GER':
                                             $text = '<center><b>Guten Tag</b></center><br><br>
                                         Ihr Handel mit ' . $purchaser['user_name'] . ' wurde r&uuml;ckg&auml;ngig gemacht, ihr Schiff steht
                                         ihnen absofort wieder zurverf&uuml;gung. Sollte es jedoch nicht wieder
                                         zurverf&uuml;gung stehen, wenden sie sich bitte an den Support.<br>
                                         Um ihren Handelspartner k&uuml;mmern wir uns schon. Er wird eine gerechte Strafe
                                         bekommen<br>
                                         <br>--------------------------------------<br>
                                         Hochachtungsvoll Ferengi Handelsgilde';
                                             $title = '<b>Handel' . $debt['code'] . ' ist nichtig</b>';
                                             break;
                                         case 'ENG':
                                             $text = '<center><b>Good morning</b></center><br><br>
                                         Your trade with ' . $purchaser['user_name'] . ' was undone, your ship will come back.
                                         If it does not return at home, please contact Support.<br>
                                         We already take care of your trading partner.
                                         He will receive a fair punishment.<br>
                                         <br>--------------------------------------<br>
                                         Full respect from The Ferengi Trade Guild';
                                             $title = '<b>Trade' . $debt['code'] . ' is void</b>';
                                             break;
                                         case 'ITA':
                                             $text = '<center><b>Buongiorno</b></center><br><br>
                                         Il vostro commercio con ' . $purchaser['user_name'] . ' &egrave; stato annullato, la vostra nave
                                         ritorner&agrave; indietro. Se non dovesse tornare, per favore contattare il
                                         Supporto.<br>
                                         Ci siamo gi&agrave; presi cura della vostra controparte commerciale.
                                         Ricever&agrave; una giusta punizione.<br>
                                         <br>--------------------------------------<br>
                                         Massimo rispetto dalla Gilda del Commercio Ferengi';
                                             $title = '<b>Scambio' . $debt['code'] . ' annullato</b>';
                                             break;
                                     }
                                     $this->MessageUser($this->bot['user_id'], $debt['user_ver'], $title, $text);
                                 }
                             }
                         } else {
                             foreach ($names as $key) {
                                 $this->sdl->log('Comparison between ' . $account[$key] . ' and ' . $debt[$key] . ' ends successfully', TICK_LOG_FILE_NPC);
                             }
                             // Debt paid off and made visible
                             $paid_debts++;
                             $sql = 'UPDATE schulden_table SET status="1" WHERE id=' . $account['code'] . '';
                             if (!$this->db->query($sql)) {
                                 $this->sdl->log('<b>Error:</b> cannot update schulden_table to "everything paid" - CONTINUED', TICK_LOG_FILE_NPC);
                             }
                             // Message to the vendor
                             switch ($vendor['language']) {
                                 case 'GER':
                                     $text = '<center><b>Guten Tag</b></center>
                                 <br>
                                 Sie haben Neue Ressourcen und/oder Truppen auf ihrem Treuhandkonto.
                                 <br>--------------------------------------<br>
                                 Hochachtungsvoll Ferengi Handelsgilde';
                                     $title = '<b>Ress. zur Verf&uuml;gung</b>';
                                     break;
                                 case 'ITA':
                                     $text = '<center><b>Buongiorno</b></center>
                                 <br>
                                 Hai nuove risorse e &#47; o truppe sul conto fiduciario.
                                 <br>--------------------------------------<br>
                                 Cordiali saluti Gilda del Commercio Ferengi';
                                     $title = '<b>Risorse disponibili</b>';
                                     break;
                                 default:
                                     $text = '<center><b>Good morning</b></center>
                                 <br>
                                 You have new resources and &#47; or troops on your trust account.
                                 <br>--------------------------------------<br>
                                 Sincerely Ferengi Commerce Guild';
                                     $title = '<b>Resources available</b>';
                                     break;
                             }
                             $this->MessageUser($this->bot['user_id'], $debt['user_ver'], $title, $text);
                             // Give the ship to the purchaser
                             $sql = 'INSERT INTO `FHB_warteschlange` VALUES (NULL , ' . $debt['user_kauf'] . ', ' . $debt['ship_id'] . ')';
                             if (!$this->db->query($sql)) {
                                 $this->sdl->log('<b>CRITICAL ERROR:</b> cannot put ship in the queue - SKIPPED', TICK_LOG_FILE_NPC);
                             } else {
                                 $this->sdl->log('User #' . $debt['user_kauf'] . ' got his new ship #' . $debt['ship_id'], TICK_LOG_FILE_NPC);
                                 // Message to the purchaser
                                 switch ($purchaser['language']) {
                                     case 'GER':
                                         $text = '<center><b>Guten Tag</b></center>
                                     <br>
                                     Sie können ihr ersteigertes Schiff abhohlen.
                                     <br>--------------------------------------<br>
                                     Hochachtungsvoll Ferengi Handelsgilde';
                                         $title = 'Neues Schiff zur Verf&uuml;gung';
                                         break;
                                     case 'ITA':
                                         $text = '<center><b>Buongiorno</b></center>
                                     <br>
                                     Puoi ritirare la tua nave vinta all&#39;asta.
                                     <br> --------------------------------------<br>
                                     Sincerely Ferengi Trade Guild';
                                         $title = '<b>Nuova nave disponibile</b>';
                                         break;
                                     default:
                                         $text = '<center><b>Good morning</b></center>
                                     <br>
                                     You can withdraw your auctioned ship.
                                     <br> --------------------------------------<br>
                                     Sincerely Ferengi Trade Guild';
                                         $title = '<b>New ship available</b>';
                                         break;
                                 }
                                 $this->MessageUser($this->bot['user_id'], $debt['user_kauf'], $title, $text);
                             }
                             $queued_ships++;
                         }
                     }
                 }
             }
         }
     }
     // Empty accounts destruction
     $deleted_accounts = 0;
     if (($destructible_debts = $this->db->query('SELECT id FROM schulden_table WHERE status=2')) == true) {
         while ($debt_to_remove = $this->db->fetchrow($destructible_debts)) {
             $sql = 'DELETE FROM schulden_table WHERE id=' . $debt_to_remove['id'] . ' AND status=2';
             if (!$this->db->query($sql)) {
                 $this->sdl->log('<b>CRITICAL ERROR:</b> cannot delete entry: ' . $debt_to_remove['id'] . ' in debts_table', TICK_LOG_FILE_NPC);
             } else {
                 $sql = 'DELETE FROM treuhandkonto WHERE code="' . $debt_to_remove['id'] . '"';
                 if (!$this->db->query($sql)) {
                     $this->sdl->log('<b>CRITICAL ERROR:</b> cannot delete entry:' . $debt_to_remove['id'] . ' in treuhandkonto', TICK_LOG_FILE_NPC);
                 }
                 $deleted_accounts++;
             }
         }
     } else {
         $this->sdl->log('<b>Error:</b> cannot execute empties accounts query, status not changed', TICK_LOG_FILE_NPC);
     }
     $this->sdl->log('Queued ships    : ' . $queued_ships, TICK_LOG_FILE_NPC);
     $this->sdl->log('Paid debts      : ' . $paid_debts, TICK_LOG_FILE_NPC);
     $this->sdl->log('Debtors         : ' . $debtors, TICK_LOG_FILE_NPC);
     $this->sdl->log('Deleted accounts: ' . $deleted_accounts, TICK_LOG_FILE_NPC);
     $this->sdl->log('Fun bidders     : ' . $fun_providers, TICK_LOG_FILE_NPC);
     $this->sdl->log('Warnings sent   : ' . $messages, TICK_LOG_FILE_NPC);
     $this->sdl->finish_job('Trust accounts monitor', TICK_LOG_FILE_NPC);
     // ########################################################################################
     // ########################################################################################
     // Calculate troops sales
     $this->sdl->start_job('Stock trading ship', TICK_LOG_FILE_NPC);
     $min_tick = $ACTUAL_TICK - 20 * 24;
     if ($min_tick < 0) {
         $min_tick = 0;
     }
     $max_tick = $ACTUAL_TICK;
     $new_graph = $ACTUAL_TICK % 20 == 0 ? 'true' : 'false';
     $this->sdl->log('Actual Tick: ' . $ACTUAL_TICK . ' -- ' . $new_graph . ' -- Period of: ' . $min_tick, TICK_LOG_FILE_NPC);
     // AC: I believe the original intention, since job's name was to graph also ships trading
     if ($new_graph == 'true') {
         $this->sdl->log('New graph is made.....', TICK_LOG_FILE_NPC);
         include "simple_graph.class.php";
         exec('cd ' . FILE_PATH_hg . 'kurs/; rm -f *.png');
         $this->sdl->start_job('Purchase - Unit', TICK_LOG_FILE_NPC);
         $this->graph_draw("unit_1");
         $this->graph_draw("unit_2");
         $this->graph_draw("unit_3");
         $this->graph_draw("unit_4");
         $this->graph_draw("unit_5");
         $this->graph_draw("unit_6");
         $this->sdl->finish_job('Purchase - Unit', TICK_LOG_FILE_NPC);
     }
     $this->sdl->finish_job('Stock trading ship', TICK_LOG_FILE_NPC);
     // ########################################################################################
     // ########################################################################################
     // Users release from TC
     $this->sdl->start_job('Users release', TICK_LOG_FILE_NPC);
     $sql = "SELECT user_id,language FROM user\n                WHERE user_trade>0 AND\n                      trade_tick<=" . $ACTUAL_TICK . " AND trade_tick!=0";
     if (!($temps = $this->db->query($sql))) {
         $this->sdl->log('<b>Error:</b> cannot query user data - SKIP', TICK_LOG_FILE_NPC);
     }
     $number_released = 0;
     while ($result = $this->db->fetchrow($temps)) {
         $sql = 'UPDATE user SET trade_tick=0 WHERE user_id="' . $result['user_id'] . '"';
         if (!$this->db->query($sql)) {
             $this->sdl->log('<b>Error:</b> cannot update user data - CONTINUED', TICK_LOG_FILE_NPC);
         }
         $this->sdl->log('User: #' . $result['user_id'] . ' got the freedom from the feared womAn of this Galaxy', TICK_LOG_FILE_NPC);
         $number_released++;
         /* Retrieve language of the sender */
         switch ($result['language']) {
             case 'GER':
                 $text = '<b>Ihr HZ-Bann ist zu ende</b>
                     <br>
                     Sollten sie keine Zugriff haben, bitte bei den Supportern melden - dazu die
                     Uhrzeit angeben wo sie diese Nachricht bekommen haben. Sonst kann ihnen nicht
                     geholfen werden.
                     <br>--------------------------------------<br>
                     Vorsitzender des Ferengi Finanz- und Handelsministeriums';
                 $title = '<b>HZ-Entbannung</b>';
                 break;
             case 'ENG':
                 $text = '<b>Your CC-ban is over</b>
                     <br>
                     If you have no access to Commercial Centre, please report to the support
                     staff - in addition indicate to them rhe time of this message. Otherwise
                     you cannot be helped by them.
                     <br>--------------------------------------<br>
                     Chairman of the Financial Ferengi - and Trade Ministry';
                 $title = '<b>CC-ban ended</b>';
                 break;
             case 'ITA':
                 $text = '<b>La vostra sospensione CC &egrave; terminata</b>
                     <br>
                     Se non doveste avere accesso al Centro Commerciale, per favore informate lo
                     staff di supporto - in aggiunta indicate loro la data di questo messaggio.
                     Altrimenti non potrete essere aiutati da loro.
                     <br>--------------------------------------<br>
                     Presidente delle Finanze Ferengi - e Ministro del Commercio';
                 $title = '<b>Sospensione CC terminata</b>';
                 break;
         }
         $this->MessageUser($this->bot['user_id'], $result['user_id'], $title, $text);
     }
     $this->sdl->log('There were ' . $number_released . ' users released', TICK_LOG_FILE_NPC);
     $this->sdl->finish_job('Users release', TICK_LOG_FILE_NPC);
     // ########################################################################################
     // ########################################################################################
     // Users lock for TC
     $this->sdl->start_job('Users lock', TICK_LOG_FILE_NPC);
     $sql = "SELECT count(*) as number,user_id FROM FHB_sperr_list GROUP By user_id";
     if (!($blacklist = $this->db->query($sql))) {
         $this->sdl->log('<b>Error:</b> cannot read blacklist data - SKIP', TICK_LOG_FILE_NPC);
     }
     $number_locks = 0;
     $users_list = '';
     while ($result = $this->db->fetchrow($blacklist)) {
         $block = 0;
         if ($result['number'] > 0) {
             if ($result['number'] < 3) {
                 $block = $result['number'] * 480 * 2;
             } else {
                 if ($result['number'] > 2) {
                     $block = pow($result['number'], 2) * 360;
                 }
             }
             $block_min = $block * TICK_DURATION;
             $sql = 'SELECT user_id,user_trade,trade_tick,language FROM user WHERE user_id="' . $result['user_id'] . '"';
             if (!($user = $this->db->queryrow($sql))) {
                 $this->sdl->log('<b>Error:</b> cannot query user data - SKIPPED', TICK_LOG_FILE_NPC);
             }
             if ($user['user_trade'] < $result['number'] && $user['trade_tick'] != 0) {
                 $number_locks++;
                 $sql = 'UPDATE user SET user_trade=' . $result['number'] . ',
                                         trade_tick=trade_tick+' . $block . '
                         WHERE user_id="' . $result['user_id'] . '"';
                 if (!$this->db->query($sql)) {
                     $this->sdl->log('<b>Error:</b> User #' . $result['user_id'] . ' cannot be locked for ' . $block . ' ticks', TICK_LOG_FILE_NPC);
                 }
                 $this->sdl->log('User: #' . $result['user_id'] . ' has gotten a higher punishment - We, which has done this injustice, are bad', TICK_LOG_FILE_NPC);
                 // Retrieve language of the sender
                 switch ($user['language']) {
                     case 'GER':
                         $text = '<b>Sie haben einen Bann f&uuml;rs HZ bekommen</b>
                             <br>Aufgrund ihrer erneuten Schulden bei Auktionen bekommen sie eine weitere Sperre von ' . $block . ' Ticks.<br>
                             Beschwerden sind sinnlos. Einfach das n&auml;chste mal bezahlen.<br><br>
                             Der Grund kann aber auch fehlverhalten im HZ sein.
                             <br>--------------------------------------<br>
                             Vorsitzender des Ferengi Finanz- und Handelsministeriums';
                         $title = '<b>HZ-Bann</b>';
                         break;
                     case 'ENG':
                         $text = '<b>You have received a ban for CC</b>
                             <br>Due to your renewed debts with auctions you get a further block of ' . $block . ' Ticks.<br>
                             Complaints are senseless. Simply pay the next time.<br><br>
                             However, the reason can also be failures in the CC.
                             <br>--------------------------------------<br>
                             Chairman of the Financial Ferengi - and Trade Ministry';
                         $title = '<b>CC-ban</b>';
                         break;
                     case 'ITA':
                         $text = '<b>Avete ricevuto una sospesione per il CC</b>
                             <br>A causa dei vostri rinnovati debiti con le aste avete ricevuto un blocco di ' . $block . ' tick.<br>
                             Reclamare &egrave; insensato. Basta pagare la prossima volta.<br><br>
                             Tuttavia, ci potrebbe essere un errore nel sistema del CC.
                             <br>--------------------------------------<br>
                             Presidente delle Finanze Ferengi - e Ministro del Commercio';
                         $title = '<b>Sospensione CC</b>';
                         break;
                 }
                 $this->MessageUser($this->bot['user_id'], $result['user_id'], $title, $text);
             } else {
                 if ($user['user_trade'] < $result['number'] && $user['trade_tick'] == 0) {
                     $number_locks++;
                     $endtick = $block + $ACTUAL_TICK;
                     $sql = 'UPDATE user SET user_trade=' . $result['number'] . ',
                                         trade_tick=' . $endtick . '
                         WHERE user_id="' . $result['user_id'] . '"';
                     if (!$this->db->query($sql)) {
                         $this->sdl->log('<b>Error:</b> User #' . $result['user_id'] . ' cannot be locked for ' . $block_min . ' minutes.', TICK_LOG_FILE_NPC);
                     }
                     $this->sdl->log('User: #' . $result['user_id'] . ' was banned - he will meet his doom', TICK_LOG_FILE_NPC);
                     // Retrieve language of the sender
                     switch ($user['language']) {
                         case 'GER':
                             $text = '<b>Sie haben einen Bann f&uuml;rs HZ bekommen</b>
                             <br>Aufgrund ihrer Schulden bei Auktionen bekommen sie eine Sperre von ' . $block_min . ' Minuten.<br>
                             Beschwerden sind sinnlos. Einfach das n&auml;chste mal bezahlen.<br><br>
                             Der Grund kann aber auch fehlverhalten im HZ sein.
                             <br>--------------------------------------<br>
                             Vorsitzender des Ferengi Finanz- und Handelsministeriums';
                             $title = '<b>HZ-Bann</b>';
                             break;
                         case 'ENG':
                             $text = '<b>You have received a ban for CC</b>
                             <br>Due to your debts with auctions you get a block of ' . $block_min . ' minutes.<br>
                             Complaints are senseless. Simply pay the next time.<br><br>
                             However, the reason can also be failures in the CC.
                             <br>--------------------------------------<br>
                             Chairman of the Financial Ferengi - and Trade Ministry';
                             $title = '<b>CC-ban</b>';
                             break;
                         case 'ITA':
                             $text = '<b>Avete ricevuto una sospesione per il CC</b>
                             <br>A causa dei vostri debiti con le aste avete ricevuto un blocco di ' . $block_min . ' minuti.<br>
                             Reclamare &egrave; insensato. Basta pagare la prossima volta.<br><br>
                             Tuttavia, ci potrebbe essere un errore nel sistema del CC.
                             <br>--------------------------------------<br>
                             Presidente delle Finanze Ferengi - e Ministro del Commercio';
                             $title = '<b>Sospensione CC</b>';
                             break;
                     }
                     $this->MessageUser($this->bot['user_id'], $result['user_id'], $title, $text);
                 } else {
                     if ($user['user_trade'] == $result['number']) {
                         $users_list .= '| ' . $result['user_id'] . ' |';
                     }
                 }
             }
         }
     }
     $this->sdl->log('Users ' . $users_list . ' have their penalties now let me turn to my problems in women clarify matters.', TICK_LOG_FILE_NPC);
     $this->sdl->log('There were ' . $number_locks . ' users locked', TICK_LOG_FILE_NPC);
     $this->sdl->finish_job('Users lock', TICK_LOG_FILE_NPC);
     // ########################################################################################
     // ########################################################################################
     // Update Ramona resources availability
     if (MALL_RESOURCES_AVAILABLE) {
         $this->sdl->start_job('Update Ramona resources svailability', TICK_LOG_FILE_NPC);
         // Read resources and units available on Ramona's planet
         $sql = 'SELECT unit_1, unit_2, unit_3, unit_4, unit_5, unit_6, resource_1, resource_2, resource_3 FROM planets
             WHERE planet_id = ' . $this->bot['planet_id'];
         $resources = $this->db->queryrow($sql);
         $this->sdl->log('Available resources: ' . $resources['resource_1'] . ' -- ' . $resources['resource_2'] . ' -- ' . $resources['resource_3'], TICK_LOG_FILE_NPC);
         $this->sdl->log('Available units: ' . $resources['unit_1'] . ' -- ' . $resources['unit_2'] . ' -- ' . $resources['unit_3'] . ' -- ' . $resources['unit_4'] . ' -- ' . $resources['unit_5'] . ' -- ' . $resources['unit_6'], TICK_LOG_FILE_NPC);
         // Check if the table for the Commercial Centre is already present
         $sql = 'SELECT unit_1, unit_2, unit_3, unit_4, unit_5, unit_6, ress_1, ress_2, ress_3 FROM FHB_Handels_Lager
             WHERE id=1';
         if (!($tradecenter = $this->db->queryrow($sql))) {
             $this->sdl->log('<b>Warning:</b> Table FHB_Handels_Lager was empty! CONTINUED', TICK_LOG_FILE_NPC);
             // Create an entry item in the table
             $sql = 'INSERT INTO FHB_Handels_Lager (unit_1, unit_2,unit_3, unit_4,unit_5,unit_6,ress_1,ress_2,ress_3)
                 VALUES (0, 0, 0, 0, 0, 0, 0, 0, 0)';
             if (!$this->db->query($sql)) {
                 $this->sdl->log('<b>Error:</b> Could not insert Handelslager - ' . $update_res, TICK_LOG_FILE_NPC);
             }
         } else {
             $this->db->lock('FHB_Handels_Lager');
             $pick_u = array();
             $pick_u[0] = $pick_u[1] = $pick_u[2] = $pick_u[3] = $pick_u[4] = $pick_u[5] = 0;
             // Pick up units only if there is a little stock pile
             if ($tradecenter['unit_1'] < 450) {
                 if ($resources['unit_1'] > 500) {
                     $pick_u[0] = $resources['unit_1'] / 450;
                 }
             }
             if ($tradecenter['unit_2'] < 450) {
                 if ($resources['unit_2'] > 500) {
                     $pick_u[1] = $resources['unit_2'] / 450;
                 }
             }
             if ($tradecenter['unit_3'] < 450) {
                 if ($resources['unit_3'] > 500) {
                     $pick_u[2] = $resources['unit_3'] / 450;
                 }
             }
             if ($tradecenter['unit_4'] < 200) {
                 if ($resources['unit_4'] > 500) {
                     $pick_u[3] = $resources['unit_4'] / 200;
                 }
             }
             if ($tradecenter['unit_5'] < 200) {
                 if ($resources['unit_5'] > 500) {
                     $pick_u[4] = $resources['unit_5'] / 200;
                 }
             }
             if ($tradecenter['unit_6'] < 200) {
                 if ($resources['unit_6'] > 500) {
                     $pick_u[5] = $resources['unit_6'] / 200;
                 }
             }
             $this->sdl->log('Add units: ' . $pick_u[0] . ' -- ' . $pick_u[1] . ' -- ' . $pick_u[2] . ' -- ' . $pick_u[3] . ' -- ' . $pick_u[4] . ' -- ' . $pick_u[5], TICK_LOG_FILE_NPC);
             // 200408 DC ---- Nothing is for nothing
             $pick_r = array();
             $pick_r[0] = $pick_r[1] = $pick_r[2] = 0;
             // Soldier lvl 1
             if ($pick_u[0] > 0) {
                 $metal_cost = $pick_u[0] * 280;
                 $mineral_cost = $pick_u[0] * 235;
                 if ($metal_cost > $tradecenter['ress_1'] || $mineral_cost > $tradecenter['ress_2']) {
                     $pick_u[0] = 0;
                 } else {
                     $this->sdl->log('Resources for Lvl 1 Soldiers: Metals ' . $metal_cost . ' Minerals ' . $mineral_cost, TICK_LOG_FILE_NPC);
                     $pick_r[0] += $metal_cost;
                     $pick_r[1] += $mineral_cost;
                 }
             }
             // Soldier lvl 2
             if ($pick_u[1] > 0) {
                 $metal_cost = $pick_u[1] * 340;
                 $mineral_cost = $pick_u[1] * 225;
                 if ($metal_cost > $tradecenter['ress_1'] || $mineral_cost > $tradecenter['ress_2']) {
                     $pick_u[1] = 0;
                 } else {
                     $this->sdl->log('Resources for Lvl 2 Soldiers: Metals ' . $metal_cost . ' Minerals ' . $mineral_cost, TICK_LOG_FILE_NPC);
                     $pick_r[0] += $metal_cost;
                     $pick_r[1] += $mineral_cost;
                 }
             }
             // Soldier lvl 3
             if ($pick_u[2] > 0) {
                 $metal_cost = $pick_u[2] * 650;
                 $mineral_cost = $pick_u[2] * 450;
                 $dilithium_cost = $pick_u[2] * 350;
                 if ($metal_cost > $tradecenter['ress_1'] || $mineral_cost > $tradecenter['ress_2'] || $dilithium_cost > $tradecenter['ress_3']) {
                     $pick_u[2] = 0;
                 } else {
                     $this->sdl->log('Resources for Lvl 3 Soldiers: Metals ' . $metal_cost . ' - Minerals ' . $mineral_cost . ' - Dilithium ' . $dilithium_cost, TICK_LOG_FILE_NPC);
                     $pick_r[0] += $metal_cost;
                     $pick_r[1] += $mineral_cost;
                     $pick_r[2] += $dilithium_cost;
                 }
             }
             // Captains
             if ($pick_u[3] > 0) {
                 $metal_cost = $pick_u[3] * 410;
                 $mineral_cost = $pick_u[3] * 210;
                 $dilithium_cost = $pick_u[3] * 115;
                 if ($metal_cost > $tradecenter['ress_1'] || $mineral_cost > $tradecenter['ress_2'] || $dilithium_cost > $tradecenter['ress_3']) {
                     $pick_u[3] = 0;
                 } else {
                     $this->sdl->log('Resources for Captains: Metals ' . $metal_cost . ' - Minerals ' . $mineral_cost . ' - Dilithium ' . $dilithium_cost, TICK_LOG_FILE_NPC);
                     $pick_r[0] += $metal_cost;
                     $pick_r[1] += $mineral_cost;
                     $pick_r[2] += $dilithium_cost;
                 }
             }
             // Techs
             if ($pick_u[4] > 0) {
                 $metal_cost = $pick_u[4] * 650;
                 $mineral_cost = $pick_u[4] * 440;
                 $dilithium_cost = $pick_u[4] * 250;
                 if ($metal_cost > $tradecenter['ress_1'] || $mineral_cost > $tradecenter['ress_2'] || $dilithium_cost > $tradecenter['ress_3']) {
                     $pick_u[4] = 0;
                 } else {
                     $this->sdl->log('Resources for Techs: Metals ' . $metal_cost . ' - Minerals ' . $mineral_cost . ' - Dilithium ' . $dilithium_cost, TICK_LOG_FILE_NPC);
                     $pick_r[0] += $metal_cost;
                     $pick_r[1] += $mineral_cost;
                     $pick_r[2] += $dilithium_cost;
                 }
             }
             // Docs
             if ($pick_u[5] > 0) {
                 $metal_cost = $pick_u[5] * 1000;
                 $mineral_cost = $pick_u[5] * 500;
                 $dilithium_cost = $pick_u[5] * 200;
                 if ($metal_cost > $tradecenter['ress_1'] || $mineral_cost > $tradecenter['ress_2'] || $dilithium_cost > $tradecenter['ress_3']) {
                     $pick_u[5] = 0;
                 } else {
                     $this->sdl->log('Resources for Docs: Metals ' . $metal_cost . ' - Minerals ' . $mineral_cost . ' - Dilithium ' . $dilithium_cost, TICK_LOG_FILE_NPC);
                     $pick_r[0] += $metal_cost;
                     $pick_r[1] += $mineral_cost;
                     $pick_r[2] += $dilithium_cost;
                 }
             }
             // DC ----
             // Pick up resources only if there is a little stock pile
             // 200408 DC ----  Sorry, no more fundings to the CC
             // 220610 AC ----  But it's needed after a galaxy reset
             if (PICK_RESOURCES_FROM_PLANET) {
                 if ($tradecenter['ress_1'] < 350000) {
                     if ($resources['resource_1'] > 150000) {
                         $pick_r[0] = $resources['resource_1'] / 100;
                     }
                 }
                 if ($tradecenter['ress_2'] < 350000) {
                     if ($resources['resource_2'] > 150000) {
                         $pick_r[1] = $resources['resource_2'] / 100;
                     }
                 }
                 if ($tradecenter['ress_3'] < 350000) {
                     if ($resources['resource_3'] > 150000) {
                         $pick_r[2] = $resources['resource_3'] / 125;
                     }
                 }
                 $this->sdl->log('Add resources: ' . $pick_r[0] . ' -- ' . $pick_r[1] . ' -- ' . $pick_r[2], TICK_LOG_FILE_NPC);
                 $update_res = 'UPDATE FHB_Handels_Lager SET
                     unit_1=unit_1+' . $pick_u[0] . ',unit_2=unit_2+' . $pick_u[1] . ',unit_3=unit_3+' . $pick_u[2] . ',
                     unit_4=unit_4+' . $pick_u[3] . ',unit_5=unit_5+' . $pick_u[4] . ',unit_6=unit_6+' . $pick_u[5] . ',
                     ress_1=ress_1+' . $pick_r[0] . ',ress_2=ress_2+' . $pick_r[1] . ',ress_3=ress_3+' . $pick_r[2] . ' WHERE id=1';
             } else {
                 $this->sdl->log('Picking resources from CC: ' . $pick_r[0] . ' -- ' . $pick_r[1] . ' -- ' . $pick_r[2], TICK_LOG_FILE_NPC);
                 $update_res = 'UPDATE FHB_Handels_Lager SET
                     unit_1=unit_1+' . $pick_u[0] . ',unit_2=unit_2+' . $pick_u[1] . ',unit_3=unit_3+' . $pick_u[2] . ',
                     unit_4=unit_4+' . $pick_u[3] . ',unit_5=unit_5+' . $pick_u[4] . ',unit_6=unit_6+' . $pick_u[5] . ',
                     ress_1=ress_1-' . $pick_r[0] . ',ress_2=ress_2-' . $pick_r[1] . ',ress_3=ress_3-' . $pick_r[2] . ' WHERE id=1';
             }
             // Update resources and units available in the commercial centre
             if (!$this->db->query($update_res)) {
                 $this->sdl->log('<b>Error:</b> Could not update Handelslager - ' . $update_res, TICK_LOG_FILE_NPC);
             } else {
                 // Remove resources from Ramona's planet
                 if (PICK_RESOURCES_FROM_PLANET) {
                     $sql = 'UPDATE planets SET
                             unit_1=unit_1-' . $pick_u[0] . ',unit_2=unit_2-' . $pick_u[1] . ',unit_3=unit_3-' . $pick_u[2] . ',
                             unit_4=unit_4-' . $pick_u[3] . ',unit_5=unit_5-' . $pick_u[4] . ',unit_6=unit_6-' . $pick_u[5] . ',
                             resource_1=resource_1-' . $pick_r[0] . ',resource_2=resource_2-' . $pick_r[1] . ',
                             resource_3=resource_3-' . $pick_r[2] . '
                         WHERE planet_id = ' . $this->bot['planet_id'];
                 } else {
                     $sql = 'UPDATE planets SET
                             unit_1=unit_1-' . $pick_u[0] . ',unit_2=unit_2-' . $pick_u[1] . ',unit_3=unit_3-' . $pick_u[2] . ',
                             unit_4=unit_4-' . $pick_u[3] . ',unit_5=unit_5-' . $pick_u[4] . ',unit_6=unit_6-' . $pick_u[5] . '
                         WHERE planet_id = ' . $this->bot['planet_id'];
                 }
                 if (!$this->db->query($sql)) {
                     $this->sdl->log('<b>Error:</b> Could not update Ramona\'s planet - ' . $sql, TICK_LOG_FILE_NPC);
                 }
                 // If needed, we have to tell to Ramona to create some fresh units
                 $sql = 'SELECT unit_1, unit_2, unit_3, unit_4, unit_5, unit_6 FROM planets
                     WHERE planet_id = ' . $this->bot['planet_id'];
                 if ($units = $this->db->queryrow($sql)) {
                     //
                     // Actually we simply reinsert initial value in the table...
                     //
                     $train_u = array();
                     $train_u[0] = $train_u[1] = $train_u[2] = $train_u[3] = $train_u[4] = $train_u[5] = 0;
                     if ($units['unit_1'] <= 500) {
                         $train_u[0] = 1000;
                     }
                     if ($units['unit_2'] <= 500) {
                         $train_u[1] = 1000;
                     }
                     if ($units['unit_3'] <= 500) {
                         $train_u[2] = 1000;
                     }
                     if ($units['unit_4'] <= 500) {
                         $train_u[3] = 1000;
                     }
                     if ($units['unit_5'] <= 500) {
                         $train_u[4] = 1000;
                     }
                     if ($units['unit_6'] <= 500) {
                         $train_u[5] = 1000;
                     }
                     // Have we something to do?
                     if ($train_u[0] != 0 || $train_u[1] != 0 || $train_u[2] != 0 || $train_u[3] != 0 || $train_u[4] != 0 || $train_u[5] != 0) {
                         $this->sdl->log('Produce new units: ' . $train_u[0] . ' -- ' . $train_u[1] . ' -- ' . $train_u[2] . ' -- ' . $train_u[3] . ' -- ' . $train_u[4] . ' -- ' . $train_u[5], TICK_LOG_FILE_NPC);
                         $sql = 'UPDATE planets SET
                             unit_1=unit_1+' . $train_u[0] . ',unit_2=unit_2+' . $train_u[1] . ',unit_3=unit_3+' . $train_u[2] . ',
                             unit_4=unit_4+' . $train_u[3] . ',unit_5=unit_5+' . $train_u[4] . ',unit_6=unit_6+' . $train_u[5] . '
                             WHERE planet_id = ' . $this->bot['planet_id'];
                         if (!$this->db->query($sql)) {
                             $this->sdl->log('<b>Error:</b> Could not instruct Ramona to produce new units - ' . $sql, TICK_LOG_FILE_NPC);
                         }
                     }
                 } else {
                     $this->sdl->log('<b>Error:</b> Cannot read from Ramona\'s planet!', TICK_LOG_FILE_NPC);
                 }
             }
             $this->db->unlock('FHB_Handels_Lager');
         }
         $this->sdl->finish_job('Update Ramona resources svailability', TICK_LOG_FILE_NPC);
     }
     // ########################################################################################
     // ########################################################################################
     // Ferengi Trade Center blacklist Cleanup
     $this->sdl->start_job('Blacklist cleanup', TICK_LOG_FILE_NPC);
     $sql = "SELECT user_id FROM FHB_sperr_list GROUP BY user_id";
     if (!($blacklist = $this->db->query($sql))) {
         $this->sdl->log('<b>Error:</b> cannot read blacklist data - SKIP', TICK_LOG_FILE_NPC);
     } else {
         while ($result = $this->db->fetchrow($blacklist)) {
             // Check if user still exists
             $sql = 'SELECT user_id FROM user WHERE user_id=' . $result['user_id'];
             $user = $this->db->query($sql);
             if ($this->db->num_rows($user) <= 0) {
                 $sql = 'DELETE FROM FHB_sperr_list WHERE user_id=' . $result['user_id'];
                 if (!$this->db->query($sql)) {
                     $log_msg = '<b>Error:</b> cannot remove dead user from blacklist - CONTINUED';
                 } else {
                     $log_msg = 'Deleted user #' . $result['user_id'] . ' removed from blacklist';
                 }
                 $this->sdl->log($log_msg, TICK_LOG_FILE_NPC);
             }
         }
     }
     $this->sdl->finish_job('Blacklist cleanup', TICK_LOG_FILE_NPC);
     // ########################################################################################
     // ########################################################################################
     // Learning is boring here fixed the cheating of resources by troops sale
     $this->sdl->start_job('Soldiers Transactions', TICK_LOG_FILE_NPC);
     $transactions = 0;
     $sql = 'SELECT id, unit_1, unit_2, unit_3, unit_4, unit_5, unit_6
             FROM FHB_cache_trupp_trade WHERE tick<=' . $ACTUAL_TICK;
     if (!($troops_traded = $this->db->query($sql))) {
         $this->sdl->log('<b>Error:</b> cannot read troops transactions - SKIP', TICK_LOG_FILE_NPC);
     } else {
         while ($cache_trade = $this->db->fetchrow($troops_traded)) {
             $transactions++;
             $this->db->lock('FHB_Handels_Lager');
             $sql = 'UPDATE FHB_Handels_Lager SET unit_1=unit_1+' . $cache_trade['unit_1'] . ',
                                                  unit_2=unit_2+' . $cache_trade['unit_2'] . ',
                                                  unit_3=unit_3+' . $cache_trade['unit_3'] . ',
                                                  unit_4=unit_4+' . $cache_trade['unit_4'] . ',
                                                  unit_5=unit_5+' . $cache_trade['unit_5'] . ',
                                                  unit_6=unit_6+' . $cache_trade['unit_6'] . '
                      WHERE id=1';
             if (!$this->db->query($sql)) {
                 $this->sdl->log('<b>Error:</b> cannot update trading stock - CONTINUED', TICK_LOG_FILE_NPC);
             }
             $this->db->unlock('FHB_Handels_Lager');
             $sql = 'DELETE FROM FHB_cache_trupp_trade WHERE id=' . $cache_trade['id'];
             if (!$this->db->query($sql)) {
                 $this->sdl->log('<b>Error:</b> cannot remove troops transaction - CONTINUED', TICK_LOG_FILE_NPC);
             }
         }
         $this->sdl->log('Transactions: ' . $transactions, TICK_LOG_FILE_NPC);
     }
     $this->sdl->finish_job('Soldiers Transactions', TICK_LOG_FILE_NPC);
     // ########################################################################################
     // ########################################################################################
     // Sensors monitoring and user warning
     $messages = array('<br><center><b>Stop the attack immediately!</b></center>
                     <br>You appeared on our sensors. Our fleets are on intercepting course.<br><br>
                     Flying on would result in a war which we will lead without taking into consideration losses against you and your allies.
                     <br>There are 5 small Light Attack Hunter on the way to your planet <TARGETPLANET>.
                     <br>--------------------------------------<br>
                     Commander of Alpha-Fleet of the Trading Empire', '<br><center><b>Stellen Sie sofort den Angriff ein!</b></center>
                     <br>Sie sind auf unseren Sensoren erschienen. Unsere Flotten sind auf Abfangkurs.<br><br>
                     Ein Weiterfliegen h&auml;tte einen Krieg zur Folge, den wir ohne R&uuml;cksicht
                     auf Verluste gegen Sie und ihre Verb&uuml;ndeten f&uuml;hren werden.
                     <br>Es sind 5 Kleine Angriffsgeschwarder unterwegs zu ihrem Planeten <TARGETPLANET>.
                     <br>--------------------------------------<br>
                     Commander der Alpha-Flotte des Handelsimperiums', '<br><center><b>Fermate immediatamente il vostro attacco!</b></center>
                     <br>Siete apparso sui nostri sensori. Le nostre flotte sono in rotta di intercettazione.<br><br>
                     Continuare provocherebbe una guerra che condurremo senza prendere in considerazione le perdite vostre e dei vostri alleati.
                     <br>Ci sono 5 piccoli Caccia Leggeri d&#146;Attacco in rotta verso il vostro pianeta <TARGETPLANET>.
                     <br>--------------------------------------<br>
                     Comandante dell&#146;Alpha-Fleet dell&#146;Impero Commerciale');
     $titles = array('<b>You are on our sensors</b>', '<b>Sie sind auf unseren Sensoren</b>', '<b>Siete sui nostri sensori</b>');
     $this->CheckSensors($ACTUAL_TICK, $titles, $messages);
     // ########################################################################################
     // ########################################################################################
     // Ships creation
     $this->sdl->start_job('Creating ships', TICK_LOG_FILE_NPC);
     $this->sdl->log('Check fleet "Alpha-Fleet IVX" composition', TICK_LOG_FILE_NPC);
     $query = 'SELECT fleet_id FROM `ship_fleets` WHERE fleet_name="Alpha-Fleet IVX" and user_id=' . $this->bot['user_id'] . ' LIMIT 0, 1';
     $this->db->query($query);
     if ($this->db->num_rows() <= 0) {
         $sql = 'INSERT INTO ship_fleets (fleet_name, user_id, planet_id, move_id, n_ships)
             VALUES ("Alpha-Fleet IVX", ' . $this->bot['user_id'] . ', ' . $this->bot['planet_id'] . ', 0, 4000)';
         if (!$this->db->query($sql)) {
             $this->sdl->log('<b>Error:</b> Could not insert new fleets data', TICK_LOG_FILE_NPC);
         } else {
             $fleet_id = $this->db->insert_id();
             $stpl1_found = true;
             $stpl2_found = true;
             if (!$fleet_id) {
                 $this->sdl->log('Error - ' . $fleet_id . ' = empty', TICK_LOG_FILE_NPC);
             }
             $sql_a = 'SELECT min_unit_1, min_unit_2, min_unit_3, min_unit_4, value_5, value_9
                      FROM ship_templates WHERE id = ' . $this->bot['ship_t_1'];
             $sql_b = 'SELECT min_unit_1, min_unit_2, min_unit_3, min_unit_4, value_5, value_9
                      FROM ship_templates WHERE id = ' . $this->bot['ship_t_2'];
             if (($stpl_a = $this->db->queryrow($sql_a)) === false) {
                 $this->sdl->log('<b>Error:</b> Could not query ship template data - ' . $sql_a, TICK_LOG_FILE_NPC);
             }
             if (($stpl_b = $this->db->queryrow($sql_b)) === false) {
                 $this->sdl->log('<b>Error:</b> Could not query ship template data - ' . $sql_b, TICK_LOG_FILE_NPC);
             }
             // Check if the templates exists
             if (empty($stpl_a)) {
                 $stpl1_found = false;
             }
             if (empty($stpl_b)) {
                 $stpl2_found = false;
             }
             $units_str_1 = $stpl_a['min_unit_1'] . ', ' . $stpl_a['min_unit_2'] . ', ' . $stpl_a['min_unit_3'] . ', ' . $stpl_a['min_unit_4'];
             $units_str_2 = $stpl_b['min_unit_1'] . ', ' . $stpl_b['min_unit_2'] . ', ' . $stpl_b['min_unit_3'] . ', ' . $stpl_b['min_unit_4'];
             $sql_c = 'INSERT INTO ships (fleet_id, user_id, template_id, experience, hitpoints, construction_time, unit_1, unit_2, unit_3, unit_4)
                 VALUES (' . $fleet_id . ', ' . $this->bot['user_id'] . ', ' . $this->bot['ship_t_1'] . ', ' . $stpl_a['value_9'] . ', ' . $stpl_a['value_5'] . ', ' . time() . ', ' . $units_str_1 . ')';
             $sql_d = 'INSERT INTO ships (fleet_id, user_id, template_id, experience, hitpoints, construction_time, unit_1, unit_2, unit_3, unit_4)
                 VALUES (' . $fleet_id . ', ' . $this->bot['user_id'] . ', ' . $this->bot['ship_t_2'] . ', ' . $stpl_b['value_9'] . ', ' . $stpl_b['value_5'] . ', ' . time() . ', ' . $units_str_2 . ')';
             for ($i = 0; $i < 4000; ++$i) {
                 if ($i < 400) {
                     // Skip if template not found
                     if (!$stpl1_found) {
                         continue;
                     }
                     if (!$this->db->query($sql_c)) {
                         $this->sdl->log('<b>Error:</b> Could not insert new ships #' . $i . ' data', TICK_LOG_FILE_NPC);
                     }
                 } else {
                     // Skip if template not found
                     if (!$stpl2_found) {
                         continue;
                     }
                     if (!$this->db->query($sql_d)) {
                         $this->sdl->log('<b>Error:</b> Could not insert new ships #' . $i . ' data', TICK_LOG_FILE_NPC);
                     }
                 }
             }
             $this->sdl->log('Fleet: ' . $fleet_id . ' - 4000 ships created', TICK_LOG_FILE_NPC);
         }
     }
     // Check whether someone has destroyed some Quark's ships
     $this->RestoreFleetLosses("Alpha-Fleet IVX", $this->bot['ship_t_2'], 4000);
     $this->sdl->log('Check fleet "Interception Omega" composition', TICK_LOG_FILE_NPC);
     $query = 'SELECT fleet_id FROM `ship_fleets` WHERE fleet_name="Interception Omega" and user_id=' . $this->bot['user_id'] . ' LIMIT 0, 1';
     $this->db->query($query);
     if ($this->db->num_rows() <= 0) {
         $sql = 'INSERT INTO ship_fleets (fleet_name, user_id, planet_id, move_id, n_ships)
             VALUES ("Interception Omega", ' . $this->bot['user_id'] . ', ' . $this->bot['planet_id'] . ', 0, 1000)';
         if (!$this->db->query($sql)) {
             $this->sdl->log('<b>Error:</b> Could not insert new fleets data', TICK_LOG_FILE_NPC);
         } else {
             $fleet_id = $this->db->insert_id();
             if (!$fleet_id) {
                 $this->sdl->log('Error - ' . $fleet_id . ' = empty', TICK_LOG_FILE_NPC);
             }
             $sql_b = 'SELECT min_unit_1, min_unit_2, min_unit_3, min_unit_4, value_5, value_9
                       FROM ship_templates WHERE id = ' . $this->bot['ship_t_2'];
             if (($stpl_b = $this->db->queryrow($sql_b)) === false) {
                 $this->sdl->log('<b>Error:</b> Could not query ship template data - ' . $sql_b, TICK_LOG_FILE_NPC);
             }
             if (!empty($stpl_b)) {
                 $units_str_2 = $stpl_b['min_unit_1'] . ', ' . $stpl_b['min_unit_2'] . ', ' . $stpl_b['min_unit_3'] . ', ' . $stpl_b['min_unit_4'];
                 $sql = 'INSERT INTO ships (fleet_id, user_id, template_id, experience, hitpoints, construction_time, unit_1, unit_2, unit_3, unit_4)
                     VALUES (' . $fleet_id . ', ' . $this->bot['user_id'] . ', ' . $this->bot['ship_t_2'] . ', ' . $stpl_b['value_9'] . ', ' . $stpl_b['value_5'] . ', ' . time() . ', ' . $units_str_2 . ')';
                 for ($i = 0; $i < 1000; ++$i) {
                     if (!$this->db->query($sql)) {
                         $this->sdl->log('<b>Error:</b> Could not insert new ships #' . $i . ' data', TICK_LOG_FILE_NPC);
                     }
                 }
                 $this->sdl->log('Fleet: ' . $fleet_id . ' - 1000 ships created', TICK_LOG_FILE_NPC);
             } else {
                 $this->sdl->log('<b>Error:</b> Could not found template ' . $this->bot['ship_t_2'] . '!', TICK_LOG_FILE_NPC);
             }
         }
     }
     // Check whether someone has destroyed some Quark's ships
     $this->RestoreFleetLosses("Interception Omega", $this->bot['ship_t_2'], 1000);
     $this->sdl->finish_job('Creating ships', TICK_LOG_FILE_NPC);
     // ########################################################################################
     // ########################################################################################
     $this->sdl->log('<b>Finished Scheduler in <font color=#009900>' . round(microtime() + time() - $starttime, 4) . ' secs</font><br>Executed Queries: <font color=#ff0000>' . $this->db->i_query . '</font></b>', TICK_LOG_FILE_NPC);
 }
    if (empty($diplomacy['user2_id'])) {
        message(NOTICE, constant($game->sprache("TEXT25")));
    }
    $opid = $diplomacy['user1_id'] == $game->player['user_id'] ? 2 : 1;
    if ($diplomacy['user1_id'] != $game->player['user_id'] && $diplomacy['user2_id'] != $game->player['user_id']) {
        message(NOTICE, constant($game->sprache("TEXT21")));
    }
    if ($diplomacy['accepted'] != 1) {
        message(NOTICE, constant($game->sprache("TEXT26")));
    }
    $sql = 'DELETE FROM user_diplomacy
            WHERE ud_id = ' . $ud_id;
    if (!$db->query($sql)) {
        message(DATABASE_ERROR, 'Could not delete diplomacy private data');
    }
    add_logbook_entry($diplomacy['user' . $opid . '_id'], LOGBOOK_UDIPLOMACY, constant($game->sprache("TEXT27")), array('what' => 'break', 'who_id' => $game->player['user_id'], 'who_name' => $game->player['user_name']));
    redirect('a=user_diplomacy');
} else {
    /*
    [05:11:14] <Secius> that makes ann on stgc meets 2x free beverages^^
    [05:11:18] <TAP> if you have nen run, then simply everything fits
    [05:11:24] <TAP> I overtake gladly ;)
    */
    /* 26/02/09 - AC: Check if it's currently present in the url request */
    if (!isset($_REQUEST['sort'])) {
        $_REQUEST['sort'] = 0;
    }
    if (!isset($_REQUEST['member_list'])) {
        $_REQUEST['member_list'] = 0;
    }
    /* */