function sn_RestoreFleetToPlanet(&$fleet_row, $start = true, $only_resources = false, $safe_fleet = false, &$result)
{
    sn_db_transaction_check(true);
    $result = CACHE_NOTHING;
    if (!is_array($fleet_row)) {
        return $result;
    }
    $prefix = $start ? 'start' : 'end';
    // Поскольку эта функция может быть вызвана не из обработчика флотов - нам надо всё заблокировать вроде бы НЕ МОЖЕТ!!!
    // TODO Проеверить от многократного срабатывания !!!
    // Тут не блокируем пока - сначала надо заблокировать пользователя, что бы не было дедлока
    //  $fleet_row = doquery("SELECT * FROM {{fleets}} WHERE `fleet_id`='{$fleet_row['fleet_id']}' LIMIT 1", true);
    // Узнаем ИД владельца планеты - без блокировки
    // TODO поменять на владельца планеты - когда его будут возвращать всегда !!!
    $user_id = db_planet_by_vector($fleet_row, "fleet_{$prefix}_", false, 'id_owner');
    $user_id = $user_id['id_owner'];
    // Блокируем пользователя
    $user = db_user_by_id($user_id, true);
    // Блокируем планету
    $planet_arrival = db_planet_by_vector($fleet_row, "fleet_{$prefix}_", true);
    // Блокируем флот
    //  $fleet_row = doquery("SELECT * FROM {{fleets}} WHERE `fleet_id`='{$fleet_row['fleet_id']}' LIMIT 1 FOR UPDATE;", true);
    // Если флот уже обработан - не существует или возращается - тогда ничего не делаем
    if (!$fleet_row || !is_array($fleet_row) || $fleet_row['fleet_mess'] == 1 && $only_resources) {
        return $result;
    }
    // Флот, который возвращается на захваченную планету, пропадает
    if ($start && $fleet_row['fleet_mess'] == 1 && $planet_arrival['id_owner'] != $fleet_row['fleet_owner']) {
        doquery("DELETE FROM {{fleets}} WHERE `fleet_id`='{$fleet_row['fleet_id']}' LIMIT 1;");
        return $result;
    }
    //pdump($planet_arrival);
    $db_changeset = array();
    if (!$only_resources) {
        flt_destroy($fleet_row);
        if ($fleet_row['fleet_owner'] == $planet_arrival['id_owner']) {
            $fleet_array = sys_unit_str2arr($fleet_row['fleet_array']);
            foreach ($fleet_array as $ship_id => $ship_count) {
                if ($ship_count) {
                    $db_changeset['unit'][] = sn_db_unit_changeset_prepare($ship_id, $ship_count, $user, $planet_arrival['id']);
                }
            }
        } else {
            return CACHE_NOTHING;
        }
    } else {
        // flt_send_back($fleet_row);
        doquery("UPDATE {{fleets}} SET fleet_resource_metal = 0, fleet_resource_crystal = 0, fleet_resource_deuterium = 0, fleet_mess = 1 WHERE `fleet_id`='{$fleet_row['fleet_id']}' LIMIT 1;");
    }
    if (!empty($db_changeset)) {
        db_changeset_apply($db_changeset);
    }
    db_planet_set_by_id($planet_arrival['id'], "`metal` = `metal` + '{$fleet_row['fleet_resource_metal']}', `crystal` = `crystal` + '{$fleet_row['fleet_resource_crystal']}', `deuterium` = `deuterium` + '{$fleet_row['fleet_resource_deuterium']}'");
    $result = CACHE_FLEET | ($start ? CACHE_PLANET_SRC : CACHE_PLANET_DST);
    return $result;
}
Example #2
0
        if (in_array($prod_id, $sn_group_factories) && get_unit_param($prod_id, P_MINING_IS_MANAGED)) {
            $field_name = pname_factory_production_field_name($prod_id);
            $percent = floor($percent / 10);
            $planetrow[$field_name] = $percent;
            //$SubQry                 .= "`{$field_name}` = '{$percent}',";
            $SubQry[] = "`{$field_name}` = '{$percent}'";
        } else {
            $debug->warning('Supplying wrong ID in production array - attempt to change some field - ID' . $prod_id, 'Resource Page', 301);
            continue;
        }
    }
    //  $SubQry = substr($SubQry, 0, -1);
    //  if($SubQry) {
    //    db_planet_set_by_id($planetrow['id'], $SubQry);
    //  }
    !empty($SubQry) ? db_planet_set_by_id($planetrow['id'], implode(',', $SubQry)) : false;
}
// -------------------------------------------------------------------------------------------------------
// $BuildTemp                   = $planetrow[ 'temp_max' ];
// $BuildEnergyTech             = $user['energy_tech'];
for ($Option = 10; $Option >= 0; $Option--) {
    $template->assign_block_vars('option', array('VALUE' => $Option * 10));
}
$caps_real = eco_get_planet_caps($user, $planetrow, 3600);
$template->assign_block_vars('production', array('TYPE' => $lang['res_basic_income'], 'METAL_TYPE' => pretty_number($caps_real['production'][RES_METAL][0], true, true), 'CRYSTAL_TYPE' => pretty_number($caps_real['production'][RES_CRYSTAL][0], true, true), 'DEUTERIUM_TYPE' => pretty_number($caps_real['production'][RES_DEUTERIUM][0], true, true), 'ENERGY_TYPE' => pretty_number($caps_real['production'][RES_ENERGY][0], true, true)));
foreach ($sn_group_factories as $unit_id) {
    if (mrc_get_level($user, $planetrow, $unit_id) > 0 && get_unit_param($unit_id)) {
        $level_plain = mrc_get_level($user, $planetrow, $unit_id, false, true);
        $template->assign_block_vars('production', array('ID' => $unit_id, 'PERCENT' => $planetrow[pname_factory_production_field_name($unit_id)] * 10, 'TYPE' => $lang['tech'][$unit_id], 'LEVEL' => $level_plain, 'LEVEL_BONUS' => mrc_get_level($user, $planetrow, $unit_id) - $level_plain, 'LEVEL_TYPE' => $unit_id > 200 ? $lang['quantity'] : $lang['level'], 'METAL_TYPE' => pretty_number($caps_real['production'][RES_METAL][$unit_id], true, true), 'CRYSTAL_TYPE' => pretty_number($caps_real['production'][RES_CRYSTAL][$unit_id], true, true), 'DEUTERIUM_TYPE' => pretty_number($caps_real['production'][RES_DEUTERIUM][$unit_id], true, true), 'ENERGY_TYPE' => pretty_number($caps_real['production'][RES_ENERGY][$unit_id], true, true), 'METAL_FULL' => pretty_number($caps_real['production_full'][RES_METAL][$unit_id], true, true), 'CRYSTAL_FULL' => pretty_number($caps_real['production_full'][RES_CRYSTAL][$unit_id], true, true), 'DEUTERIUM_FULL' => pretty_number($caps_real['production_full'][RES_DEUTERIUM][$unit_id], true, true), 'ENERGY_FULL' => pretty_number($caps_real['production_full'][RES_ENERGY][$unit_id], true, true), 'SELECT' => $row_select, 'P_MINING_IS_MANAGED' => get_unit_param($unit_id, P_MINING_IS_MANAGED)));
    }
}
Example #3
0
/**
 * @param        $pos_galaxy
 * @param        $pos_system
 * @param        $pos_planet
 * @param        $user_id
 * @param int    $moon_chance
 * <p><b>0</b> случайный размер луны</p>
 * <p>1..100 Шанс выпадения луны</p>
 * <p>> 100 Размер луны</p>
 * @param string $moon_name
 * @param bool   $update_debris
 * @param array  $options
 *
 * @return array|false|resource
 */
