function flt_mission_colonize(&$mission_data)
{
    $fleet_row =& $mission_data['fleet'];
    $src_user_row =& $mission_data['src_user'];
    global $lang;
    $TargetAdress = sprintf($lang['sys_adress_planet'], $fleet_row['fleet_end_galaxy'], $fleet_row['fleet_end_system'], $fleet_row['fleet_end_planet']);
    $fleet_array = sys_unit_str2arr($fleet_row['fleet_array']);
    $TheMessage = $lang['sys_colo_no_colonizer'];
    if ($fleet_array[SHIP_COLONIZER] >= 1) {
        $TheMessage = $lang['sys_colo_notfree'];
        if (!$mission_data['dst_planet'] || empty($mission_data['dst_planet'])) {
            $iPlanetCount = get_player_current_colonies($src_user_row);
            // Can we colonize more planets?
            $TheMessage = $lang['sys_colo_maxcolo'];
            if ($iPlanetCount < get_player_max_colonies($src_user_row)) {
                // Yes, we can colonize
                $TheMessage = $lang['sys_colo_badpos'];
                $NewOwnerPlanet = uni_create_planet($fleet_row['fleet_end_galaxy'], $fleet_row['fleet_end_system'], $fleet_row['fleet_end_planet'], $fleet_row['fleet_owner'], "{$lang['sys_colo_defaultname']} {$iPlanetCount}", false, array('user_row' => $src_user_row));
                if ($NewOwnerPlanet) {
                    $TheMessage = $lang['sys_colo_arrival'] . $TargetAdress . $lang['sys_colo_allisok'];
                    msg_send_simple_message($fleet_row['fleet_owner'], '', $fleet_row['fleet_start_time'], MSG_TYPE_SPY, $lang['sys_colo_mess_from'], $lang['sys_colo_mess_report'], $TheMessage);
                    $fleet_array[SHIP_COLONIZER]--;
                    $fleet_row['fleet_amount']--;
                    $fleet_row['fleet_array'] = sys_unit_arr2str($fleet_array);
                    return RestoreFleetToPlanet($fleet_row, false);
                }
            }
        }
    }
    doquery("UPDATE `{{fleets}}` SET `fleet_mess` = '1' WHERE `fleet_id` = '{$fleet_row['fleet_id']}' LIMIT 1;");
    msg_send_simple_message($fleet_row['fleet_owner'], '', $fleet_row['fleet_start_time'], MSG_TYPE_SPY, $lang['sys_colo_mess_from'], $lang['sys_colo_mess_report'], "{$lang['sys_colo_arrival']}{$TargetAdress}{$TheMessage}");
    return CACHE_FLEET;
}
function flt_mission_relocate($mission_data)
{
    $fleet_row = $mission_data['fleet'];
    $destination_planet = $mission_data['dst_planet'];
    if (!$destination_planet || !is_array($destination_planet)) {
        doquery("UPDATE {{fleets}} SET `fleet_mess` = 1 WHERE `fleet_id` = {$fleet_row['fleet_id']} LIMIT 1;");
        return CACHE_FLEET;
    }
    /*
        // flt_mission_relocate
        $TargetAdress         = sprintf ($lang['sys_adress_planet'], $fleet_row['fleet_start_galaxy'], $fleet_row['fleet_start_system'], $fleet_row['fleet_start_planet']);
        $TargetAddedGoods     = sprintf ($lang['sys_stay_mess_goods'],
                          $lang['Metal'], pretty_number($fleet_row['fleet_resource_metal']),
                          $lang['Crystal'], pretty_number($fleet_row['fleet_resource_crystal']),
                          $lang['Deuterium'], pretty_number($fleet_row['fleet_resource_deuterium']));
    
        $TargetMessage        = $lang['sys_stay_mess_back'] ."<a href=\"galaxy.php?mode=3&galaxy=". $fleet_row['fleet_start_galaxy'] ."&system=". $fleet_row['fleet_start_system'] ."\">";
        $TargetMessage       .= $TargetAdress. "</a>". $lang['sys_stay_mess_bend'] ."<br />". $TargetAddedGoods;
    
        SendSimpleMessage ( $fleet_row['fleet_owner'], '', $fleet_row['fleet_end_time'], 5, $lang['sys_mess_qg'], $lang['sys_mess_fleetback'], $TargetMessage);
    */
    global $lang;
    $TargetUserID = $destination_planet['id_owner'];
    $TargetAdress = sprintf($lang['sys_adress_planet'], $fleet_row['fleet_end_galaxy'], $fleet_row['fleet_end_system'], $fleet_row['fleet_end_planet']);
    $TargetAddedGoods = sprintf($lang['sys_stay_mess_goods'], $lang['Metal'], pretty_number($fleet_row['fleet_resource_metal']), $lang['Crystal'], pretty_number($fleet_row['fleet_resource_crystal']), $lang['Deuterium'], pretty_number($fleet_row['fleet_resource_deuterium']));
    $TargetMessage = $lang['sys_stay_mess_start'] . "<a href=\"galaxy.php?mode=3&galaxy=" . $fleet_row['fleet_end_galaxy'] . "&system=" . $fleet_row['fleet_end_system'] . "\">";
    $TargetMessage .= $TargetAdress . "</a>" . $lang['sys_stay_mess_end'] . "<br />" . $TargetAddedGoods;
    msg_send_simple_message($TargetUserID, '', $fleet_row['fleet_start_time'], MSG_TYPE_TRANSPORT, $lang['sys_mess_qg'], $lang['sys_stay_mess_stay'], $TargetMessage);
    return RestoreFleetToPlanet($fleet_row, false);
}
/**
 * flt_mission_transport.php
 *
 * @version 2.0 return cacher result
 * @version 1
 * @copyright 2008 By Chlorel for XNova
 */
function flt_mission_transport(&$mission_data)
{
    $fleet_row =& $mission_data['fleet'];
    $source_planet =& $mission_data['src_planet'];
    $destination_planet =& $mission_data['dst_planet'];
    if (!isset($destination_planet['id']) || !$destination_planet['id_owner']) {
        // doquery("UPDATE {{fleets}} SET `fleet_mess` = 1 WHERE `fleet_id` = {$fleet_row['fleet_id']} LIMIT 1;");
        flt_send_back($fleet_row);
        return CACHE_FLEET;
    }
    global $lang;
    $Message = sprintf($lang['sys_tran_mess_user'], $source_planet['name'], uni_render_coordinates_href($fleet_row, 'fleet_start_', 3, ''), $destination_planet['name'], uni_render_coordinates_href($fleet_row, 'fleet_end_', 3, ''), $fleet_row['fleet_resource_metal'], $lang['Metal'], $fleet_row['fleet_resource_crystal'], $lang['Crystal'], $fleet_row['fleet_resource_deuterium'], $lang['Deuterium']);
    msg_send_simple_message($fleet_row['fleet_target_owner'], '', $fleet_row['fleet_start_time'], MSG_TYPE_TRANSPORT, $lang['sys_mess_tower'], $lang['sys_mess_transport'], $Message);
    if ($fleet_row['fleet_target_owner'] != $fleet_row['fleet_owner']) {
        msg_send_simple_message($fleet_row['fleet_owner'], '', $fleet_row['fleet_start_time'], MSG_TYPE_TRANSPORT, $lang['sys_mess_tower'], $lang['sys_mess_transport'], $Message);
    }
    /*
      $Message = sprintf( $lang['sys_tran_mess_owner'],
                  $TargetName, uni_render_coordinates_href($fleet_row, 'fleet_end_', 3, ''),
                  $fleet_row['fleet_resource_metal'], $lang['Metal'],
                  $fleet_row['fleet_resource_crystal'], $lang['Crystal'],
                  $fleet_row['fleet_resource_deuterium'], $lang['Deuterium'] );
      msg_send_simple_message ( $StartOwner, '', $fleet_row['fleet_start_time'], MSG_TYPE_TRANSPORT, $lang['sys_mess_tower'], $lang['sys_mess_transport'], $Message);
    */
    return RestoreFleetToPlanet($fleet_row, false, true);
}
/**
 * flt_mission_transport.php
 *
 * @version 2.0 return cacher result
 * @version 1
 * @copyright 2008 By Chlorel for XNova
 */
function flt_mission_transport($mission_data)
{
    $fleet_row = $mission_data['fleet'];
    $source_planet = $mission_data['src_planet'];
    $destination_planet = $mission_data['dst_planet'];
    if (!$destination_planet || !is_array($destination_planet) || !$destination_planet['id_owner']) {
        doquery("UPDATE {{fleets}} SET `fleet_mess` = 1 WHERE `fleet_id` = {$fleet_row['fleet_id']} LIMIT 1;");
        return CACHE_FLEET;
    }
    /*
      // flt_mission_transport
      $Message = sprintf($lang['sys_tran_mess_back'], $StartName, GetStartAdressLink($fleet_row, ''));
      SendSimpleMessage($StartOwner, '', $fleet_row['fleet_end_time'], 5, $lang['sys_mess_tower'], $lang['sys_mess_fleetback'], $Message);
    */
    global $lang;
    $StartName = $source_planet['name'];
    $StartOwner = $fleet_row['fleet_owner'];
    $TargetName = $destination_planet['name'];
    $TargetOwner = $fleet_row['fleet_target_owner'];
    $Message = sprintf($lang['sys_tran_mess_owner'], $TargetName, uni_render_coordinates_href($fleet_row, 'fleet_end_', 3, ''), $fleet_row['fleet_resource_metal'], $lang['Metal'], $fleet_row['fleet_resource_crystal'], $lang['Crystal'], $fleet_row['fleet_resource_deuterium'], $lang['Deuterium']);
    msg_send_simple_message($StartOwner, '', $fleet_row['fleet_start_time'], MSG_TYPE_TRANSPORT, $lang['sys_mess_tower'], $lang['sys_mess_transport'], $Message);
    if ($TargetOwner != $StartOwner) {
        $Message = sprintf($lang['sys_tran_mess_user'], $StartName, uni_render_coordinates_href($fleet_row, 'fleet_start_', 3, ''), $TargetName, uni_render_coordinates_href($fleet_row, 'fleet_end_', 3, ''), $fleet_row['fleet_resource_metal'], $lang['Metal'], $fleet_row['fleet_resource_crystal'], $lang['Crystal'], $fleet_row['fleet_resource_deuterium'], $lang['Deuterium']);
        msg_send_simple_message($TargetOwner, '', $fleet_row['fleet_start_time'], MSG_TYPE_TRANSPORT, $lang['sys_mess_tower'], $lang['sys_mess_transport'], $Message);
    }
    return RestoreFleetToPlanet($fleet_row, false, true);
}
function msg_ali_send($message, $subject, $ally_rank_id = 0, $ally_id = 0)
{
    global $time_now, $user;
    $ally_id = $ally_id ? $ally_id : $user['ally_id'];
    $query = doquery("SELECT id, username FROM {{users}} WHERE ally_id = '{$ally_id}'" . ($ally_rank_id >= 0 ? " AND ally_rank_id = {$ally_rank_id}" : ''));
    $list = '';
    while ($u = mysql_fetch_assoc($query)) {
        $sendList[] = $u['id'];
        $list .= "<br>{$u['username']} ";
    }
    msg_send_simple_message($sendList, $user['id'], $time_now, MSG_TYPE_ALLIANCE, $user['username'], $subject, sys_bbcodeParse($message, true));
    return $list;
}
function flt_mission_destroy($mission_data)
{
    $result = flt_mission_attack($mission_data);
    if (empty($result) || $result['won'] != 1) {
        return $result;
    }
    $fleet_row = $mission_data['fleet'];
    $destination_planet = $mission_data['dst_planet'];
    if (!$destination_planet || !is_array($destination_planet)) {
        doquery("UPDATE {{fleets}} SET `fleet_mess` = 1 WHERE `fleet_id` = {$fleet_row['fleet_id']} LIMIT 1;");
        return;
    }
    global $lang;
    $MoonSize = $destination_planet['diameter'];
    $MoonName = $destination_planet['name'];
    $RipsKilled = 0;
    $MoonDestroyed = 0;
    foreach ($result['rw'][count($result['rw']) - 1]['attackers'] as $fleet) {
        foreach ($fleet['detail'] as $shipID => $shipNum) {
            $Rips += $shipID == SHIP_DEATH_STAR ? $shipNum : 0;
        }
    }
    if ($Rips > 0) {
        $MoonDestChance = min(99, round((100 - sqrt($MoonSize)) * sqrt($Rips)));
        $RipDestChance = round(sqrt($MoonSize) / 2);
        $UserChance = mt_rand(1, 100);
        if ($UserChance > 0 and $UserChance <= $MoonDestChance) {
            $RipsKilled = 0;
            $MoonDestroyed = 1;
        } elseif ($UserChance > 0 and $UserChance <= $RipDestChance) {
            $RipsKilled = 1;
            $MoonDestroyed = 0;
        }
    }
    if ($MoonDestroyed == 1) {
        doquery("DELETE FROM {{planets}} WHERE `id` ='{$destination_planet['id']}';");
        $message = $lang['sys_moon_destroyed'];
    } elseif ($RipsKilled == 1) {
        //TODO: !!!!!!!!!!!!!!!!!!!!!!!!!!!!!! А нужно удалять все флоты !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        doquery("DELETE FROM {{fleets}} WHERE `fleet_id` = '{$fleet_row["fleet_id"]}';");
        $message = $lang['sys_rips_destroyed'];
    } else {
        $message = $lang['sys_rips_come_back'];
    }
    $message .= "<br><br>";
    $message .= $lang['sys_chance_moon_destroy'] . intval($MoonDestChance) . "%. <br>" . $lang['sys_chance_rips_destroy'] . intval($RipDestChance) . "%";
    msg_send_simple_message($fleet_row['fleet_owner'], '', $fleet_row['fleet_start_time'], MSG_TYPE_COMBAT, $lang['sys_mess_tower'], $lang['sys_moon_destruction_report'], $message);
    msg_send_simple_message($destination_planet['id_owner'], '', $fleet_row['fleet_start_time'], MSG_TYPE_COMBAT, $lang['sys_mess_tower'], $lang['sys_moon_destruction_report'], $message);
    return $result;
}
/**
* SendSimpleMessage.php
*
* @version 1.3
* @copyright 2008 by Chlorel for XNova
  Revision history :
  1.0 - Initial release (mise en fonction generique)
  1.1 - Ajout gestion des messages par type pour le module de messages
  1.2 - Correction bug (addslashes pour les zone texte pouvant contenir une apostrophe)
  1.3 - Correction bug (integration de la variable $Time pour afficher l'heure exacte de l'evenement pour les flottes)
  1.4 - copyright (c) 2010 by Gorlum for http://supernova.ws
        [+] Ability to mass-send emails. Mass-sending done via two queries - one for messages table, one for users table
  1.5 - copyright (c) 2010-2011 by Gorlum for http://supernova.ws
        [+] SuperMassMailing - authlevel=3 player can send messages to whole server ('*' as $owners)
*/
function msg_ali_send($message, $subject, $ally_rank_id = 0, $ally_id = 0)
{
    global $user;
    $ally_id = $ally_id ? $ally_id : $user['ally_id'];
    $list = '';
    $query = db_user_list("ally_id = '{$ally_id}'" . ($ally_rank_id >= 0 ? " AND ally_rank_id = {$ally_rank_id}" : ''), false, 'id, username');
    // while ($u = db_fetch($query))
    foreach ($query as $u) {
        $sendList[] = $u['id'];
        $list .= "<br>{$u['username']} ";
    }
    msg_send_simple_message($sendList, $user['id'], SN_TIME_NOW, MSG_TYPE_ALLIANCE, $user['username'], $subject, $message, true);
    return $list;
}
function sn_user_birthday_celebrate()
{
    global $config, $lang;
    sn_db_transaction_start();
    $query = db_user_list_to_celebrate($config->user_birthday_range);
    while ($row = db_fetch($query)) {
        $row['username'] = db_escape($row['username']);
        rpg_points_change($row['id'], RPG_BIRTHDAY, $config->user_birthday_gift, "Birthday gift for user {$row['username']} ID {$row['id']} on his birthday on {$row['user_birthday']}. Gift last gaved at {$row['user_birthday_celebrated']}");
        db_user_set_by_id($row['id'], "`user_birthday_celebrated` = '{$row['current_birthday']}'");
        msg_send_simple_message($row['id'], 0, SN_TIME_NOW, MSG_TYPE_ADMIN, $lang['sys_administration'], $lang['sys_birthday'], sprintf($lang['sys_birthday_message'], $row['username'], $row['current_birthday'], $config->user_birthday_gift, $lang['sys_dark_matter_sh']), true, true);
    }
    $config->db_saveItem('user_birthday_celebrate', SN_TIME_NOW);
    sn_db_transaction_commit();
}
/**
 * MissionCaseStay.php
 *
 * version 2.0 returns results for new fleet handler
 * @version 1.1
 * @copyright 2008 by Chlorel for XNova
 */
