Example #1
0
/**
 * @param classConfig $config
 */
function init_update(&$config)
{
    $update_file = SN_ROOT_PHYSICAL . "includes/update" . DOT_PHP_EX;
    if (file_exists($update_file)) {
        if (filemtime($update_file) > $config->db_loadItem('var_db_update') || $config->db_loadItem('db_version') < DB_VERSION) {
            if (defined('IN_ADMIN')) {
                sn_db_transaction_start();
                // Для защиты от двойного запуска апдейта - начинаем транзакцию. Так запись в базе будет блокирована
                if (SN_TIME_NOW >= $config->db_loadItem('var_db_update_end')) {
                    $config->db_saveItem('var_db_update_end', SN_TIME_NOW + ($config->upd_lock_time ? $config->upd_lock_time : 300));
                    sn_db_transaction_commit();
                    require_once $update_file;
                    sys_refresh_tablelist();
                    $current_time = time();
                    $config->db_saveItem('var_db_update', $current_time);
                    $config->db_saveItem('var_db_update_end', $current_time);
                } elseif (filemtime($update_file) > $config->var_db_update) {
                    $timeout = $config->var_db_update_end - SN_TIME_NOW;
                    die("Обновляется база данных. Рассчетное время окончания - {$timeout} секунд (время обновления может увеличиваться). Пожалуйста, подождите...<br />\n            Obnovljaetsja baza dannyh. Rasschetnoe vremya okonchanija - {$timeout} secund. Pozhalujsta, podozhdute...<br />\n            Database update in progress. Estimated update time {$timeout} seconds (can increase depending on update process). Please wait...");
                }
                sn_db_transaction_rollback();
            } else {
                die('Происходит обновление сервера - пожалуйста, подождите...<br />
          Proishodit obnovlenie servera - pozhalujsta, podozhdute...<br />
          Server upgrading now - please wait...<br />
          <a href="admin/overview.php">Admin link</a>');
            }
        }
    }
}
Example #2
0
/**
 * @param $UserID
 */
function DeleteSelectedUser($UserID)
{
    // TODO: Full rewrite
    sn_db_transaction_start();
    $TheUser = db_user_by_id($UserID);
    if ($TheUser['ally_id'] != 0) {
        $TheAlly = doquery("SELECT * FROM `{{alliance}}` WHERE `id` = '" . $TheUser['ally_id'] . "';", '', true);
        $TheAlly['ally_members'] -= 1;
        if ($TheAlly['ally_members'] > 0) {
            doquery("UPDATE `{{alliance}}` SET `ally_members` = '" . $TheAlly['ally_members'] . "' WHERE `id` = '" . $TheAlly['id'] . "';");
        } else {
            doquery("DELETE FROM `{{alliance}}` WHERE `id` = '" . $TheAlly['id'] . "';");
            doquery("DELETE FROM `{{statpoints}}` WHERE `stat_type` = '2' AND `id_owner` = '" . $TheAlly['id'] . "';");
        }
    }
    doquery("DELETE FROM `{{statpoints}}` WHERE `stat_type` = '1' AND `id_owner` = '" . $UserID . "';");
    db_planet_list_delete_by_owner($UserID);
    doquery("DELETE FROM `{{messages}}` WHERE `message_sender` = '" . $UserID . "';");
    doquery("DELETE FROM `{{messages}}` WHERE `message_owner` = '" . $UserID . "';");
    doquery("DELETE FROM `{{notes}}` WHERE `owner` = '" . $UserID . "';");
    doquery("DELETE FROM `{{fleets}}` WHERE `fleet_owner` = '" . $UserID . "';");
    //  doquery ( "DELETE FROM `{{rw}}` WHERE `id_owner1` = '" . $UserID . "';");
    //  doquery ( "DELETE FROM `{{rw}}` WHERE `id_owner2` = '" . $UserID . "';");
    doquery("DELETE FROM `{{buddy}}` WHERE `BUDDY_SENDER_ID` = '" . $UserID . "';");
    doquery("DELETE FROM `{{buddy}}` WHERE `BUDDY_OWNER_ID` = '" . $UserID . "';");
    doquery("DELETE FROM `{{annonce}}` WHERE `user` = '" . $UserID . "';");
    classSupernova::db_del_record_by_id(LOC_USER, $UserID);
    doquery("DELETE FROM `{{referrals}}` WHERE (`id` = '{$UserID}') OR (`id_partner` = '{$UserID}');");
    global $config;
    $config->db_saveItem('users_amount', $config->db_loadItem('users_amount') - 1);
    sn_db_transaction_commit();
}
Example #3
0
function scheduler_process()
{
    global $config, $user, $debug, $lang;
    $is_admin_request = false;
    $ts_var_stat_update = strtotime($config->db_loadItem('var_stat_update'));
    $ts_scheduled_update = sys_schedule_get_prev_run($config->db_loadItem('stats_schedule'), $config->var_stat_update);
    if (sys_get_param_int('admin_update')) {
        define('USER_LEVEL', isset($user['authlevel']) ? $user['authlevel'] : -1);
        if (USER_LEVEL > 0) {
            $is_admin_request = true;
            $ts_scheduled_update = SN_TIME_NOW;
        }
    }
    if ($ts_scheduled_update > $ts_var_stat_update) {
        lng_include('admin');
        sn_db_transaction_start();
        $ts_var_stat_update_end = strtotime($config->db_loadItem('var_stat_update_end'));
        if (SN_TIME_NOW > $ts_var_stat_update_end) {
            $old_server_status = $config->db_loadItem('game_disable');
            $config->db_saveItem('game_disable', GAME_DISABLE_STAT);
            $config->db_saveItem('var_stat_update_end', date(FMT_DATE_TIME_SQL, SN_TIME_NOW + ($config->db_loadItem('stats_minimal_interval') ? $config->stats_minimal_interval : 600)));
            $config->db_saveItem('var_stat_update_msg', 'Update started');
            sn_db_transaction_commit();
            $msg = $is_admin_request ? 'admin request' : 'scheduler';
            $next_run = date(FMT_DATE_TIME_SQL, sys_schedule_get_prev_run($config->stats_schedule, $config->var_stat_update, true));
            $msg = "Running stat updates: {$msg}. Config->var_stat_update = " . $config->var_stat_update . ', $ts_scheduled_update = ' . date(FMT_DATE_TIME_SQL, $ts_scheduled_update) . ', next_stat_update = ' . $next_run;
            $debug->warning($msg, 'Stat update', LOG_INFO_STAT_PROCESS);
            $total_time = microtime(true);
            // require_once('../includes/sys_stat.php');
            require_once SN_ROOT_PHYSICAL . 'includes/includes/sys_stat.php';
            sys_stat_calculate();
            $total_time = microtime(true) - $total_time;
            $msg = "Stat update complete in {$total_time} seconds.";
            $debug->warning($msg, 'Stat update', LOG_INFO_STAT_PROCESS);
            $msg = "{$lang['adm_done']}: {$total_time} {$lang['sys_sec']}.";
            // . date(FMT_DATE_TIME, $ts_scheduled_update) . ' ' . date(FMT_DATE_TIME, $config->var_stat_update);
            // TODO: Analyze maintenance result. Add record to log if error. Add record to log if OK
            $maintenance_result = sys_maintenance();
            $config->db_saveItem('var_stat_update', SN_TIME_SQL);
            $config->db_saveItem('var_stat_update_msg', $msg);
            $config->db_saveItem('var_stat_update_next', $next_run);
            $config->db_saveItem('var_stat_update_admin_forced', SN_TIME_SQL);
            $config->db_saveItem('var_stat_update_end', SN_TIME_SQL);
            $config->db_saveItem('game_disable', $old_server_status);
        } elseif ($ts_scheduled_update > $ts_var_stat_update) {
            $timeout = strtotime($config->db_loadItem('var_stat_update_end')) - SN_TIME_NOW;
            $msg = $config->db_loadItem('var_stat_update_msg');
            $msg = "{$msg} ETA {$timeout} seconds. Please wait...";
        }
        sn_db_transaction_rollback();
    } elseif ($is_admin_request) {
        $msg = 'Stat is up to date';
    }
    return $msg;
}
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();
}
Example #5
0
function survey_vote(&$user)
{
    if (empty($user['id'])) {
        return true;
    }
    sn_db_transaction_start();
    $survey_id = sys_get_param_id('survey_id');
    $is_voted = doquery("SELECT `survey_vote_id` FROM `{{survey_votes}}` WHERE survey_parent_id = {$survey_id} AND survey_vote_user_id = {$user['id']} FOR UPDATE;", true);
    if (empty($is_voted)) {
        $survey_vote_id = sys_get_param_id('survey_vote');
        $is_answer_exists = doquery("SELECT `survey_answer_id` FROM `{{survey_answers}}` WHERE survey_parent_id = {$survey_id} AND survey_answer_id = {$survey_vote_id};", true);
        if (!empty($is_answer_exists)) {
            $user_name_safe = db_escape($user['username']);
            doquery("INSERT INTO {{survey_votes}} SET `survey_parent_id` = {$survey_id}, `survey_parent_answer_id` = {$survey_vote_id}, `survey_vote_user_id` = {$user['id']}, `survey_vote_user_name` = '{$user_name_safe}';");
        }
    }
    sn_db_transaction_commit();
    return true;
}
Example #6
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 #7
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 #8
0
function sn_sec_login_register($username_unsafe, $password_raw, $email_unsafe, $language, $remember_me = 1, &$result)
{
    global $lang, $config;
    sn_db_transaction_start();
    try {
        if ($config->game_mode == GAME_BLITZ) {
            throw new exception(REGISTER_ERROR_USERNAME_WRONG, ERR_ERROR);
        }
        if (!$username_unsafe) {
            throw new exception(REGISTER_ERROR_USERNAME_WRONG, ERR_ERROR);
        }
        $username_safe = db_escape($username_unsafe);
        $db_check = doquery("SELECT `player_id` FROM {{player_name_history}} WHERE `player_name` = '{$username_safe}' LIMIT 1;", true);
        if (!empty($db_check)) {
            throw new exception(REGISTER_ERROR_USERNAME_EXISTS, ERR_ERROR);
        }
        if (strlen(trim($password_raw)) < 4 || strlen(trim($password_raw)) != strlen($password_raw)) {
            throw new exception(REGISTER_ERROR_PASSWORD_INSECURE, ERR_ERROR);
        }
        $password_raw = trim($password_raw);
        //    $password_repeat_raw = trim(sys_get_param('password_repeat'));
        //    if($password_raw <> $password_repeat_raw) {
        //      throw new exception(REGISTER_ERROR_PASSWORD_DIFFERENT, ERR_ERROR);
        //    }
        if (db_user_by_email($email_unsafe, true)) {
            throw new exception(REGISTER_ERROR_EMAIL_EXISTS, ERR_ERROR);
        }
        player_create($username_unsafe, $password_raw, $email_unsafe, array('partner_id' => $partner_id = sys_get_param_int('id_ref', sys_get_param_int('partner_id')), 'language_iso' => $language, 'remember_me' => $remember_me));
        sn_db_transaction_commit();
        $email_message = sprintf($lang['log_reg_email_text'], $config->game_name, SN_ROOT_VIRTUAL, sys_safe_output($username_unsafe), sys_safe_output($password_raw));
        @mymail($email_unsafe, sprintf($lang['log_reg_email_title'], $config->game_name), $email_message);
        // sec_set_cookie_by_fields($user['id'], $user['username'], $user['password'], $remember_me);
        $result = REGISTER_SUCCESS;
    } catch (exception $e) {
        sn_db_transaction_rollback();
        $result = $e->getMessage();
    }
    return $result;
}
Example #9
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'));
}
function flt_flying_fleet_handler($skip_fleet_update = false)
{
    /*
    [*] Нужно ли заворачивать ВСЕ в одну транзакцию?
          С одной стороны - да, что бы данные были гарантированно на момент снапшота
          С другой стороны - нет, потому что при большой активности это все будет блокировать слишком много рядов, да и таймаут будет большой для ожидания всего разлоченного
          Стоит завернуть каждую миссию отдельно? Это сильно увеличит количество запросов, зато так же сильно снизит количество блокировок.
        Resume: НЕТ! Надо оставить все в одной транзакции! Так можно будет поддерживать consistency кэша. Там буквально сантисекунды блокировки
    [*] Убрать кэшированние данных о пользователях и планета. Офигенно освободит память - проследить!
          НЕТ! Считать, скольким флотам нужна будет инфа и кэшировать только то, что используется больше раза!
          Заодно можно будет исключить перересчет очередей/ресурсов - сильно ускорит дело!
          Особенно будет актуально, когда все бонусы будут в одной таблице
          Ну и никто не заставляет как сейчас брать ВСЕ из таблицы - только по полям. Гемор, но не сильный - сделать запрос по группам sn_data
          И писать в БД только один раз результат
    [*] Нужно ли на этом этапе знать полную информацию о флотах?
          Заблокировать флоты можно и неполным запросом. Блокировка флотов - это не страшно. Ну, не пройдет одна-две отмены - так никто и не гарантировал реалтайма!
          С одной стороны - да, уменьшит количество запросов
          С другой стооны - расход памяти
          Все равно надо будет знать полную инфу о флоте в момент обработки
    [*] Сделать тестовую БД для расчетов
    [*] Но не раньше, чем переписать все миссии
    */
    global $config, $debug;
    if ($config->game_disable != GAME_DISABLE_NONE || $skip_fleet_update) {
        return;
    }
    sn_db_transaction_start();
    if ($config->db_loadItem('game_disable') != GAME_DISABLE_NONE || SN_TIME_NOW - strtotime($config->db_loadItem('fleet_update_last')) <= $config->fleet_update_interval) {
        sn_db_transaction_rollback();
        return;
    }
    // Watchdog timer
    if ($config->db_loadItem('fleet_update_lock')) {
        if (SN_TIME_NOW - strtotime($config->fleet_update_lock) <= mt_rand(240, 300)) {
            sn_db_transaction_rollback();
            return;
        } else {
            $debug->warning('Flying fleet handler was locked too long - watchdog unlocked', 'FFH Error', 504);
        }
    }
    $config->db_saveItem('fleet_update_lock', SN_TIME_SQL);
    $config->db_saveItem('fleet_update_last', SN_TIME_SQL);
    sn_db_transaction_commit();
    //log_file('Начинаем обсчёт флотов');
    //log_file('Обсчёт ракет');
    sn_db_transaction_start();
    coe_o_missile_calculate();
    sn_db_transaction_commit();
    $fleet_list = array();
    $fleet_event_list = array();
    $missions_used = array();
    sn_db_transaction_start();
    //log_file('Запрос на флоты');
    $_fleets = doquery("SELECT * FROM `{{fleets}}` WHERE\n    (`fleet_start_time` <= " . SN_TIME_NOW . " AND `fleet_mess` = 0)\n    OR (`fleet_end_stay` <= " . SN_TIME_NOW . " AND fleet_end_stay > 0 AND `fleet_mess` = 0)\n    OR (`fleet_end_time` <= " . SN_TIME_NOW . ")\n  FOR UPDATE;");
    //log_file('Выборка флотов');
    while ($fleet_row = db_fetch($_fleets)) {
        set_time_limit(15);
        // Унифицировать код с темплейтным разбором эвентов на планете!
        $fleet_list[$fleet_row['fleet_id']] = $fleet_row;
        $missions_used[$fleet_row['fleet_mission']] = 1;
        if ($fleet_row['fleet_start_time'] <= SN_TIME_NOW && $fleet_row['fleet_mess'] == 0) {
            $fleet_event_list[] = array('fleet_row' => &$fleet_list[$fleet_row['fleet_id']], 'fleet_time' => $fleet_list[$fleet_row['fleet_id']]['fleet_start_time'], 'fleet_event' => EVENT_FLT_ARRIVE);
        }
        if ($fleet_row['fleet_end_stay'] > 0 && $fleet_row['fleet_end_stay'] <= SN_TIME_NOW && $fleet_row['fleet_mess'] == 0) {
            $fleet_event_list[] = array('fleet_row' => &$fleet_list[$fleet_row['fleet_id']], 'fleet_time' => $fleet_list[$fleet_row['fleet_id']]['fleet_end_stay'], 'fleet_event' => EVENT_FLT_ACOMPLISH);
        }
        if ($fleet_row['fleet_end_time'] <= SN_TIME_NOW) {
            $fleet_event_list[] = array('fleet_row' => &$fleet_list[$fleet_row['fleet_id']], 'fleet_time' => $fleet_list[$fleet_row['fleet_id']]['fleet_end_time'], 'fleet_event' => EVENT_FLT_RETURN);
        }
    }
    sn_db_transaction_commit();
    //log_file('Сортировка и подгрузка модулей');
    uasort($fleet_event_list, 'flt_flyingFleetsSort');
    unset($_fleets);
    // TODO: Грузить только используемые модули из $missions_used
    $mission_files = array(MT_ATTACK => 'flt_mission_attack', MT_AKS => 'flt_mission_attack', MT_DESTROY => 'flt_mission_attack', MT_TRANSPORT => 'flt_mission_transport', MT_RELOCATE => 'flt_mission_relocate', MT_HOLD => 'flt_mission_hold', MT_SPY => 'flt_mission_spy', MT_COLONIZE => 'flt_mission_colonize', MT_RECYCLE => 'flt_mission_recycle', MT_EXPLORE => 'flt_mission_explore');
    foreach ($missions_used as $mission_id => $cork) {
        require_once SN_ROOT_PHYSICAL . "includes/includes/{$mission_files[$mission_id]}" . DOT_PHP_EX;
    }
    //log_file('Обработка миссий');
    $sn_groups_mission = sn_get_groups('missions');
    foreach ($fleet_event_list as $fleet_event) {
        // TODO: Указатель тут потом сделать
        // TODO: СЕЙЧАС НАДО ПРОВЕРЯТЬ ПО БАЗЕ - А ЖИВОЙ ЛИ ФЛОТ?!
        $fleet_row = $fleet_event['fleet_row'];
        if (!$fleet_row) {
            // Fleet was destroyed in course of previous actions
            continue;
        }
        //log_file('Миссия');
        // TODO Обернуть всё в транзакции. Начинать надо заранее, блокируя все таблицы внутренним локом SELECT 1 FROM {{users}}
        sn_db_transaction_start();
        $config->db_saveItem('fleet_update_last', SN_TIME_SQL);
        $mission_data = $sn_groups_mission[$fleet_row['fleet_mission']];
        // Формируем запрос, блокирующий сразу все нужные записи
        db_flying_fleet_lock($mission_data, $fleet_row);
        $fleet_row = doquery("SELECT * FROM {{fleets}} WHERE fleet_id = {$fleet_row['fleet_id']} FOR UPDATE", true);
        if (!$fleet_row || empty($fleet_row)) {
            // Fleet was destroyed in course of previous actions
            sn_db_transaction_commit();
            continue;
        }
        if ($fleet_event['fleet_event'] == EVENT_FLT_RETURN) {
            // Fleet returns to planet
            RestoreFleetToPlanet($fleet_row, true, false, true);
            sn_db_transaction_commit();
            continue;
        }
        if ($fleet_event['fleet_event'] == EVENT_FLT_ARRIVE && $fleet_row['fleet_mess'] != 0) {
            // При событии EVENT_FLT_ARRIVE флот всегда должен иметь fleet_mess == 0
            // В противном случае это означает, что флот уже был обработан ранее - например, при САБе
            sn_db_transaction_commit();
            continue;
        }
        // TODO: Здесь тоже указатели
        // TODO: Кэширование
        // TODO: Выбирать только нужные поля
        // шпионаж не дает нормальный ID fleet_end_planet_id 'dst_planet'
        $mission_data = array('fleet' => &$fleet_row, 'dst_user' => $mission_data['dst_user'] || $mission_data['dst_planet'] ? db_user_by_id($fleet_row['fleet_target_owner'], true) : null, 'dst_planet' => $mission_data['dst_planet'] ? db_planet_by_vector($fleet_row, 'fleet_end_', true, '`id`, `id_owner`, `name`') : null, 'src_user' => $mission_data['src_user'] || $mission_data['src_planet'] ? db_user_by_id($fleet_row['fleet_owner'], true) : null, 'src_planet' => $mission_data['src_planet'] ? db_planet_by_vector($fleet_row, 'fleet_start_', true, '`id`, `id_owner`, `name`') : null, 'fleet_event' => $fleet_event['fleet_event']);
        if ($mission_data['dst_planet']) {
            // $mission_data['dst_planet'] = sys_o_get_updated($mission_data['dst_user'], $mission_data['dst_planet']['id'], $fleet_row['fleet_start_time']);
            if ($mission_data['dst_planet']['id_owner']) {
                $mission_data['dst_planet'] = sys_o_get_updated($mission_data['dst_planet']['id_owner'], $mission_data['dst_planet']['id'], $fleet_row['fleet_start_time']);
            }
            $mission_data['dst_user'] = $mission_data['dst_user'] ? $mission_data['dst_planet']['user'] : null;
            $mission_data['dst_planet'] = $mission_data['dst_planet']['planet'];
        }
        switch ($fleet_row['fleet_mission']) {
            // Для боевых атак нужно обновлять по САБу и по холду - таки надо возвращать данные из обработчика миссий!
            case MT_AKS:
            case MT_ATTACK:
            case MT_DESTROY:
                $attack_result = flt_mission_attack($mission_data);
                $mission_result = CACHE_COMBAT;
                break;
                /*
                case MT_DESTROY:
                  $attack_result = flt_mission_destroy($mission_data);
                  $mission_result = CACHE_COMBAT;
                break;
                */
            /*
            case MT_DESTROY:
              $attack_result = flt_mission_destroy($mission_data);
              $mission_result = CACHE_COMBAT;
            break;
            */
            case MT_TRANSPORT:
                $mission_result = flt_mission_transport($mission_data);
                break;
            case MT_HOLD:
                $mission_result = flt_mission_hold($mission_data);
                break;
            case MT_RELOCATE:
                $mission_result = flt_mission_relocate($mission_data);
                break;
            case MT_EXPLORE:
                $mission_result = flt_mission_explore($mission_data);
                break;
            case MT_RECYCLE:
                $mission_result = flt_mission_recycle($mission_data);
                break;
            case MT_COLONIZE:
                $mission_result = flt_mission_colonize($mission_data);
                break;
            case MT_SPY:
                $mission_result = flt_mission_spy($mission_data);
                break;
            case MT_MISSILE:
                // Missiles !!
                break;
                //      default:
                //        doquery("DELETE FROM `{{fleets}}` WHERE `fleet_id` = '{$fleet_row['fleet_id']}' LIMIT 1;");
                //      break;
        }
        sn_db_transaction_commit();
    }
    sn_db_transaction_start();
    $config->db_saveItem('fleet_update_last', SN_TIME_SQL);
    $config->db_saveItem('fleet_update_lock', '');
    sn_db_transaction_commit();
    //  log_file('Закончили обсчёт флотов');
}
Example #11
0
 public function __construct()
 {
     $this->write_full_url = !classSupernova::$config->security_write_full_url_disabled;
     // Инфа об устройстве и браузере - общая для всех
     sn_db_transaction_start();
     $this->device_cypher = $_COOKIE[SN_COOKIE_D];
     if ($this->device_cypher) {
         $cypher_safe = db_escape($this->device_cypher);
         $device_id = doquery("SELECT `device_id` FROM {{security_device}} WHERE `device_cypher` = '{$cypher_safe}' LIMIT 1 FOR UPDATE", true);
         if (!empty($device_id['device_id'])) {
             $this->device_id = $device_id['device_id'];
         }
     }
     if ($this->device_id <= 0) {
         do {
             $cypher_safe = db_escape($this->device_cypher = sys_random_string());
             $row = doquery("SELECT `device_id` FROM {{security_device}} WHERE `device_cypher` = '{$cypher_safe}' LIMIT 1 FOR UPDATE", true);
         } while (!empty($row));
         doquery("INSERT INTO {{security_device}} (`device_cypher`) VALUES ('{$cypher_safe}');");
         $this->device_id = db_insert_id();
         sn_setcookie(SN_COOKIE_D, $this->device_cypher, PERIOD_FOREVER, SN_ROOT_RELATIVE);
     }
     sn_db_transaction_commit();
     sn_db_transaction_start();
     $this->user_agent = $_SERVER['HTTP_USER_AGENT'];
     $this->browser_id = db_get_set_unique_id_value($_SERVER['HTTP_USER_AGENT'], 'browser_id', 'security_browser', 'browser_user_agent');
     sn_db_transaction_commit();
     sn_db_transaction_start();
     $this->page_address = substr($_SERVER['PHP_SELF'], strlen(SN_ROOT_RELATIVE));
     $this->page_address_id = db_get_set_unique_id_value($this->page_address, 'url_id', 'security_url', 'url_string');
     sn_db_transaction_commit();
     if ($this->write_full_url) {
         sn_db_transaction_start();
         $this->page_url = substr($_SERVER['REQUEST_URI'], strlen(SN_ROOT_RELATIVE));
         if (strpos($_SERVER['REQUEST_URI'], '/simulator.php') === 0) {
             $this->page_url = '/simulator.php';
         }
         $this->page_url_id = db_get_set_unique_id_value($this->page_url, 'url_id', 'security_url', 'url_string');
         sn_db_transaction_commit();
     }
     $ip = sec_player_ip();
     $this->ip_v4_string = $ip['ip'];
     $this->ip_v4_int = ip2longu($this->ip_v4_string);
     $this->ip_v4_proxy_chain = $ip['proxy_chain'];
 }