function uni_create_moon($pos_galaxy, $pos_system, $pos_planet, $user_id, $moon_chance = 0, $moon_name = '', $update_debris = true, $options = array())
{
    global $lang;
    $moon_name = '';
    $moon_row = array();
    $moon = db_planet_by_gspt($pos_galaxy, $pos_system, $pos_planet, PT_MOON, false, 'id');
    if (!$moon['id']) {
        $moon_planet = db_planet_by_gspt($pos_galaxy, $pos_system, $pos_planet, PT_PLANET, true, '`id`, `temp_min`, `temp_max`, `name`, `debris_metal`, `debris_crystal`');
        if ($moon_planet['id']) {
            $base_storage_size = BASE_STORAGE_SIZE;
            if (!$moon_chance) {
                $size = mt_rand(1100, 8999);
            } elseif ($moon_chance <= 100) {
                $size = mt_rand($moon_chance * 100 + 1000, $moon_chance * 200 + 2999);
            } else {
                $size = $moon_chance;
            }
            $moon_chance = min(30, ceil($size / 1000));
            $temp_min = $moon_planet['temp_min'] - rand(10, 45);
            $temp_max = $temp_min + 40;
            $moon_name = $moon_name ? $moon_name : "{$moon_planet['name']} {$lang['sys_moon']}";
            $moon_name_safe = db_escape($moon_name);
            $field_max = ceil($size / 1000);
            if (isset($options['image']) && $options['image']) {
                $moon_image = $options['image'];
            } else {
                $moon_image = 'mond';
            }
            $moon_row = classSupernova::db_ins_record(LOC_PLANET, "`id_owner` = '{$user_id}', `parent_planet` = '{$moon_planet['id']}', `name` = '{$moon_name_safe}', `last_update` = " . SN_TIME_NOW . ", `image` = '{$moon_image}',\n          `galaxy` = '{$pos_galaxy}', `system` = '{$pos_system}', `planet` = '{$pos_planet}', `planet_type` = " . PT_MOON . ",\n          `diameter` = '{$size}', `field_max` = '{$field_max}', `density` = 2500, `density_index` = 2, `temp_min` = '{$temp_min}', `temp_max` = '{$temp_max}',\n          `metal` = '0', `metal_perhour` = '0', `metal_max` = '{$base_storage_size}',\n          `crystal` = '0', `crystal_perhour` = '0', `crystal_max` = '{$base_storage_size}',\n          `deuterium` = '0', `deuterium_perhour` = '0', `deuterium_max` = '{$base_storage_size}'");
            if ($update_debris) {
                $debris_spent = $moon_chance * 1000000;
                $metal_spent = round(min($moon_planet['debris_metal'], $debris_spent * mt_rand(50, 75) / 100));
                $crystal_spent = min($moon_planet['debris_crystal'], $debris_spent - $metal_spent);
                $metal_spent = min($moon_planet['debris_metal'], $debris_spent - $crystal_spent);
                // Need if crystal less then their part
                db_planet_set_by_id($moon_planet['id'], "`debris_metal` = GREATEST(0, `debris_metal` - {$metal_spent}), `debris_crystal` = GREATEST(0, `debris_crystal` - {$crystal_spent})");
            }
        }
    }
    return $moon_row;
}
/**
 * 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']}';");
    }
}
Example #5
0
function sn_imperium_view($template = null)
{
    global $user, $lang;
    $planets = array();
    $ques = array();
    $sn_group_factories = sn_get_groups('factories');
    $planet_density = sn_get_groups('planet_density');
    if (sys_get_param('save_production')) {
        $production = sys_get_param('percent');
        if (is_array($production) && !empty($production)) {
            // sn_db_transaction_start();
            $query = array();
            $planet_row_list = db_planet_list_sorted($user, false, '*');
            // while($planet = db_fetch($planet_row_list))
            foreach ($planet_row_list as $planet) {
                foreach ($sn_group_factories as $factory_unit_id) {
                    $unit_db_name_porcent = pname_factory_production_field_name($factory_unit_id);
                    if (get_unit_param($factory_unit_id, P_MINING_IS_MANAGED) && isset($production[$factory_unit_id][$planet['id']]) && ($actual_porcent = intval($production[$factory_unit_id][$planet['id']] / 10)) >= 0 && $actual_porcent <= 10 && $actual_porcent != $planet[$unit_db_name_porcent]) {
                        $query[$planet['id']][] = "{$unit_db_name_porcent} = {$actual_porcent}";
                    }
                }
            }
            foreach ($query as $planet_id => $query_data) {
                db_planet_set_by_id($planet_id, implode(',', $query_data));
            }
            // sn_db_transaction_commit();
        }
    }
    $planet_row_list = db_planet_list_sorted($user);
    // while ($planet = db_fetch($planet_row_list))
    foreach ($planet_row_list as $planet) {
        sn_db_transaction_start();
        $global_data = sys_o_get_updated($user, $planet['id'], SN_TIME_NOW, false, true);
        $planets[$planet['id']] = $global_data['planet'];
        // $ques[$planet['id']] = que_get($user['id'], $planet['id'], false);
        $ques[$planet['id']] = $global_data['que'];
        sn_db_transaction_commit();
    }
    $template = gettemplate('imperium', $template);
    $template->assign_var('amount', count($planets) + 2);
    for ($i = 100; $i >= 0; $i -= 10) {
        $template->assign_block_vars('percent', array('PERCENT' => $i));
    }
    $fleet_id = 1;
    $fleets = array();
    $total['temp_min'] = 1000;
    $total['temp_max'] = -999;
    foreach ($planets as $planet_index => &$planet) {
        $list_planet_que = $ques[$planet_index];
        $planet_template = tpl_parse_planet($planet);
        $planet_fleet_id = 0;
        $fleet_list = $planet_template['fleet_list'];
        //flt_get_fleets_to_planet($planet);
        if ($fleet_list['own']['count']) {
            $planet_fleet_id = "p{$fleet_id}";
            $fleets[] = tpl_parse_fleet_sn($fleet_list['own']['total'], $planet_fleet_id);
            $fleet_id++;
        }
        $template->assign_block_vars('planet', array_merge($planet_template, array('PLANET_FLEET_ID' => $planet_fleet_id, 'METAL_CUR' => pretty_number($planet['metal'], true, $planet['caps']['total_storage'][RES_METAL]), 'METAL_PROD' => pretty_number($planet['caps']['total'][RES_METAL]), 'CRYSTAL_CUR' => pretty_number($planet['crystal'], true, $planet['caps']['total_storage'][RES_CRYSTAL]), 'CRYSTAL_PROD' => pretty_number($planet['caps']['total'][RES_CRYSTAL]), 'DEUTERIUM_CUR' => pretty_number($planet['deuterium'], true, $planet['caps']['total_storage'][RES_DEUTERIUM]), 'DEUTERIUM_PROD' => pretty_number($planet['caps']['total'][RES_DEUTERIUM]), 'ENERGY_CUR' => pretty_number($planet['caps'][RES_ENERGY][BUILD_CREATE] - $planet['caps'][RES_ENERGY][BUILD_DESTROY], true, true), 'ENERGY_MAX' => pretty_number($planet['caps'][RES_ENERGY][BUILD_CREATE]), 'TEMP_MIN' => $planet['temp_min'], 'TEMP_MAX' => $planet['temp_max'], 'DENSITY_CLASS' => $planet['density_index'], 'DENSITY_RICHNESS' => $planet_density[$planet['density_index']][UNIT_PLANET_DENSITY_RICHNESS], 'DENSITY_CLASS_TEXT' => $lang['uni_planet_density_types'][$planet['density_index']])));
        $planet['fleet_list'] = $planet_template['fleet_list'];
        $planet['BUILDING_ID'] = $planet_template['BUILDING_ID'];
        $planet['hangar_que'] = $planet_template['hangar_que'];
        $planet['full_que'] = $list_planet_que;
        $total['fields'] += $planet['field_current'];
        $total['metal'] += $planet['metal'];
        $total['crystal'] += $planet['crystal'];
        $total['deuterium'] += $planet['deuterium'];
        $total['energy'] += $planet['energy_max'] - $planet['energy_used'];
        $total['fields_max'] += eco_planet_fields_max($planet);
        $total['metal_perhour'] += $planet['caps']['total'][RES_METAL];
        $total['crystal_perhour'] += $planet['caps']['total'][RES_CRYSTAL];
        $total['deuterium_perhour'] += $planet['caps']['total'][RES_DEUTERIUM];
        $total['energy_max'] += $planet['caps'][RES_ENERGY][BUILD_CREATE];
        $total['temp_min'] = min($planet['temp_min'], $total['temp_min']);
        $total['temp_max'] = max($planet['temp_max'], $total['temp_max']);
    }
    tpl_assign_fleet($template, $fleets);
    unset($planet);
    $show_groups = array(UNIT_STRUCTURES => 'structures', UNIT_STRUCTURES_SPECIAL => 'structures', UNIT_SHIPS => 'fleet', UNIT_DEFENCE => 'defense');
    foreach ($show_groups as $unit_group_id => $mode) {
        $template->assign_block_vars('prods', array('NAME' => $lang['tech'][$unit_group_id]));
        $unit_group = get_unit_param('techtree', $unit_group_id);
        foreach ($unit_group as $unit_id) {
            $unit_count = $unit_count_abs = 0;
            $block_vars = array();
            $unit_is_factory = in_array($unit_id, $sn_group_factories) && get_unit_param($unit_id, P_MINING_IS_MANAGED);
            // $unit_db_name = pname_resource_name($unit_id);
            foreach ($planets as $planet) {
                $unit_level_plain = mrc_get_level($user, $planet, $unit_id, false, true);
                $level_plus['FACTORY'] = $unit_is_factory;
                $level_plus['LEVEL_PLUS_YELLOW'] = 0;
                $level_plus['LEVEL_PLUS_GREEN'] = 0;
                $level_plus['PERCENT'] = $unit_is_factory ? $unit_level_plain ? $planet[pname_factory_production_field_name($unit_id)] * 10 : -1 : -1;
                switch ($mode) {
                    /*
                    case 'structures':
                      $level_plus_build = $ques[$planet['id']]['in_que'][que_get_unit_que($unit_id)][$user['id']][$planet['id']][$unit_id];
                      if($level_plus_build)
                      {
                        $level_plus['LEVEL_PLUS_GREEN'] = $level_plus_build < 0 ? $level_plus_build : "+{$level_plus_build}";
                        $total['units'][$unit_id]['LEVEL_PLUS_GREEN'] += $level_plus['LEVEL_PLUS_GREEN'];
                      }
                    break;
                    */
                    /** @noinspection PhpMissingBreakStatementInspection */
                    case 'fleet':
                        $level_plus['LEVEL_PLUS_YELLOW'] = $planet['fleet_list']['own']['total'][$unit_id] <= 0 ? $planet['fleet_list']['own']['total'][$unit_id] : "+{$planet['fleet_list']['own']['total'][$unit_id]}";
                        $total['units'][$unit_id]['LEVEL_PLUS_YELLOW'] += $level_plus['LEVEL_PLUS_YELLOW'];
                    case 'structures':
                    case 'defense':
                        $level_plus_build = $ques[$planet['id']]['in_que'][que_get_unit_que($unit_id)][$user['id']][$planet['id']][$unit_id];
                        if ($level_plus_build) {
                            $level_plus['LEVEL_PLUS_GREEN'] = $level_plus_build < 0 ? $level_plus_build : "+{$level_plus_build}";
                            // $level_plus['LEVEL_PLUS_GREEN'] = "+{$level_plus_build}";
                            $total['units'][$unit_id]['LEVEL_PLUS_GREEN'] += $level_plus['LEVEL_PLUS_GREEN'];
                        }
                        break;
                    default:
                        break;
                }
                $block_vars[] = array_merge($level_plus, array('ID' => $planet['id'], 'TYPE' => $planet['planet_type'], 'LEVEL' => $unit_level_plain == 0 && !$level_plus['LEVEL_PLUS_YELLOW'] && !$level_plus['LEVEL_PLUS_GREEN'] ? '-' : $unit_level_plain));
                $unit_count += $unit_level_plain;
                $unit_count_abs += $unit_level_plain + abs($level_plus['LEVEL_PLUS_YELLOW']) + abs($level_plus['LEVEL_PLUS_GREEN']);
            }
            if ($unit_count_abs) {
                $template->assign_block_vars('prods', array('ID' => $unit_id, 'FIELD' => 'unit_' . $unit_id, 'NAME' => $lang['tech'][$unit_id], 'MODE' => $mode));
                foreach ($block_vars as $block_var) {
                    $template->assign_block_vars('prods.planet', $block_var);
                }
                $unit_green = $total['units'][$unit_id]['LEVEL_PLUS_GREEN'];
                $unit_yellow = $total['units'][$unit_id]['LEVEL_PLUS_YELLOW'];
                $template->assign_block_vars('prods.planet', array('ID' => 0, 'LEVEL' => $unit_count, 'LEVEL_PLUS_GREEN' => $unit_green == 0 ? '' : ($unit_green > 0 ? "+{$unit_green}" : $unit_green), 'LEVEL_PLUS_YELLOW' => $unit_yellow == 0 ? '' : ($unit_yellow > 0 ? "+{$unit_yellow}" : $unit_yellow), 'PERCENT' => $unit_is_factory ? '' : -1, 'FACTORY' => $unit_is_factory));
            }
        }
    }
    $template->assign_block_vars('planet', array_merge(array('ID' => 0, 'NAME' => $lang['sys_total'], 'FIELDS_CUR' => $total['fields'], 'FIELDS_MAX' => $total['fields_max'], 'METAL_CUR' => pretty_number($total['metal']), 'METAL_PROD' => pretty_number($total['metal_perhour']), 'CRYSTAL_CUR' => pretty_number($total['crystal']), 'CRYSTAL_PROD' => pretty_number($total['crystal_perhour']), 'DEUTERIUM_CUR' => pretty_number($total['deuterium']), 'DEUTERIUM_PROD' => pretty_number($total['deuterium_perhour']), 'ENERGY_CUR' => pretty_number($total['energy']), 'ENERGY_MAX' => pretty_number($total['energy_max']), 'TEMP_MIN' => $total['temp_min'], 'TEMP_MAX' => $total['temp_max'])));
    $template->assign_vars(array('COLONIES_CURRENT' => get_player_current_colonies($user), 'COLONIES_MAX' => get_player_max_colonies($user), 'EXPEDITIONS_CURRENT' => get_player_current_expeditions($user), 'EXPEDITIONS_MAX' => get_player_max_expeditons($user), 'PLANET_DENSITY_RICHNESS_NORMAL' => PLANET_DENSITY_RICHNESS_NORMAL, 'PLANET_DENSITY_RICHNESS_AVERAGE' => PLANET_DENSITY_RICHNESS_AVERAGE, 'PLANET_DENSITY_RICHNESS_GOOD' => PLANET_DENSITY_RICHNESS_GOOD, 'PLANET_DENSITY_RICHNESS_PERFECT' => PLANET_DENSITY_RICHNESS_PERFECT));
    //$template->assign_recursive($template_result);
    return $template;
}
Example #6
0
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;
}
function sn_ube_combat_result_apply(&$combat_data)
{
    // TODO: Поменять все отладки на запросы
    $destination_user_id = $combat_data[UBE_FLEETS][0][UBE_OWNER];
    $outcome =& $combat_data[UBE_OUTCOME];
    $planet_info =& $outcome[UBE_PLANET];
    $planet_id = $planet_info[PLANET_ID];
    // Обновляем поле обломков на планете
    if (!$combat_data[UBE_OPTIONS][UBE_COMBAT_ADMIN] && !empty($outcome[UBE_DEBRIS])) {
        db_planet_set_by_gspt($planet_info[PLANET_GALAXY], $planet_info[PLANET_SYSTEM], $planet_info[PLANET_PLANET], PT_PLANET, "`debris_metal` = `debris_metal` + " . floor($outcome[UBE_DEBRIS][RES_METAL]) . ", `debris_crystal` = `debris_crystal` + " . floor($outcome[UBE_DEBRIS][RES_CRYSTAL]));
    }
    $db_save = array(UBE_FLEET_GROUP => array());
    $fleets_outcome =& $outcome[UBE_FLEETS];
    foreach ($combat_data[UBE_FLEETS] as $fleet_id => &$fleet_info) {
        if ($fleet_info[UBE_FLEET_GROUP]) {
            $db_save[UBE_FLEET_GROUP][$fleet_info[UBE_FLEET_GROUP]] = $fleet_info[UBE_FLEET_GROUP];
        }
        $fleet_info[UBE_COUNT] = $fleet_info[UBE_COUNT] ? $fleet_info[UBE_COUNT] : array();
        $fleets_outcome[$fleet_id][UBE_UNITS_LOST] = $fleets_outcome[$fleet_id][UBE_UNITS_LOST] ? $fleets_outcome[$fleet_id][UBE_UNITS_LOST] : array();
        $fleet_query = array();
        $db_changeset = array();
        $old_fleet_count = array_sum($fleet_info[UBE_COUNT]);
        $new_fleet_count = $old_fleet_count - array_sum($fleets_outcome[$fleet_id][UBE_UNITS_LOST]);
        // Перебираем юниты если во время боя количество юнитов изменилось и при этом во флоту остались юниты или это планета
        if ($new_fleet_count != $old_fleet_count && (!$fleet_id || $new_fleet_count)) {
            // Просматриваем результаты изменения флотов
            foreach ($fleet_info[UBE_COUNT] as $unit_id => $unit_count) {
                // Перебираем аутком на случай восстановления юнитов
                $units_lost = (double) $fleets_outcome[$fleet_id][UBE_UNITS_LOST][$unit_id];
                $units_left = $unit_count - $units_lost;
                if ($fleet_id) {
                    // Не планета - всегда сразу записываем строку итогов флота
                    $fleet_query[$unit_id] = "{$unit_id},{$units_left}";
                } elseif ($units_lost) {
                    // Планета - записываем в ИД юнита его потери только если есть потери
                    // $unit_db_name = get_unit_param($unit_id, P_NAME);
                    // $fleet_query[$unit_id] = "`{$unit_db_name}` = `{$unit_db_name}` - {$units_lost}";
                    // pdump($fleet_info);
                    // die();
                    $db_changeset['unit'][] = sn_db_unit_changeset_prepare($unit_id, -$units_lost, $combat_data[UBE_PLAYERS][$destination_user_id][UBE_PLAYER_DATA], $planet_id);
                }
            }
            if ($fleet_id) {
                // Для флотов перегенерируем массив как одно вхождение в SET SQL-запроса
                $fleet_query = implode(';', $fleet_query);
                $fleet_query = array("`fleet_array` = '{$fleet_query}'");
            }
        }
        // Если во флоте остались юниты или это планета - генерируем изменение ресурсов
        if ($new_fleet_count || !$fleet_id) {
            foreach (sn_get_groups('resources_loot') as $resource_id) {
                $resource_change = (double) $fleets_outcome[$fleet_id][UBE_RESOURCES_LOOTED][$resource_id] + (double) $fleets_outcome[$fleet_id][UBE_CARGO_DROPPED][$resource_id];
                if ($resource_change) {
                    $resource_db_name = ($fleet_id ? 'fleet_resource_' : '') . pname_resource_name($resource_id);
                    $fleet_query[] = "`{$resource_db_name}` = `{$resource_db_name}` - ({$resource_change})";
                }
            }
        }
        /*
            if(empty($fleet_query))
            {
              continue;
            }
        */
        if ($fleet_id && $new_fleet_count) {
            // Если защитник и не РМФ - отправляем флот назад
            if ($fleet_info[UBE_FLEET_TYPE] == UBE_DEFENDERS && !$outcome[UBE_SFR] || $fleet_info[UBE_FLEET_TYPE] == UBE_ATTACKERS) {
                $fleet_query[] = '`fleet_mess` = 1';
            }
            // Если флот в группе - помечаем нулем
            //      if($fleet_info[UBE_FLEET_GROUP])
            //      {
            //        $fleet_query[] = '`fleet_group` = 0';
            //      }
        }
        //global $debug;
        $fleet_query = implode(',', $fleet_query);
        if ($fleet_id) {
            if ($fleet_info[UBE_FLEET_TYPE] == UBE_ATTACKERS && $outcome[UBE_MOON_REAPERS] == UBE_MOON_REAPERS_DIED) {
                $new_fleet_count = 0;
            }
            if ($new_fleet_count) {
                if ($fleet_query) {
                    doquery("UPDATE {{fleets}} SET {$fleet_query}, `fleet_amount` = '{$new_fleet_count}' WHERE `fleet_id` = {$fleet_id} LIMIT 1");
                }
            } else {
                // Удаляем пустые флоты
                doquery("DELETE FROM {{fleets}} WHERE `fleet_id` = {$fleet_id} LIMIT 1");
                db_unit_list_delete(0, LOC_FLEET, $fleet_id, 0);
            }
        } else {
            // Сохраняем изменения ресурсов - если они есть
            if ($fleet_query) {
                db_planet_set_by_id($planet_id, $fleet_query);
            }
            if (!empty($db_changeset)) {
                db_changeset_apply($db_changeset);
            }
        }
    }
    // TODO: Связать сабы с флотами констраинтами ON DELETE SET NULL
    // $db_save[UBE_FLEET_GROUP][$fleet_info[UBE_FLEET_GROUP]] = $fleet_info[UBE_FLEET_GROUP];
    if (!empty($db_save[UBE_FLEET_GROUP])) {
        $db_save[UBE_FLEET_GROUP] = implode(',', $db_save[UBE_FLEET_GROUP]);
        doquery("DELETE FROM {{aks}} WHERE `id` IN ({$db_save[UBE_FLEET_GROUP]})");
    }
    if ($outcome[UBE_MOON] == UBE_MOON_CREATE_SUCCESS) {
        $moon_row = uni_create_moon($planet_info[PLANET_GALAXY], $planet_info[PLANET_SYSTEM], $planet_info[PLANET_PLANET], $destination_user_id, $outcome[UBE_MOON_SIZE], '', false);
        $outcome[UBE_MOON_NAME] = $moon_row['name'];
        unset($moon_row);
    } elseif ($outcome[UBE_MOON] == UBE_MOON_DESTROY_SUCCESS) {
        db_planet_delete_by_id($planet_id);
    }
    $bashing_list = array();
    foreach ($combat_data[UBE_PLAYERS] as $player_id => $player_info) {
        if ($player_info[UBE_ATTACKER]) {
            if ($outcome[UBE_MOON] != UBE_MOON_DESTROY_SUCCESS) {
                $bashing_list[] = "({$player_id}, {$planet_id}, {$combat_data[UBE_TIME]})";
            }
            if ($combat_data[UBE_OPTIONS][UBE_MISSION_TYPE] == MT_ATTACK && $combat_data[UBE_OPTIONS][UBE_DEFENDER_ACTIVE]) {
                $str_loose_or_win = $outcome[UBE_COMBAT_RESULT] == UBE_COMBAT_RESULT_WIN ? 'raidswin' : 'raidsloose';
                db_user_set_by_id($player_id, "`xpraid` = `xpraid` + 1, `raids` = `raids` + 1, `{$str_loose_or_win}` = `{$str_loose_or_win}` + 1");
            }
        }
    }
    $bashing_list = implode(',', $bashing_list);
    if ($bashing_list) {
        doquery("INSERT INTO {{bashing}} (bashing_user_id, bashing_planet_id, bashing_time) VALUES {$bashing_list};");
    }
}
Example #8
0
        }
        foreach (sn_get_groups('resources_loot') as $resource_id) {
            $resource_name = pname_resource_name($resource_id);
            $template->assign_var("{$resource_name}_cost", $final_cost[$resource_id]);
            $final_cost[$resource_id] = floor($final_cost[$resource_id] * $bonus);
            $template->assign_var("{$resource_name}_bonus", $final_cost[$resource_id]);
        }
        if ($_GET['btn_confirm']) {
            $time = SN_TIME_NOW + PERIOD_DAY;
            db_unit_list_delete($planet['id_owner'], LOC_PLANET, $planet['id']);
            db_planet_set_by_id($planet['id'], "id_owner = 0, destruyed = {$time}");
            if ($moon) {
                db_unit_list_delete($planet['id_owner'], LOC_PLANET, $moon['id']);
                db_planet_set_by_id($moon['id'], "id_owner = 0, destruyed = {$time}");
            }
            db_planet_set_by_id($destination['id'], "metal = metal + '{$final_cost[RES_METAL]}', crystal = crystal + '{$final_cost[RES_CRYSTAL]}', deuterium = deuterium + '{$final_cost[RES_DEUTERIUM]}'");
            $template->assign_var('CHECK', 2);
        }
    }
    sn_db_transaction_commit();
}
$template->assign_vars(array('galaxy_src' => $galaxy_src, 'system_src' => $system_src, 'planet_src' => $planet_src, 'galaxy_dst' => $galaxy_dst, 'system_dst' => $system_dst, 'planet_dst' => $planet_dst, 'bonus' => $bonus, 'username' => $username));
display(parsetemplate($template, $parse), $lang['adm_pl_comp_title'], false, '', true);
function killer_add_planet($planet)
{
    global $final_cost;
    $final_cost = array();
    $sn_group_resources_loot = sn_get_groups('resources_loot');
    /*
    foreach($sn_group_resources_loot as &$value)
    {
Example #9
0
 $uni_galaxyRowPlanet = $planet_list[$Planet][PT_PLANET];
 $planet_fleet_id = 0;
 if ($uni_galaxyRowPlanet['destruyed']) {
     CheckAbandonPlanetState($uni_galaxyRowPlanet);
 } elseif ($uni_galaxyRowPlanet['id']) {
     if ($cached['users'][$uni_galaxyRowPlanet['id_owner']]) {
         $uni_galaxyRowUser = $cached['users'][$uni_galaxyRowPlanet['id_owner']];
     } else {
         $uni_galaxyRowUser = db_user_by_id($uni_galaxyRowPlanet['id_owner']);
         $cached['users'][$uni_galaxyRowUser['id']] = $uni_galaxyRowUser;
     }
     if (!$uni_galaxyRowUser['id']) {
         $debug->warning("Planet '{$uni_galaxyRowPlanet['name']}' [{$uni_galaxy}:{$uni_system}:{$Planet}] has no owner!", 'Userless planet', 503);
         $uni_galaxyRowPlanet['destruyed'] = SN_TIME_NOW + 60 * 60 * 24;
         $uni_galaxyRowPlanet['id_owner'] = 0;
         db_planet_set_by_id($uni_galaxyRowPlanet['id'], "id_owner = 0, destruyed = {$uni_galaxyRowPlanet['destruyed']}");
     }
     if ($uni_galaxyRowUser['id']) {
         $planetcount++;
         if ($uni_galaxyRowUser['ally_id']) {
             if ($cached['allies'][$uni_galaxyRowUser['ally_id']]) {
                 $allyquery = $cached['allies'][$uni_galaxyRowUser['ally_id']];
             } else {
                 $allyquery = doquery("SELECT * FROM `{{alliance}}` WHERE `id` = '{$uni_galaxyRowUser['ally_id']}';", '', true);
                 $cached['allies'][$uni_galaxyRowUser['ally_id']] = $allyquery;
             }
         }
         $fleets_to_planet = flt_get_fleets_to_planet(false, $fleet_list[$Planet][PT_PLANET]);
         if ($fleets_to_planet['own']['count']) {
             $planet_fleet_id = $fleet_id;
             $fleets[] = tpl_parse_fleet_sn($fleets_to_planet['own']['total'], $fleet_id);
Example #10
0
function sn_sys_planet_core_transmute(&$user, &$planetrow)
{
    if (!sys_get_param_str('transmute')) {
        return array();
    }
    global $lang;
    try {
        if ($planetrow['planet_type'] != PT_PLANET) {
            throw new exception($lang['ov_core_err_not_a_planet'], ERR_ERROR);
        }
        if ($planetrow['density_index'] == ($new_density_index = sys_get_param_id('density_type'))) {
            throw new exception($lang['ov_core_err_same_density'], ERR_WARNING);
        }
        sn_db_transaction_start();
        $user = db_user_by_id($user['id'], true, '*');
        $planetrow = db_planet_by_id($planetrow['id'], true, '*');
        //    $global_data = sys_o_get_updated($user, $planetrow['id'], SN_TIME_NOW);
        //    $user = $global_data['user'];
        //    $planetrow = $global_data['planet'];
        $planet_density_index = $planetrow['density_index'];
        $density_price_chart = planet_density_price_chart($planet_density_index);
        if (!isset($density_price_chart[$new_density_index])) {
            // Hack attempt
            throw new exception($lang['ov_core_err_denisty_type_wrong'], ERR_ERROR);
        }
        $user_dark_matter = mrc_get_level($user, false, RES_DARK_MATTER);
        $transmute_cost = get_unit_param(UNIT_PLANET_DENSITY, 'cost');
        $transmute_cost = $transmute_cost[RES_DARK_MATTER] * $density_price_chart[$new_density_index];
        if ($user_dark_matter < $transmute_cost) {
            throw new exception($lang['ov_core_err_no_dark_matter'], ERR_ERROR);
        }
        $sn_data_planet_density = sn_get_groups('planet_density');
        foreach ($sn_data_planet_density as $key => $value) {
            if ($key == $new_density_index) {
                break;
            }
            $prev_density_index = $key;
        }
        $new_density = round(($sn_data_planet_density[$new_density_index][UNIT_PLANET_DENSITY] + $sn_data_planet_density[$prev_density_index][UNIT_PLANET_DENSITY]) / 2);
        rpg_points_change($user['id'], RPG_PLANET_DENSITY_CHANGE, -$transmute_cost, array('Planet %1$s ID %2$d at coordinates %3$s changed density type from %4$d "%5$s" to %6$d "%7$s". New density is %8$d kg/m3', $planetrow['name'], $planetrow['id'], uni_render_coordinates($planetrow), $planet_density_index, $lang['uni_planet_density_types'][$planet_density_index], $new_density_index, $lang['uni_planet_density_types'][$new_density_index], $new_density));
        db_planet_set_by_id($planetrow['id'], "`density` = {$new_density}, `density_index` = {$new_density_index}");
        sn_db_transaction_commit();
        $planetrow['density'] = $new_density;
        $planetrow['density_index'] = $new_density_index;
        $result = array('STATUS' => ERR_NONE, 'MESSAGE' => sprintf($lang['ov_core_err_none'], $lang['uni_planet_density_types'][$planet_density_index], $lang['uni_planet_density_types'][$new_density_index], $new_density));
    } catch (exception $e) {
        sn_db_transaction_rollback();
        $result = array('STATUS' => $e->getCode(), 'MESSAGE' => $e->getMessage());
    }
    return $result;
}
Example #11
0
            die;
        }
        $prod_id = intval($prod_id);
        if (in_array($prod_id, $sn_group_factories)) {
            $field_name = pname_factory_production_field_name($prod_id);
            $percent = floor($percent / 10);
            $planetrow[$field_name] = $percent;
            $SubQry .= "`{$field_name}` = '{$percent}',";
        } else {
            $debug->warning('Supplying wrong ID in production array - attempt to change some field', 'Resource Page', 301);
            die;
        }
    }
    $SubQry = substr($SubQry, 0, -1);
    if ($SubQry) {
        db_planet_set_by_id($planetrow['id'], $SubQry);
    }
}
// -------------------------------------------------------------------------------------------------------
$BuildTemp = $planetrow['temp_max'];
$BuildEnergyTech = $user['energy_tech'];
for ($Option = 10; $Option >= 0; $Option--) {
    $template->assign_block_vars('option', array('VALUE' => $Option * 10));
}
$caps_real = eco_get_planet_caps($user, $planetrow, 3600);
$template->assign_block_vars('production', array('TYPE' => $lang['res_basic_income'], 'METAL_TYPE' => pretty_number($caps_real['production'][RES_METAL][0], true, true), 'CRYSTAL_TYPE' => pretty_number($caps_real['production'][RES_CRYSTAL][0], true, true), 'DEUTERIUM_TYPE' => pretty_number($caps_real['production'][RES_DEUTERIUM][0], true, true), 'ENERGY_TYPE' => pretty_number($caps_real['production'][RES_ENERGY][0], true, true)));
foreach ($sn_group_factories as $unit_id) {
    if (mrc_get_level($user, $planetrow, $unit_id) > 0 && get_unit_param($unit_id)) {
        $level_plain = mrc_get_level($user, $planetrow, $unit_id, false, true);
        $template->assign_block_vars('production', array('ID' => $unit_id, 'PERCENT' => $planetrow[pname_factory_production_field_name($unit_id)] * 10, 'TYPE' => $lang['tech'][$unit_id], 'LEVEL' => $level_plain, 'LEVEL_BONUS' => mrc_get_level($user, $planetrow, $unit_id) - $level_plain, 'LEVEL_TYPE' => $unit_id > 200 ? $lang['quantity'] : $lang['level'], 'METAL_TYPE' => pretty_number($caps_real['production'][RES_METAL][$unit_id], true, true), 'CRYSTAL_TYPE' => pretty_number($caps_real['production'][RES_CRYSTAL][$unit_id], true, true), 'DEUTERIUM_TYPE' => pretty_number($caps_real['production'][RES_DEUTERIUM][$unit_id], true, true), 'ENERGY_TYPE' => pretty_number($caps_real['production'][RES_ENERGY][$unit_id], true, true), 'METAL_FULL' => pretty_number($caps_real['production_full'][RES_METAL][$unit_id], true, true), 'CRYSTAL_FULL' => pretty_number($caps_real['production_full'][RES_CRYSTAL][$unit_id], true, true), 'DEUTERIUM_FULL' => pretty_number($caps_real['production_full'][RES_DEUTERIUM][$unit_id], true, true), 'ENERGY_FULL' => pretty_number($caps_real['production_full'][RES_ENERGY][$unit_id], true, true), 'SELECT' => $row_select));
    }
Example #12
0
     $sector_cost = $sector_cost[BUILD_CREATE][RES_DARK_MATTER];
     $planet_fill = floor($planetrow['field_current'] / eco_planet_fields_max($planetrow) * 100);
     $planet_fill = $planet_fill > 100 ? 100 : $planet_fill;
     $can_teleport = uni_planet_teleport_check($user, $planetrow);
     $template->assign_vars(array('DARK_MATTER' => $user_dark_matter, 'PLANET_FILL' => floor($planetrow['field_current'] / eco_planet_fields_max($planetrow) * 100), 'PLANET_FILL_BAR' => $planet_fill, 'SECTOR_CAN_BUY' => $sector_cost <= $user_dark_matter, 'SECTOR_COST' => $sector_cost, 'SECTOR_COST_TEXT' => pretty_number($sector_cost), 'planet_field_current' => $planetrow['field_current'], 'planet_field_max' => eco_planet_fields_max($planetrow), 'CAN_TELEPORT' => $can_teleport['result'] == ERR_NONE, 'CAN_NOT_TELEPORT_MSG' => $can_teleport['message'], 'TELEPORT_COST_TEXT' => pretty_number($config->planet_teleport_cost, true, $user_dark_matter), 'CAN_CAPITAL' => $user_dark_matter >= $config->planet_capital_cost, 'CAPITAL_COST_TEXT' => pretty_number($config->planet_capital_cost, true, $user_dark_matter), 'PLANET_DENSITY_INDEX' => $planet_density_index, 'PLANET_CORE_TEXT' => $lang['uni_planet_density_types'][$planet_density_index], 'IS_CAPITAL' => $planetrow['id'] == $user['id_planet'], 'PAGE_HINT' => $lang['ov_manage_page_hint']));
     foreach ($result as &$a_result) {
         $template->assign_block_vars('result', $a_result);
     }
     display($template, $lang['rename_and_abandon_planet']);
     break;
 default:
     sn_sys_sector_buy();
     if (sys_get_param_str('rename') && ($new_name = sys_get_param_str('new_name'))) {
         $planetrow['name'] = $new_name;
         $new_name_safe = db_escape($new_name);
         db_planet_set_by_id($planetrow['id'], "`name` = '{$new_name_safe}'");
     }
     $result[] = sn_sys_planet_core_transmute($user, $planetrow);
     $template = gettemplate('planet_overview', true);
     $user_dark_matter = mrc_get_level($user, false, RES_DARK_MATTER);
     $planet_density_index = $planetrow['density_index'];
     $density_price_chart = planet_density_price_chart($planetrow);
     tpl_planet_density_info($template, $density_price_chart, $user_dark_matter);
     rpg_level_up($user, RPG_STRUCTURE);
     rpg_level_up($user, RPG_RAID);
     rpg_level_up($user, RPG_TECH);
     rpg_level_up($user, RPG_EXPLORE);
     $fleet_id = 1;
     $fleet_list = flt_get_fleets($user['id']);
     $fleets = flt_parse_fleets_to_events($fleet_list);
     $planet_count = 0;
Example #13
0
function sys_o_get_updated($user, $planet, $UpdateTime, $simulation = false, $no_user_update = false)
{
    sn_db_transaction_check(true);
    $no_data = array('user' => false, 'planet' => false, 'que' => false);
    if (!$planet) {
        return $no_data;
    }
    if (!$no_user_update) {
        $user = intval(is_array($user) && $user['id'] ? $user['id'] : $user);
        if (!$user) {
            // TODO - Убрать позже
            print '<h1>СООБЩИТЕ ЭТО АДМИНУ: sys_o_get_updated() - USER пустой!</h1>';
            $backtrace = debug_backtrace();
            array_shift($backtrace);
            pdump($backtrace);
            die;
        }
        $user = db_user_by_id($user, !$simulation, '*', true);
    }
    if (empty($user['id'])) {
        return $no_data;
    }
    if (is_array($planet) && isset($planet['galaxy']) && $planet['galaxy']) {
        $planet = db_planet_by_vector($planet, '', !$simulation);
    } else {
        $planet = intval(is_array($planet) && isset($planet['id']) ? $planet['id'] : $planet);
        $planet = db_planet_by_id($planet, !$simulation);
    }
    if (!is_array($planet) || !isset($planet['id'])) {
        return $no_data;
    }
    $que = que_process($user, $planet, $UpdateTime);
    $ProductionTime = max(0, $UpdateTime - $planet['last_update']);
    $planet['prev_update'] = $planet['last_update'];
    $planet['last_update'] += $ProductionTime;
    /*
    $que = eco_que_process($user, $planet, $ProductionTime);
    $hangar_built = $ProductionTime && !$simulation ? eco_bld_que_hangar($user, $planet, $ProductionTime) : array();
    */
    // TODO ЭТО НАДО ДЕЛАТЬ ТОЛЬКО ПРИ СПЕЦУСЛОВИЯХ
    $caps_real = eco_get_planet_caps($user, $planet, $ProductionTime);
    $resources_increase = array(RES_METAL => 0, RES_CRYSTAL => 0, RES_DEUTERIUM => 0);
    switch ($planet['planet_type']) {
        case PT_PLANET:
            foreach ($resources_increase as $resource_id => &$increment) {
                $resource_name = pname_resource_name($resource_id);
                $increment = $caps_real['total'][$resource_id] * $ProductionTime / 3600;
                $store_free = $caps_real['total_storage'][$resource_id] - $planet[$resource_name];
                $increment = min($increment, max(0, $store_free));
                if ($planet[$resource_name] + $increment < 0 && !$simulation) {
                    global $debug;
                    $debug->warning("Player ID {$user['id']} have negative resources on ID {$planet['id']}.{$planet['planet_type']} [{$planet['galaxy']}:{$planet['system']}:{$planet['planet']}]. Difference {$planet[$resource_name]} of {$resource_name}", 'Negative Resources', 501);
                }
                $planet[$resource_name] += $increment;
                $planet[$resource_name . '_perhour'] = $caps_real['total'][$resource_id];
            }
            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;
    }
    // TODO пересчитывать размер планеты только при постройке чего-нибудь и при покупке сектора
    $planet['field_current'] = 0;
    $sn_group_build_allow = sn_get_groups('build_allow');
    if (is_array($sn_group_build_allow[$planet['planet_type']])) {
        foreach ($sn_group_build_allow[$planet['planet_type']] as $building_id) {
            $planet['field_current'] += mrc_get_level($user, $planet, $building_id, !$simulation, true);
        }
    }
    if ($simulation) {
        return array('user' => $user, 'planet' => $planet, 'que' => $que);
    }
    db_planet_set_by_id($planet['id'], "`last_update` = '{$planet['last_update']}', `field_current` = {$planet['field_current']},\n    `metal` = `metal` + '{$resources_increase[RES_METAL]}', `crystal` = `crystal` + '{$resources_increase[RES_CRYSTAL]}', `deuterium` = `deuterium` + '{$resources_increase[RES_DEUTERIUM]}',\n    `metal_perhour` = '{$planet['metal_perhour']}', `crystal_perhour` = '{$planet['crystal_perhour']}', `deuterium_perhour` = '{$planet['deuterium_perhour']}',\n    `energy_used` = '{$planet['energy_used']}', `energy_max` = '{$planet['energy_max']}'");
    return array('user' => $user, 'planet' => $planet, 'que' => $que);
}
Example #14
0
function sn_options_model()
{
    global $user, $user_option_list, $lang, $template_result, $config;
    $language_new = sys_get_param_str('langer', $user['lang']);
    if ($language_new != $user['lang']) {
        $lang->lng_switch($language_new);
    }
    lng_include('options');
    lng_include('messages');
    $FMT_DATE = preg_replace(array('/d/', '/m/', '/Y/'), array('DD', 'MM', 'YYYY'), FMT_DATE);
    if (sys_get_param_str('mode') == 'change') {
        if ($user['authlevel'] > 0) {
            $planet_protection = sys_get_param_int('adm_pl_prot') ? $user['authlevel'] : 0;
            db_planet_set_by_owner($user['id'], "`id_level` = '{$planet_protection}'");
            db_user_set_by_id($user['id'], "`admin_protection` = '{$planet_protection}'");
            $user['admin_protection'] = $planet_protection;
        }
        if (sys_get_param_int('vacation') && !$config->user_vacation_disable) {
            sn_db_transaction_start();
            if ($user['authlevel'] < 3) {
                if ($user['vacation_next'] > SN_TIME_NOW) {
                    message($lang['opt_vacation_err_timeout'], $lang['Error'], 'index.php?page=options', 5);
                    die;
                }
                $is_building = doquery("SELECT * FROM `{{fleets}}` WHERE `fleet_owner` = '{$user['id']}' LIMIT 1;", true);
                if ($is_building) {
                    message($lang['opt_vacation_err_your_fleet'], $lang['Error'], 'index.php?page=options', 5);
                    die;
                }
                $que = que_get($user['id'], false);
                if (!empty($que)) {
                    message($lang['opt_vacation_err_que'], $lang['Error'], 'index.php?page=options', 5);
                    die;
                }
                $query = classSupernova::db_get_record_list(LOC_PLANET, "`id_owner` = {$user['id']}");
                foreach ($query as $planet) {
                    // $planet = sys_o_get_updated($user, $planet, SN_TIME_NOW);
                    // $planet = $planet['planet'];
                    db_planet_set_by_id($planet['id'], "last_update = " . SN_TIME_NOW . ", energy_used = '0', energy_max = '0',\n            metal_perhour = '{$config->metal_basic_income}', crystal_perhour = '{$config->crystal_basic_income}', deuterium_perhour = '{$config->deuterium_basic_income}',\n            metal_mine_porcent = '0', crystal_mine_porcent = '0', deuterium_sintetizer_porcent = '0', solar_plant_porcent = '0',\n            fusion_plant_porcent = '0', solar_satelit_porcent = '0', ship_sattelite_sloth_porcent = 0");
                }
                $user['vacation'] = SN_TIME_NOW + $config->player_vacation_time;
            } else {
                $user['vacation'] = SN_TIME_NOW;
            }
            sn_db_transaction_commit();
        }
        foreach ($user_option_list as $option_group_id => $option_group) {
            foreach ($option_group as $option_name => $option_value) {
                if ($user[$option_name] !== null) {
                    $user[$option_name] = sys_get_param_str($option_name);
                } else {
                    $user[$option_name] = $option_value;
                }
            }
        }
        $options = sys_user_options_pack($user);
        $player_options = sys_get_param('options');
        if (!empty($player_options)) {
            array_walk($player_options, function (&$value) {
                // TODO - Когда будет больше параметров - сделать больше проверок
                $value = intval($value);
            });
            classSupernova::$user_options->offsetSet($player_options);
            // pdump($player_options);die();
            //      player_save_option_array($user, $player_options);
        }
        $username = substr(sys_get_param_str_unsafe('username'), 0, 32);
        $username_safe = db_escape($username);
        if ($username && $user['username'] != $username && $config->game_user_changename != SERVER_PLAYER_NAME_CHANGE_NONE && sys_get_param_int('username_confirm') && !strpbrk($username, LOGIN_REGISTER_CHARACTERS_PROHIBITED)) {
            // проверка на корректность
            sn_db_transaction_start();
            $name_check = doquery("SELECT * FROM {{player_name_history}} WHERE `player_name` LIKE \"{$username_safe}\" LIMIT 1 FOR UPDATE;", true);
            if (!$name_check || $name_check['player_id'] == $user['id']) {
                $user = db_user_by_id($user['id'], true);
                switch ($config->game_user_changename) {
                    case SERVER_PLAYER_NAME_CHANGE_PAY:
                        if (mrc_get_level($user, $planetrow, RES_DARK_MATTER) < $config->game_user_changename_cost) {
                            $template_result['.']['result'][] = array('STATUS' => ERR_ERROR, 'MESSAGE' => $lang['opt_msg_name_change_err_no_dm']);
                            break;
                        }
                        rpg_points_change($user['id'], RPG_NAME_CHANGE, -$config->game_user_changename_cost, sprintf('Пользователь ID %d сменил имя с "%s" на "%s"', $user['id'], $user['username'], $username));
                    case SERVER_PLAYER_NAME_CHANGE_FREE:
                        db_user_set_by_id($user['id'], "`username` = '{$username_safe}'");
                        doquery("REPLACE INTO {{player_name_history}} SET `player_id` = {$user['id']}, `player_name` = '{$username_safe}'");
                        // TODO: Change cookie to not force user relogin
                        // sn_setcookie(SN_COOKIE, '', time() - PERIOD_WEEK, SN_ROOT_RELATIVE);
                        $template_result['.']['result'][] = array('STATUS' => ERR_NONE, 'MESSAGE' => $lang['opt_msg_name_changed']);
                        $user['username'] = $username;
                        break;
                }
            } else {
                $template_result['.']['result'][] = array('STATUS' => ERR_ERROR, 'MESSAGE' => $lang['opt_msg_name_change_err_used_name']);
            }
            sn_db_transaction_commit();
        }
        if ($new_password = sys_get_param('newpass1')) {
            try {
                if ($new_password != sys_get_param('newpass2')) {
                    throw new Exception($lang['opt_err_pass_unmatched'], ERR_WARNING);
                }
                if (!classSupernova::$auth->password_change(sys_get_param('db_password'), $new_password)) {
                    throw new Exception($lang['opt_err_pass_wrong'], ERR_WARNING);
                }
                throw new Exception($lang['opt_msg_pass_changed'], ERR_NONE);
            } catch (Exception $e) {
                $template_result['.']['result'][] = array('STATUS' => in_array($e->getCode(), array(ERR_NONE, ERR_WARNING, ERR_ERROR)) ? $e->getCode() : ERR_ERROR, 'MESSAGE' => $e->getMessage());
            }
        }
        $user['email'] = sys_get_param_str('db_email');
        //    if(!$template_result[F_ACCOUNT]['account_email'] && ($email_2 = sys_get_param_str('db_email2'))) {
        //      core_auth::email_set($email_2);
        //    }
        $user['dpath'] = sys_get_param_str('dpath');
        $user['lang'] = sys_get_param_str('langer', $user['lang']);
        //    if($lang->lng_switch($user['lang'])) {
        //      lng_include('options');
        //      lng_include('messages');
        //    }
        $user['design'] = sys_get_param_int('design');
        $user['noipcheck'] = sys_get_param_int('noipcheck');
        // $user['spio_anz'] = sys_get_param_int('spio_anz');
        // $user['settings_fleetactions'] = sys_get_param_int('settings_fleetactions', 1);
        // $user['settings_tooltiptime'] = sys_get_param_int('settings_tooltiptime');
        // $user['settings_esp'] = sys_get_param_int('settings_esp');
        // $user['settings_wri'] = sys_get_param_int('settings_wri');
        // $user['settings_bud'] = sys_get_param_int('settings_bud');
        // $user['settings_mis'] = sys_get_param_int('settings_mis');
        // $user['settings_statistics'] = sys_get_param_int('settings_statistics');
        // $user['settings_info'] = sys_get_param_int('settings_info');
        // $user['settings_rep'] = sys_get_param_int('settings_rep');
        // $user['planet_sort']  = sys_get_param_int('settings_sort');
        // $user['planet_sort_order'] = sys_get_param_int('settings_order');
        $user['deltime'] = !sys_get_param_int('deltime') ? 0 : ($user['deltime'] ? $user['deltime'] : SN_TIME_NOW + $config->player_delete_time);
        $gender = sys_get_param_int('gender', $user['gender']);
        !isset($lang['sys_gender_list'][$gender]) ? $gender = $user['gender'] : false;
        $user['gender'] = $user['gender'] == GENDER_UNKNOWN ? $gender : $user['gender'];
        try {
            if ($user['birthday']) {
                throw new exception();
            }
            $user_birthday = sys_get_param_str_unsafe('user_birthday');
            if (!$user_birthday || $user_birthday == $FMT_DATE) {
                throw new exception();
            }
            // Some black magic to parse any valid date format - those that contains all three "d", "m" and "Y" and any of the delimeters "\", "/", ".", "-"
            $pos['d'] = strpos(FMT_DATE, 'd');
            $pos['m'] = strpos(FMT_DATE, 'm');
            $pos['Y'] = strpos(FMT_DATE, 'Y');
            asort($pos);
            $i = 0;
            foreach ($pos as &$position) {
                $position = ++$i;
            }
            $regexp = "/" . preg_replace(array('/\\\\/', '/\\//', '/\\./', '/\\-/', '/d/', '/m/', '/Y/'), array('\\\\\\', '\\/', '\\.', '\\-', '(\\d?\\d)', '(\\d?\\d)', '(\\d{4})'), FMT_DATE) . "/";
            if (!preg_match($regexp, $user_birthday, $match)) {
                throw new exception();
            }
            if (!checkdate($match[$pos['m']], $match[$pos['d']], $match[$pos['Y']])) {
                throw new exception();
            }
            $user['user_birthday'] = db_escape("{$match[$pos['Y']]}-{$match[$pos['m']]}-{$match[$pos['d']]}");
            // EOF black magic! Now we have valid SQL date in $user['user_birthday'] - independent of date format
            $year = date('Y', SN_TIME_NOW);
            if (mktime(0, 0, 0, $match[$pos['m']], $match[$pos['d']], $year) > SN_TIME_NOW) {
                $year--;
            }
            $user['user_birthday_celebrated'] = db_escape("{$year}-{$match[$pos['m']]}-{$match[$pos['d']]}");
            $user_birthday = ", `user_birthday` = '{$user['user_birthday']}', `user_birthday_celebrated` = '{$user['user_birthday_celebrated']}'";
        } catch (exception $e) {
            $user_birthday = '';
        }
        require_once 'includes/includes/sys_avatar.php';
        $avatar_upload_result = sys_avatar_upload($user['id'], $user['avatar']);
        $template_result['.']['result'][] = $avatar_upload_result;
        $user_time_diff = playerTimeDiff::user_time_diff_get();
        if (sys_get_param_int('PLAYER_OPTION_TIME_DIFF_FORCED')) {
            playerTimeDiff::user_time_diff_set(array(PLAYER_OPTION_TIME_DIFF => sys_get_param_int('PLAYER_OPTION_TIME_DIFF'), PLAYER_OPTION_TIME_DIFF_UTC_OFFSET => 0, PLAYER_OPTION_TIME_DIFF_FORCED => 1, PLAYER_OPTION_TIME_DIFF_MEASURE_TIME => SN_TIME_SQL));
        } elseif (sys_get_param_int('opt_time_diff_clear') || $user_time_diff[PLAYER_OPTION_TIME_DIFF_FORCED]) {
            playerTimeDiff::user_time_diff_set(array(PLAYER_OPTION_TIME_DIFF => '', PLAYER_OPTION_TIME_DIFF_UTC_OFFSET => 0, PLAYER_OPTION_TIME_DIFF_FORCED => 0, PLAYER_OPTION_TIME_DIFF_MEASURE_TIME => SN_TIME_SQL));
        }
        $user_options_safe = db_escape($user['options']);
        db_user_set_by_id($user['id'], "`email` = '{$user['email']}', `lang` = '{$user['lang']}', `avatar` = '{$user['avatar']}',\n      `dpath` = '{$user['dpath']}', `design` = '{$user['design']}', `noipcheck` = '{$user['noipcheck']}',\n      `deltime` = '{$user['deltime']}', `vacation` = '{$user['vacation']}', `options` = '{$user_options_safe}', `gender` = {$user['gender']}\n      {$user_birthday}");
        $template_result['.']['result'][] = array('STATUS' => ERR_NONE, 'MESSAGE' => $lang['opt_msg_saved']);
    } elseif (sys_get_param_str('result') == 'ok') {
        $template_result['.']['result'][] = array('STATUS' => ERR_NONE, 'MESSAGE' => $lang['opt_msg_saved']);
    }
    $user = db_user_by_id($user['id']);
    $options = sys_user_options_unpack($user);
}
Example #15
0
    $QryInsertFleet .= "`fleet_amount` = '{$fleet_ship_count}', ";
    $QryInsertFleet .= "`fleet_array` = '{$FleetDBArray}', ";
    $QryInsertFleet .= "`fleet_start_time` = '{$fleet_start_time}', ";
    if ($planetrow['id']) {
        $QryInsertFleet .= "`fleet_start_planet_id` = '{$planetrow['id']}', ";
    }
    $QryInsertFleet .= "`fleet_start_galaxy` = '{$planetrow['galaxy']}', `fleet_start_system` = '{$planetrow['system']}', `fleet_start_planet` = '{$planetrow['planet']}', `fleet_start_type`   = '{$planetrow['planet_type']}', ";
    $QryInsertFleet .= "`fleet_end_time` = '{$fleet_end_time}', ";
    if ($target_row['id']) {
        $QryInsertFleet .= "`fleet_end_planet_id` = '{$target_row['id']}', ";
    }
    $QryInsertFleet .= "`fleet_end_galaxy` = '{$target_coord['galaxy']}', `fleet_end_system` = '{$target_coord['system']}', `fleet_end_planet` = '{$target_coord['planet']}', `fleet_end_type` = '{$target_planet_type}', ";
    $QryInsertFleet .= "`fleet_target_owner` = '{$target_row['id_owner']}', ";
    $QryInsertFleet .= "`start_time` = " . SN_TIME_NOW . ";";
    doquery($QryInsertFleet);
}
db_planet_set_by_id($planetrow['id'], "`deuterium` = `deuterium` - {$travel_data['consumption']}");
db_changeset_apply($db_changeset);
sn_db_transaction_commit();
$ships_sent = array();
//$ships_sent_js = array();
$ships_sent_js = 0;
foreach ($fleet_array as $unit_id => $unit_count) {
    $ships_sent[] = "{$unit_count} {$lang['tech'][$unit_id]}";
    $ships_sent_js += mrc_get_level($user, $planetrow, $unit_id, false, true);
}
$ships_sent = implode(', ', $ships_sent);
//$ships_sent_js = implode(',', $ships_sent_js);
$ships_sent_js = "{$unit_group}={$ships_sent_js}";
$ResultMessage = "{$lang['gs_sending']} {$ships_sent} {$lang['gs_to']} {$target_coord['galaxy']}:{$target_coord['system']}:{$target_coord['planet']}|{$ships_sent_js}";
die($ResultMessage);
Example #16
0
require '../common.' . substr(strrchr(__FILE__, '.'), 1);
// if($user['authlevel'] < 2)
if ($user['authlevel'] < 3) {
    AdminMessage($lang['adm_err_denied']);
}
AdminMessage('Временно не работает');
require "includes/admin_planet_edit.inc" . DOT_PHP_EX;
$template = gettemplate('admin/admin_planet_edit', true);
$mode = admin_planet_edit_mode($template, $admin_planet_edit_mode_list);
$planet_id = sys_get_param_id('planet_id');
$unit_list = sys_get_param('unit_list');
if (sys_get_param('change_data') && !empty($unit_list)) {
    $query_string = array();
    foreach ($unit_list as $unit_id => $unit_amount) {
        if ($unit_query_string = admin_planet_edit_query_string($unit_id, $unit_amount, $mode)) {
            $query_string[] = $unit_query_string;
        }
    }
    if (!empty($query_string)) {
        db_planet_set_by_id($planet_id, implode(', ', $query_string));
    }
}
if ($planet_id) {
    $edit_planet_row = db_planet_by_id($planet_id);
    admin_planet_edit_template($template, $edit_planet_row, $mode);
}
foreach ($admin_planet_edit_mode_list as $page_mode => $mode_locale) {
    $template->assign_block_vars('page_menu', array('ID' => $page_mode, 'TEXT' => $mode_locale));
}
$template->assign_vars(array('MODE' => $mode, 'PLANET_ID' => $planet_id, 'PLANET_NAME' => empty($edit_planet_row) ? '' : $lang['sys_planet_type'][$edit_planet_row['planet_type']] . ' ' . uni_render_planet($edit_planet_row), 'PAGE_HINT' => $lang['adm_planet_edit_hint']));
display($template, $lang['adm_am_ttle'], false, '', true);
Example #17
0
             $ship_list = sys_get_param('ships');
             $db_changeset = array();
             foreach ($ship_list as $ship_id => $ship_count) {
                 if (!in_array($ship_id, sn_get_groups('fleet'))) {
                     continue;
                 }
                 $ship_count = max(0, min(floor($ship_count), mrc_get_level($user, $planetrow, $ship_id)));
                 if ($ship_count) {
                     $db_changeset['unit'][] = sn_db_unit_changeset_prepare($ship_id, -$ship_count, $user, $planetrow['id']);
                     $db_changeset['unit'][] = sn_db_unit_changeset_prepare($ship_id, $ship_count, $user, $TargetGate['id']);
                 }
             }
             // Dit monsieur, y avait quelque chose a envoyer ???
             if (!empty($db_changeset)) {
                 db_planet_set_by_id($TargetGate['id'], "`last_jump_time` = " . SN_TIME_NOW . "");
                 db_planet_set_by_id($planetrow['id'], "`last_jump_time` = " . SN_TIME_NOW . "");
                 db_changeset_apply($db_changeset);
                 db_user_set_by_id($user['id'], "`current_planet` = '{$TargetGate['id']}'");
                 $planetrow['last_jump_time'] = SN_TIME_NOW;
                 $RetMessage = $lang['gate_jump_done'] . " - " . pretty_time(uni_get_time_to_jump($planetrow));
             } else {
                 $RetMessage = $lang['gate_wait_data'];
             }
         } else {
             $RetMessage = $lang['gate_wait_dest'] . " - " . pretty_time($NextDestTime);
         }
     } else {
         $RetMessage = $lang['gate_no_dest_g'];
     }
 } else {
     $RetMessage = $lang['gate_wait_star'] . " - " . pretty_time($NextJumpTime);
Example #18
0
$scan_system = sys_get_param_int('system');
$scan_planet = sys_get_param_int('planet');
$scan_planet_type = 1;
// sys_get_param_int('planettype');
$id = sys_get_param_id('id');
$source_galaxy = $planetrow['galaxy'];
$source_system = $planetrow['system'];
$source_planet = $planetrow['planet'];
$sensorRange = GetPhalanxRange($sensorLevel);
$system_distance = abs($source_system - $scan_system);
if ($system_distance > $sensorRange || $scan_galaxy != $source_galaxy) {
    message($lang['phalanx_rangeerror'], $lang['tech'][STRUC_MOON_PHALANX], '', 3);
}
$cost = $sensorLevel * 1000;
if ($planetrow['deuterium'] < $cost) {
    message($lang['phalanx_nodeuterium'], "phalanx", '', 3);
}
$planet_scanned = db_planet_by_gspt($scan_galaxy, $scan_system, $scan_planet, $scan_planet_type);
if (!$planet_scanned['id']) {
    message($lang['phalanx_planet_not_exists'], $lang['tech'][STRUC_MOON_PHALANX], '', 3);
}
if ($planet_scanned['destruyed']) {
    message($lang['phalanx_planet_destroyed'], $lang['tech'][STRUC_MOON_PHALANX], '', 3);
}
db_planet_set_by_id($user['current_planet'], "deuterium = deuterium - {$cost}");
$template = gettemplate('planet_fleet_list', true);
$fleet_list = flt_get_fleets($planet_scanned, true);
$fleets = flt_parse_fleets_to_events($fleet_list, $planet_scanned);
//int_get_missile_to_planet("SELECT * FROM `{{iraks}}` WHERE fleet_end_galaxy = {$scan_galaxy} AND fleet_end_system = {$scan_system} AND fleet_end_planet = {$scan_planet};");
tpl_assign_fleet($template, $fleets);
display($template, $lang['tech'][STRUC_MOON_PHALANX], false, '', false, false);
Example #19
0
function que_delete($que_type, $user = array(), $planet = array(), $clear = false)
{
    $planets_locked = array();
    // TODO: Some checks
    sn_db_transaction_start();
    $user = db_user_by_id($user['id'], true);
    $planet['id'] = $planet['id'] && $que_type !== QUE_RESEARCH ? $planet['id'] : 0;
    $global_que = que_get($user['id'], $planet['id'], $que_type, true);
    //pdump($global_que);
    //pdump($planet['id']);
    //pdump($global_que[$que_type][$planet['id']]);
    if (!empty($global_que['ques'][$que_type][$user['id']][$planet['id']])) {
        $que = array_reverse($global_que['ques'][$que_type][$user['id']][$planet['id']]);
        foreach ($que as $que_item) {
            db_que_delete_by_id($que_item['que_id']);
            if ($que_item['que_planet_id_origin']) {
                $planet['id'] = $que_item['que_planet_id_origin'];
            }
            if (!isset($planets_locked[$planet['id']])) {
                $planets_locked[$planet['id']] = $planet['id'] ? db_planet_by_id($planet['id'], true) : $planet;
            }
            $build_data = sys_unit_str2arr($que_item['que_unit_price']);
            db_change_units($user, $planets_locked[$planet['id']], array(RES_METAL => $build_data[RES_METAL] * $que_item['que_unit_amount'], RES_CRYSTAL => $build_data[RES_CRYSTAL] * $que_item['que_unit_amount'], RES_DEUTERIUM => $build_data[RES_DEUTERIUM] * $que_item['que_unit_amount']));
            if (!$clear) {
                break;
            }
        }
        if (is_numeric($planet['id'])) {
            db_planet_set_by_id($planet['id'], "`que_processed` = UNIX_TIMESTAMP(NOW())");
        } elseif (is_numeric($user['id'])) {
            db_user_set_by_id($user['id'], '`que_processed` = UNIX_TIMESTAMP(NOW())');
        }
        sn_db_transaction_commit();
    } else {
        sn_db_transaction_rollback();
    }
    //die();
    header("Location: {$_SERVER['PHP_SELF']}?mode={$que_type}" . "&ally_id=" . sys_get_param_id('ally_id'));
}
Example #20
0
     }
 } elseif (($hire = sys_get_param_int('hire')) && in_array($hire, sn_get_groups('governors')) && (!get_unit_param($hire, P_MAX_STACK) || $planetrow['PLANET_GOVERNOR_ID'] != $hire || $planetrow['PLANET_GOVERNOR_ID'] == $hire && $planetrow['PLANET_GOVERNOR_LEVEL'] < get_unit_param($hire, P_MAX_STACK))) {
     sn_db_transaction_start();
     $user = db_user_by_id($user['id'], true);
     $planetrow = db_planet_by_id($planetrow['id'], true);
     $build_data = eco_get_build_data($user, $planetrow, $hire, $planetrow['PLANET_GOVERNOR_ID'] == $hire ? $planetrow['PLANET_GOVERNOR_LEVEL'] : 0);
     if ($build_data['CAN'][BUILD_CREATE]) {
         if ($planetrow['PLANET_GOVERNOR_ID'] == $hire) {
             $planetrow['PLANET_GOVERNOR_LEVEL']++;
             $query = '`PLANET_GOVERNOR_LEVEL` + 1';
         } else {
             $planetrow['PLANET_GOVERNOR_LEVEL'] = 1;
             $planetrow['PLANET_GOVERNOR_ID'] = $hire;
             $query = '1';
         }
         db_planet_set_by_id($planetrow['id'], "`PLANET_GOVERNOR_ID` = {$hire}, `PLANET_GOVERNOR_LEVEL` = {$query}");
         rpg_points_change($user['id'], RPG_GOVERNOR, -$build_data[BUILD_CREATE][RES_DARK_MATTER], sprintf($lang['ov_governor_purchase'], $lang['tech'][$hire], $hire, $planetrow['PLANET_GOVERNOR_LEVEL'], uni_render_planet_full($planetrow, '', false, true)));
         //  => 'Игрок купил Губернатора %1$s ID %2$d уровня %3$d на планету %4$s',
         // die();
     }
     sn_db_transaction_commit();
     sys_redirect('overview.php?mode=manage');
     die;
 }
 lng_include('mrc_mercenary');
 int_planet_pretemplate($planetrow, $template);
 foreach (sn_get_groups('governors') as $governor_id) {
     if ($planetrow['planet_type'] == PT_MOON && $governor_id == MRC_TECHNOLOGIST) {
         continue;
     }
     $governor_level = $planetrow['PLANET_GOVERNOR_ID'] == $governor_id ? $planetrow['PLANET_GOVERNOR_LEVEL'] : 0;
Example #21
0
function art_use(&$user, &$planetrow, $unit_id)
{
    global $lang;
    if (!in_array($unit_id, sn_get_groups('artifacts'))) {
        return;
    }
    sn_db_transaction_start();
    $user = db_user_by_id($user['id'], true);
    $unit_level = $artifact_level_old = mrc_get_level($user, array(), $unit_id, true);
    if ($unit_level > 0) {
        $db_changeset = array();
        switch ($unit_id) {
            case ART_LHC:
            case ART_HOOK_SMALL:
            case ART_HOOK_MEDIUM:
            case ART_HOOK_LARGE:
                $has_moon = db_planet_by_parent($planetrow['id'], true, '`id`');
                if ($planetrow['planet_type'] == PT_PLANET && !$has_moon['id']) {
                    $unit_level--;
                    $moon_chance = $unit_id == ART_LHC ? uni_calculate_moon_chance($planetrow['debris_metal'] + $planetrow['debris_crystal']) : ($unit_id == ART_HOOK_MEDIUM ? mt_rand(1100, 8999) : ($unit_id == ART_HOOK_SMALL ? 1100 : 8999));
                    $random = $unit_id == ART_LHC ? mt_rand(1, 100) : $moon_chance;
                    if ($random <= $moon_chance) {
                        $new_moon_row = uni_create_moon($planetrow['galaxy'], $planetrow['system'], $planetrow['planet'], $user['id'], $moon_chance);
                        $message = sprintf($lang['art_moon_create'][$unit_id], $new_moon_row['name'], uni_render_coordinates($planetrow), pretty_number($moon_chance));
                    } else {
                        $message = $lang['art_lhc_moon_fail'];
                    }
                    msg_send_simple_message($user['id'], 0, 0, MSG_TYPE_ADMIN, $lang['art_lhc_from'], $lang['art_lhc_subj'], $message);
                } else {
                    $message = $lang['art_moon_exists'];
                }
                break;
            case ART_RCD_SMALL:
            case ART_RCD_MEDIUM:
            case ART_RCD_LARGE:
                $planetrow = db_planet_by_id($planetrow['id'], true);
                if ($planetrow['planet_type'] != PT_PLANET) {
                    $message = $lang['art_rcd_err_moon'];
                    break;
                }
                $que = que_get($user['id'], $planetrow['id'], QUE_STRUCTURES, false);
                if (!empty($que['items'])) {
                    $message = $lang['art_rcd_err_que'];
                    break;
                }
                $artifact_deploy = get_unit_param($unit_id, P_DEPLOY);
                // $deployment_str = '';
                $sectors_used = 0;
                foreach ($artifact_deploy as $deploy_unit_id => $deploy_unit_level) {
                    if (!($levels_deployed = max(0, $deploy_unit_level - mrc_get_level($user, $planetrow, $deploy_unit_id, true, true)))) {
                        continue;
                    }
                    $sectors_used += $levels_deployed;
                    $db_changeset['unit'][] = sn_db_unit_changeset_prepare($deploy_unit_id, $levels_deployed, $user, $planetrow['id']);
                    //$deploy_unit_name = get_unit_param($deploy_unit_id, P_NAME);
                    //$deployment_str .= ",`{$deploy_unit_name}` = GREATEST(`{$deploy_unit_name}`, {$deploy_unit_level})";
                }
                if ($sectors_used == 0) {
                    $message = $lang['art_rcd_err_no_sense'];
                    break;
                }
                $unit_level--;
                db_planet_set_by_id($planetrow['id'], "`field_current` = `field_current` + {$sectors_used}");
                $message = sprintf($lang['art_rcd_ok'], $lang['tech'][$unit_id], $planetrow['name'], uni_render_coordinates($planetrow));
                msg_send_simple_message($user['id'], 0, 0, MSG_TYPE_QUE, $lang['art_rcd_subj'], $lang['art_rcd_subj'], $message);
                break;
            case ART_HEURISTIC_CHIP:
                $que_item = null;
                $que = que_get($user['id'], $planetrow['id'], QUE_RESEARCH, true);
                $current_que =& $que['ques'][QUE_RESEARCH][$user['id']][0];
                if (!empty($current_que)) {
                    reset($current_que);
                    $que_item =& $que['ques'][QUE_RESEARCH][$user['id']][0][key($current_que)];
                }
                if (!empty($que_item) && $que_item['que_time_left'] > 60) {
                    $unit_level--;
                    $old_time = $que_item['que_time_left'];
                    $que_item['que_time_left'] = $que_item['que_time_left'] > PERIOD_HOUR ? ceil($que_item['que_time_left'] / 2) : 0;
                    db_que_set_time_left_by_id($que_item['que_id'], $que_item['que_time_left']);
                    $message = sprintf($lang['art_heurestic_chip_ok'], $lang['tech'][$que_item['que_unit_id']], $que_item['que_unit_level'], sys_time_human($old_time - $que_item['que_time_left']));
                    msg_send_simple_message($user['id'], 0, 0, MSG_TYPE_QUE, $lang['art_heurestic_chip_subj'], $lang['art_heurestic_chip_subj'], $message);
                } else {
                    $message = $lang['art_heurestic_chip_no_research'];
                }
                break;
            case ART_NANO_BUILDER:
                $planetrow = db_planet_by_id($planetrow['id'], true);
                $que_item = null;
                $que = que_get($user['id'], $planetrow['id'], QUE_STRUCTURES, true);
                $current_que =& $que['ques'][QUE_STRUCTURES][$user['id']][$planetrow['id']];
                // $que_item = &$que['que'][QUE_STRUCTURES][0];
                if (!empty($current_que)) {
                    reset($current_que);
                    $que_item =& $que['ques'][QUE_STRUCTURES][$user['id']][$planetrow['id']][key($current_que)];
                }
                if (isset($que_item) && $que_item['que_time_left'] > 60) {
                    $unit_level--;
                    $old_time = $que_item['que_time_left'];
                    $que_item['que_time_left'] = $que_item['que_time_left'] > PERIOD_HOUR ? ceil($que_item['que_time_left'] / 2) : 0;
                    db_que_set_time_left_by_id($que_item['que_id'], $que_item['que_time_left']);
                    $message = sprintf($lang['art_nano_builder_ok'], $que_item['que_unit_mode'] == BUILD_CREATE ? $lang['art_nano_builder_build'] : $lang['art_nano_builder_destroy'], $lang['tech'][$que_item['que_unit_id']], $que_item['que_unit_level'], $planetrow['name'], uni_render_coordinates($planetrow), sys_time_human($old_time - $que_item['que_time_left']));
                    msg_send_simple_message($user['id'], 0, 0, MSG_TYPE_QUE, $lang['art_nano_builder_subj'], $lang['art_nano_builder_subj'], $message);
                } else {
                    $message = $lang['art_nano_builder_no_que'];
                }
                break;
        }
        if ($unit_level != $artifact_level_old) {
            $db_changeset['unit'][] = sn_db_unit_changeset_prepare($unit_id, $unit_level - $artifact_level_old, $user);
            db_changeset_apply($db_changeset);
        }
    } else {
        $message = $lang['art_err_no_artifact'];
    }
    sn_db_transaction_commit();
    message($message, "{$lang['tech'][UNIT_ARTIFACTS]} - {$lang['tech'][$unit_id]}", ($request_uri = sys_get_param_str_unsafe('REQUEST_URI')) ? $request_uri : 'artifacts' . DOT_PHP_EX . '#' . $unit_id, 5);
}