Example #1
0
/**
 * This file is under the GPL liscence, which must be included with the file under distrobution (license.txt)
 * this file was made by Xnova, edited to support Toms combat engine by Anthony (MadnessReD) [http://madnessred.co.cc/]
 * Do not edit this comment block
 */
function flt_mission_attack($mission_data)
{
    global $lang, $sn_data, $time_now;
    $fleet_row = $mission_data['fleet'];
    $destination_user = $mission_data['dst_user'];
    $destination_planet = $mission_data['dst_planet'];
    if (!$fleet_row) {
        return;
    }
    if (!$destination_user || !$destination_planet || !is_array($destination_user) || !is_array($destination_planet)) {
        doquery("UPDATE {{fleets}} SET `fleet_mess` = 1 WHERE `fleet_id` = {$fleet_row['fleet_id']} LIMIT 1;");
        return;
    }
    $TargetUserID = $destination_planet['id_owner'];
    $attackFleets = array();
    // ACS function: put all fleet into an array
    if ($fleet_row['fleet_group'] != 0) {
        $fleets = doquery('SELECT * FROM {{fleets}} WHERE fleet_group=' . $fleet_row['fleet_group']);
        while ($fleet = mysql_fetch_assoc($fleets)) {
            BE_attackFleetFill(&$attackFleets, $fleet);
        }
    } else {
        BE_attackFleetFill(&$attackFleets, $fleet_row);
    }
    $db_admiral_name = $sn_data[MRC_ADMIRAL]['name'];
    $defenseFleets = array(0 => array('def' => array(), 'user' => array('id' => $destination_user['id'], 'username' => $destination_user['username'], $db_admiral_name => $destination_user[$db_admiral_name], 'defence_tech' => $destination_user['defence_tech'], 'shield_tech' => $destination_user['shield_tech'], 'military_tech' => $destination_user['military_tech'])));
    foreach ($sn_data['groups']['combat'] as $combatUnitID) {
        if ($destination_planet[$sn_data[$combatUnitID]['name']] > 0) {
            $defenseFleets[0]['def'][$combatUnitID] = $destination_planet[$sn_data[$combatUnitID]['name']];
        }
    }
    $fleets = doquery('SELECT * FROM {{fleets}} WHERE `fleet_end_galaxy` = ' . $fleet_row['fleet_end_galaxy'] . ' AND `fleet_end_system` = ' . $fleet_row['fleet_end_system'] . ' AND `fleet_end_planet` = ' . $fleet_row['fleet_end_planet'] . ' AND `fleet_end_type` = ' . $fleet_row['fleet_end_type'] . ' AND fleet_start_time<' . $time_now . ' AND fleet_end_stay>=' . $time_now);
    while ($fleet = mysql_fetch_assoc($fleets)) {
        BE_attackFleetFill(&$defenseFleets, $fleet, 'def');
    }
    $start = microtime(true);
    $result = coe_attack_calculate($attackFleets, $defenseFleets);
    $totaltime = microtime(true) - $start;
    // Update galaxy (debree)
    if ($destination_user['authlevel'] == 0) {
        doquery('UPDATE {{planets}} SET `debris_metal` = `debris_metal` + ' . ($result['debree']['att'][0] + $result['debree']['def'][0]) . ' , debris_crystal = debris_crystal+' . ($result['debree']['att'][1] + $result['debree']['def'][1]) . ' WHERE `galaxy` = ' . $fleet_row['fleet_end_galaxy'] . ' AND `system` = ' . $fleet_row['fleet_end_system'] . ' AND `planet` = ' . $fleet_row['fleet_end_planet'] . ' AND `planet_type` = 1 LIMIT 1;');
    }
    // !G+ post-calculation for Attackers: fleet left and possible loot
    $loot = BE_calculatePostAttacker($destination_planet, $attackFleets, $result, false);
    if ($result['won'] == 2 && count($result['rw']) == 2) {
        $one_round_loss = true;
    } else {
        $one_round_loss = false;
    }
    // Update fleets & planets
    foreach ($attackFleets as $fleetID => $attacker) {
        if ($attacker['totalCount'] > 0) {
            $sqlQuery = 'UPDATE {{fleets}} SET ';
            if ($result['won'] == 1) {
                $sqlQuery .= '`fleet_resource_metal` = `fleet_resource_metal` + ' . ($attacker['loot']['metal'] + 0) . ', ';
                $sqlQuery .= '`fleet_resource_crystal` = `fleet_resource_crystal` + ' . ($attacker['loot']['crystal'] + 0) . ', ';
                $sqlQuery .= '`fleet_resource_deuterium` = `fleet_resource_deuterium` + ' . ($attacker['loot']['deuterium'] + 0) . ', ';
            }
            $sqlQuery .= '`fleet_array` = "' . substr($attacker['fleetArray'], 0, -1) . '", ';
            $sqlQuery .= '`fleet_amount` = ' . $attacker['totalCount'] . ', `fleet_mess` = 1 WHERE `fleet_id` = ' . $fleetID;
            doquery($sqlQuery);
        }
    }
    if ($fleet_row['fleet_mission'] == MT_AKS && $fleet_row['fleet_group']) {
        doquery("DELETE FROM {{aks}} WHERE id={$fleet_row['fleet_group']} LIMIT 1;");
        doquery("UPDATE {{fleets}} SET fleet_group = 0 WHERE fleet_group = {$fleet_row['fleet_group']} AND fleet_mission = " . MT_AKS . ";");
    }
    foreach ($defenseFleets as $fleetID => $defender) {
        $fleetArray = '';
        $totalCount = 0;
        if ($fleetID == 0) {
            foreach ($defender['def'] as $element => $amount) {
                $fleetArray .= "`{$sn_data[$element]['name']}` = '{$amount}', ";
            }
            doquery('UPDATE {{planets}} SET ' . $fleetArray . ' metal = metal - ' . $loot['looted']['metal'] . ', crystal = crystal - ' . $loot['looted']['crystal'] . ', deuterium=deuterium-' . $loot['looted']['deuterium'] . ' WHERE id=' . $destination_planet['id']);
        } else {
            foreach ($defender['def'] as $element => $amount) {
                if ($amount) {
                    $fleetArray .= $element . ',' . $amount . ';';
                }
                $totalCount += $amount;
            }
            if ($totalCount <= 0) {
                doquery("DELETE FROM `{{fleets}}` WHERE `fleet_id` = '{$fleetID}'");
            } else {
                doquery("UPDATE {{fleets}} SET fleet_array = '{$fleetArray}', fleet_amount = {$totalCount}" . ($one_round_loss ? '' : ', fleet_mess = 1') . " WHERE fleet_id = {$fleetID} LIMIT 1;");
            }
        }
    }
    // TvdW (c) 2008
    $planet_coordinates = uni_render_coordinates($fleet_row, 'fleet_end_');
    // FROM HERE THE SCRIPT WAS IMPORTED (not TvdW code anymore)
    $MoonChance = BE_calculateMoonChance($result);
    if (mt_rand(1, 100) <= $MoonChance && ($TargetPlanetName = uni_create_moon($fleet_row['fleet_end_galaxy'], $fleet_row['fleet_end_system'], $fleet_row['fleet_end_planet'], $TargetUserID, $MoonChance))) {
        $GottenMoon = sprintf($lang['sys_moonbuilt'], $TargetPlanetName, $planet_coordinates);
    }
    // Adjust number of raids made/win/loose and xpraid
    $str_loose_or_win = $result['won'] == 1 ? 'raidswin' : 'raidsloose';
    doquery("UPDATE {{users}} SET `xpraid` = `xpraid` + 1, `raids` = `raids` + 1, `{$str_loose_or_win}` = `{$str_loose_or_win}` + 1 WHERE id = '{$fleet_row['fleet_owner']}' LIMIT 1;");
    $bashing_list = array();
    foreach ($defenseFleets as $fleetID => $defender) {
        $users2[$defender['user']['id']] = $users_defender[$defender['user']['id']] = $defender['user']['id'];
    }
    foreach ($attackFleets as $fleetID => $attacker) {
        $users2[$attacker['user']['id']] = $users_attacker[$attacker['user']['id']] = $attacker['user']['id'];
        // Generating attackers list for bashing table
        $bashing_list[$attacker['user']['id']] = "({$attacker['user']['id']}, {$destination_planet['id']}, {$fleet_row['fleet_end_time']})";
    }
    $bashing_list = implode(',', $bashing_list);
    doquery("INSERT INTO {{bashing}} (bashing_user_id, bashing_planet_id, bashing_time) VALUES {$bashing_list};");
    //MadnessRed CR Creation.
    $raport = formatCR($result, $loot['looted'], $MoonChance, $GottenMoon, $totaltime);
    $raport = $raport['html'];
    $rid = md5($raport);
    $QryInsertRapport = 'INSERT INTO `{{rw}}` SET ';
    $QryInsertRapport .= '`time` = UNIX_TIMESTAMP(), ';
    $QryInsertRapport .= '`owners` = "' . implode(',', $users2) . '", ';
    $QryInsertRapport .= '`id_owner1` = "' . $attacker['user']['id'] . '", ';
    $QryInsertRapport .= '`id_owner2` = "' . $defender['user']['id'] . '", ';
    $QryInsertRapport .= '`rid` = "' . $rid . '", ';
    $QryInsertRapport .= '`raport` = "' . mysql_real_escape_string($raport) . '"';
    doquery($QryInsertRapport) or die("Error inserting CR to database" . mysql_error() . "<br /><br />Trying to execute:" . mysql_query());
    switch ($result['won']) {
        case 0:
            $color_attackers = $color_defenders = 'orange';
            break;
        case 1:
            $color_attackers = 'green';
            $color_defenders = 'red';
            break;
        case 2:
            $color_attackers = 'red';
            $color_defenders = 'green';
            break;
    }
    $raport_part1 = '<span OnClick=\'f("rw.php?raport=' . $rid . '", "");\' ><center><font color=';
    $raport_part2 = ">{$lang['sys_mess_attack_report']} {$planet_coordinates}</font></span><br /><br />" . "<font color=\"red\">{$lang['sys_perte_attaquant']}: " . pretty_number($result['lost']['att'], true) . "</font>&nbsp;<font color=\"green\">{$lang['sys_perte_defenseur']}: " . pretty_number($result['lost']['def'], true) . "</font><br />" . "{$lang['sys_debris']} {$lang['Metal']} <font color=\"#adaead\">" . pretty_number($result['debree']['att'][0] + $result['debree']['def'][0], true) . "</font> {$lang['Crystal']} <font color=\"#ef51ef\">" . pretty_number($result['debree']['att'][1] + $result['debree']['def'][1], true) . '</font><br />' . ($result['won'] == 1 ? "{$lang['sys_gain']} " . "{$lang['Metal']} <font color=\"#adaead\">" . pretty_number($loot['looted']['metal'], true) . '</font> ' . "{$lang['Crystal']} <font color=\"#ef51ef\">" . pretty_number($loot['looted']['crystal'], true) . '</font> ' . "{$lang['Deuterium']} <font color=\"#f77542\">" . pretty_number($loot['looted']['deuterium'], true) . '</font><br />' : '') . "{$st_1}{$st_2}</center>";
    $raport_acs = $one_round_loss ? "<center><span class=\"negative\">{$lang['sys_mess_attack_report']} {$planet_coordinates}\r\n{$lang['sys_coe_lost_contact']}</span></center>" : "{$raport_part1}{$color_attackers}{$raport_part2}";
    foreach ($users_attacker as $id) {
        //    if ($id != $fleet_row['fleet_owner'] && $id != 0)
        if ($id) {
            msg_send_simple_message($id, '', $fleet_row['fleet_start_time'], MSG_TYPE_COMBAT, $lang['sys_mess_tower'], $lang['sys_mess_attack_report'], $raport_acs);
        }
    }
    $raport_hold = "{$raport_part1}{$color_defenders}{$raport_part2}";
    foreach ($users_defender as $id) {
        if ($id && $id != $fleet_row['fleet_owner']) {
            msg_send_simple_message($id, '', $fleet_row['fleet_start_time'], MSG_TYPE_COMBAT, $lang['sys_mess_tower'], $lang['sys_mess_attack_report'], $raport_hold);
        }
    }
    return $result;
}
Example #2
0
     $skin = DEFAULT_SKINPATH;
     $language = DEFAULT_LANG;
     $galaxy = 1;
     $system = $system_step;
     $planet = round($config->game_maxPlanet / 2);
     foreach ($imported_string as &$string_data) {
         $string_data = explode(',', $string_data);
         $username_safe = $string_data[0];
         //      $user_new = player_create($username_safe, $string_data[1], '', array(
         //        'galaxy' => $galaxy,
         //        'system' => $system,
         //        'planet' => $planet,
         //      ), $create_result);
         $user_new = player_create($username_safe, sys_random_string(), array('password_encoded_unsafe' => core_auth::password_encode($string_data[1], ''), 'galaxy' => $galaxy, 'system' => $system, 'planet' => $planet));
         // $user_new = &$create_result[F_LOGIN_USER];
         $moon_row = uni_create_moon($galaxy, $system, $planet, $user_new['id'], 30, '', false);
         if (($system += $system_step) >= $config->game_maxSystem) {
             $galaxy++;
             $system = $system_step;
         }
     }
     doquery('UPDATE {{users}} SET dark_matter = 50000, dark_matter_total = 50000;');
     $config->db_saveItem('users_amount', $config->users_amount + $new_players);
     // pdump($imported_string);
     // generated_string
 } elseif (sys_get_param_str('import_result') && ($blitz_result_string = sys_get_param_str('blitz_result_string'))) {
     $blitz_result = explode(';', $blitz_result_string);
     $blitz_last_update = $blitz_result[0];
     // Пока не используется
     unset($blitz_result[0]);
     foreach ($blitz_result as $blitz_result_data) {
Example #3
0
<?php

/**
 * admin/add_moon.php
 *
 * @version 2
 * @copyright 2014 Gorlum for http://supernova.ws
 */
define('INSIDE', true);
define('INSTALL', false);
define('IN_ADMIN', true);
require '../common.' . substr(strrchr(__FILE__, '.'), 1);
// if ($user['authlevel'] < 2)
if ($user['authlevel'] < 3) {
    AdminMessage($lang['adm_err_denied']);
}
$template = gettemplate("admin/add_moon", true);
if (sys_get_param_str('mode') == 'addit') {
    $PlanetID = sys_get_param_id('user');
    $MoonName = sys_get_param_str('name');
    sn_db_transaction_start();
    $PlanetSelected = db_planet_by_id($PlanetID, true, '`galaxy`, `system`, `planet`, `id_owner`');
    uni_create_moon($PlanetSelected['galaxy'], $PlanetSelected['system'], $PlanetSelected['planet'], $PlanetSelected['id_owner'], 0, $MoonName);
    sn_db_transaction_commit();
    AdminMessage($lang['addm_done'], $lang['addm_title']);
}
display($template, $lang['addm_title'], false, '', true);
function sn_ube_combat_result_apply(&$combat_data)
{
    // TODO: Поменять все отладки на запросы
    $destination_user_id = $combat_data[UBE_FLEETS][0][UBE_OWNER];
    $outcome =& $combat_data[UBE_OUTCOME];
    $planet_info =& $outcome[UBE_PLANET];
    $planet_id = $planet_info[PLANET_ID];
    // Обновляем поле обломков на планете
    if (!$combat_data[UBE_OPTIONS][UBE_COMBAT_ADMIN] && !empty($outcome[UBE_DEBRIS])) {
        db_planet_set_by_gspt($planet_info[PLANET_GALAXY], $planet_info[PLANET_SYSTEM], $planet_info[PLANET_PLANET], PT_PLANET, "`debris_metal` = `debris_metal` + " . floor($outcome[UBE_DEBRIS][RES_METAL]) . ", `debris_crystal` = `debris_crystal` + " . floor($outcome[UBE_DEBRIS][RES_CRYSTAL]));
    }
    $db_save = array(UBE_FLEET_GROUP => array());
    $fleets_outcome =& $outcome[UBE_FLEETS];
    foreach ($combat_data[UBE_FLEETS] as $fleet_id => &$fleet_info) {
        if ($fleet_info[UBE_FLEET_GROUP]) {
            $db_save[UBE_FLEET_GROUP][$fleet_info[UBE_FLEET_GROUP]] = $fleet_info[UBE_FLEET_GROUP];
        }
        $fleet_info[UBE_COUNT] = $fleet_info[UBE_COUNT] ? $fleet_info[UBE_COUNT] : array();
        $fleets_outcome[$fleet_id][UBE_UNITS_LOST] = $fleets_outcome[$fleet_id][UBE_UNITS_LOST] ? $fleets_outcome[$fleet_id][UBE_UNITS_LOST] : array();
        $fleet_query = array();
        $db_changeset = array();
        $old_fleet_count = array_sum($fleet_info[UBE_COUNT]);
        $new_fleet_count = $old_fleet_count - array_sum($fleets_outcome[$fleet_id][UBE_UNITS_LOST]);
        // Перебираем юниты если во время боя количество юнитов изменилось и при этом во флоту остались юниты или это планета
        if ($new_fleet_count != $old_fleet_count && (!$fleet_id || $new_fleet_count)) {
            // Просматриваем результаты изменения флотов
            foreach ($fleet_info[UBE_COUNT] as $unit_id => $unit_count) {
                // Перебираем аутком на случай восстановления юнитов
                $units_lost = (double) $fleets_outcome[$fleet_id][UBE_UNITS_LOST][$unit_id];
                $units_left = $unit_count - $units_lost;
                if ($fleet_id) {
                    // Не планета - всегда сразу записываем строку итогов флота
                    $fleet_query[$unit_id] = "{$unit_id},{$units_left}";
                } elseif ($units_lost) {
                    // Планета - записываем в ИД юнита его потери только если есть потери
                    // $unit_db_name = get_unit_param($unit_id, P_NAME);
                    // $fleet_query[$unit_id] = "`{$unit_db_name}` = `{$unit_db_name}` - {$units_lost}";
                    // pdump($fleet_info);
                    // die();
                    $db_changeset['unit'][] = sn_db_unit_changeset_prepare($unit_id, -$units_lost, $combat_data[UBE_PLAYERS][$destination_user_id][UBE_PLAYER_DATA], $planet_id);
                }
            }
            if ($fleet_id) {
                // Для флотов перегенерируем массив как одно вхождение в SET SQL-запроса
                $fleet_query = implode(';', $fleet_query);
                $fleet_query = array("`fleet_array` = '{$fleet_query}'");
            }
        }
        // Если во флоте остались юниты или это планета - генерируем изменение ресурсов
        if ($new_fleet_count || !$fleet_id) {
            foreach (sn_get_groups('resources_loot') as $resource_id) {
                $resource_change = (double) $fleets_outcome[$fleet_id][UBE_RESOURCES_LOOTED][$resource_id] + (double) $fleets_outcome[$fleet_id][UBE_CARGO_DROPPED][$resource_id];
                if ($resource_change) {
                    $resource_db_name = ($fleet_id ? 'fleet_resource_' : '') . pname_resource_name($resource_id);
                    $fleet_query[] = "`{$resource_db_name}` = `{$resource_db_name}` - ({$resource_change})";
                }
            }
        }
        /*
            if(empty($fleet_query))
            {
              continue;
            }
        */
        if ($fleet_id && $new_fleet_count) {
            // Если защитник и не РМФ - отправляем флот назад
            if ($fleet_info[UBE_FLEET_TYPE] == UBE_DEFENDERS && !$outcome[UBE_SFR] || $fleet_info[UBE_FLEET_TYPE] == UBE_ATTACKERS) {
                $fleet_query[] = '`fleet_mess` = 1';
            }
            // Если флот в группе - помечаем нулем
            //      if($fleet_info[UBE_FLEET_GROUP])
            //      {
            //        $fleet_query[] = '`fleet_group` = 0';
            //      }
        }
        //global $debug;
        $fleet_query = implode(',', $fleet_query);
        if ($fleet_id) {
            if ($fleet_info[UBE_FLEET_TYPE] == UBE_ATTACKERS && $outcome[UBE_MOON_REAPERS] == UBE_MOON_REAPERS_DIED) {
                $new_fleet_count = 0;
            }
            if ($new_fleet_count) {
                if ($fleet_query) {
                    doquery("UPDATE {{fleets}} SET {$fleet_query}, `fleet_amount` = '{$new_fleet_count}' WHERE `fleet_id` = {$fleet_id} LIMIT 1");
                }
            } else {
                // Удаляем пустые флоты
                doquery("DELETE FROM {{fleets}} WHERE `fleet_id` = {$fleet_id} LIMIT 1");
                db_unit_list_delete(0, LOC_FLEET, $fleet_id, 0);
            }
        } else {
            // Сохраняем изменения ресурсов - если они есть
            if ($fleet_query) {
                db_planet_set_by_id($planet_id, $fleet_query);
            }
            if (!empty($db_changeset)) {
                db_changeset_apply($db_changeset);
            }
        }
    }
    // TODO: Связать сабы с флотами констраинтами ON DELETE SET NULL
    // $db_save[UBE_FLEET_GROUP][$fleet_info[UBE_FLEET_GROUP]] = $fleet_info[UBE_FLEET_GROUP];
    if (!empty($db_save[UBE_FLEET_GROUP])) {
        $db_save[UBE_FLEET_GROUP] = implode(',', $db_save[UBE_FLEET_GROUP]);
        doquery("DELETE FROM {{aks}} WHERE `id` IN ({$db_save[UBE_FLEET_GROUP]})");
    }
    if ($outcome[UBE_MOON] == UBE_MOON_CREATE_SUCCESS) {
        $moon_row = uni_create_moon($planet_info[PLANET_GALAXY], $planet_info[PLANET_SYSTEM], $planet_info[PLANET_PLANET], $destination_user_id, $outcome[UBE_MOON_SIZE], '', false);
        $outcome[UBE_MOON_NAME] = $moon_row['name'];
        unset($moon_row);
    } elseif ($outcome[UBE_MOON] == UBE_MOON_DESTROY_SUCCESS) {
        db_planet_delete_by_id($planet_id);
    }
    $bashing_list = array();
    foreach ($combat_data[UBE_PLAYERS] as $player_id => $player_info) {
        if ($player_info[UBE_ATTACKER]) {
            if ($outcome[UBE_MOON] != UBE_MOON_DESTROY_SUCCESS) {
                $bashing_list[] = "({$player_id}, {$planet_id}, {$combat_data[UBE_TIME]})";
            }
            if ($combat_data[UBE_OPTIONS][UBE_MISSION_TYPE] == MT_ATTACK && $combat_data[UBE_OPTIONS][UBE_DEFENDER_ACTIVE]) {
                $str_loose_or_win = $outcome[UBE_COMBAT_RESULT] == UBE_COMBAT_RESULT_WIN ? 'raidswin' : 'raidsloose';
                db_user_set_by_id($player_id, "`xpraid` = `xpraid` + 1, `raids` = `raids` + 1, `{$str_loose_or_win}` = `{$str_loose_or_win}` + 1");
            }
        }
    }
    $bashing_list = implode(',', $bashing_list);
    if ($bashing_list) {
        doquery("INSERT INTO {{bashing}} (bashing_user_id, bashing_planet_id, bashing_time) VALUES {$bashing_list};");
    }
}
Example #5
0
<?php

/**
 * add_moon.php
 *
 * @version 1
 * @copyright 2008 by Chlorel for XNova
 */
define('INSIDE', true);
define('INSTALL', false);
define('IN_ADMIN', true);
require '../common.' . substr(strrchr(__FILE__, '.'), 1);
if ($user['authlevel'] < 2) {
    AdminMessage($lang['adm_err_denied']);
}
$mode = $_POST['mode'];
$PageTpl = gettemplate("admin/add_moon");
$parse = $lang;
if ($mode == 'addit') {
    $PlanetID = $_POST['user'];
    $MoonName = $_POST['name'];
    $PlanetSelected = doquery("SELECT * FROM {{planets}} WHERE `id` = '{$PlanetID}' LIMIT 1;", '', true);
    $Galaxy = $PlanetSelected['galaxy'];
    $System = $PlanetSelected['system'];
    $Planet = $PlanetSelected['planet'];
    $Owner = $PlanetSelected['id_owner'];
    uni_create_moon($Galaxy, $System, $Planet, $Owner, 20, $MoonName);
    AdminMessage($lang['addm_done'], $lang['addm_title']);
}
$Page = parsetemplate($PageTpl, $parse);
display($Page, $lang['addm_title'], false, '', true);
Example #6
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);
}