Example #12
0
 public function payment_request_response()
 {
     global $debug;
     $this->db = core_auth::$main_provider->db;
     $this->account = new Account($this->db);
     // TODO - REPLACE WITH INNATE CALL!
     sn_db_transaction_start();
     try {
         $response = $this->payment_request_process();
     } catch (Exception $e) {
         $response['result'] = $e->getCode();
         $response['message'] = $e->getMessage();
     }
     if ($response['result'] == SN_PAYMENT_REQUEST_OK) {
         sn_db_transaction_commit();
         $debug->warning('Результат операции: код ' . $response['result'] . ' сообщение "' . $response['message'] . '"', 'Успешный платёж', LOG_INFO_PAYMENT);
     } else {
         sn_db_transaction_rollback();
         $debug->warning('Результат операции: код ' . $response['result'] . ' сообщение "' . $response['message'] . '"', 'Ошибка платежа', LOG_INFO_PAYMENT, true);
     }
     // Переводим код результата из СН в код платежной системы
     if (is_array($this->result_translations) && !empty($this->result_translations)) {
         $response['result'] = isset($this->result_translations[$response['result']]) ? $this->result_translations[$response['result']] : $this->result_translations[SN_PAYMENT_REQUEST_UNDEFINED_ERROR];
     }
     return $response;
 }