function flt_mission_relocate($mission_data)
{
    $fleet_row =& $mission_data['fleet'];
    $destination_planet =& $mission_data['dst_planet'];
    if (!$destination_planet || !is_array($destination_planet)) {
        // doquery("UPDATE {{fleets}} SET `fleet_mess` = 1 WHERE `fleet_id` = {$fleet_row['fleet_id']} LIMIT 1;");
        flt_send_back($mission_data['fleet']);
        return CACHE_FLEET;
    }
    global $lang;
    $Message = sprintf($lang['sys_tran_mess_user'], $mission_data['src_planet']['name'], uni_render_coordinates_href($fleet_row, 'fleet_start_', 3, ''), $destination_planet['name'], uni_render_coordinates_href($fleet_row, 'fleet_end_', 3, ''), $fleet_row['fleet_resource_metal'], $lang['Metal'], $fleet_row['fleet_resource_crystal'], $lang['Crystal'], $fleet_row['fleet_resource_deuterium'], $lang['Deuterium']) . '<br />' . $lang['sys_relocate_mess_user'];
    foreach (sys_unit_str2arr($fleet_row['fleet_array']) as $ship_id => $ship_count) {
        $Message .= $lang['tech'][$ship_id] . ' - ' . $ship_count . '<br />';
    }
    msg_send_simple_message($fleet_row['fleet_owner'], '', $fleet_row['fleet_start_time'], MSG_TYPE_TRANSPORT, $lang['sys_mess_qg'], $lang['sys_stay_mess_stay'], $Message);
    return RestoreFleetToPlanet($fleet_row, false);
}
function flt_mission_colonize($mission_data)
{
    $fleet_row = $mission_data['fleet'];
    $src_user_row = $mission_data['src_user'];
    $destination_planet = $mission_data['dst_planet'];
    global $lang;
    $TargetAdress = sprintf($lang['sys_adress_planet'], $fleet_row['fleet_end_galaxy'], $fleet_row['fleet_end_system'], $fleet_row['fleet_end_planet']);
    $fleet_array = sys_unit_str2arr($fleet_row['fleet_array']);
    $TheMessage = $lang['sys_colo_no_colonizer'];
    if ($fleet_array[SHIP_COLONIZER] >= 1) {
        $TheMessage = $lang['sys_colo_notfree'];
        if (!$destination_planet) {
            $iMaxColo = $src_user_row['colonisation_tech'] + 1;
            $iPlanetCount = doquery("SELECT count(*) as `planet_count` FROM `{{planets}}` WHERE `id_owner` = '{$fleet_row['fleet_owner']}' AND `planet_type` = '1';", '', true);
            $iPlanetCount = $iPlanetCount['planet_count'];
            // Can we colonize more planets?
            $TheMessage = $lang['sys_colo_maxcolo'];
            if ($iPlanetCount < $iMaxColo && $iPlanetCount < $GLOBALS['config']->player_max_colonies + 1) {
                // Yes, we can colonize
                $TheMessage = $lang['sys_colo_badpos'];
                $NewOwnerPlanet = uni_create_planet($fleet_row['fleet_end_galaxy'], $fleet_row['fleet_end_system'], $fleet_row['fleet_end_planet'], $fleet_row['fleet_owner'], "{$lang['sys_colo_defaultname']} ¹{$iPlanetCount}");
                if ($NewOwnerPlanet) {
                    $TheMessage = $lang['sys_colo_arrival'] . $TargetAdress . $lang['sys_colo_allisok'];
                    msg_send_simple_message($fleet_row['fleet_owner'], '', $fleet_row['fleet_start_time'], MSG_TYPE_SPY, $lang['sys_colo_mess_from'], $lang['sys_colo_mess_report'], $TheMessage);
                    $fleet_array[SHIP_COLONIZER]--;
                    $fleet_row['fleet_amount']--;
                    $fleet_row['fleet_array'] = sys_unit_arr2str($fleet_array);
                    if ($fleet_row['fleet_array']) {
                        $GLOBALS['debug']->warning("Sending several type of ships with colonizer leads to resource duplication. Resource duplicate X time where X - number of ship type<br>Fleet: {$fleet_row['fleet_array']}", 'Colonization With Fleet', 304);
                    }
                    return RestoreFleetToPlanet($fleet_row, false);
                }
            }
        }
    }
    doquery("UPDATE `{{fleets}}` SET `fleet_mess` = '1' WHERE `fleet_id` = '{$fleet_row['fleet_id']}' LIMIT 1;");
    msg_send_simple_message($fleet_row['fleet_owner'], '', $fleet_row['fleet_start_time'], MSG_TYPE_SPY, $lang['sys_colo_mess_from'], $lang['sys_colo_mess_report'], "{$lang['sys_colo_arrival']}{$TargetAdress}{$TheMessage}");
    return CACHE_FLEET;
}
function HandleTechnologieBuild(&$user, &$planetrow)
{
    global $sn_data, $time_now, $lang;
    if ($user['b_tech_planet']) {
        if ($user['b_tech_planet'] != $planetrow['id']) {
            $planet = doquery("SELECT * FROM `{{planets}}` WHERE `id` = '{$user['b_tech_planet']}' LIMIT 1;", '', true);
        } else {
            $planet = $planetrow;
        }
        if ($planet['b_tech'] && $planet['b_tech_id'] && $planet['b_tech'] <= $time_now) {
            $unit_id = $planet['b_tech_id'];
            $unit_db_name = $sn_data[$unit_id]['name'];
            $user[$unit_db_name]++;
            msg_send_simple_message($user['id'], 0, $time_now, MSG_TYPE_QUE, $lang['msg_que_research_from'], $lang['msg_que_research_subject'], sprintf($lang['msg_que_research_message'], $lang['tech'][$planet['b_tech_id']], $user[$unit_db_name]));
            $quest_list = qst_get_quests($user['id']);
            $quest_triggers = qst_active_triggers($quest_list);
            $quest_rewards = array();
            // TODO: Check mutiply condition quests
            $quest_trigger_list = array_keys($quest_triggers, $unit_id);
            foreach ($quest_trigger_list as $quest_id) {
                if ($quest_list[$quest_id]['quest_unit_amount'] <= $user[$unit_db_name] && $quest_list[$quest_id]['quest_status_status'] != QUEST_STATUS_COMPLETE) {
                    $quest_rewards[$quest_id] = $quest_list[$quest_id]['quest_rewards'];
                    $quest_list[$quest_id]['quest_status_status'] = QUEST_STATUS_COMPLETE;
                }
            }
            qst_reward($user, $planet, $quest_rewards, $quest_list);
            doquery("UPDATE `{{planets}}` SET `b_tech` = '0', `b_tech_id` = '0' WHERE `id` = '{$planet['id']}' LIMIT 1;");
            doquery("UPDATE `{{users}}` SET `{$unit_db_name}` = `{$unit_db_name}` + 1, `b_tech_planet` = '0' WHERE `id` = '{$user['id']}' LIMIT 1;");
            $planet["b_tech_id"] = 0;
        } elseif ($planet["b_tech_id"] == 0) {
            // Il n'y a rien a l'ouest ...
            // Pas de Technologie en cours devait y avoir un bug lors de la derniere connexion
            // On met l'enregistrement informant d'une techno en cours de recherche a jours
            doquery("UPDATE `{{users}}` SET `b_tech_planet` = '0'  WHERE `id` = '{$user['id']}' LIMIT 1;");
        }
    }
}
function flt_mission_spy(&$mission_data)
{
    global $lang;
    $fleet_row =& $mission_data['fleet'];
    $target_user_row =& $mission_data['dst_user'];
    $target_planet_row =& $mission_data['dst_planet'];
    $spying_user_row =& $mission_data['src_user'];
    $spying_planet_row =& $mission_data['src_planet'];
    if (!isset($target_user_row['id']) || !isset($target_planet_row['id']) || !isset($spying_user_row['id'])) {
        doquery("UPDATE {{fleets}} SET `fleet_mess` = 1 WHERE `fleet_id` = {$fleet_row['fleet_id']} LIMIT 1;");
        return;
    }
    $fleet_array = sys_unit_str2arr($fleet_row['fleet_array']);
    if ($fleet_array[SHIP_SPY] > 0) {
        $TargetSpyLvl = GetSpyLevel($target_user_row);
        $CurrentSpyLvl = GetSpyLevel($spying_user_row);
        $spy_diff_empire = $CurrentSpyLvl - $TargetSpyLvl;
        $spy_probes = $fleet_array[SHIP_SPY];
        $spy_diff = $spy_diff_empire + sqrt($spy_probes) - 1;
        $combat_pack[0] = array(RES_METAL => $target_planet_row['metal'], RES_CRYSTAL => $target_planet_row['crystal'], RES_DEUTERIUM => $target_planet_row['deuterium']);
        $spy_message = "<table width=\"440\" cellspacing = \"1\"><tr><td class=\"c\" colspan=\"4\">{$lang['sys_spy_maretials']} {$target_planet_row['name']} ";
        $spy_message .= uni_render_coordinates_href($target_planet_row, '', 3);
        $spy_message .= " ({$lang['Player_']} '{$target_user_row['username']}') {$lang['On_']} ";
        $spy_message .= date(FMT_DATE_TIME, $fleet_row['fleet_end_time']);
        $spy_message .= "</td></tr><tr>";
        $spy_message .= "<td width=220>{$lang['sys_metal']}</td><td width=220 align=right>" . pretty_number($target_planet_row['metal']) . "</td>";
        $spy_message .= "<td width=220>{$lang['sys_crystal']}</td></td><td width=220 align=right>" . pretty_number($target_planet_row['crystal']) . "</td>";
        $spy_message .= "</tr><tr>";
        $spy_message .= "<td width=220>{$lang['sys_deuterium']}</td><td width=220 align=right>" . pretty_number($target_planet_row['deuterium']) . "</td>";
        $spy_message .= "<td width=220>{$lang['sys_energy']}</td><td width=220 align=right>" . pretty_number($target_planet_row['energy_max']) . "</td>";
        $spy_message .= "</tr>";
        if ($spy_diff >= 2) {
            $spy_message .= "<div class='spy_medium'>" . flt_spy_scan($target_planet_row, 'fleet', $lang['tech'][UNIT_SHIPS], $target_user_row) . "</div>";
            coe_compress_add_units(sn_get_groups('fleet'), $target_planet_row, $combat_pack[0]);
        }
        if ($spy_diff >= 3) {
            $spy_message .= "<div class='spy_medium'>" . flt_spy_scan($target_planet_row, 'defense', $lang['tech'][UNIT_DEFENCE], $target_user_row) . "</div>";
            coe_compress_add_units(sn_get_groups('defense_active'), $target_planet_row, $combat_pack[0]);
        }
        if ($spy_diff >= 5) {
            $spy_message .= "<div class='spy_long'>" . flt_spy_scan($target_planet_row, 'structures', $lang['tech'][UNIT_STRUCTURES], $target_user_row) . "</div>";
        }
        if ($spy_diff_empire >= 0) {
            $spy_message .= "<div class='spy_long'>" . flt_spy_scan($target_planet_row, 'tech', $lang['tech'][UNIT_TECHNOLOGIES], $target_user_row) . "</div>";
            coe_compress_add_units(array(TECH_WEAPON, TECH_SHIELD, TECH_ARMOR), $target_planet_row, $combat_pack[0], $target_user_row);
        }
        // TODO: Наемники, губернаторы, артефакты и прочее имперское
        $simulator_link = sn_ube_simulator_encode_replay($combat_pack, 'D');
        $target_unit_list = 0;
        foreach (sn_get_groups('fleet') as $unit_id) {
            $target_unit_list += max(0, mrc_get_level($target_user_row, $target_planet_row, $unit_id, false, true));
        }
        $spy_detected = $spy_probes * $target_unit_list / 4 * pow(2, $TargetSpyLvl - $CurrentSpyLvl);
        if (mt_rand(0, 99) > $spy_detected) {
            $spy_outcome_str = sprintf($lang['sys_mess_spy_detect_chance'], $spy_detected);
            $spy_detected = false;
        } else {
            $spy_outcome_str = $lang['sys_mess_spy_destroyed'];
            $spy_detected = true;
        }
        $spy_message .= "<tr><th class=\"c_c\" colspan=4>";
        $spy_message .= "{$spy_outcome_str}<br />";
        $spy_message .= "<a href=\"fleet.php?target_mission=1&planet_type={$fleet_row['fleet_end_type']}&galaxy={$fleet_row['fleet_end_galaxy']}&system={$fleet_row['fleet_end_system']}&planet={$fleet_row['fleet_end_planet']} \">{$lang['type_mission'][1]}</a><br />";
        $spy_message .= "<a href=\"simulator.php?replay={$simulator_link}\">{$lang['COE_combatSimulator']}</a><br />";
        $spy_message .= "</th></tr></table>";
        // End of link generation
        msg_send_simple_message($spying_user_row['id'], '', $fleet_row['fleet_start_time'], MSG_TYPE_SPY, $lang['sys_mess_qg'], $lang['sys_mess_spy_report'], $spy_message);
        $target_message = "{$lang['sys_mess_spy_ennemyfleet']} {$spying_planet_row['name']} " . uni_render_coordinates_href($spying_planet_row, '', 3);
        $target_message .= " {$lang['sys_mess_spy_seen_at']} {$target_planet_row['name']} " . uni_render_coordinates($target_planet_row);
        $target_user_id = $fleet_row['fleet_target_owner'];
        if ($spy_detected) {
            doquery("DELETE FROM {{fleets}} WHERE `fleet_id` = '{$fleet_row['fleet_id']}' LIMIT 1;");
            $debris_planet_id = $target_planet_row['planet_type'] == PT_PLANET ? $target_planet_row['id'] : $target_planet_row['parent_planet'];
            $spy_cost = get_unit_param(SHIP_SPY, P_COST);
            db_planet_set_by_id($debris_planet_id, "`debris_metal` = `debris_metal` + " . floor($spy_probes * $spy_cost[RES_METAL] * 0.3) . ", `debris_crystal` = `debris_crystal` + " . floor($spy_probes * $spy_cost[RES_CRYSTAL] * 0.3));
            $target_message .= "<br />{$lang['sys_mess_spy_destroyed_enemy']}";
            $result = CACHE_FLEET | CACHE_PLANET_DST;
        } else {
            $result = CACHE_FLEET;
        }
        msg_send_simple_message($target_user_id, '', $fleet_row['fleet_start_time'], MSG_TYPE_SPY, $lang['sys_mess_spy_control'], $lang['sys_mess_spy_activity'], $target_message);
    }
    if (!$spy_detected) {
        doquery("UPDATE {{fleets}} SET `fleet_mess` = '1' WHERE `fleet_id` = '{$fleet_row['fleet_id']}' LIMIT 1;");
    }
    return $result;
}
Exemple #13
0
/**
 * PlanetResourceUpdate.php
 *
 * 2.1 - copyright (c) 2010 by Gorlum for http://supernova.ws
 *     [+] Bit more optimization
 * 2.0 - copyright (c) 2009-2010 by Gorlum for http://supernova.ws
 *     [+] Full rewrote and optimization
 * 1.1 - @copyright 2008 By Chlorel for XNova
 *     [*] Mise a jour automatique mines / silos / energie ...
 * 1.0 - @copyright 2008 By Chlorel for XNova
 *     [*] Mise en module initiale
 */
