本文整理汇总了PHP中sn_db_transaction_start函数的典型用法代码示例。如果您正苦于以下问题:PHP sn_db_transaction_start函数的具体用法?PHP sn_db_transaction_start怎么用?PHP sn_db_transaction_start使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了sn_db_transaction_start函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: init_update
/**
* @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>');
}
}
}
}
示例2: DeleteSelectedUser
/**
* @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();
}
示例3: scheduler_process
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;
}
示例4: sn_user_birthday_celebrate
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();
}
示例5: survey_vote
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;
}
示例6: sn_imperium_view
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}";
//.........这里部分代码省略.........
示例7: sn_options_model
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);
}
//.........这里部分代码省略.........
示例8: sn_sec_login_register
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;
}
示例9: que_delete
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'));
}
示例10: flt_flying_fleet_handler
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();
//.........这里部分代码省略.........
示例11: __construct
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'];
}
示例12: payment_request_response
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;
}
示例13: register_player_db_create
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;
}
}
示例14: sys_stat_calculate
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)) {
//.........这里部分代码省略.........
示例15: register
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;
}