Example #13
0
 protected function register_player_db_create($player_name_unsafe)
 {
     try {
         // Проверить корректность имени
         $this->register_player_name_validate($player_name_unsafe);
         sn_db_transaction_start();
         // Проверить наличие такого имени в истории имён
         if (db_player_name_exists($player_name_unsafe)) {
             throw new Exception(REGISTER_ERROR_PLAYER_NAME_EXISTS, ERR_ERROR);
         }
         // Узнаем язык и емейл игрока
         $player_language = '';
         $player_email = '';
         // TODO - порнография - работа должна происходить над списком аккаунтов, а не только на одном аккаунте...
         foreach ($this->providers_authorised as $provider) {
             if (!$player_language && $provider->account->account_language) {
                 $player_language = $provider->account->account_language;
             }
             if (!$player_email && $provider->account->account_email) {
                 $player_email = $provider->account->account_email;
             }
         }
         $player_language = sys_get_param_str('lang') ? sys_get_param_str('lang') : $player_language;
         $player_language = $player_language ? $player_language : DEFAULT_LANG;
         // TODO - дописать эксепшнов в процедуре создания игрока
         self::$user = player_create($player_name_unsafe, $player_email, array('partner_id' => $partner_id = sys_get_param_int('id_ref', sys_get_param_int('partner_id')), 'language_iso' => static::$db->db_escape($player_language)));
         // Зарегестрировать на него аккаунты из self::$accounts_authorised
         $a_user = self::$user;
         foreach ($this->providers_authorised as $provider) {
             // TODO - порнография. Должен быть отдельный класс трансляторов - в т.ч. и кэширующий транслятор
             // TODO - ну и работа должна происходить над списком аккаунтов, а не только на одном аккаунте...
             // self::db_translate_register_user($provider->provider_id, $provider->account->account_id, $a_user['id']);
             PlayerToAccountTranslate::db_translate_register_user($provider->provider_id, $provider->account->account_id, $a_user['id']);
         }
         // Установить куку игрока
         self::cookie_set(self::$user['id']);
         sn_db_transaction_commit();
         $this->register_status = LOGIN_SUCCESS;
     } catch (Exception $e) {
         sn_db_transaction_rollback();
         // Если старое имя занято
         self::$user = null;
         $this->register_status == LOGIN_UNDEFINED ? $this->register_status = $e->getMessage() : false;
     }
 }