function sys_o_get_updated($user, $planet, $UpdateTime, $simulation = false)
{
    global $time_now, $sn_data, $lang;
    $no_data = array('user' => false, 'planet' => false, 'que' => false);
    if (!$planet) {
        return $no_data;
    }
    $suffix = $simulation ? '' : 'FOR UPDATE';
    if (is_array($planet)) {
        if (!(isset($planet['id']) && $planet['id']) || !$simulation) {
            $planet = doquery("SELECT * FROM `{{planets}}` WHERE `galaxy` = '{$planet['galaxy']}' AND `system` = '{$planet['system']}' AND `planet` = '{$planet['planet']}' and `planet_type` = '{$planet['planet_type']}' LIMIT 1 {$suffix};", '', true);
        }
    } else {
        $planet = doquery("SELECT * FROM `{{planets}}` WHERE `id` = '{$planet}' LIMIT 1 {$suffix};", '', true);
    }
    if (!($planet && isset($planet['id']) && $planet['id'])) {
        return $no_data;
    }
    if (!$user || !is_array($user) || !isset($user['id'])) {
        $user = doquery("SELECT * FROM `{{users}}` WHERE `id` = {$planet['id_owner']} LIMIT 1 {$suffix};", '', true);
        if (!$user) {
            return $no_data;
        }
    }
    $ProductionTime = max(0, $UpdateTime - $planet['last_update']);
    $planet['last_update'] += $ProductionTime;
    $Caps = ECO_getPlanetCaps($user, $planet);
    $incRes = array('metal' => 0, 'crystal' => 0, 'deuterium' => 0);
    switch ($planet['planet_type']) {
        case PT_PLANET:
            foreach ($incRes as $resName => &$incCount) {
                //        $Caps['planet'][$resName] = max(0, $Caps['planet'][$resName]);
                $incCount = ($Caps[$resName . '_perhour'][0] + $Caps['planet'][$resName . '_perhour'] * $Caps['production']) * $ProductionTime / 3600;
                $store_free = $Caps['planet'][$resName . '_max'] - $Caps['planet'][$resName];
                //        $incCount = max(0, min($incCount, max(0, $store_free)));
                $incCount = min($incCount, max(0, $store_free));
                if ($planet[$resName] + $incCount < 0) {
                    $GLOBALS['debug']->warning("Player ID {$user['id']} have negative resources on ID {$planet['id']}.{$planet['planet_type']} [{$planet['galaxy']}:{$planet['system']}:{$planet['planet']}]. Difference {$planet[$resName]} of {$resName}", 'Negative Resources', 501);
                }
                $Caps['planet'][$resName] += $incCount;
                $Caps['planet'][$resName . '_perhour'] = $Caps['real'][$resName . '_perhour'];
            }
            break;
        case PT_MOON:
        default:
            $planet['metal_perhour'] = 0;
            $planet['crystal_perhour'] = 0;
            $planet['deuterium_perhour'] = 0;
            $planet['energy_used'] = 0;
            $planet['energy_max'] = 0;
            break;
    }
    $planet = array_merge($planet, $Caps['planet']);
    $que = eco_que_process($user, $planet, $ProductionTime);
    if ($simulation) {
        return array('user' => $user, 'planet' => $planet, 'que' => $que);
    }
    $QryUpdatePlanet = "UPDATE {{planets}} SET `last_update` = '{$planet['last_update']}', ";
    $QryUpdatePlanet .= "`metal`     = `metal`     + '{$incRes['metal']}', `crystal`   = `crystal`   + '{$incRes['crystal']}', `deuterium` = `deuterium` + '{$incRes['deuterium']}', ";
    $QryUpdatePlanet .= "`metal_perhour` = '{$planet['metal_perhour']}', `crystal_perhour` = '{$planet['crystal_perhour']}', `deuterium_perhour` = '{$planet['deuterium_perhour']}', ";
    $QryUpdatePlanet .= "`energy_used` = '{$planet['energy_used']}', `energy_max` = '{$planet['energy_max']}', ";
    $built = eco_bld_handle_que($user, $planet, $ProductionTime);
    if ($built['built']) {
        foreach ($built['built'] as $Element => $Count) {
            $Element = intval($Element);
            $Count = intval($Count);
            if ($Element) {
                $QryUpdatePlanet .= "`{$sn_data[$Element]['name']}` = `{$sn_data[$Element]['name']}` + '{$Count}', ";
            }
        }
        if (!$planet['b_hangar']) {
            msg_send_simple_message($user['id'], 0, $time_now, MSG_TYPE_QUE, $lang['msg_que_planet_from'], $lang['msg_que_hangar_subject'], sprintf($lang['msg_que_hangar_message'], uni_render_planet($planet)));
        }
    }
    $QryUpdatePlanet .= "`b_hangar_id` = '{$planet['b_hangar_id']}', ";
    $QryUpdatePlanet .= "`b_hangar` = '{$planet['b_hangar']}' ";
    $QryUpdatePlanet .= $que['query'] != $planet['que'] ? ",{$que['query']} " : '';
    if (!empty($que['built'])) {
        $message = array();
        foreach ($que['built'] as $unit_id => $built_count) {
            if ($built_count > 0) {
                $message[] = sprintf($lang['msg_que_built_message'], uni_render_planet($planet), $lang['tech'][$unit_id], $built_count);
            } else {
                $message[] = sprintf($lang['msg_que_destroy_message'], uni_render_planet($planet), $lang['tech'][$unit_id], -$built_count);
            }
        }
        msg_send_simple_message($user['id'], 0, $time_now, MSG_TYPE_QUE, $lang['msg_que_planet_from'], $lang['msg_que_built_subject'], implode('<br />', $message));
    }
    $QryUpdatePlanet .= "WHERE `id` = '{$planet['id']}' LIMIT 1;";
    doquery($QryUpdatePlanet);
    if (!empty($que['xp'])) {
        foreach ($que['xp'] as $xp_type => $xp_amount) {
            rpg_level_up($user, $xp_type, $xp_amount);
        }
    }
    // Can't use array_merge here - it will broke numeric array indexes those broke quest_id
    // TODO: Make own function for this
    foreach ($built['rewards'] as $quest_id => $quest_reward) {
        $que['rewards'][$quest_id] = $quest_reward;
    }
    qst_reward($user, $planet, $que['rewards'], $que['quests']);
    $planet['planet_caps'] = $Caps;
    return array('user' => $user, 'planet' => $planet, 'que' => $que);
}
/**
 * MissionCaseRecycling.php
 *
 * @version 1.0
 * @copyright 2008 By Chlorel for XNova
 */