Example #14
0
function sys_stat_calculate()
{
    global $config, $sta_update_step;
    ini_set('memory_limit', $config->stats_php_memory ? $config->stats_php_memory : '1024M');
    $user_skip_list = sys_stat_get_user_skip_list();
    // $sn_groups_resources_loot = sn_get_groups('resources_loot');
    $rate[RES_METAL] = $config->rpg_exchange_metal;
    $rate[RES_CRYSTAL] = $config->rpg_exchange_crystal / $config->rpg_exchange_metal;
    $rate[RES_DEUTERIUM] = $config->rpg_exchange_deuterium / $config->rpg_exchange_metal;
    $rate[RES_DARK_MATTER] = $config->rpg_exchange_darkMatter / $config->rpg_exchange_metal;
    $sta_update_step = -1;
    sta_set_time_limit('starting update');
    $counts = $points = $unit_cost_cache = $user_allies = array();
    sn_db_transaction_start();
    sta_set_time_limit('calculating players stats');
    $i = 0;
    // Блокируем всех пользователей
    classSupernova::db_lock_tables('users');
    $user_list = db_user_list('', true, 'id, dark_matter, metal, crystal, deuterium, user_as_ally, ally_id');
    $row_num = count($user_list);
    // while($player = db_fetch($query))
    foreach ($user_list as $player) {
        if ($i++ % 100 == 0) {
            sta_set_time_limit("calculating players stats (player {$i}/{$row_num})", false);
        }
        if (array_key_exists($user_id = $player['id'], $user_skip_list)) {
            continue;
        }
        $resources = $player['metal'] * $rate[RES_METAL] + $player['crystal'] * $rate[RES_CRYSTAL] + $player['deuterium'] * $rate[RES_DEUTERIUM] + $player['dark_matter'] * $rate[RES_DARK_MATTER];
        $counts[$user_id][UNIT_RESOURCES] += $resources;
        // $points[$user_id][UNIT_RESOURCES] += $resources;
        // А здесь мы фильтруем пользователей по $user_skip_list - далее не нужно этого делать, потому что
        if (!isset($user_skip_list[$user_id])) {
            $user_allies[$user_id] = $player['ally_id'];
        }
    }
    unset($user_list);
    classSupernova::cache_clear(LOC_USER, true);
    //pdump(classSupernova::$data[LOC_USER]);
    //pdump(classSupernova::$locks[LOC_USER]);
    sta_set_time_limit('calculating planets stats');
    $i = 0;
    $query = db_planet_list_resources_by_owner();
    $row_num = db_num_rows($query);
    while ($planet = db_fetch($query)) {
        if ($i++ % 100 == 0) {
            sta_set_time_limit("calculating planets stats (planet {$i}/{$row_num})", false);
        }
        if (array_key_exists($user_id = $planet['id_owner'], $user_skip_list)) {
            continue;
        }
        $resources = $planet['metal'] * $rate[RES_METAL] + $planet['crystal'] * $rate[RES_CRYSTAL] + $planet['deuterium'] * $rate[RES_DEUTERIUM];
        $counts[$user_id][UNIT_RESOURCES] += $resources;
        // $points[$user_id][UNIT_RESOURCES] += $resources;
    }
    // Calculation of Fleet-In-Flight
    sta_set_time_limit('calculating flying fleets stats');
    $i = 0;
    $query = doquery("SELECT fleet_owner, fleet_array, fleet_resource_metal, fleet_resource_crystal, fleet_resource_deuterium FROM {{fleets}};");
    $row_num = db_num_rows($query);
    while ($fleet_row = db_fetch($query)) {
        if ($i++ % 100 == 0) {
            sta_set_time_limit("calculating flying fleets stats (fleet {$i}/{$row_num})", false);
        }
        if (array_key_exists($user_id = $fleet_row['fleet_owner'], $user_skip_list)) {
            continue;
        }
        $fleet = sys_unit_str2arr($fleet_row['fleet_array']);
        foreach ($fleet as $unit_id => $unit_amount) {
            $counts[$user_id][UNIT_SHIPS] += $unit_amount;
            if (!isset($unit_cost_cache[$unit_id][0])) {
                $unit_cost_cache[$unit_id][0] = get_unit_param($unit_id, P_COST);
            }
            $unit_cost_data =& $unit_cost_cache[$unit_id][0];
            $points[$user_id][UNIT_SHIPS] += ($unit_cost_data[RES_METAL] * $rate[RES_METAL] + $unit_cost_data[RES_CRYSTAL] * $rate[RES_CRYSTAL] + $unit_cost_data[RES_DEUTERIUM] * $rate[RES_DEUTERIUM]) * $unit_amount;
        }
        $resources = $fleet_row['fleet_resource_metal'] * $rate[RES_METAL] + $fleet_row['fleet_resource_crystal'] * $rate[RES_CRYSTAL] + $fleet_row['fleet_resource_deuterium'] * $rate[RES_DEUTERIUM];
        $counts[$user_id][UNIT_RESOURCES] += $resources;
        // $points[$user_id][UNIT_RESOURCES] += $resources;
    }
    sta_set_time_limit('calculating unit stats');
    $i = 0;
    $query = db_unit_list_stat_calculate();
    $row_num = db_num_rows($query);
    while ($unit = db_fetch($query)) {
        if ($i++ % 100 == 0) {
            sta_set_time_limit("calculating unit stats (unit {$i}/{$row_num})", false);
        }
        if (array_key_exists($user_id = $unit['unit_player_id'], $user_skip_list)) {
            continue;
        }
        $counts[$user_id][$unit['unit_type']] += $unit['unit_level'] * $unit['unit_amount'];
        $total_cost = eco_get_total_cost($unit['unit_snid'], $unit['unit_level']);
        $points[$user_id][$unit['unit_type']] += (isset($total_cost['total']) ? $total_cost['total'] : 0) * $unit['unit_amount'];
    }
    sta_set_time_limit('calculating ques stats');
    $i = 0;
    $query = db_que_list_stat();
    $row_num = db_num_rows($query);
    while ($que_item = db_fetch($query)) {
        if ($i++ % 100 == 0) {
            sta_set_time_limit("calculating ques stats (que item {$i}/{$row_num})", false);
        }
        if (array_key_exists($user_id = $que_item['que_player_id'], $user_skip_list)) {
            continue;
        }
        $que_unit_amount = $que_item['que_unit_amount'];
        $que_item = sys_unit_str2arr($que_item['que_unit_price']);
        $resources = ($que_item[RES_METAL] * $rate[RES_METAL] + $que_item[RES_CRYSTAL] * $rate[RES_CRYSTAL] + $que_item[RES_DEUTERIUM] * $rate[RES_DEUTERIUM]) * $que_unit_amount;
        $counts[$user_id][UNIT_RESOURCES] += $resources;
        // $points[$user_id][UNIT_RESOURCES] += $resources;
    }
    sta_set_time_limit('archiving old statistic');
    // Statistic rotation
    // doquery("DELETE FROM {{statpoints}} WHERE `stat_code` >= 14;");
    doquery("DELETE FROM {{statpoints}} WHERE `stat_date` < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL {$config->stats_history_days} DAY));");
    doquery("UPDATE {{statpoints}} SET `stat_code` = `stat_code` + 1;");
    sta_set_time_limit('posting new user stats to DB');
    $data = array();
    foreach ($user_allies as $user_id => $ally_id) {
        // $counts[UNIT_RESOURCES] дублирует $points[UNIT_RESOURCES], поэтому $points не заполняем, а берем $counts и делим на 1000
        $points[$user_id][UNIT_RESOURCES] = $counts[$user_id][UNIT_RESOURCES] / 1000;
        $points[$user_id] = array_map('floor', $points[$user_id]);
        $counts[$user_id] = array_map('floor', $counts[$user_id]);
        $ally_id = $ally_id ? $ally_id : 'NULL';
        $user_defence_points = $points[$user_id][UNIT_DEFENCE] + $points[$user_id][UNIT_DEF_MISSILES];
        $user_defence_counts = $counts[$user_id][UNIT_DEFENCE] + $counts[$user_id][UNIT_DEF_MISSILES];
        $user_points = array_sum($points[$user_id]);
        $user_counts = array_sum($counts[$user_id]);
        $data[] = $q = "({$user_id},{$ally_id},1,1,'{$points[$user_id][UNIT_TECHNOLOGIES]}','{$counts[$user_id][UNIT_TECHNOLOGIES]}'," . "'{$points[$user_id][UNIT_STRUCTURES]}','{$counts[$user_id][UNIT_STRUCTURES]}','{$user_defence_points}','{$user_defence_counts}'," . "'{$points[$user_id][UNIT_SHIPS]}','{$counts[$user_id][UNIT_SHIPS]}','{$points[$user_id][UNIT_RESOURCES]}','{$counts[$user_id][UNIT_RESOURCES]}'," . "{$user_points},{$user_counts}," . SN_TIME_NOW . ")";
        sys_stat_calculate_flush($data);
    }
    sys_stat_calculate_flush($data, true);
    // Updating Allie's stats
    sta_set_time_limit('posting new Alliance stats to DB');
    doquery("INSERT INTO {{statpoints}}\n      (`tech_points`, `tech_count`, `build_points`, `build_count`, `defs_points`, `defs_count`,\n        `fleet_points`, `fleet_count`, `res_points`, `res_count`, `total_points`, `total_count`,\n        `stat_date`, `id_owner`, `id_ally`, `stat_type`, `stat_code`,\n        `tech_old_rank`, `build_old_rank`, `defs_old_rank`, `fleet_old_rank`, `res_old_rank`, `total_old_rank`\n      )\n      SELECT\n        SUM(u.`tech_points`)+aus.`tech_points`, SUM(u.`tech_count`)+aus.`tech_count`, SUM(u.`build_points`)+aus.`build_points`, SUM(u.`build_count`)+aus.`build_count`,\n        SUM(u.`defs_points`)+aus.`defs_points`, SUM(u.`defs_count`)+aus.`defs_count`, SUM(u.`fleet_points`)+aus.`fleet_points`, SUM(u.`fleet_count`)+aus.`fleet_count`,\n        SUM(u.`res_points`)+aus.`res_points`, SUM(u.`res_count`)+aus.`res_count`, SUM(u.`total_points`)+aus.`total_points`, SUM(u.`total_count`)+aus.`total_count`,\n        " . SN_TIME_NOW . ", NULL, u.`id_ally`, 2, 1,\n        a.tech_rank, a.build_rank, a.defs_rank, a.fleet_rank, a.res_rank, a.total_rank\n      FROM {{statpoints}} as u\n        join {{alliance}} as al on al.id = u.id_ally\n        left join {{statpoints}} as aus on aus.id_owner = al.ally_user_id and aus.stat_type = 1 AND aus.stat_code = 1\n        LEFT JOIN {{statpoints}} as a ON a.id_ally = u.id_ally AND a.stat_code = 2 AND a.stat_type = 2\n      WHERE u.`stat_type` = 1 AND u.stat_code = 1 AND u.id_ally<>0\n      GROUP BY u.`id_ally`");
    // Удаляем больше не нужные записи о достижении игрока-альянса
    db_stat_list_delete_ally_player();
    // Some variables we need to update ranks
    $qryResetRowNum = 'SET @rownum=0;';
    $qryFormat = 'UPDATE {{statpoints}} SET `%1$s_rank` = (SELECT @rownum:=@rownum+1) WHERE `stat_type` = %2$d AND `stat_code` = 1 ORDER BY `%1$s_points` DESC, `id_owner` ASC, `id_ally` ASC;';
    $rankNames = array('tech', 'build', 'defs', 'fleet', 'res', 'total');
    // Updating player's ranks
    sta_set_time_limit("updating ranks for players");
    foreach ($rankNames as $rankName) {
        sta_set_time_limit("updating player rank '{$rankName}'", false);
        doquery($qryResetRowNum);
        doquery(sprintf($qryFormat, $rankName, 1));
    }
    sta_set_time_limit("updating ranks for Alliances");
    // --- Updating Allie's ranks
    foreach ($rankNames as $rankName) {
        sta_set_time_limit("updating Alliances rank '{$rankName}'", false);
        doquery($qryResetRowNum);
        doquery(sprintf($qryFormat, $rankName, 2));
    }
    sta_set_time_limit('setting previous user stats from archive');
    doquery("UPDATE {{statpoints}} as new\n      LEFT JOIN {{statpoints}} as old ON old.id_owner = new.id_owner AND old.stat_code = 2 AND old.stat_type = new.stat_type\n    SET\n      new.tech_old_rank = old.tech_rank,\n      new.build_old_rank = old.build_rank,\n      new.defs_old_rank  = old.defs_rank ,\n      new.fleet_old_rank = old.fleet_rank,\n      new.res_old_rank = old.res_rank,\n      new.total_old_rank = old.total_rank\n    WHERE\n      new.stat_type = 1 AND new.stat_code = 1;");
    sta_set_time_limit('setting previous allies stats from archive');
    doquery("UPDATE {{statpoints}} as new\n      LEFT JOIN {{statpoints}} as old ON old.id_ally = new.id_ally AND old.stat_code = 2 AND old.stat_type = new.stat_type\n    SET\n      new.tech_old_rank = old.tech_rank,\n      new.build_old_rank = old.build_rank,\n      new.defs_old_rank  = old.defs_rank ,\n      new.fleet_old_rank = old.fleet_rank,\n      new.res_old_rank = old.res_rank,\n      new.total_old_rank = old.total_rank\n    WHERE\n      new.stat_type = 2 AND new.stat_code = 1;");
    sta_set_time_limit('updating players current rank and points');
    db_stat_list_update_user_stats();
    sta_set_time_limit('updating Allys current rank and points');
    db_stat_list_update_ally_stats();
    // Counting real user count and updating values
    $config->db_saveItem('users_amount', db_user_count());
    sn_db_transaction_commit();
}
Example #15
0
 protected function register()
 {
     // TODO РЕГИСТРАЦИЯ ВСЕГДА ДОЛЖНА ЛОГИНИТЬ ПОЛЬЗОВАТЕЛЯ!
     $this->flog('Регистрация: начинаем. Провайдер ' . $this->provider_id);
     try {
         if (!$this->is_register) {
             $this->flog('Регистрация: не выставлен флаг регистрации - пропускаем');
             throw new Exception(LOGIN_UNDEFINED, ERR_ERROR);
         }
         $this->register_validate_input();
         sn_db_transaction_start();
         // $this->provider_account = new Account($this->db);
         // $this->account_check_duplicate_name_or_email($this->input_login_unsafe, $this->input_email_unsafe);
         $this->account->db_get_by_name_or_email($this->input_login_unsafe, $this->input_email_unsafe);
         if ($this->account->is_exists) {
             if ($this->account->account_email == $this->input_email_unsafe) {
                 throw new Exception(REGISTER_ERROR_EMAIL_EXISTS, ERR_ERROR);
             } else {
                 throw new Exception(REGISTER_ERROR_ACCOUNT_NAME_EXISTS, ERR_ERROR);
             }
         }
         //      if($this->provider_account->db_get_by_name($this->input_login_unsafe)) {
         //        throw new Exception(REGISTER_ERROR_ACCOUNT_NAME_EXISTS, ERR_ERROR);
         //      }
         //
         //      if($this->provider_account->db_get_by_email($this->input_email_unsafe)) {
         //        throw new Exception(REGISTER_ERROR_EMAIL_EXISTS, ERR_ERROR);
         //      }
         // Проблемы с созданием аккаунта - вызовут эксершн и обработается catch()
         $this->account->db_create($this->input_login_unsafe, $this->input_login_password_raw, $this->input_email_unsafe, $this->input_language_unsafe);
         //      $this->db_account_create(
         //        $this->input_login_unsafe,
         //        $this->input_login_password_raw,
         //        $this->input_email_unsafe,
         //        $this->input_language_unsafe
         //      );
         // $this->data[F_ACCOUNT] = $this->db_account_get_by_id($account_id);
         // Устанавливать не надо - мы дальше пойдем по workflow
         $this->account_login_status = LOGIN_SUCCESS;
         $this->cookie_set();
         // А вот это пока не нужно. Трансляцией аккаунтов в юзеров и созданием новых юзеров для новозашедших аккаунтов занимается Auth
         // $this->register_account();
         sn_db_transaction_commit();
     } catch (Exception $e) {
         sn_db_transaction_rollback();
         $this->account_login_status == LOGIN_UNDEFINED ? $this->account_login_status = $e->getMessage() : false;
     }
     return $this->account_login_status;
 }
Example #16
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 #17
0
function mrc_mercenary_hire($mode, $user, $mercenary_id)
{
    global $config, $lang, $sn_powerup_buy_discounts;
    try {
        $is_permanent = $mode == UNIT_PLANS || !$config->empire_mercenary_temporary;
        $cost_alliance_multiplyer = SN_IN_ALLY === true && $mode == UNIT_PLANS ? $config->ali_bonus_members : 1;
        $cost_alliance_multiplyer = $cost_alliance_multiplyer >= 1 ? $cost_alliance_multiplyer : 1;
        if (!in_array($mercenary_id, sn_get_groups($mode == UNIT_PLANS ? 'plans' : 'mercenaries'))) {
            throw new Exception($lang['mrc_msg_error_wrong_mercenary'], ERR_ERROR);
        }
        if (!mrc_officer_accessible($user, $mercenary_id)) {
            throw new Exception($lang['mrc_msg_error_requirements'], ERR_ERROR);
        }
        $mercenary_level = sys_get_param_int('mercenary_level');
        if ($mercenary_level < 0 || $mercenary_level > get_unit_param($mercenary_id, P_MAX_STACK)) {
            throw new Exception($lang['mrc_msg_error_wrong_level'], ERR_ERROR);
        }
        if ($mercenary_level && !array_key_exists($mercenary_period = sys_get_param_int('mercenary_period'), $sn_powerup_buy_discounts)) {
            throw new Exception($lang['mrc_msg_error_wrong_period'], ERR_ERROR);
        }
        sn_db_transaction_start();
        $mercenary_level_old = mrc_get_level($user, $planetrow, $mercenary_id, true, true);
        if ($config->empire_mercenary_temporary && $mercenary_level_old && $mercenary_level) {
            throw new Exception($lang['mrc_msg_error_already_hired'], ERR_ERROR);
            // Can't hire already hired temp mercenary - dismiss first
        } elseif ($config->empire_mercenary_temporary && !$mercenary_level_old && !$mercenary_level) {
            throw new Exception('', ERR_NONE);
            // Can't dismiss (!$mercenary_level) not hired (!$mercenary_level_old) temp mercenary. But no error
        }
        if ($mercenary_level) {
            $darkmater_cost = eco_get_total_cost($mercenary_id, $mercenary_level);
            if (!$config->empire_mercenary_temporary && $mercenary_level_old) {
                $darkmater_cost_old = eco_get_total_cost($mercenary_id, $mercenary_level_old);
                $darkmater_cost[BUILD_CREATE][RES_DARK_MATTER] -= $darkmater_cost_old[BUILD_CREATE][RES_DARK_MATTER];
            }
            $darkmater_cost = ceil($darkmater_cost[BUILD_CREATE][RES_DARK_MATTER] * $mercenary_period * $sn_powerup_buy_discounts[$mercenary_period] / $config->empire_mercenary_base_period);
        } else {
            $darkmater_cost = 0;
        }
        $darkmater_cost *= $cost_alliance_multiplyer;
        if (mrc_get_level($user, null, RES_DARK_MATTER) < $darkmater_cost) {
            throw new Exception($lang['mrc_msg_error_no_resource'], ERR_ERROR);
        }
        if ($darkmater_cost && $mercenary_level || !$is_permanent) {
            $unit_row = db_unit_by_location($user['id'], LOC_USER, $user['id'], $mercenary_id);
            if (is_array($unit_row) && ($dismiss_left_days = floor((strtotime($unit_row['unit_time_finish']) - SN_TIME_NOW) / PERIOD_DAY))) {
                $dismiss_full_cost = eco_get_total_cost($mercenary_id, $unit_row['unit_level']);
                $dismiss_full_cost = $dismiss_full_cost[BUILD_CREATE][RES_DARK_MATTER];
                $dismiss_full_days = round((strtotime($unit_row['unit_time_finish']) - strtotime($unit_row['unit_time_start'])) / PERIOD_DAY);
                /*
                        print(sprintf($lang['mrc_mercenary_dismissed_log'], $lang['tech'][$mercenary_id], $mercenary_id, $dismiss_full_cost, $dismiss_full_days,
                          $unit_row['unit_time_start'], $unit_row['unit_time_finish'], $dismiss_left_days, floor($dismiss_full_cost * $dismiss_left_days / $dismiss_full_days)
                          ));
                */
                rpg_points_change($user['id'], RPG_MERCENARY_DISMISSED, 0, sprintf($lang['mrc_mercenary_dismissed_log'], $lang['tech'][$mercenary_id], $mercenary_id, $dismiss_full_cost, $dismiss_full_days, $unit_row['unit_time_start'], $unit_row['unit_time_finish'], $dismiss_left_days, floor($dismiss_full_cost * $dismiss_left_days / $dismiss_full_days)));
            }
            db_unit_list_delete($user['id'], LOC_USER, $user['id'], $mercenary_id);
        }
        if ($darkmater_cost && $mercenary_level) {
            db_unit_set_insert("unit_player_id = {$user['id']},\n        unit_location_type = " . LOC_USER . ",\n        unit_location_id = {$user['id']},\n        unit_type = {$mode},\n        unit_snid = {$mercenary_id},\n        unit_level = {$mercenary_level},\n        unit_time_start = " . (!$is_permanent ? 'FROM_UNIXTIME(' . SN_TIME_NOW . ')' : 'null') . ",\n        unit_time_finish = " . (!$is_permanent ? 'FROM_UNIXTIME(' . (SN_TIME_NOW + $mercenary_period) . ')' : 'null'));
            rpg_points_change($user['id'], $mode == UNIT_PLANS ? RPG_PLANS : RPG_MERCENARY, -$darkmater_cost, sprintf($lang[$mode == UNIT_PLANS ? 'mrc_plan_bought_log' : 'mrc_mercenary_hired_log'], $lang['tech'][$mercenary_id], $mercenary_id, $darkmater_cost, round($mercenary_period / PERIOD_DAY)));
        }
        sn_db_transaction_commit();
        sys_redirect($_SERVER['REQUEST_URI']);
    } catch (Exception $e) {
        sn_db_transaction_rollback();
        $operation_result = array('STATUS' => in_array($e->getCode(), array(ERR_NONE, ERR_WARNING, ERR_ERROR)) ? $e->getCode() : ERR_ERROR, 'MESSAGE' => $e->getMessage());
    }
    return $operation_result;
}
Example #18
0
     $template->assign_block_vars('result', $result);
     display($template, $lang['rename_and_abandon_planet']);
     break;
 default:
     sn_sys_sector_buy();
     $template = gettemplate('planet_overview', true);
     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);
     //    int_get_missile_to_planet("SELECT * FROM `{{iraks}}` WHERE `fleet_owner` = '{$user['id']}'");
     $planet_count = 0;
     sn_db_transaction_start();
     $planets_query = db_planet_list_sorted($user, false, '*');
     foreach ($planets_query as $an_id => $UserPlanet) {
         $UserPlanet = sys_o_get_updated($user, $UserPlanet['id'], SN_TIME_NOW, false, true);
         $list_planet_que = $UserPlanet['que'];
         $UserPlanet = $UserPlanet['planet'];
         $template_planet = tpl_parse_planet($UserPlanet);
         $planet_fleet_id = 0;
         $fleet_list = $template_planet['fleet_list'];
         if ($fleet_list['own']['count']) {
             $planet_fleet_id = "p{$UserPlanet['id']}";
             $fleets_to_planet[$UserPlanet['id']] = tpl_parse_fleet_sn($fleet_list['own']['total'], $planet_fleet_id);
             //        $fleet_id++;tpl_parse_fleet_sn
         }
         if ($UserPlanet['planet_type'] == PT_MOON) {
             continue;
Example #19
0
 function payment_request_response()
 {
     global $debug;
     sn_db_transaction_start();
     try {
         $response = $this->payment_request_process();
     } catch (exception $e) {
         $response['result'] = $e->getCode();
         $response['message'] = $e->getMessage();
     }
     if ($response['result'] == SN_PAYMENT_REQUEST_OK) {
         sn_db_transaction_commit();
         // $debug->warning('Результат операции: код ' . $response['result'] . ' сообщение "' . $response['message'] . '"', 'Ошибка платежа', LOG_INFO_PAYMENT);
     } else {
         sn_db_transaction_rollback();
         $debug->warning('Результат операции: код ' . $response['result'] . ' сообщение "' . $response['message'] . '"', 'Ошибка платежа', LOG_INFO_PAYMENT);
     }
     // Переводим код результата из СН в код платежной системы
     if (is_array($this->result_translations) && !empty($this->result_translations)) {
         $response['result'] = isset($this->result_translations[$response['result']]) ? $this->result_translations[$response['result']] : $this->result_translations[SN_PAYMENT_REQUEST_UNDEFINED_ERROR];
     }
     return $response;
 }
Example #20
0
function flt_t_send_fleet($user, &$from, $to, $fleet, $mission, $options = array())
{
    //ini_set('error_reporting', E_ALL);
    $internal_transaction = !sn_db_transaction_check(false) ? sn_db_transaction_start() : false;
    //pdump($internal_transaction);
    // TODO Потенциальный дедлок - если успела залочится запись пользователя - хозяина планеты
    $user = db_user_by_id($user['id'], true);
    $from = sys_o_get_updated($user, $from['id'], SN_TIME_NOW);
    $from = $from['planet'];
    $can_attack = flt_can_attack($from, $to, $fleet, $mission, $options);
    if ($can_attack != ATTACK_ALLOWED) {
        $internal_transaction ? sn_db_transaction_rollback() : false;
        return $can_attack;
    }
    $fleet_group = isset($options['fleet_group']) ? floatval($options['fleet_group']) : 0;
    $travel_data = flt_travel_data($user, $from, $to, $fleet, $options['fleet_speed_percent']);
    $fleet_start_time = SN_TIME_NOW + $travel_data['duration'];
    if ($mission == MT_EXPLORE || $mission == MT_HOLD) {
        $stay_duration = $options['stay_time'] * 3600;
        $stay_time = $fleet_start_time + $stay_duration;
    } else {
        $stay_duration = 0;
        $stay_time = 0;
    }
    $fleet_end_time = $fleet_start_time + $travel_data['duration'] + $stay_duration;
    $fleet_ship_count = 0;
    $fleet_string = '';
    $db_changeset = array();
    $planet_fields = array();
    foreach ($fleet as $unit_id => $amount) {
        if (!$amount || !$unit_id) {
            continue;
        }
        if (in_array($unit_id, sn_get_groups('fleet'))) {
            $fleet_ship_count += $amount;
            $fleet_string .= "{$unit_id},{$amount};";
            $db_changeset['unit'][] = sn_db_unit_changeset_prepare($unit_id, -$amount, $user, $from['id']);
        } elseif (in_array($unit_id, sn_get_groups('resources_loot'))) {
            $planet_fields[pname_resource_name($unit_id)]['delta'] -= $amount;
        }
    }
    $to['id_owner'] = intval($to['id_owner']);
    $QryInsertFleet = "INSERT INTO {{fleets}} SET ";
    $QryInsertFleet .= "`fleet_owner` = '{$user['id']}', ";
    $QryInsertFleet .= "`fleet_mission` = '{$mission}', ";
    $QryInsertFleet .= "`fleet_amount` = '{$fleet_ship_count}', ";
    $QryInsertFleet .= "`fleet_array` = '{$fleet_string}', ";
    $QryInsertFleet .= "`fleet_start_time` = '{$fleet_start_time}', ";
    if ($from['id']) {
        $QryInsertFleet .= "`fleet_start_planet_id` = '{$from['id']}', ";
    }
    $QryInsertFleet .= "`fleet_start_galaxy` = '{$from['galaxy']}', ";
    $QryInsertFleet .= "`fleet_start_system` = '{$from['system']}', ";
    $QryInsertFleet .= "`fleet_start_planet` = '{$from['planet']}', ";
    $QryInsertFleet .= "`fleet_start_type` = '{$from['planet_type']}', ";
    $QryInsertFleet .= "`fleet_end_time` = '{$fleet_end_time}', ";
    $QryInsertFleet .= "`fleet_end_stay` = '{$stay_time}', ";
    if ($to['id']) {
        $QryInsertFleet .= "`fleet_end_planet_id` = '{$to['id']}', ";
    }
    $QryInsertFleet .= "`fleet_end_galaxy` = '{$to['galaxy']}', ";
    $QryInsertFleet .= "`fleet_end_system` = '{$to['system']}', ";
    $QryInsertFleet .= "`fleet_end_planet` = '{$to['planet']}', ";
    $QryInsertFleet .= "`fleet_end_type` = '{$to['planet_type']}', ";
    $QryInsertFleet .= "`fleet_resource_metal` = " . floatval($fleet[RES_METAL]) . ", ";
    $QryInsertFleet .= "`fleet_resource_crystal` = " . floatval($fleet[RES_CRYSTAL]) . ", ";
    $QryInsertFleet .= "`fleet_resource_deuterium` = " . floatval($fleet[RES_DEUTERIUM]) . ", ";
    $QryInsertFleet .= "`fleet_target_owner` = '{$to['id_owner']}', ";
    $QryInsertFleet .= "`fleet_group` = '{$fleet_group}', ";
    $QryInsertFleet .= "`start_time` = " . SN_TIME_NOW . ";";
    doquery($QryInsertFleet);
    $planet_fields[pname_resource_name(RES_DEUTERIUM)]['delta'] -= $travel_data['consumption'];
    $db_changeset['planets'][] = array('action' => SQL_OP_UPDATE, P_VERSION => 1, 'where' => array('id' => $from['id']), 'fields' => $planet_fields);
    db_changeset_apply($db_changeset);
    $internal_transaction ? sn_db_transaction_commit() : false;
    $from = db_planet_by_id($from['id']);
    return ATTACK_ALLOWED;
    //ini_set('error_reporting', E_ALL ^ E_NOTICE);
}
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);
}