function flt_mission_recycle(&$mission_data)
{
    $fleet_row =& $mission_data['fleet'];
    $destination_planet =& $mission_data['dst_planet'];
    if (!$fleet_row) {
        return CACHE_NOTHING;
    }
    if (!isset($destination_planet['id'])) {
        // doquery("UPDATE {{fleets}} SET `fleet_mess` = 1 WHERE `fleet_id` = {$fleet_row['fleet_id']} LIMIT 1;");
        flt_send_back($mission_data['fleet']);
        return CACHE_FLEET;
    }
    global $lang;
    $RecyclerCapacity = 0;
    $OtherFleetCapacity = 0;
    $fleet_array = sys_unit_str2arr($fleet_row['fleet_array']);
    foreach ($fleet_array as $unit_id => $unit_count) {
        if (in_array($unit_id, sn_get_groups('fleet'))) {
            $capacity = get_unit_param($unit_id, P_CAPACITY) * $unit_count;
            if (in_array($unit_id, sn_get_groups('flt_recyclers'))) {
                $RecyclerCapacity += $capacity;
            } else {
                $OtherFleetCapacity += $capacity;
            }
        }
    }
    $IncomingFleetGoods = $fleet_row["fleet_resource_metal"] + $fleet_row["fleet_resource_crystal"] + $fleet_row["fleet_resource_deuterium"];
    if ($IncomingFleetGoods > $OtherFleetCapacity) {
        $RecyclerCapacity -= $IncomingFleetGoods - $OtherFleetCapacity;
    }
    if ($destination_planet["debris_metal"] + $destination_planet["debris_crystal"] <= $RecyclerCapacity) {
        $RecycledGoods["metal"] = $destination_planet["debris_metal"];
        $RecycledGoods["crystal"] = $destination_planet["debris_crystal"];
    } else {
        if ($destination_planet["debris_metal"] > $RecyclerCapacity / 2 and $destination_planet["debris_crystal"] > $RecyclerCapacity / 2) {
            $RecycledGoods["metal"] = $RecyclerCapacity / 2;
            $RecycledGoods["crystal"] = $RecyclerCapacity / 2;
        } else {
            if ($destination_planet["debris_metal"] > $destination_planet["debris_crystal"]) {
                $RecycledGoods["crystal"] = $destination_planet["debris_crystal"];
                if ($destination_planet["debris_metal"] > $RecyclerCapacity - $RecycledGoods["crystal"]) {
                    $RecycledGoods["metal"] = $RecyclerCapacity - $RecycledGoods["crystal"];
                } else {
                    $RecycledGoods["metal"] = $destination_planet["debris_metal"];
                }
            } else {
                $RecycledGoods["metal"] = $destination_planet["debris_metal"];
                if ($destination_planet["debris_crystal"] > $RecyclerCapacity - $RecycledGoods["metal"]) {
                    $RecycledGoods["crystal"] = $RecyclerCapacity - $RecycledGoods["metal"];
                } else {
                    $RecycledGoods["crystal"] = $destination_planet["debris_crystal"];
                }
            }
        }
    }
    $NewCargo['Metal'] = $fleet_row["fleet_resource_metal"] + $RecycledGoods["metal"];
    $NewCargo['Crystal'] = $fleet_row["fleet_resource_crystal"] + $RecycledGoods["crystal"];
    $NewCargo['Deuterium'] = $fleet_row["fleet_resource_deuterium"];
    db_planet_set_by_gspt($fleet_row['fleet_end_galaxy'], $fleet_row['fleet_end_system'], $fleet_row['fleet_end_planet'], PT_PLANET, "`debris_metal` = `debris_metal` - '{$RecycledGoods['metal']}', `debris_crystal` = `debris_crystal` - '{$RecycledGoods['crystal']}'");
    $Message = sprintf($lang['sys_recy_gotten'], pretty_number($RecycledGoods["metal"]), $lang['Metal'], pretty_number($RecycledGoods["crystal"]), $lang['Crystal']);
    msg_send_simple_message($fleet_row['fleet_owner'], '', $fleet_row['fleet_start_time'], MSG_TYPE_RECYCLE, $lang['sys_mess_spy_control'], $lang['sys_recy_report'], $Message);
    $QryUpdateFleet = "UPDATE {{fleets}} SET `fleet_mess` = 1,`fleet_resource_metal` = '{$NewCargo['Metal']}',`fleet_resource_crystal` = '{$NewCargo['Crystal']}',`fleet_resource_deuterium` = '{$NewCargo['Deuterium']}' ";
    $QryUpdateFleet .= "WHERE `fleet_id` = '{$fleet_row['fleet_id']}' LIMIT 1;";
    doquery($QryUpdateFleet);
    return CACHE_FLEET | CACHE_PLANET_DST;
}
Exemple #15
0
 }
 $re ? $subject = $lang['msg_answer_prefix'] . $subject : false;
 if (sys_get_param_str('msg_send')) {
     $subject = $subject ? $subject : $lang['msg_subject_default'];
     if (!$recipient_id) {
         $error_list[] = array('MESSAGE' => $lang['msg_err_player_not_found'], 'STATUS' => ERR_ERROR);
     }
     $text = sys_get_param_str('text');
     if (!$text) {
         $error_list[] = array('MESSAGE' => $lang['msg_err_no_text'], 'STATUS' => ERR_ERROR);
     }
     if (empty($error_list)) {
         $error_list[] = array('MESSAGE' => $lang['msg_not_message_sent'], 'STATUS' => ERR_NONE);
         $user_safe_name = db_escape($user['username']);
         $recipient_name = db_escape($recipient_name);
         msg_send_simple_message($recipient_id, $user['id'], SN_TIME_NOW, MSG_TYPE_PLAYER, "{$user_safe_name} [{$user['galaxy']}:{$user['system']}:{$user['planet']}]", $subject, $text, true);
         //$recipient_id = 0;
         //$recipient_name = '';
         //$subject = '';
         $text = '';
         $msg_sent = true;
     } else {
         $subject = sys_get_param_str_unsafe('subject');
         $text = sys_get_param_str_unsafe('text');
     }
     $recipient_name = sys_get_param_str_unsafe('recipient_name');
 }
 $subject = $subject ? $subject : $lang['msg_subject_default'];
 $template->assign_vars(array('RECIPIENT_ID' => $recipient_id, 'RECIPIENT_NAME' => htmlspecialchars($recipient_name), 'SUBJECT' => htmlspecialchars($subject), 'TEXT' => htmlspecialchars($text)));
 foreach ($error_list as $error_message) {
     $template->assign_block_vars('result', $error_message);
Exemple #16
0
    if (!empty($text)) {
        $idAnnounce = sys_get_param_int('id');
        $dtDateTime = empty($announce_time) ? "FROM_UNIXTIME(" . time() . ")" : "'{$announce_time}'";
        if ($mode == 'edit') {
            doquery("UPDATE {{announce}} SET `tsTimeStamp`={$dtDateTime}, `strAnnounce`='{$text}', detail_url = '{$detail_url}' WHERE `idAnnounce`={$idAnnounce}");
        } else {
            doquery("INSERT INTO {{announce}} SET `tsTimeStamp`={$dtDateTime}, `strAnnounce`='{$text}', detail_url = '{$detail_url}'");
        }
        doquery("UPDATE {{users}} SET `news_lastread` = `news_lastread` + 1;");
        if (sys_get_param_int('news_mass_mail')) {
            $text = $_POST['text'];
            if ($detail_url) {
                // TODO: Move merging detail url to template
                $text = "{$text} <a href=\"{$detail_url}\">{$lang['news_more']}</a>";
            }
            msg_send_simple_message('*', 0, 0, MSG_TYPE_ADMIN, $lang['sys_administration'], $lang['news_title'], $text);
        }
        $mode = '';
    }
    switch ($mode) {
        case 'del':
            doquery("DELETE FROM {{announce}} WHERE `idAnnounce`={$announce_id} LIMIT 1;");
            $mode = '';
            break;
        case 'edit':
            $template->assign_var('ID', $announce_id);
        case 'copy':
            $announce = doquery("SELECT * FROM {{announce}} WHERE `idAnnounce`={$announce_id} LIMIT 1;", '', true);
            break;
    }
} else {
/**
 * This file is under the GPL liscence, which must be included with the file under distrobution (license.txt)
 * this file was made by Xnova, edited to support Toms combat engine by Anthony (MadnessReD) [http://madnessred.co.cc/]
 * Do not edit this comment block
 */
function flt_mission_attack($mission_data)
{
    global $lang, $sn_data, $time_now;
    $fleet_row = $mission_data['fleet'];
    $destination_user = $mission_data['dst_user'];
    $destination_planet = $mission_data['dst_planet'];
    if (!$fleet_row) {
        return;
    }
    if (!$destination_user || !$destination_planet || !is_array($destination_user) || !is_array($destination_planet)) {
        doquery("UPDATE {{fleets}} SET `fleet_mess` = 1 WHERE `fleet_id` = {$fleet_row['fleet_id']} LIMIT 1;");
        return;
    }
    $TargetUserID = $destination_planet['id_owner'];
    $attackFleets = array();
    // ACS function: put all fleet into an array
    if ($fleet_row['fleet_group'] != 0) {
        $fleets = doquery('SELECT * FROM {{fleets}} WHERE fleet_group=' . $fleet_row['fleet_group']);
        while ($fleet = mysql_fetch_assoc($fleets)) {
            BE_attackFleetFill(&$attackFleets, $fleet);
        }
    } else {
        BE_attackFleetFill(&$attackFleets, $fleet_row);
    }
    $db_admiral_name = $sn_data[MRC_ADMIRAL]['name'];
    $defenseFleets = array(0 => array('def' => array(), 'user' => array('id' => $destination_user['id'], 'username' => $destination_user['username'], $db_admiral_name => $destination_user[$db_admiral_name], 'defence_tech' => $destination_user['defence_tech'], 'shield_tech' => $destination_user['shield_tech'], 'military_tech' => $destination_user['military_tech'])));
    foreach ($sn_data['groups']['combat'] as $combatUnitID) {
        if ($destination_planet[$sn_data[$combatUnitID]['name']] > 0) {
            $defenseFleets[0]['def'][$combatUnitID] = $destination_planet[$sn_data[$combatUnitID]['name']];
        }
    }
    $fleets = doquery('SELECT * FROM {{fleets}} WHERE `fleet_end_galaxy` = ' . $fleet_row['fleet_end_galaxy'] . ' AND `fleet_end_system` = ' . $fleet_row['fleet_end_system'] . ' AND `fleet_end_planet` = ' . $fleet_row['fleet_end_planet'] . ' AND `fleet_end_type` = ' . $fleet_row['fleet_end_type'] . ' AND fleet_start_time<' . $time_now . ' AND fleet_end_stay>=' . $time_now);
    while ($fleet = mysql_fetch_assoc($fleets)) {
        BE_attackFleetFill(&$defenseFleets, $fleet, 'def');
    }
    $start = microtime(true);
    $result = coe_attack_calculate($attackFleets, $defenseFleets);
    $totaltime = microtime(true) - $start;
    // Update galaxy (debree)
    if ($destination_user['authlevel'] == 0) {
        doquery('UPDATE {{planets}} SET `debris_metal` = `debris_metal` + ' . ($result['debree']['att'][0] + $result['debree']['def'][0]) . ' , debris_crystal = debris_crystal+' . ($result['debree']['att'][1] + $result['debree']['def'][1]) . ' WHERE `galaxy` = ' . $fleet_row['fleet_end_galaxy'] . ' AND `system` = ' . $fleet_row['fleet_end_system'] . ' AND `planet` = ' . $fleet_row['fleet_end_planet'] . ' AND `planet_type` = 1 LIMIT 1;');
    }
    // !G+ post-calculation for Attackers: fleet left and possible loot
    $loot = BE_calculatePostAttacker($destination_planet, $attackFleets, $result, false);
    if ($result['won'] == 2 && count($result['rw']) == 2) {
        $one_round_loss = true;
    } else {
        $one_round_loss = false;
    }
    // Update fleets & planets
    foreach ($attackFleets as $fleetID => $attacker) {
        if ($attacker['totalCount'] > 0) {
            $sqlQuery = 'UPDATE {{fleets}} SET ';
            if ($result['won'] == 1) {
                $sqlQuery .= '`fleet_resource_metal` = `fleet_resource_metal` + ' . ($attacker['loot']['metal'] + 0) . ', ';
                $sqlQuery .= '`fleet_resource_crystal` = `fleet_resource_crystal` + ' . ($attacker['loot']['crystal'] + 0) . ', ';
                $sqlQuery .= '`fleet_resource_deuterium` = `fleet_resource_deuterium` + ' . ($attacker['loot']['deuterium'] + 0) . ', ';
            }
            $sqlQuery .= '`fleet_array` = "' . substr($attacker['fleetArray'], 0, -1) . '", ';
            $sqlQuery .= '`fleet_amount` = ' . $attacker['totalCount'] . ', `fleet_mess` = 1 WHERE `fleet_id` = ' . $fleetID;
            doquery($sqlQuery);
        }
    }
    if ($fleet_row['fleet_mission'] == MT_AKS && $fleet_row['fleet_group']) {
        doquery("DELETE FROM {{aks}} WHERE id={$fleet_row['fleet_group']} LIMIT 1;");
        doquery("UPDATE {{fleets}} SET fleet_group = 0 WHERE fleet_group = {$fleet_row['fleet_group']} AND fleet_mission = " . MT_AKS . ";");
    }
    foreach ($defenseFleets as $fleetID => $defender) {
        $fleetArray = '';
        $totalCount = 0;
        if ($fleetID == 0) {
            foreach ($defender['def'] as $element => $amount) {
                $fleetArray .= "`{$sn_data[$element]['name']}` = '{$amount}', ";
            }
            doquery('UPDATE {{planets}} SET ' . $fleetArray . ' metal = metal - ' . $loot['looted']['metal'] . ', crystal = crystal - ' . $loot['looted']['crystal'] . ', deuterium=deuterium-' . $loot['looted']['deuterium'] . ' WHERE id=' . $destination_planet['id']);
        } else {
            foreach ($defender['def'] as $element => $amount) {
                if ($amount) {
                    $fleetArray .= $element . ',' . $amount . ';';
                }
                $totalCount += $amount;
            }
            if ($totalCount <= 0) {
                doquery("DELETE FROM `{{fleets}}` WHERE `fleet_id` = '{$fleetID}'");
            } else {
                doquery("UPDATE {{fleets}} SET fleet_array = '{$fleetArray}', fleet_amount = {$totalCount}" . ($one_round_loss ? '' : ', fleet_mess = 1') . " WHERE fleet_id = {$fleetID} LIMIT 1;");
            }
        }
    }
    // TvdW (c) 2008
    $planet_coordinates = uni_render_coordinates($fleet_row, 'fleet_end_');
    // FROM HERE THE SCRIPT WAS IMPORTED (not TvdW code anymore)
    $MoonChance = BE_calculateMoonChance($result);
    if (mt_rand(1, 100) <= $MoonChance && ($TargetPlanetName = uni_create_moon($fleet_row['fleet_end_galaxy'], $fleet_row['fleet_end_system'], $fleet_row['fleet_end_planet'], $TargetUserID, $MoonChance))) {
        $GottenMoon = sprintf($lang['sys_moonbuilt'], $TargetPlanetName, $planet_coordinates);
    }
    // Adjust number of raids made/win/loose and xpraid
    $str_loose_or_win = $result['won'] == 1 ? 'raidswin' : 'raidsloose';
    doquery("UPDATE {{users}} SET `xpraid` = `xpraid` + 1, `raids` = `raids` + 1, `{$str_loose_or_win}` = `{$str_loose_or_win}` + 1 WHERE id = '{$fleet_row['fleet_owner']}' LIMIT 1;");
    $bashing_list = array();
    foreach ($defenseFleets as $fleetID => $defender) {
        $users2[$defender['user']['id']] = $users_defender[$defender['user']['id']] = $defender['user']['id'];
    }
    foreach ($attackFleets as $fleetID => $attacker) {
        $users2[$attacker['user']['id']] = $users_attacker[$attacker['user']['id']] = $attacker['user']['id'];
        // Generating attackers list for bashing table
        $bashing_list[$attacker['user']['id']] = "({$attacker['user']['id']}, {$destination_planet['id']}, {$fleet_row['fleet_end_time']})";
    }
    $bashing_list = implode(',', $bashing_list);
    doquery("INSERT INTO {{bashing}} (bashing_user_id, bashing_planet_id, bashing_time) VALUES {$bashing_list};");
    //MadnessRed CR Creation.
    $raport = formatCR($result, $loot['looted'], $MoonChance, $GottenMoon, $totaltime);
    $raport = $raport['html'];
    $rid = md5($raport);
    $QryInsertRapport = 'INSERT INTO `{{rw}}` SET ';
    $QryInsertRapport .= '`time` = UNIX_TIMESTAMP(), ';
    $QryInsertRapport .= '`owners` = "' . implode(',', $users2) . '", ';
    $QryInsertRapport .= '`id_owner1` = "' . $attacker['user']['id'] . '", ';
    $QryInsertRapport .= '`id_owner2` = "' . $defender['user']['id'] . '", ';
    $QryInsertRapport .= '`rid` = "' . $rid . '", ';
    $QryInsertRapport .= '`raport` = "' . mysql_real_escape_string($raport) . '"';
    doquery($QryInsertRapport) or die("Error inserting CR to database" . mysql_error() . "<br /><br />Trying to execute:" . mysql_query());
    switch ($result['won']) {
        case 0:
            $color_attackers = $color_defenders = 'orange';
            break;
        case 1:
            $color_attackers = 'green';
            $color_defenders = 'red';
            break;
        case 2:
            $color_attackers = 'red';
            $color_defenders = 'green';
            break;
    }
    $raport_part1 = '<span OnClick=\'f("rw.php?raport=' . $rid . '", "");\' ><center><font color=';
    $raport_part2 = ">{$lang['sys_mess_attack_report']} {$planet_coordinates}</font></span><br /><br />" . "<font color=\"red\">{$lang['sys_perte_attaquant']}: " . pretty_number($result['lost']['att'], true) . "</font>&nbsp;<font color=\"green\">{$lang['sys_perte_defenseur']}: " . pretty_number($result['lost']['def'], true) . "</font><br />" . "{$lang['sys_debris']} {$lang['Metal']} <font color=\"#adaead\">" . pretty_number($result['debree']['att'][0] + $result['debree']['def'][0], true) . "</font> {$lang['Crystal']} <font color=\"#ef51ef\">" . pretty_number($result['debree']['att'][1] + $result['debree']['def'][1], true) . '</font><br />' . ($result['won'] == 1 ? "{$lang['sys_gain']} " . "{$lang['Metal']} <font color=\"#adaead\">" . pretty_number($loot['looted']['metal'], true) . '</font> ' . "{$lang['Crystal']} <font color=\"#ef51ef\">" . pretty_number($loot['looted']['crystal'], true) . '</font> ' . "{$lang['Deuterium']} <font color=\"#f77542\">" . pretty_number($loot['looted']['deuterium'], true) . '</font><br />' : '') . "{$st_1}{$st_2}</center>";
    $raport_acs = $one_round_loss ? "<center><span class=\"negative\">{$lang['sys_mess_attack_report']} {$planet_coordinates}\r\n{$lang['sys_coe_lost_contact']}</span></center>" : "{$raport_part1}{$color_attackers}{$raport_part2}";
    foreach ($users_attacker as $id) {
        //    if ($id != $fleet_row['fleet_owner'] && $id != 0)
        if ($id) {
            msg_send_simple_message($id, '', $fleet_row['fleet_start_time'], MSG_TYPE_COMBAT, $lang['sys_mess_tower'], $lang['sys_mess_attack_report'], $raport_acs);
        }
    }
    $raport_hold = "{$raport_part1}{$color_defenders}{$raport_part2}";
    foreach ($users_defender as $id) {
        if ($id && $id != $fleet_row['fleet_owner']) {
            msg_send_simple_message($id, '', $fleet_row['fleet_start_time'], MSG_TYPE_COMBAT, $lang['sys_mess_tower'], $lang['sys_mess_attack_report'], $raport_hold);
        }
    }
    return $result;
}
Exemple #18
0
     $error_list[] = array('TEXT' => $lang['msg_err_self_send'], 'CLASS' => 'error');
 }
 $subject = sys_get_param_str('subject');
 if (sys_get_param_str('msg_send')) {
     $subject = $subject ? $subject : $lang['msg_subject_default'];
     if (!$recipient_id) {
         $error_list[] = array('TEXT' => $lang['msg_err_player_not_found'], 'CLASS' => 'error');
     }
     $text = sys_get_param_str('text');
     if (!$text) {
         $error_list[] = array('TEXT' => $lang['msg_err_no_text'], 'CLASS' => 'error');
     }
     if (empty($error_list)) {
         $error_list[] = array('TEXT' => $lang['msg_not_message_sent'], 'CLASS' => 'success');
         $recipient_name = mysql_real_escape_string($recipient_name);
         msg_send_simple_message($recipient_id, $user['id'], $time_now, MSG_TYPE_PLAYER, "{$user['username']} [{$user['galaxy']}:{$user['system']}:{$user['planet']}]", $subject, $text, true);
         $recipient_id = 0;
         $recipient_name = '';
         $subject = '';
         $text = '';
         $msg_sent = true;
     } else {
         $recipient_name = sys_get_param_str_raw('recipient_name');
         $subject = sys_get_param_str_raw('subject');
         $text = sys_get_param_str_raw('text');
     }
 }
 $subject = $subject ? $subject : $lang['msg_subject_default'];
 $template->assign_vars(array('RECIPIENT_ID' => $recipient_id, 'RECIPIENT_NAME' => $recipient_name, 'SUBJECT' => $subject, 'TEXT' => $text));
 foreach ($error_list as $error_message) {
     $template->assign_block_vars('messages', $error_message);
function sn_ube_message_send(&$combat_data)
{
    global $lang;
    // TODO: Отсылать каждому игроку сообщение на его языке!
    $outcome =& $combat_data[UBE_OUTCOME];
    $planet_info =& $outcome[UBE_PLANET];
    // Генерируем текст письма
    $text_common = sprintf($lang['ube_report_msg_body_common'], date(FMT_DATE_TIME, $combat_data['UBE_TIME']), $lang['sys_planet_type_sh'][$planet_info[PLANET_TYPE]], $planet_info[PLANET_GALAXY], $planet_info[PLANET_SYSTEM], $planet_info[PLANET_PLANET], htmlentities($planet_info[PLANET_NAME], ENT_COMPAT, 'UTF-8'), $lang[$outcome['UBE_COMBAT_RESULT'] == UBE_COMBAT_RESULT_WIN ? 'ube_report_info_outcome_win' : ($outcome['UBE_COMBAT_RESULT'] == UBE_COMBAT_RESULT_DRAW ? 'ube_report_info_outcome_draw' : 'ube_report_info_outcome_loss')]);
    $text_defender = '';
    foreach ($outcome[UBE_DEBRIS] as $resource_id => $resource_amount) {
        if ($resource_id == RES_DEUTERIUM) {
            continue;
        }
        $text_defender .= "{$lang['tech'][$resource_id]}: " . pretty_number($resource_amount) . '<br />';
    }
    if ($text_defender) {
        $text_defender = "{$lang['ube_report_msg_body_debris']}{$text_defender}<br />";
    }
    if ($outcome[UBE_MOON] == UBE_MOON_CREATE_SUCCESS) {
        $text_defender .= "{$lang['ube_report_moon_created']} {$outcome[UBE_MOON_SIZE]} {$lang['sys_kilometers_short']}<br /><br />";
    } elseif ($outcome[UBE_MOON] == UBE_MOON_CREATE_FAILED) {
        $text_defender .= "{$lang['ube_report_moon_chance']} {$outcome[UBE_MOON_CHANCE]}%<br /><br />";
    }
    if ($combat_data[UBE_OPTIONS][UBE_MISSION_TYPE] == MT_DESTROY) {
        if ($outcome[UBE_MOON_REAPERS] == UBE_MOON_REAPERS_NONE) {
            $text_defender .= $lang['ube_report_moon_reapers_none'];
        } else {
            $text_defender .= "{$lang['ube_report_moon_reapers_wave']}. {$lang['ube_report_moon_reapers_chance']} {$outcome[UBE_MOON_DESTROY_CHANCE]}%. ";
            $text_defender .= $lang[$outcome[UBE_MOON] == UBE_MOON_DESTROY_SUCCESS ? 'ube_report_moon_reapers_success' : 'ube_report_moon_reapers_failure'] . "<br />";
            $text_defender .= "{$lang['ube_report_moon_reapers_outcome']} {$outcome[UBE_MOON_REAPERS_DIE_CHANCE]}%. ";
            $text_defender .= $lang[$outcome[UBE_MOON_REAPERS] == UBE_MOON_REAPERS_RETURNED ? 'ube_report_moon_reapers_survive' : 'ube_report_moon_reapers_died'];
        }
        $text_defender .= '<br /><br />';
    }
    $text_defender .= "{$lang['ube_report_info_link']}: <a href=\"index.php?page=battle_report&cypher={$combat_data[UBE_REPORT_CYPHER]}\">{$combat_data[UBE_REPORT_CYPHER]}</a>";
    // TODO: Оптимизировать отсылку сообщений - отсылать пакетами
    foreach ($combat_data[UBE_PLAYERS] as $player_id => $player_info) {
        $message = $text_common . ($outcome[UBE_SFR] && $player_info[UBE_ATTACKER] ? $lang['ube_report_msg_body_sfr'] : $text_defender);
        msg_send_simple_message($player_id, '', $combat_data[UBE_TIME], MSG_TYPE_COMBAT, $lang['sys_mess_tower'], $lang['sys_mess_attack_report'], $message);
    }
}
Exemple #20
0
 public function password_change($old_password_unsafe, $new_password_unsafe)
 {
     global $lang;
     if (empty($this->providers_authorised)) {
         // TODO - такого быть не может!
         self::flog("Не найдено ни одного авторизированного провайдера в self::\$providers_authorised", true);
         return false;
     }
     // TODO - Проверять пароль на корректность
     // TODO - Не менять (?) пароль у аккаунтов, к которым пристёгнут хоть один игрок с AUTH_LEVEL > 0
     $salt_unsafe = self::password_salt_generate();
     $providers_changed_password = array();
     foreach ($this->providers_authorised as $provider_id => $provider) {
         if (!$provider->is_feature_supported(AUTH_FEATURE_PASSWORD_CHANGE) || !$provider->password_change($old_password_unsafe, $new_password_unsafe, $salt_unsafe)) {
             continue;
         }
         // Узнаем список игроков, которые прикреплены к этому аккаунту
         // $account_translation = self::db_translate_get_users_from_account_list($provider_id, $provider->account->account_id);
         $account_translation = PlayerToAccountTranslate::db_translate_get_users_from_account_list($provider_id, $provider->account->account_id);
         // Рассылаем уведомления о смене пароля в ЛС
         foreach ($account_translation as $user_id => $provider_info) {
             // TODO - УКазывать тип аккаунта, на котором сменён пароль
             msg_send_simple_message($user_id, 0, SN_TIME_NOW, MSG_TYPE_ADMIN, $lang['sys_administration'], $lang['sys_login_register_message_title'], sprintf($lang['sys_login_register_message_body'], $provider->account->account_name, $new_password_unsafe), false);
         }
         $providers_changed_password[$provider_id] = $provider;
     }
     // TODO - отсылать уведомление на емейл
     return !empty($providers_changed_password);
 }
Exemple #21
0
function flt_mission_spy($mission_data)
{
    global $time_now;
    $fleet_row = $mission_data['fleet'];
    $target_user_row = $mission_data['dst_user'];
    $target_planet_row = $mission_data['dst_planet'];
    $spying_user_row = $mission_data['src_user'];
    $spying_planet_row = $mission_data['src_planet'];
    if (!$target_user_row || !$target_planet_row || !is_array($target_user_row) || !is_array($target_planet_row)) {
        doquery("UPDATE {{fleets}} SET `fleet_mess` = 1 WHERE `fleet_id` = {$fleet_row['fleet_id']} LIMIT 1;");
        return;
    }
    $fleet_array = sys_unit_str2arr($fleet_row['fleet_array']);
    if ($fleet_array[SHIP_SPY] > 0) {
        $TargetSpyLvl = GetSpyLevel($target_user_row);
        //mrc_modify_value($target_user_row, $target_planet_row, MRC_SPY, GetSpyLevel($target_user_row));
        $CurrentSpyLvl = GetSpyLevel($spying_user_row);
        //mrc_modify_value($spying_user_row, $spying_planet_row, MRC_SPY, GetSpyLevel($spying_user_row));
        $spy_probes = $fleet_array[SHIP_SPY];
        $spy_diff = $CurrentSpyLvl + sqrt($spy_probes) - 1 - $TargetSpyLvl;
        /*
            pdump($spy_probes, '$spy_probes');
            pdump($CurrentSpyLvl, '$CurrentSpyLvl');
            pdump($TargetSpyLvl, '$TargetSpyLvl');
            pdump(sqrt($spy_probes), 'sqrt($spy_probes)');
            pdump($spy_diff, '$spy_diff');
        */
        global $lang, $sn_data;
        $spy_resources = flt_spy_scan($target_planet_row, 0, $lang['sys_spy_maretials'], $target_user_row['username']);
        $spy_info = flt_spy_scan($target_planet_row, 1, $lang['sys_spy_fleet']);
        $spy_fleet = "<div class='spy_medium'>{$spy_info}</div>";
        $spy_info = flt_spy_scan($target_planet_row, 2, $lang['sys_spy_defenses']);
        $spy_defence = "<div class='spy_medium'>{$spy_info}</div>";
        $spy_info = flt_spy_scan($target_planet_row, 3, $lang['tech'][0]);
        $spy_buildings = "<div class='spy_long'>{$spy_info}</div>";
        $combat_pack[0] = array(RES_METAL => $target_planet_row['metal'], RES_CRYSTAL => $target_planet_row['crystal'], RES_DEUTERIUM => $target_planet_row['deuterium']);
        $spy_message = $spy_resources;
        if ($spy_diff >= 2) {
            $spy_message .= $spy_fleet;
            coe_compress_add_units($sn_data['groups']['fleet'], $target_planet_row, $combat_pack[0]);
        }
        if ($spy_diff >= 3) {
            $spy_message .= $spy_defence;
            coe_compress_add_units($sn_data['groups']['defense_active'], $target_planet_row, $combat_pack[0]);
        }
        if ($spy_diff >= 5) {
            $spy_message .= $spy_buildings;
        }
        if ($spy_diff >= 7) {
            $spy_info = flt_spy_scan($target_user_row, 4, $lang['tech'][TECH_TECHNOLOGY]);
            $spy_tech = "<div class='spy_long'>{$spy_info}</div>";
            $spy_message .= $spy_tech;
            coe_compress_add_units(array(TECH_WEAPON, TECH_SHIELD, TECH_ARMOR), $target_user_row, $combat_pack[0]);
        }
        $simulator_link = eco_sym_encode_replay($combat_pack, 'D');
        $target_unit_list = 0;
        foreach ($sn_data['groups']['fleet'] as $unit_id) {
            $target_unit_list += max(0, $target_planet_row[$sn_data[$unit_id]['name']]);
        }
        $spy_detected = $spy_probes * $target_unit_list / 4 * pow(2, $TargetSpyLvl - $CurrentSpyLvl);
        if (mt_rand(0, 99) > $spy_detected) {
            $DestProba = sprintf($lang['sys_mess_spy_detect_chance'], $spy_detected);
            $spy_detected = false;
        } else {
            $DestProba = $lang['sys_mess_spy_destroyed'];
            $spy_detected = true;
        }
        $spy_message .= "<br /><center><a href=\"fleet.php?target_mission=1&planet_type={$fleet_row['fleet_end_type']}&galaxy={$fleet_row['fleet_end_galaxy']}";
        $spy_message .= "&system={$fleet_row['fleet_end_system']}&planet={$fleet_row['fleet_end_planet']} \">{$lang['type_mission'][1]}</a></center>";
        $spy_message .= "<center><a href=\"simulator.php?replay={$simulator_link}\">{$lang['COE_combatSimulator']}</a></center><br />";
        $spy_message .= "<center>" . $DestProba . "</center>";
        // End of link generation
        msg_send_simple_message($spying_user_row['id'], '', $fleet_row['fleet_start_time'], MSG_TYPE_SPY, $lang['sys_mess_qg'], $lang['sys_mess_spy_report'], $spy_message);
        $TargetMessage = $lang['sys_mess_spy_ennemyfleet'] . " " . $spying_planet_row['name'];
        $TargetMessage .= "<a href=\"galaxy.php?mode=3&galaxy=" . $spying_planet_row["galaxy"] . "&system=" . $spying_planet_row["system"] . "\">";
        $TargetMessage .= "[" . $spying_planet_row["galaxy"] . ":" . $spying_planet_row["system"] . ":" . $spying_planet_row["planet"] . "]</a> ";
        $TargetMessage .= $lang['sys_mess_spy_seen_at'] . " " . $target_planet_row['name'];
        $TargetMessage .= " [" . $target_planet_row["galaxy"] . ":" . $target_planet_row["system"] . ":" . $target_planet_row["planet"] . "].";
        $target_user_id = $fleet_row['fleet_target_owner'];
        if ($spy_detected) {
            doquery("DELETE FROM {{fleets}} WHERE `fleet_id` = '{$fleet_row['fleet_id']}' LIMIT 1;");
            if ($target_planet_row['planet_type'] == PT_PLANET) {
                $debris_planet_id = $target_planet_row['id'];
            } else {
                $debris_planet_id = $target_planet_row['parent_planet'];
            }
            $QryUpdateGalaxy = "UPDATE {{planets}} SET ";
            $QryUpdateGalaxy .= "`debris_metal` = `debris_metal` + '" . floor($spy_probes * $sn_data[SHIP_SPY]['metal'] * 0.3) . "', ";
            $QryUpdateGalaxy .= "`debris_crystal` = `debris_crystal` + '" . floor($spy_probes * $sn_data[SHIP_SPY]['crystal'] * 0.3) . "' ";
            $QryUpdateGalaxy .= "WHERE `id` = '{$debris_planet_id}' LIMIT 1;";
            doquery($QryUpdateGalaxy);
            $TargetMessage .= "<br />{$lang['sys_mess_spy_destroyed_enemy']}";
            //      msg_send_simple_message ( $target_user_id, '', $fleet_row['fleet_start_time'], MSG_TYPE_SPY, $lang['sys_mess_spy_control'], $lang['sys_mess_spy_activity'], $TargetMessage . );
            $result = CACHE_FLEET | CACHE_PLANET_DST;
        } else {
            $result = CACHE_FLEET;
        }
        msg_send_simple_message($target_user_id, '', $fleet_row['fleet_start_time'], MSG_TYPE_SPY, $lang['sys_mess_spy_control'], $lang['sys_mess_spy_activity'], $TargetMessage);
    }
    if (!$spy_detected) {
        doquery("UPDATE {{fleets}} SET `fleet_mess` = '1' WHERE `fleet_id` = '{$fleet_row['fleet_id']}' LIMIT 1;");
    }
    return $result;
}
Exemple #22
0
function qst_reward(&$user, &$planet, &$rewards, &$quest_list)
{
    global $lang, $sn_data;
    foreach ($rewards as $quest_id => $rewards_list_string) {
        $comment_reward = array();
        $planet_reward = array();
        $user_reward = array();
        $user_reward_dm = 0;
        $comment = sprintf($lang['qst_msg_complete_body'], $quest_list[$quest_id]['quest_name']);
        $rewards_list_array = explode(';', $rewards_list_string);
        foreach ($rewards_list_array as $reward_string) {
            list($reward_id, $reward_amount) = explode(',', $reward_string);
            $reward_db_name = $sn_data[$reward_id]['name'];
            $reward_db_string = "`{$reward_db_name}` = `{$reward_db_name}` + {$reward_amount}";
            if ($reward_id == RES_DARK_MATTER) {
                $user_reward_dm = $reward_amount;
            }
            if ($sn_data[$reward_id]['location'] == LOC_USER) {
                $user[$reward_db_name] += $reward_amount;
                $user_reward[] = $reward_db_string;
            } elseif ($sn_data[$reward_id]['location'] == LOC_PLANET) {
                $planet[$reward_db_name] += $reward_amount;
                $planet_reward[] = $reward_db_string;
            } else {
                continue;
            }
            $comment_reward[] = $reward_amount . ' ' . $lang['tech'][$reward_id];
        }
        if (!empty($comment_reward)) {
            $comment .= " {$lang['qst_msg_your_reward']} " . implode(',', $comment_reward);
            if (!empty($user_reward)) {
                $user_reward = implode(',', $user_reward);
                doquery("UPDATE {{users}} SET {$user_reward} WHERE `id` = {$user['id']} LIMIT 1;");
                if ($user_reward_dm) {
                    rpg_points_change($user['id'], RPG_QUEST, $user_reward_dm, $comment, true);
                }
            }
            if (!empty($planet_reward)) {
                $planet_reward = implode(',', $planet_reward);
                doquery("UPDATE {{planets}} SET {$planet_reward} WHERE `id` = {$planet['id']} LIMIT 1;");
            }
        }
        sn_db_perform('{{quest_status}}', array('quest_status_quest_id' => $quest_id, 'quest_status_user_id' => $user['id'], 'quest_status_status' => QUEST_STATUS_COMPLETE));
        msg_send_simple_message($user['id'], 0, $time_now, MSG_TYPE_ADMIN, $lang['msg_from_admin'], $lang['qst_msg_complete_subject'], $comment);
    }
}
/**
 * MissionCaseRecycling.php
 *
 * @version 1.0
 * @copyright 2008 By Chlorel for XNova
 */
function flt_mission_recycle($mission_data)
{
    $fleet_row = $mission_data['fleet'];
    $destination_planet = $mission_data['dst_planet'];
    if (!$fleet_row) {
        return CACHE_NOTHING;
    }
    if (!$destination_planet || !is_array($destination_planet)) {
        doquery("UPDATE {{fleets}} SET `fleet_mess` = 1 WHERE `fleet_id` = {$fleet_row['fleet_id']} LIMIT 1;");
        return CACHE_FLEET;
    }
    global $sn_data, $lang;
    /*
    
    // Это надо будет вставить наверное в RestoreFleetToPlanet
          $Message         = sprintf( $lang['sys_tran_mess_owner'],
                $StartName, GetStartAdressLink($fleet_row, ''),
                pretty_number($fleet_row['fleet_resource_metal']), $lang['Metal'],
                pretty_number($fleet_row['fleet_resource_crystal']), $lang['Crystal'],
                pretty_number($fleet_row['fleet_resource_deuterium']), $lang['Deuterium'] );
          SendSimpleMessage ( $fleet_row['fleet_owner'], '', $fleet_row['fleet_end_time'], 4, $lang['sys_mess_spy_control'], $lang['sys_mess_fleetback'], $Message);
    */
    $FleetRecord = explode(";", $fleet_row['fleet_array']);
    $RecyclerCapacity = 0;
    $OtherFleetCapacity = 0;
    foreach ($FleetRecord as $Item => $Group) {
        if ($Group != '') {
            $Class = explode(",", $Group);
            if ($Class[0] == SHIP_RECYCLER) {
                $RecyclerCapacity += $sn_data[$Class[0]]["capacity"] * $Class[1];
            } else {
                $OtherFleetCapacity += $sn_data[$Class[0]]["capacity"] * $Class[1];
            }
        }
    }
    $IncomingFleetGoods = $fleet_row["fleet_resource_metal"] + $fleet_row["fleet_resource_crystal"] + $fleet_row["fleet_resource_deuterium"];
    if ($IncomingFleetGoods > $OtherFleetCapacity) {
        $RecyclerCapacity -= $IncomingFleetGoods - $OtherFleetCapacity;
    }
    if ($destination_planet["debris_metal"] + $destination_planet["debris_crystal"] <= $RecyclerCapacity) {
        $RecycledGoods["metal"] = $destination_planet["debris_metal"];
        $RecycledGoods["crystal"] = $destination_planet["debris_crystal"];
    } else {
        if ($destination_planet["debris_metal"] > $RecyclerCapacity / 2 and $destination_planet["debris_crystal"] > $RecyclerCapacity / 2) {
            $RecycledGoods["metal"] = $RecyclerCapacity / 2;
            $RecycledGoods["crystal"] = $RecyclerCapacity / 2;
        } else {
            if ($destination_planet["debris_metal"] > $destination_planet["debris_crystal"]) {
                $RecycledGoods["crystal"] = $destination_planet["debris_crystal"];
                if ($destination_planet["debris_metal"] > $RecyclerCapacity - $RecycledGoods["crystal"]) {
                    $RecycledGoods["metal"] = $RecyclerCapacity - $RecycledGoods["crystal"];
                } else {
                    $RecycledGoods["metal"] = $destination_planet["debris_metal"];
                }
            } else {
                $RecycledGoods["metal"] = $destination_planet["debris_metal"];
                if ($destination_planet["debris_crystal"] > $RecyclerCapacity - $RecycledGoods["metal"]) {
                    $RecycledGoods["crystal"] = $RecyclerCapacity - $RecycledGoods["metal"];
                } else {
                    $RecycledGoods["crystal"] = $destination_planet["debris_crystal"];
                }
            }
        }
    }
    $NewCargo['Metal'] = $fleet_row["fleet_resource_metal"] + $RecycledGoods["metal"];
    $NewCargo['Crystal'] = $fleet_row["fleet_resource_crystal"] + $RecycledGoods["crystal"];
    $NewCargo['Deuterium'] = $fleet_row["fleet_resource_deuterium"];
    $QryUpdateGalaxy = "UPDATE `{{planets}}` SET `debris_metal` = `debris_metal` - '{$RecycledGoods['metal']}', `debris_crystal` = `debris_crystal` - '{$RecycledGoods['crystal']}' ";
    $QryUpdateGalaxy .= "WHERE `planet_type` = 1 AND `galaxy` = '{$fleet_row['fleet_end_galaxy']}' AND `system` = '{$fleet_row['fleet_end_system']}' AND `planet` = '{$fleet_row['fleet_end_planet']}' LIMIT 1;";
    doquery($QryUpdateGalaxy);
    $Message = sprintf($lang['sys_recy_gotten'], pretty_number($RecycledGoods["metal"]), $lang['Metal'], pretty_number($RecycledGoods["crystal"]), $lang['Crystal']);
    msg_send_simple_message($fleet_row['fleet_owner'], '', $fleet_row['fleet_start_time'], MSG_TYPE_RECYCLE, $lang['sys_mess_spy_control'], $lang['sys_recy_report'], $Message);
    $QryUpdateFleet = "UPDATE {{fleets}} SET `fleet_mess` = 1,`fleet_resource_metal` = '{$NewCargo['Metal']}',`fleet_resource_crystal` = '{$NewCargo['Crystal']}',`fleet_resource_deuterium` = '{$NewCargo['Deuterium']}' ";
    $QryUpdateFleet .= "WHERE `fleet_id` = '{$fleet_row['fleet_id']}' LIMIT 1;";
    doquery($QryUpdateFleet);
    return CACHE_FLEET | CACHE_PLANET_DST;
}
function flt_mission_explore(&$mission_data)
{
    if (!isset($mission_data['fleet_event']) || $mission_data['fleet_event'] != EVENT_FLT_ACOMPLISH) {
        return CACHE_NONE;
    }
    global $lang, $config;
    static $ship_data, $rates;
    $result = array('$mission_data' => $mission_data, '$outcome_list' => array(), '$mission_outcome' => FLT_EXPEDITION_OUTCOME_NONE, '$outcome_value' => 0, '$outcome_percent' => 0, '$outcome_mission_sub' => -1, '$fleet' => array(), '$fleet_lost' => array(), '$found_dark_matter' => 0, '$fleet_metal_points' => 0);
    $fleet =& $result['$fleet'];
    //  $fleet_left = &$result['$fleet_left'];
    $fleet_lost =& $result['$fleet_lost'];
    $outcome_mission_sub =& $result['$outcome_mission_sub'];
    $outcome_percent =& $result['$outcome_percent'];
    $found_dark_matter =& $result['$found_dark_matter'];
    $mission_outcome =& $result['$mission_outcome'];
    $outcome_value =& $result['$outcome_value'];
    $outcome_list =& $result['$outcome_list'];
    $fleet_metal_points =& $result['$fleet_metal_points'];
    if (!$ship_data) {
        foreach (sn_get_groups('fleet') as $unit_id) {
            $unit_info = get_unit_param($unit_id);
            if ($unit_info[P_UNIT_TYPE] != UNIT_SHIPS || !isset($unit_info['engine'][0]['speed']) || !$unit_info['engine'][0]['speed']) {
                continue;
            }
            $ship_data[$unit_id][P_COST_METAL] = get_unit_cost_in($unit_info[P_COST]);
        }
        $rates = get_resource_exchange();
    }
    $fleet_row = $mission_data['fleet'];
    $fleet = sys_unit_str2arr($fleet_row['fleet_array']);
    $fleet_capacity = 0;
    $fleet_metal_points = 0;
    foreach ($fleet as $ship_id => $ship_amount) {
        $unit_info = get_unit_param($ship_id);
        $fleet_capacity += $ship_amount * $unit_info[P_CAPACITY];
        $fleet_metal_points += $ship_amount * $ship_data[$ship_id][P_COST_METAL];
    }
    $fleet_capacity = max(0, $fleet_capacity - $fleet_row['fleet_resource_metal'] + $fleet_row['fleet_resource_crystal'] + $fleet_row['fleet_resource_deuterium']);
    $flt_stay_hours = ($fleet_row['fleet_end_stay'] - $fleet_row['fleet_start_time']) / 3600 * ($config->game_speed_expedition ? $config->game_speed_expedition : 1);
    $outcome_list = sn_get_groups('mission_explore_outcome_list');
    $outcome_list[FLT_EXPEDITION_OUTCOME_NONE]['chance'] = ceil(200 / pow($flt_stay_hours, 1 / 1.7));
    $chance_max = 0;
    foreach ($outcome_list as $key => &$value) {
        if (!$value['chance']) {
            unset($outcome_list[$key]);
            continue;
        }
        $value['value'] = $chance_max = $value['chance'] + $chance_max;
    }
    $outcome_value = mt_rand(0, $chance_max);
    // $outcome_value = 409;
    $outcome_description =& $outcome_list[$mission_outcome = FLT_EXPEDITION_OUTCOME_NONE];
    foreach ($outcome_list as $key => &$value) {
        if (!$value['chance']) {
            continue;
        }
        $mission_outcome = $key;
        $outcome_description = $value;
        if ($outcome_value <= $outcome_description['value']) {
            break;
        }
    }
    // Вычисляем вероятность выпадения данного числа в общем пуле
    $msg_sender = $lang['flt_mission_expedition']['msg_sender'];
    $msg_title = $lang['flt_mission_expedition']['msg_title'];
    $outcome_percent = ($outcome_description['value'] - $outcome_value) / $outcome_description['chance'];
    $msg_text = '';
    $msg_text_addon = '';
    $found_dark_matter = 0;
    //  $outcome_mission_sub = -1;
    switch ($mission_outcome) {
        //  switch(FLT_EXPEDITION_OUTCOME_LOST_FLEET) { // TODO DEBUG!
        case FLT_EXPEDITION_OUTCOME_LOST_FLEET:
            flt_mission_explore_outcome_lost_fleet($result);
            //      // $fleet_left = 1 - mt_rand(1, 3) * 0.25;// * 0.25;
            //      $fleet_left = 1 - mt_rand(1, 3) * mt_rand(200000, 300000) / 1000000;
            //      $fleet_lost = array();
            //      foreach($fleet as $unit_id => &$unit_amount) {
            //        $ships_left = floor($unit_amount * $fleet_left);
            //        $fleet_lost[$unit_id] = $unit_amount - $ships_left;
            //        $unit_amount = $ships_left;
            //        if(!$unit_amount) {
            //          unset($fleet[$unit_id]);
            //        }
            //      }
            break;
        case FLT_EXPEDITION_OUTCOME_LOST_FLEET_ALL:
            flt_mission_explore_outcome_lost_fleet_all($result);
            //      $fleet_lost = $fleet;
            //      $fleet = array();
            break;
        case FLT_EXPEDITION_OUTCOME_FOUND_FLEET:
            $outcome_mission_sub = $outcome_percent >= 0.99 ? 0 : ($outcome_percent >= 0.9 ? 1 : 2);
            $outcome_percent = $outcome_description['percent'][$outcome_mission_sub];
            // Рассчитываем эквивалент найденного флота в метале
            // $found_in_metal = min($outcome_percent * $fleet_metal_points, $config->resource_multiplier * 10000000); // game_speed
            $found_in_metal = min($outcome_percent * $fleet_metal_points, game_resource_multiplier(true) * 10000000);
            // game_speed
            //  13 243 754 000 g x1
            //  60 762 247 000 a x10
            // 308 389 499 488 000 b x500
            // Рассчитываем стоимость самого дорого корабля в металле
            $max_metal_cost = 0;
            foreach ($fleet as $ship_id => $ship_amount) {
                $max_metal_cost = max($max_metal_cost, $ship_data[$ship_id]['metal_cost']);
            }
            // Ограничиваем корабли только теми, чья стоимость в металле меньше или равно стоимости самого дорогого корабля
            $can_be_found = array();
            foreach ($ship_data as $ship_id => $ship_info) {
                if ($ship_info['metal_cost'] < $max_metal_cost) {
                    $can_be_found[$ship_id] = $ship_info['metal_cost'];
                }
            }
            // Убираем колонизаторы и шпионов - миллиарды шпионов и колонизаторов нам не нужны
            unset($can_be_found[SHIP_COLONIZER]);
            unset($can_be_found[SHIP_SPY]);
            $fleet_found = array();
            while (count($can_be_found) && $found_in_metal >= max($can_be_found)) {
                $found_index = mt_rand(1, count($can_be_found)) - 1;
                $found_ship = array_slice($can_be_found, $found_index, 1, true);
                $found_ship_cost = reset($found_ship);
                $found_ship_id = key($found_ship);
                if ($found_ship_cost > $found_in_metal) {
                    unset($can_be_found[$found_ship_id]);
                } else {
                    $found_ship_count = mt_rand(1, floor($found_in_metal / $found_ship_cost));
                    $fleet_found[$found_ship_id] += $found_ship_count;
                    $found_in_metal -= $found_ship_count * $found_ship_cost;
                }
            }
            if (empty($fleet_found)) {
                $msg_text_addon = $lang['flt_mission_expedition']['outcomes'][$mission_outcome]['no_result'];
            } else {
                foreach ($fleet_found as $unit_id => $unit_amount) {
                    $fleet[$unit_id] += $unit_amount;
                }
            }
            break;
        case FLT_EXPEDITION_OUTCOME_FOUND_RESOURCES:
            $outcome_mission_sub = $outcome_percent >= 0.99 ? 0 : ($outcome_percent >= 0.9 ? 1 : 2);
            $outcome_percent = $outcome_description['percent'][$outcome_mission_sub];
            // Рассчитываем количество найденных ресурсов
            $found_in_metal = ceil(min($outcome_percent * $fleet_metal_points, game_resource_multiplier(true) * 10000000, $fleet_capacity) * mt_rand(950000, 1050000) / 1000000);
            // game_speed
            $resources_found[RES_METAL] = floor(mt_rand(300000, 700000) / 1000000 * $found_in_metal);
            $found_in_metal -= $resources_found[RES_METAL];
            $found_in_metal = floor($found_in_metal * $rates[RES_METAL] / $rates[RES_CRYSTAL]);
            $resources_found[RES_CRYSTAL] = floor(mt_rand(500000, 1000000) / 1000000 * $found_in_metal);
            $found_in_metal -= $resources_found[RES_CRYSTAL];
            $found_in_metal = floor($found_in_metal * $rates[RES_CRYSTAL] / $rates[RES_DEUTERIUM]);
            $resources_found[RES_DEUTERIUM] = $found_in_metal;
            $fleet_row['fleet_resource_metal'] += $resources_found[RES_METAL];
            $fleet_row['fleet_resource_crystal'] += $resources_found[RES_CRYSTAL];
            $fleet_row['fleet_resource_deuterium'] += $resources_found[RES_DEUTERIUM];
            if (array_sum($resources_found) == 0) {
                $msg_text_addon = $lang['flt_mission_expedition']['outcomes'][$mission_outcome]['no_result'];
            }
            break;
        case FLT_EXPEDITION_OUTCOME_FOUND_DM:
            $outcome_mission_sub = $outcome_percent >= 0.99 ? 0 : ($outcome_percent >= 0.9 ? 1 : 2);
            $outcome_percent = $outcome_description['percent'][$outcome_mission_sub];
            // Рассчитываем количество найденной ТМ
            $found_dark_matter = floor(min($outcome_percent * $fleet_metal_points / $rates[RES_DARK_MATTER], 10000) * mt_rand(750000, 1000000) / 1000000);
            if (!$found_dark_matter) {
                $msg_text_addon = $lang['flt_mission_expedition']['outcomes'][$mission_outcome]['no_result'];
            }
            break;
        case FLT_EXPEDITION_OUTCOME_FOUND_ARTIFACT:
            break;
        default:
            break;
    }
    flt_mission_explore_addon($result);
    $query_data = array();
    if ($found_dark_matter) {
        rpg_points_change($fleet_row['fleet_owner'], RPG_EXPEDITION, $found_dark_matter, 'Expedition Bonus');
        $msg_text_addon = sprintf($lang['flt_mission_expedition']['found_dark_matter'], $found_dark_matter);
    }
    if (!empty($fleet_lost)) {
        $msg_text_addon = $lang['flt_mission_expedition']['lost_fleet'];
        foreach ($fleet_lost as $ship_id => $ship_amount) {
            $msg_text_addon .= $lang['tech'][$ship_id] . ' - ' . $ship_amount . "\r\n";
        }
    }
    $fleet_row['fleet_amount'] = array_sum($fleet);
    if (!empty($fleet) && $fleet_row['fleet_amount']) {
        if (!empty($fleet_found)) {
            $msg_text_addon = $lang['flt_mission_expedition']['found_fleet'];
            foreach ($fleet_found as $ship_id => $ship_amount) {
                $msg_text_addon .= $lang['tech'][$ship_id] . ' - ' . $ship_amount . "\r\n";
            }
        }
        if (!empty($resources_found) && array_sum($resources_found) > 0) {
            $msg_text_addon = $lang['flt_mission_expedition']['found_resources'];
            foreach ($resources_found as $ship_id => $ship_amount) {
                $msg_text_addon .= $lang['tech'][$ship_id] . ' - ' . $ship_amount . "\r\n";
            }
            $query_data[] = "`fleet_resource_metal` = `fleet_resource_metal` + {$resources_found[RES_METAL]}";
            $query_data[] = "`fleet_resource_crystal` = `fleet_resource_crystal` + {$resources_found[RES_CRYSTAL]}";
            $query_data[] = "`fleet_resource_deuterium` = `fleet_resource_deuterium` + {$resources_found[RES_DEUTERIUM]}";
        }
        if (!empty($fleet_lost) || !empty($fleet_found)) {
            $fleet_row['fleet_array'] = sys_unit_arr2str($fleet);
            $query_data[] = "`fleet_amount` = {$fleet_row['fleet_amount']}";
            $query_data[] = "`fleet_array` = '{$fleet_row['fleet_array']}'";
        }
        $query_data[] = '`fleet_mess` = 1';
        $query_data = "UPDATE {{fleets}} SET " . implode(',', $query_data);
    } else {
        // Удалить флот
        $query_data = "DELETE FROM {{fleets}}";
    }
    $query_data .= " WHERE `fleet_id` = {$fleet_row['fleet_id']} LIMIT 1";
    doquery($query_data);
    db_user_set_by_id($fleet_row['fleet_owner'], "`player_rpg_explore_xp` = `player_rpg_explore_xp` + 1");
    if (!$msg_text) {
        $messages =& $lang['flt_mission_expedition']['outcomes'][$mission_outcome]['messages'];
        if ($outcome_mission_sub >= 0 && is_array($messages)) {
            $messages =& $messages[$outcome_mission_sub];
        }
        $msg_text = is_string($messages) ? $messages : (is_array($messages) ? $messages[mt_rand(0, count($messages) - 1)] : '');
    }
    $msg_text = sprintf($msg_text, $fleet_row['fleet_id'], uni_render_coordinates($fleet_row, 'fleet_end_')) . ($msg_text_addon ? "\r\n" . $msg_text_addon : '');
    msg_send_simple_message($fleet_row['fleet_owner'], '', $fleet_row['fleet_end_stay'], MSG_TYPE_EXPLORE, $msg_sender, $msg_title, $msg_text);
    return CACHE_FLEET | CACHE_USER_SRC;
}
/**
 * Copyright (c) 2009-2010 by Gorlum for http://supernova.ws
 *       OpenSource as long as you don't remove this Copyright
 * V3 2009-11-13
 * V2 2009-10-10
 */
function coe_o_missile_calculate()
{
    sn_db_transaction_check(true);
    global $lang;
    $iraks = doquery("SELECT * FROM {{iraks}} WHERE `fleet_end_time` <= " . SN_TIME_NOW . " FOR UPDATE;");
    while ($fleetRow = db_fetch($iraks)) {
        set_time_limit(15);
        $db_changeset = array();
        $targetUser = db_user_by_id($fleetRow['fleet_target_owner'], true);
        $target_planet_row = sys_o_get_updated($targetUser, array('galaxy' => $fleetRow['fleet_end_galaxy'], 'system' => $fleetRow['fleet_end_system'], 'planet' => $fleetRow['fleet_end_planet'], 'planet_type' => PT_PLANET), SN_TIME_NOW);
        $target_planet_row = $target_planet_row['planet'];
        $rowAttacker = db_user_by_id($fleetRow['fleet_owner'], true);
        if ($target_planet_row['id']) {
            $planetDefense = array();
            foreach (sn_get_groups('defense_active') as $unit_id) {
                $planetDefense[$unit_id] = array(mrc_get_level($targetUser, $target_planet_row, $unit_id, true, true));
            }
            $message = '';
            $interceptors = mrc_get_level($targetUser, $target_planet_row, UNIT_DEF_MISSILE_INTERCEPTOR, true, true);
            //$target_planet_row[$interceptor_db_name]; // Number of interceptors
            $missiles = $fleetRow['fleet_amount'];
            // Number of MIP
            if ($interceptors >= $missiles) {
                $message = $lang['mip_all_destroyed'];
                $db_changeset['unit'][] = sn_db_unit_changeset_prepare(UNIT_DEF_MISSILE_INTERCEPTOR, -$missiles, $targetUser, $target_planet_row['id']);
            } else {
                if ($interceptors) {
                    $message = sprintf($lang['mip_destroyed'], $interceptors);
                    $db_changeset['unit'][] = sn_db_unit_changeset_prepare(UNIT_DEF_MISSILE_INTERCEPTOR, -$interceptors, $targetUser, $target_planet_row['id']);
                }
                //        $message .= $lang['mip_defense_destroyed'];
                $attackResult = COE_missileAttack($targetUser, $rowAttacker, $missiles - $interceptors, $planetDefense, $fleetRow['primaer']);
                foreach ($attackResult['structures'] as $key => $structure) {
                    $destroyed = $planetDefense[$key][0] - $structure[0];
                    if ($destroyed) {
                        $db_changeset['unit'][] = sn_db_unit_changeset_prepare($key, -$destroyed, $targetUser, $target_planet_row['id']);
                        $message .= "&nbsp;&nbsp;{$lang['tech'][$key]} - {$destroyed} {$lang['quantity']}<br>";
                    }
                }
                if (!empty($message)) {
                    $message = $lang['mip_defense_destroyed'] . $message . "{$lang['mip_recycled']}{$lang['Metal']}: {$attackResult['metal']}, {$lang['Crystal']}: {$attackResult['crystal']}<br>";
                    db_planet_set_by_id($target_planet_row['id'], "`metal` = `metal` + {$attackResult['metal']}, `crystal` = `crystal` + {$attackResult['crystal']}");
                }
                //        $message .= "{$lang['mip_recycled']}{$lang['Metal']}: {$attackResult['metal']}, {$lang['Crystal']}: {$attackResult['crystal']}<br>";
            }
            db_changeset_apply($db_changeset);
            $fleetRow['fleet_start_type'] = PT_PLANET;
            $sourcePlanet = db_planet_by_vector($fleetRow, 'fleet_start_', false, 'name');
            $message_vorlage = sprintf($lang['mip_body_attack'], $fleetRow['fleet_amount'], addslashes($sourcePlanet['name']), $fleetRow['fleet_start_galaxy'], $fleetRow['fleet_start_system'], $fleetRow['fleet_start_planet'], addslashes($target_planet_row['name']), $fleetRow['fleet_end_galaxy'], $fleetRow['fleet_end_system'], $fleetRow['fleet_end_planet']);
            empty($message) ? $message = $lang['mip_no_defense'] : false;
            // empty($message) && ($message = $lang['mip_no_defense']);
            msg_send_simple_message($fleetRow['fleet_owner'], '', SN_TIME_NOW, MSG_TYPE_SPY, $lang['mip_sender_amd'], $lang['mip_subject_amd'], $message_vorlage . $message);
            msg_send_simple_message($fleetRow['fleet_target_owner'], '', SN_TIME_NOW, MSG_TYPE_SPY, $lang['mip_sender_amd'], $lang['mip_subject_amd'], $message_vorlage . $message);
        }
        doquery("DELETE FROM {{iraks}} WHERE id = '{$fleetRow['id']}';");
    }
}
Exemple #26
0
function qst_reward(&$user, &$rewards, &$quest_list)
{
    if (empty($rewards)) {
        return;
    }
    global $lang;
    $db_changeset = array();
    $total_rewards = array();
    $comment_dm = '';
    foreach ($rewards as $quest_id => $user_data) {
        foreach ($user_data as $user_id => $planet_data) {
            foreach ($planet_data as $planet_id => $reward_list) {
                $comment = sprintf($lang['qst_msg_complete_body'], $quest_list[$quest_id]['quest_name']);
                $comment_dm .= isset($reward_list[RES_DARK_MATTER]) ? $comment : '';
                $comment_reward = array();
                foreach ($reward_list as $unit_id => $unit_amount) {
                    $comment_reward[] = $unit_amount . ' ' . $lang['tech'][$unit_id];
                    $total_rewards[$user_id][$planet_id][$unit_id] += $unit_amount;
                }
                $comment .= " {$lang['qst_msg_your_reward']} " . implode(',', $comment_reward);
                msg_send_simple_message($user['id'], 0, SN_TIME_NOW, MSG_TYPE_ADMIN, $lang['msg_from_admin'], $lang['qst_msg_complete_subject'], $comment);
                sn_db_perform('{{quest_status}}', array('quest_status_quest_id' => $quest_id, 'quest_status_user_id' => $user_id, 'quest_status_status' => QUEST_STATUS_COMPLETE));
            }
        }
    }
    $group_resources = sn_get_groups('resources_loot');
    $quest_rewards_allowed = sn_get_groups('quest_rewards');
    if (!empty($total_rewards)) {
        foreach ($total_rewards as $user_id => $planet_data) {
            $user_row = classSupernova::db_get_record_by_id(LOC_USER, $user_id);
            foreach ($planet_data as $planet_id => $unit_data) {
                $local_changeset = array();
                foreach ($unit_data as $unit_id => $unit_amount) {
                    if (!isset($quest_rewards_allowed[$unit_id])) {
                        continue;
                    }
                    if ($unit_id == RES_DARK_MATTER) {
                        rpg_points_change($user['id'], RPG_QUEST, $unit_amount, $comment_dm);
                    } elseif (isset($group_resources[$unit_id])) {
                        $local_changeset[pname_resource_name($unit_id)] = array('delta' => $unit_amount);
                    } else {
                        $db_changeset['unit'][] = sn_db_unit_changeset_prepare($unit_id, $unit_amount, $user_row, $planet_id);
                    }
                    // unit
                }
                if (!empty($local_changeset)) {
                    $planet_id = $planet_id == 0 && isset($user_row['id_planet']) ? $user_row['id_planet'] : $planet_id;
                    $db_changeset[$planet_id ? 'planets' : 'users'][] = array('action' => SQL_OP_UPDATE, P_VERSION => 1, 'where' => array("id" => $planet_id ? $planet_id : $user_id), 'fields' => $local_changeset);
                }
            }
        }
        classSupernova::db_changeset_apply($db_changeset);
    }
}
/**
 * MissionCaseExpedition.php
 *
 * version 2.0 returns results for new fleet handler
 * @version 1.0
 * @copyright 2008 By Chlorel for XNova
 */
function flt_mission_explore($mission_data)
{
    global $lang, $sn_data;
    $fleet_row = $mission_data['fleet'];
    $FleetOwner = $fleet_row['fleet_owner'];
    $MessSender = $lang['sys_mess_qg'];
    $MessTitle = $lang['sys_expe_report'];
    // La Flotte vient de finir son exploration
    // Table de ratio de points par type de vaisseau
    $PointsFlotte = array(SHIP_CARGO_SMALL => 1.0, SHIP_CARGO_BIG => 1.5, SHIP_CARGO_SUPER => 1.0, SHIP_FIGHTER_LIGHT => 0.5, SHIP_FIGHTER_HEAVY => 1.5, SHIP_FIGHTER_ASSAULT => 3.0, SHIP_DESTROYER => 2.0, SHIP_CRUISER => 2.5, SHIP_COLONIZER => 0.5, SHIP_RECYCLER => 1.0, SHIP_SPY => 0.0, SHIP_BOMBER => 3.0, SHIP_SATTELITE_SOLAR => 0.0, SHIP_DESTRUCTOR => 3.5, SHIP_DEATH_STAR => 5.0, SHIP_BATTLESHIP => 3.2, SHIP_SUPERNOVA => 9.9);
    // Table de ratio de gains en nombre par type de vaisseau
    $RatioGain = array(SHIP_CARGO_SMALL => 0.1, SHIP_CARGO_BIG => 0.1, SHIP_FIGHTER_LIGHT => 0.1, SHIP_FIGHTER_HEAVY => 0.05, SHIP_FIGHTER_ASSAULT => 0.0125, SHIP_DESTROYER => 0.25, SHIP_CRUISER => 0.125, SHIP_COLONIZER => 0.05, SHIP_CARGO_SUPER => 0.05, SHIP_RECYCLER => 0.1, SHIP_SPY => 0.1, SHIP_BOMBER => 0.0625, SHIP_SATTELITE_SOLAR => 0.0, SHIP_DESTRUCTOR => 0.0625, SHIP_DEATH_STAR => 0.03125, SHIP_BATTLESHIP => 0.0625, SHIP_SUPERNOVA => 0.00125);
    $FleetStayDuration = ($fleet_row['fleet_end_stay'] - $fleet_row['fleet_start_time']) / 3600;
    // Initialisation du contenu de la Flotte
    $farray = explode(';', $fleet_row['fleet_array']);
    foreach ($farray as $Item => $Group) {
        if ($Group != '') {
            $Class = explode(',', $Group);
            $TypeVaisseau = $Class[0];
            $NbreVaisseau = $Class[1];
            $LaFlotte[$TypeVaisseau] = $NbreVaisseau;
            //On calcul les ressources maximum qui peuvent être récupéré
            $FleetCapacity += $sn_data[$TypeVaisseau]['capacity'];
            // Maintenant on calcul en points toute la flotte
            $FleetPoints += $NbreVaisseau * $PointsFlotte[$TypeVaisseau];
        }
    }
    // Espace deja occupé dans les soutes si ce devait etre le cas
    $FleetUsedCapacity = $fleet_row['fleet_resource_metal'] + $fleet_row['fleet_resource_crystal'] + $fleet_row['fleet_resource_deuterium'];
    $FleetCapacity -= $FleetUsedCapacity;
    //On récupère le nombre total de vaisseaux
    $FleetCount = $fleet_row['fleet_amount'];
    // Bon on les mange comment ces explorateurs ???
    $Hasard = mt_rand(0, 10);
    $MessSender = "{$lang['sys_mess_qg']} ({$Hasard})";
    if ($Hasard < 3) {
        // Pas de bol, on les mange tout crus
        $Hasard += 1;
        $LostAmount = ($Hasard * 33 + 1) / 100;
        // Message pour annoncer la bonne mauvaise nouvelle
        if ($LostAmount == 100) {
            // Supprimer effectivement la flotte
            msg_send_simple_message($FleetOwner, '', $fleet_row['fleet_end_stay'], MSG_TYPE_EXPLORE, $MessSender, $MessTitle, $lang['sys_expe_blackholl_2']);
            doquery("DELETE FROM {{fleets}} WHERE `fleet_id` = {$fleet_row['fleet_id']}");
        } else {
            foreach ($LaFlotte as $Ship => $Count) {
                $LostShips[$Ship] = intval($Count * $LostAmount);
                $NewFleetArray .= $Ship . ',' . ($Count - $LostShips[$Ship]) . ';';
            }
            doquery("UPDATE {{fleets}} SET `fleet_array` = '{$NewFleetArray}', `fleet_mess` = '1' WHERE `fleet_id` = '{$fleet_row['fleet_id']}';");
            msg_send_simple_message($FleetOwner, '', $fleet_row['fleet_end_stay'], MSG_TYPE_EXPLORE, $MessSender, $MessTitle, $lang['sys_expe_blackholl_1']);
        }
    } elseif ($Hasard == 3) {
        // Ah un tour pour rien
        doquery("UPDATE {{fleets}} SET `fleet_mess` = '1' WHERE `fleet_id` = {$fleet_row['fleet_id']}");
        rpg_points_change($fleet_row['fleet_owner'], RPG_EXPEDITION, 1, 'Expedition Bonus');
        msg_send_simple_message($FleetOwner, '', $fleet_row['fleet_end_stay'], MSG_TYPE_EXPLORE, $MessSender, $MessTitle, $lang['sys_expe_nothing_1']);
    } elseif ($Hasard >= 4 && $Hasard < 7) {
        // Gains de ressources
        if ($FleetCapacity > 5000) {
            $MinCapacity = $FleetCapacity - 5000;
            $MaxCapacity = $FleetCapacity;
            $FoundGoods = rand($MinCapacity, $MaxCapacity);
            $FoundMetal = intval($FoundGoods / 2);
            $FoundCrist = intval($FoundGoods / 4);
            $FoundDeute = intval($FoundGoods / 6);
            $QryUpdateFleet = "UPDATE {{fleets}} SET ";
            $QryUpdateFleet .= "`fleet_resource_metal` = `fleet_resource_metal` + '{$FoundMetal}', ";
            $QryUpdateFleet .= "`fleet_resource_crystal` = `fleet_resource_crystal` + '{$FoundCrist}', ";
            $QryUpdateFleet .= "`fleet_resource_deuterium` = `fleet_resource_deuterium` + '{$FoundDeute}', ";
            $QryUpdateFleet .= "`fleet_mess` = '1'  ";
            $QryUpdateFleet .= "WHERE `fleet_id` = '{$fleet_row['fleet_id']}';";
            doquery($QryUpdateFleet);
            $Message = sprintf($lang['sys_expe_found_goods'], pretty_number($FoundMetal), $lang['Metal'], pretty_number($FoundCrist), $lang['Crystal'], pretty_number($FoundDeute), $lang['Deuterium']);
            msg_send_simple_message($FleetOwner, '', $fleet_row['fleet_end_stay'], MSG_TYPE_EXPLORE, $MessSender, $MessTitle, $Message);
        }
    } elseif ($Hasard == 7) {
        // Ah un tour pour rien
        doquery("UPDATE {{fleets}} SET `fleet_mess` = '1' WHERE `fleet_id` = {$fleet_row['fleet_id']}");
        msg_send_simple_message($FleetOwner, '', $fleet_row['fleet_end_stay'], MSG_TYPE_EXPLORE, $MessSender, $MessTitle, $lang['sys_expe_nothing_2']);
    } elseif ($Hasard >= 8 && $Hasard < 11) {
        // Gain de vaisseaux
        $FoundChance = $FleetPoints / $FleetCount;
        foreach ($sn_data['groups']['fleet'] as $Ship) {
            if ($LaFlotte[$Ship] != 0) {
                $FoundShip[$Ship] = round($LaFlotte[$Ship] * $RatioGain[$Ship]);
                if ($FoundShip[$Ship] > 0) {
                    $LaFlotte[$Ship] += $FoundShip[$Ship];
                }
            }
        }
        $NewFleetArray = '';
        $FoundShipMess = '';
        foreach ($LaFlotte as $Ship => $Count) {
            if ($Count > 0) {
                $NewFleetArray .= "{$Ship},{$Count};";
            }
        }
        if ($FoundShip) {
            foreach ($FoundShip as $Ship => $Count) {
                if ($Count != 0) {
                    $FoundShipMess .= "{$Count} {$lang['tech'][$Ship]},";
                }
            }
        }
        doquery("UPDATE {{fleets}} SET `fleet_array` = '{$NewFleetArray}', `fleet_mess` = '1' WHERE `fleet_id` = '{$fleet_row['fleet_id']}' LIMIT 1;");
        $Message = "{$lang['sys_expe_found_ships']}{$FoundShipMess}";
        msg_send_simple_message($FleetOwner, '', $fleet_row['fleet_end_stay'], MSG_TYPE_EXPLORE, $MessSender, $MessTitle, $Message);
    }
    return CACHE_FLEET | CACHE_USER_SRC;
}
Exemple #28
0
 protected function password_reset_confirm()
 {
     global $lang, $config;
     if (!$this->is_password_reset_confirm) {
         return $this->account_login_status;
     }
     if ($this->account_login_status != LOGIN_UNDEFINED) {
         return $this->account_login_status;
     }
     // Проверяем поддержку сброса пароля
     if (!$this->is_feature_supported(AUTH_FEATURE_PASSWORD_RESET)) {
         return $this->account_login_status;
     }
     try {
         $code_unsafe = sys_get_param_str_unsafe('password_reset_code');
         if (empty($code_unsafe)) {
             throw new Exception(PASSWORD_RESTORE_ERROR_CODE_EMPTY, ERR_ERROR);
         }
         sn_db_transaction_start();
         $confirmation = $this->confirmation->db_confirmation_get_by_type_and_code(CONFIRM_PASSWORD_RESET, $code_unsafe);
         // OK 4.5
         if (empty($confirmation)) {
             throw new Exception(PASSWORD_RESTORE_ERROR_CODE_WRONG, ERR_ERROR);
         }
         if (SN_TIME_NOW - strtotime($confirmation['create_time']) > AUTH_PASSWORD_RESET_CONFIRMATION_EXPIRE) {
             throw new Exception(PASSWORD_RESTORE_ERROR_CODE_TOO_OLD, ERR_ERROR);
         }
         unset($this->account);
         $this->account = new Account($this->db);
         if (!$this->account->db_get_by_email($confirmation['email'])) {
             throw new Exception(PASSWORD_RESTORE_ERROR_CODE_OK_BUT_NO_ACCOUNT_FOR_EMAIL, ERR_ERROR);
         }
         $new_password_unsafe = $this->make_random_password();
         $salt_unsafe = $this->password_salt_generate();
         if (!$this->account->db_set_password($new_password_unsafe, $salt_unsafe)) {
             // Ошибка смены пароля
             throw new Exception(AUTH_ERROR_INTERNAL_PASSWORD_CHANGE_ON_RESTORE, ERR_ERROR);
         }
         $this->account_login_status = LOGIN_UNDEFINED;
         $this->remember_me = 1;
         $this->cookie_set();
         $this->login_cookie();
         if ($this->account_login_status == LOGIN_SUCCESS) {
             // TODO - НЕ ОБЯЗАТЕЛЬНО ОТПРАВЛЯТЬ ЧЕРЕЗ ЕМЕЙЛ! ЕСЛИ ЭТО ФЕЙСБУЧЕК ИЛИ ВКШЕЧКА - МОЖНО ЧЕРЕЗ ЛС ПИСАТЬ!!
             $message_header = sprintf($lang['log_lost_email_title'], $config->game_name);
             $message = sprintf($lang['log_lost_email_pass'], $config->game_name, $this->account->account_name, $new_password_unsafe);
             @($operation_result = mymail($confirmation['email'], $message_header, htmlspecialchars($message)));
             // $users_translated = classSupernova::$auth->db_translate_get_users_from_account_list($this->provider_id, $this->account->account_id); // OK 4.5
             $users_translated = PlayerToAccountTranslate::db_translate_get_users_from_account_list($this->provider_id, $this->account->account_id);
             // OK 4.5
             if (!empty($users_translated)) {
                 // Отправляем в лички письмо о сбросе пароля
                 // ПО ОПРЕДЕЛЕНИЮ в $users_translated только
                 //    - аккаунты, поддерживающие сброс пароля
                 //    - список аккаунтов, имеющих тот же емейл, что указан в Подтверждении
                 //    - игроки, привязанные только к этим аккаунтам
                 // Значит им всем сразу скопом можно отправлять сообщения
                 $message = sprintf($lang['sys_password_reset_message_body'], $new_password_unsafe);
                 $message = sys_bbcodeParse($message) . '<br><br>';
                 // msg_send_simple_message($found_provider->data[F_USER_ID], 0, SN_TIME_NOW, MSG_TYPE_ADMIN, $lang['sys_administration'], $lang['sys_login_register_message_title'], $message);
                 foreach ($users_translated as $user_id => $providers_list) {
                     msg_send_simple_message($user_id, 0, SN_TIME_NOW, MSG_TYPE_ADMIN, $lang['sys_administration'], $lang['sys_login_register_message_title'], $message);
                 }
             } else {
                 // Фигня - может быть и пустой, если у нас есть только аккаунт, но нет пользователей
                 // throw new Exception(AUTH_PASSWORD_RESET_INSIDE_ERROR_NO_ACCOUNT_FOR_CONFIRMATION, ERR_ERROR);
             }
         }
         $this->confirmation->db_confirmation_delete_by_type_and_email(CONFIRM_PASSWORD_RESET, $confirmation['email']);
         // OK 4.5
         sn_db_transaction_commit();
         sys_redirect('overview.php');
     } catch (Exception $e) {
         sn_db_transaction_rollback();
         $this->account_login_status = $e->getMessage();
     }
     return $this->account_login_status;
 }
Exemple #29
0
    }
    if (isset($_POST["temat"]) && $_POST["temat"] != '') {
        $config->temat = $_POST['temat'];
    }
    if ($user['authlevel'] == 3) {
        $kolor = 'red';
        $ranga = 'Administrator';
    } elseif ($user['authlevel'] == 4) {
        $kolor = 'skyblue';
        $ranga = 'GameOperator';
    } elseif ($user['authlevel'] == 5) {
        $kolor = 'yellow';
        $ranga = 'SuperGameOperator';
    }
    if ($config->tresc != '' and $config->temat) {
        $sq = doquery("SELECT `id` FROM {{users}}");
        $Time = time();
        $From = "<font color=\"" . $kolor . "\">" . $ranga . " " . $user['username'] . "</font>";
        $Subject = "<font color=\"" . $kolor . "\">" . $config->temat . "</font>";
        $Message = "<font color=\"" . $kolor . "\"><b>" . $config->tresc . "</b></font>";
        while ($u = mysql_fetch_assoc($sq)) {
            msg_send_simple_message($u['id'], $user['id'], $Time, MSG_TYPE_ADMIN, $From, $Subject, $Message);
        }
        message("<font color=\"lime\">Wys³a³e¶ wiadomo¶æ do wszystkich graczy</font>", "Complete", "../overview." . PHP_EX, 3);
    }
} else {
    $parse['dpath'] = $dpath;
    $parse['debug'] = $config->debug == 1 ? " checked='checked'/" : '';
    $page .= parsetemplate(gettemplate('admin/messall_body'), $parse);
    display($page, '', false, '', true);
}
Exemple #30
0
        $new_friend_row = db_user_by_id($new_friend_id, true, '`id`, `username`');
    } elseif ($new_friend_name = sys_get_param_str_unsafe('request_user_name')) {
        $new_friend_row = db_user_by_username($new_friend_name, true, '`id`, `username`');
        $new_friend_name = db_escape($new_friend_name);
    }
    if ($new_friend_row['id'] == $user['id']) {
        unset($new_friend_row);
        throw new exception('buddy_err_adding_self', ERR_ERROR);
    }
    // Checking for user name & request text - in case if it was request to adding new request
    if (isset($new_friend_row['id']) && ($new_request_text = sys_get_param_str('request_text'))) {
        $check_relation = doquery("SELECT `BUDDY_ID` FROM {{buddy}} WHERE\n      (`BUDDY_SENDER_ID` = {$user['id']} AND `BUDDY_OWNER_ID` = {$new_friend_row['id']})\n      OR\n      (`BUDDY_SENDER_ID` = {$new_friend_row['id']} AND `BUDDY_OWNER_ID` = {$user['id']})\n      LIMIT 1 FOR UPDATE;", true);
        if (isset($check_relation['BUDDY_ID'])) {
            throw new exception('buddy_err_adding_exists', ERR_WARNING);
        }
        msg_send_simple_message($new_friend_row['id'], $user['id'], SN_TIME_NOW, MSG_TYPE_PLAYER, $user['username'], $lang['buddy_msg_adding_title'], sprintf($lang['buddy_msg_adding_text'], $user['username']));
        doquery($q = "INSERT INTO {{buddy}} SET `BUDDY_SENDER_ID` = {$user['id']}, `BUDDY_OWNER_ID` = {$new_friend_row['id']}, `BUDDY_REQUEST` = '{$new_request_text}';");
        sn_db_transaction_commit();
        throw new exception('buddy_err_adding_none', ERR_NONE);
    }
} catch (exception $e) {
    $result[] = array('STATUS' => in_array($e->getCode(), array(ERR_NONE, ERR_WARNING, ERR_ERROR)) ? $e->getCode() : ERR_ERROR, 'MESSAGE' => $lang[$e->getMessage()]);
}
// TODO - Это просто заглушка. Дойдут руки - разобраться, в чём проблема
sn_db_transaction_rollback();
$query = db_buddy_list_by_user($user['id']);
while ($row = db_fetch($query)) {
    $row['BUDDY_REQUEST'] = sys_bbcodeParse($row['BUDDY_REQUEST']);
    $row['BUDDY_ACTIVE'] = $row['BUDDY_STATUS'] == BUDDY_REQUEST_ACTIVE;
    $row['BUDDY_DENIED'] = $row['BUDDY_STATUS'] == BUDDY_REQUEST_DENIED;
    $row['BUDDY_INCOMING'] = $row['BUDDY_OWNER_ID'] == $user['id'];