function add_news_entry($type, $information)
{
    global $sql, $smarty;
    require_once dirname(__FILE__) . '/news_resource.php';
    $sql->select(array('news_entries', 'news_entry_id'));
    $sql->where(array('news_entries', 'type', $type));
    $sql->raw(array('orderby', 'RAND(' . microfloat() . ')'));
    $sql->limit(1);
    $db_result = $sql->execute();
    $db_row = mysql_fetch_array($db_result, MYSQL_ASSOC);
    $news_entry_id = $db_row['news_entry_id'];
    $posted = $information['posted'];
    $information['posted'] = format_timestamp($information['posted']);
    foreach ($information as $key => $value) {
        $smarty->assign($key, $value);
    }
    $smarty->fetch('news:' . $news_entry_id);
    $entry_subject = $smarty->get_template_vars('subject');
    $entry_body = $smarty->get_template_vars('body');
    $news_insert = array('round_id' => $_SESSION['round_id'], 'type' => $type, 'subject' => $entry_subject, 'body' => $entry_body, 'posted' => $posted);
    $fields = array('kingdom_id', 'player_id', 'planet_id');
    foreach ($fields as $value) {
        if (!empty($information[$value])) {
            $news_insert[$value] = $information[$value];
        }
    }
    $sql->execute('news', $news_insert);
}
function unpause_round()
{
    global $sql;
    $round_id = $_REQUEST['round_id'];
    $sql->select(array(array('rounds', 'pause_time'), array('rounds', 'stoptime')));
    $sql->where(array('rounds', 'round_id', $round_id));
    $sql->limit(1);
    $db_result = $sql->execute();
    $db_row = mysql_fetch_array($db_result, MYSQL_ASSOC);
    $fastforward = microfloat() - $db_row['pause_time'];
    if (!empty($_REQUEST['skip'])) {
        $fastforward -= abs((int) $_REQUEST['skip']);
    }
    $sql->set(array(array('rounds', 'stoptime', "raw:`rounds`.`stoptime` + {$fastforward}"), array('rounds', 'pause_time', 0)));
    $sql->where(array('rounds', 'round_id', $round_id));
    $sql->limit(1);
    $db_result = $sql->execute();
    if ($db_result && mysql_affected_rows() > 0) {
        $unpause = array('combat' => 'completion', 'planets' => 'lastupdated', 'tasks' => 'completion');
        foreach ($unpause as $table => $field) {
            $sql->set(array($table, $field, "raw:`{$table}`.`{$field}` + {$fastforward}"));
            $sql->where(array($table, 'round_id', $round_id));
            $db_result = $sql->execute();
        }
    }
}
 function update_to()
 {
     if (empty($this->data['update_to'])) {
         $this->data['update_to'] = microfloat();
     }
     return $this->data['update_to'];
 }
function help_status()
{
    global $smarty;
    $db_query = "\n\t\t\tSELECT \n\t\t\t\t`round_id`, \n\t\t\t\t`round_engine`, \n\t\t\t\t`name`, \n\t\t\t\t`description`, \n\t\t\t\t`starttime`, \n\t\t\t\t`stoptime`, \n\t\t\t\t`starsystems`, \n\t\t\t\t`planets`, \n\t\t\t\t`resistance`, \n\t\t\t\t`speed`, \n\t\t\t\t`resourcetick`, \n\t\t\t\t`combattick` \n\t\t\tFROM `rounds` \n\t\t\tWHERE `round_id` = '" . $_SESSION['round_id'] . "' \n\t\t\tLIMIT 1";
    $db_result = mysql_query($db_query);
    $round = mysql_fetch_array($db_result, MYSQL_ASSOC);
    $round['speed'] /= 1000;
    // Dynamic attack limit based on elapsed time of current round
    $end_time = 3456000 * $_SESSION['round_speed'];
    $current_time = microfloat() - $round['starttime'];
    $attack_limit = 1 - $current_time / $end_time;
    if ($attack_limit < 0) {
        $attack_limit = 0;
    }
    $round['attack_limit'] = round($attack_limit * 100, 2);
    $round['description'] = nl2br($round['description']);
    $round['starttime'] = format_timestamp($round['starttime']);
    $round['stoptime'] = format_timestamp($round['stoptime']);
    $round['resistance'] = format_number($round['resistance']);
    $round['resourcetick'] = format_time(timeparser($round['resourcetick'] / 1000));
    $round['combattick'] = format_time(timeparser($round['combattick'] / 1000));
    $smarty->assign('round', $round);
    $smarty->display('help_status.tpl');
    exit;
}
function reports_list()
{
    global $smarty, $sql;
    $sql->select(array(array('planets', 'planet_id'), array('planets', 'name'), array('combatreports', 'combatreport_id'), array('combatreports', 'status'), array('combatreports', 'date')));
    $sql->where(array(array('combatreports', 'round_id', $_SESSION['round_id']), array('combatreports', 'kingdom_id', $_SESSION['kingdom_id']), array('planets', 'planet_id', array('combatreports', 'planet_id'))));
    $sql->orderby(array('combatreports', 'date', 'desc'));
    $sql->limit(30);
    if (!empty($_POST['planet_id'])) {
        $sql->where(array('combatreports', 'planet_id', abs((int) $_POST['planet_id'])));
    }
    if (!empty($_POST['time'])) {
        $sql->where(array('combatreports', 'date', "raw:'" . microfloat() . "' - ('" . mysql_real_escape_string(abs((int) $_POST['time'])) . "' * (`rounds`.`combattick` / 1000))", '>='));
    }
    if (!empty($_POST['status'])) {
        foreach ($_POST['status'] as $key => $value) {
            $key = abs((int) $key);
            if ($key >= 0 && $key <= 3) {
                $status[$key] = true;
            }
        }
        if (!empty($status)) {
            $sql->where(array('combatreports', 'status', array_keys($status), 'IN'));
        }
    }
    $db_result = $sql->execute();
    $combatreports = array();
    while ($db_row = mysql_fetch_array($db_result, MYSQL_ASSOC)) {
        unset($report);
        $report['combatreport_id'] = $db_row['combatreport_id'];
        $report['date'] = format_timestamp($db_row['date']);
        $report['location'] = 'P#' . $db_row['planet_id'] . ' ' . $db_row['name'];
        if ($db_row['status'] == 0) {
            $report['status'] = 'Ongoing';
        } elseif ($db_row['status'] == 1) {
            $report['status'] = 'Won';
        } else {
            $report['status'] = 'Lost';
        }
        $combatreports[$db_row['planet_id']][$db_row['combatreport_id']] = $report;
    }
    $smarty->assign('combatreports', $combatreports);
    $smarty->display('reports_list.tpl');
}
function rebuild_maps()
{
    global $sql;
    $sql->set(array('quadrants', 'active', 0));
    $sql->execute();
    $db_query = "DELETE FROM `starsystems`";
    $db_result = mysql_query($db_query);
    // Rebuild quadrant and starsystem tables.
    $db_query = "SELECT `round_id`, `quadrant_id`, `starsystem_id`, `status` FROM `planets`";
    $db_result = mysql_query($db_query);
    while ($db_row = mysql_fetch_array($db_result, MYSQL_ASSOC)) {
        if (empty($db_row['round_id'])) {
            continue;
        }
        if (!isset($map_tables[$db_row['round_id']][$db_row['quadrant_id']][$db_row['starsystem_id']])) {
            $map_tables[$db_row['round_id']][$db_row['quadrant_id']][$db_row['starsystem_id']] = 0;
        }
        if (empty($db_row['status'])) {
            $map_tables[$db_row['round_id']][$db_row['quadrant_id']][$db_row['starsystem_id']]++;
        }
    }
    srand(microfloat());
    foreach ($map_tables as $round_id => $quadrants) {
        foreach ($quadrants as $quadrant_id => $starsystems) {
            $sql->set(array('quadrants', 'active', 1));
            $sql->where(array('quadrants', 'quadrant_id', $quadrant_id));
            $sql->execute();
            $defined_starsystems = array();
            foreach ($starsystems as $starsystem_id => $count) {
                $x = rand(0, 6);
                $y = rand(0, 6);
                while (isset($defined_starsystems[$x . $y])) {
                    $x = rand(0, 6);
                    $y = rand(0, 6);
                }
                $defined_starsystems[$x . $y] = true;
                $starsystem_insert = array('starsystem_id' => $starsystem_id, 'quadrant_id' => $quadrant_id, 'round_id' => $round_id, 'available' => $count, 'total' => 7, 'x' => $x, 'y' => $y);
                $sql->execute('starsystems', $starsystem_insert);
            }
        }
    }
}
 function planet()
 {
     // If requesting a specific / relative planet
     if (isset($_REQUEST['planet_id'])) {
         $planet_id = $_REQUEST['planet_id'];
         // Let's duplicate our effort for sake of simplicity. We can always refactor later.
         if (in_array($planet_id, array('previous', 'next'))) {
             $planetList = 'own';
             $action = $planet_id;
             $player =& $this->data->player($_SESSION['player_id']);
             $planets = $player['planets'];
             $planet_current = $player['planet_current'];
             $planet_id = $this->get_adjacent_planet($planets, $planet_current, $action);
             $this->set_current_planet($player, $planet_id, $planetList);
         } else {
             if (in_array($planet_id, array('previous_permissions', 'next_permissions'))) {
                 $planetList = 'permission';
                 if ($planet_id == 'previous_permissions') {
                     $action = 'previous';
                 } else {
                     $action = 'next';
                 }
                 permissions_update_planets($_SESSION['player_id']);
                 $player =& $this->data->player($_SESSION['player_id']);
                 $planets = $player['planets_permissions'];
                 $planet_current = $player['planet_permission_current'];
                 if (empty($planets)) {
                     $this->smarty->append('status', 'You do not have permission to access any other planets');
                     $this->smarty->display('error.tpl');
                     exit;
                 }
                 $planet_id = $this->get_adjacent_planet($planets, $planet_current, $action);
                 $this->set_current_planet($player, $planet_id, $planetList);
             } else {
                 $planet_id = abs((int) $planet_id);
             }
         }
         $_SESSION['planet_id'] = $planet_id;
     } else {
         $player =& $this->data->player($_SESSION['player_id']);
         $planet_id = $player['planet_current'];
     }
     $this->data->updater->update(0, $planet_id);
     $permissions = permissions_check(PERMISSION_PLANET, $planet_id);
     $round = $this->data->round();
     $planet = $this->data->planet($planet_id);
     if (!empty($planet['player_id'])) {
         $player = $this->data->player($planet['player_id']);
         $planet['player_name'] = strshort($player['name'], 15);
         if ($player['npc'] == 1) {
             $planet['npc_player'] = true;
         }
     }
     if (!empty($planet['kingdom_id'])) {
         $kingdom = $this->data->kingdom($planet['kingdom_id']);
         $planet['kingdom_name'] = strshort($kingdom['name'], 15);
     }
     $planet['permissions'] = $permissions;
     if ($planet['player_id'] == $_SESSION['player_id']) {
         $_SESSION['planet_id'] = $planet['planet_id'];
     }
     $planet['score'] = format_number($planet['score']);
     $planet['score_peak'] = format_number($planet['score_peak']);
     if ($permissions['grant']) {
         if (!empty($planet['minerals'])) {
             $planet['minerals'] = array_sum($planet['minerals']);
         } else {
             $planet['minerals'] = 0;
         }
         $resource_deficiency = 0;
         foreach (array('food', 'workers', 'energy', 'minerals') as $resource) {
             if ($resource_deficiency != 0) {
                 $planet[$resource . 'deficiency'] = $planet[$resource . 'rate'];
             }
             $planet[$resource . 'rate'] += $resource_deficiency;
             if ($planet[$resource . 'rate'] < 0 && $planet[$resource] < abs($planet[$resource . 'rate'])) {
                 $resource_deficiency = $planet[$resource . 'rate'] + $planet[$resource];
             }
             $planet[$resource] = format_number($planet[$resource], true);
             $planet[$resource . 'rate'] = format_number($planet[$resource . 'rate'], true, true);
         }
         if ($permissions['build']) {
             $types[] = 1;
         }
         if ($permissions['research']) {
             $types[] = 2;
             $types[] = 3;
         }
         if ($permissions['commission']) {
             $types[] = 4;
         }
         unset($planet['researching'], $planet['building'], $planet['army'], $planet['navy']);
         // Get tasks currently running on the planet
         $db_query = "SELECT DISTINCT `task_id`, `attribute`, `number`, `type` FROM `tasks` WHERE `round_id` = '" . $_SESSION['round_id'] . "' AND `planet_id` = '" . $planet_id . "' AND `type` IN ('" . implode("', '", $types) . "') ORDER BY `completion` DESC";
         $db_result_tasks = mysql_query($db_query);
         while ($tasks = mysql_fetch_array($db_result_tasks, MYSQL_ASSOC)) {
             $this->sql->select(array('tasks', 'completion'));
             $this->sql->where(array(array('tasks', 'round_id', $_SESSION['round_id']), array('tasks', 'task_id', $tasks['task_id'])));
             $this->sql->limit(1);
             switch ($tasks['type']) {
                 case 1:
                     $this->sql->select(array('buildings', 'name'));
                     $this->sql->where(array('buildings', 'building_id', array('tasks', 'building_id')));
                     $db_result = $this->sql->execute();
                     $db_row = mysql_fetch_array($db_result, MYSQL_ASSOC);
                     $planet['building']['name'] = strshort($db_row['name'], 15);
                     $planet['building']['time'] = format_time(timeparser($db_row['completion'] - microfloat()));
                     break;
                 case 2:
                     $this->sql->select(array('concepts', 'name'));
                     $this->sql->where(array('concepts', 'concept_id', array('tasks', 'concept_id')));
                     $db_result = $this->sql->execute();
                     $db_row = mysql_fetch_array($db_result, MYSQL_ASSOC);
                     $planet['researching']['name'] = strshort($db_row['name'], 15);
                     $planet['researching']['time'] = format_time(timeparser($db_row['completion'] - microfloat()));
                     break;
                 case 3:
                     $designs = array('army', 'navy', 'weapon');
                     $this->sql->select(array($designs[$tasks['number']] . 'designs', 'name'));
                     $this->sql->where(array($designs[$tasks['number']] . 'designs', $designs[$tasks['number']] . 'design_id', array('tasks', 'design_id')));
                     $db_result = $this->sql->execute();
                     $db_row = mysql_fetch_array($db_result, MYSQL_ASSOC);
                     $planet['researching']['name'] = strshort($db_row['name'], 15);
                     $planet['researching']['time'] = format_time(timeparser($db_row['completion'] - microfloat()));
                     break;
                 case 4:
                     $this->sql->select(array($tasks['attribute'] . 'blueprints', 'name'));
                     $this->sql->where(array($tasks['attribute'] . 'blueprints', $tasks['attribute'] . 'blueprint_id', array('tasks', 'unit_id')));
                     $db_result = $this->sql->execute();
                     $db_row = mysql_fetch_array($db_result, MYSQL_ASSOC);
                     $planet[$tasks['attribute']]['name'] = strshort($db_row['name'], 15);
                     $planet[$tasks['attribute']]['time'] = format_time(timeparser($db_row['completion'] - microfloat()));
                     break;
             }
         }
         $planet['nextupdate'] = format_time($round['resourcetick'] - (microfloat() - $planet['lastupdated']));
     }
     $this->smarty->assign('planet', $planet);
     $this->smarty->display('info_planet.tpl');
 }
function options_planet_save()
{
    if (empty($_REQUEST['code'])) {
        $_SESSION['status'][] = 'Please enter a planet code first.';
        options_planet();
        exit;
    }
    $planet_code = $_REQUEST['code'];
    if (strlen($planet_code) != 32) {
        $_SESSION['status'][] = 'Invalid planet code entered. Please check the code and try again.';
        options_planet();
        exit;
    }
    $db_query = "\n\t\t\tSELECT `planet_id` \n\t\t\tFROM `planets` \n\t\t\tWHERE \n\t\t\t\t`code` = '" . mysql_real_escape_string($planet_code) . "' AND \n\t\t\t\t`kingdom_id` = '" . $_SESSION['kingdom_id'] . "' AND \n\t\t\t\t`player_id` = '0' \n\t\t\tLIMIT 1";
    $db_result = mysql_query($db_query);
    if (mysql_num_rows($db_result) == 0) {
        $_SESSION['status'][] = 'That planet code has been taken already, does not exist, or is not in your kingdom.';
        options_planet();
        exit;
    }
    $db_row = mysql_fetch_array($db_result, MYSQL_ASSOC);
    global $data;
    $round = $data->round();
    $planet =& $data->planet($db_row['planet_id']);
    $kingdom =& $data->kingdom($planet['kingdom_id']);
    $player =& $data->player($_SESSION['player_id']);
    $planet['code'] = '';
    $planet['status'] = PLANETSTATUS_OCCUPIED;
    $planet['warptime_construction'] = $planet['warptime_research'] = (microfloat() - $round['starttime']) * $round['warptime'];
    $planet['player_id'] = $_SESSION['player_id'];
    $planet['lastupdated'] = microfloat();
    $kingdom['planets'][$planet['planet_id']] = true;
    $player['planets'][$planet['planet_id']] = true;
    $data->save();
    global $smarty;
    $smarty->append('status', 'Planet successfully claimed.');
    options_planet();
    exit;
}
function mail_send()
{
    global $smarty;
    $mail['to'] = $_POST['to'];
    $mail['subject'] = $_POST['subject'];
    $mail['body'] = $_POST['body'];
    if ($mail['to'] == 'Administration') {
        $db_query = "\n\t\t\t\tSELECT `player_id` \n\t\t\t\tFROM `players` \n\t\t\t\tWHERE \n\t\t\t\t\t`round_id` = '" . $_SESSION['round_id'] . "' AND \n\t\t\t\t\t`user_id` = '1'";
        $db_result = mysql_query($db_query);
        if (mysql_num_rows($db_result) == 0) {
            $to = 0;
        } else {
            $db_row = mysql_fetch_array($db_result, MYSQL_ASSOC);
            $to = $db_row['player_id'];
        }
    } else {
        $db_query = "\n\t\t\t\tSELECT `player_id` \n\t\t\t\tFROM `players` \n\t\t\t\tWHERE \n\t\t\t\t\t`round_id` = '" . $_SESSION['round_id'] . "' AND \n\t\t\t\t\t`name` = '" . mysql_real_escape_string($mail['to']) . "'";
        $db_result = mysql_query($db_query);
        if (mysql_num_rows($db_result) == 0) {
            $status[] = 'Incorrect player name. Please check it and try again.';
        } else {
            $db_row = mysql_fetch_array($db_result, MYSQL_ASSOC);
            $to = $db_row['player_id'];
        }
    }
    if (empty($mail['subject'])) {
        $status[] = 'Enter a subject and try again.';
    }
    if (empty($mail['body'])) {
        $status[] = 'Cannot send a blank message.';
    }
    if (!empty($status)) {
        $smarty->append('status', $status);
        $smarty->assign('mail', $mail);
        $smarty->display('mail_compose.tpl');
        exit;
    }
    $db_query = "INSERT INTO `mail` (`round_id`, `to_player_id`, `from_player_id`, `time`, `subject`, `body`) VALUES (\n\t\t\t'" . $_SESSION['round_id'] . "', \n\t\t\t'" . $to . "', \n\t\t\t'" . $_SESSION['player_id'] . "', \n\t\t\t'" . microfloat() . "', \n\t\t\t'" . mysql_real_escape_string($mail['subject']) . "', \n\t\t\t'" . mysql_real_escape_string($mail['body']) . "'\n\t\t)";
    $db_result = mysql_query($db_query);
    $db_query = "UPDATE `players` SET `mail` = '1' WHERE `player_id` = '" . $to . "'";
    $db_result = mysql_query($db_query);
    $status[] = 'Message sent successfully.';
    $smarty->append('status', $status);
    mail_list();
    exit;
}
 function upgrade()
 {
     $planet_id = $this->planet_id;
     if (isset($_POST['mode']) && $_POST['mode'] == 'js') {
         $output_mode = 'javascript';
     } else {
         $output_mode = '';
     }
     permissions_check(PERMISSION_PLANET, $planet_id, 'research');
     $designs['main'] = array(0 => 'army', 1 => 'navy', 2 => 'weapon');
     foreach ($designs['main'] as $key => $value) {
         if (!empty($_POST[$value . 'design_id'])) {
             $design_id = (int) $_POST[$value . 'design_id'];
             $design_name = $value;
             $type = $key;
             break;
         }
     }
     $attribute = $_POST['attribute'];
     if (empty($design_name) || empty($attribute)) {
         $status[] = 'No upgrade selected.';
         if ($output_mode == 'javascript') {
             echo 'alert(\'' . implode("\n", $status) . '\'); varUpgrading = false; varError = true;';
             exit;
         }
         $this->smarty->append('status', $status);
         $this->overview();
         exit;
     }
     if ($attribute != mysql_real_escape_string($attribute)) {
         error(__FILE__, __LINE__, 'DATA_INVALID', 'Invalid attribute selected');
     }
     $db_query = "\n\t\t\t\tSELECT \n\t\t\t\t\t`time`, \n\t\t\t\t\t`workers`, \n\t\t\t\t\t`energy`, \n\t\t\t\t\t`minerals`, \n\t\t\t\t\t`mineralspread`, \n\t\t\t\t\t`techlevel_current`, \n\t\t\t\t\t`techlevel_max`, \n\t\t\t\t\t`" . $attribute . "_base`, \n\t\t\t\t\t`" . $attribute . "_max`, \n\t\t\t\t\t`" . $attribute . "_inc`, \n\t\t\t\t\t`" . $attribute . "_per`, \n\t\t\t\t\t`" . $attribute . "_size`, \n\t\t\t\t\t`" . $attribute . "_sizeinc`, \n\t\t\t\t\t`size_base`, \n\t\t\t\t\t`size_max` \n\t\t\t\tFROM \n\t\t\t\t\t`" . $design_name . "designs` \n\t\t\t\tWHERE \n\t\t\t\t\t`kingdom_id` = '" . $_SESSION['kingdom_id'] . "' AND \n\t\t\t\t\t`" . $design_name . "design_id` = '" . $design_id . "' \n\t\t\t\tLIMIT 1";
     $db_result = mysql_query($db_query);
     if (mysql_num_rows($db_result) == 0) {
         error(__FILE__, __LINE__, 'DATA_INVALID', 'Invalid design selected');
     }
     $design = mysql_fetch_array($db_result, MYSQL_ASSOC);
     $design['mineralspread'] = unserialize($design['mineralspread']);
     if ($design['techlevel_current'] >= $design['techlevel_max']) {
         $status[] = 'The tech level has been maxed out.';
     }
     if ($design[$attribute . '_base'] == $design[$attribute . '_max']) {
         $status[] = 'That attribute has been maxed out.';
     }
     if (!empty($status)) {
         if ($output_mode == 'javascript') {
             echo 'alert(\'' . implode("\n", $status) . '\'); varUpgrading = false; varError = true;';
             exit;
         }
         $this->smarty->append('status', $status);
         $this->overview();
         exit;
     }
     $db_query = "SELECT `planet_id` FROM `tasks` WHERE `kingdom_id` = '" . $_SESSION['kingdom_id'] . "' AND `type` IN ('2', '3') AND (`planet_id` = '" . $planet_id . "' OR `design_id` = '" . $design_id . "') LIMIT 2";
     $db_result = mysql_query($db_query);
     while ($db_row = mysql_fetch_array($db_result, MYSQL_ASSOC)) {
         if ($db_row['planet_id'] == $planet_id) {
             $status[] = 'That planet is already researching something.';
         } else {
             $status[] = 'That design is already being researched elsewhere';
         }
     }
     if (!empty($status)) {
         if ($output_mode == 'javascript') {
             echo 'alert(\'' . implode("\n", $status) . '\'); varUpgrading = false; varError = true;';
             exit;
         }
         $this->smarty->append('status', $status);
         $this->overview();
         exit;
     }
     $db_query = "SELECT `player_id`, `workers`, `energy`, `minerals`, `researchbonus` FROM `planets` WHERE `planet_id` = '" . $planet_id . "' LIMIT 1";
     $db_result = mysql_query($db_query);
     $planet = mysql_fetch_array($db_result, MYSQL_ASSOC);
     $planet['minerals'] = unserialize($planet['minerals']);
     $resources = array('workers', 'energy');
     foreach ($resources as $value) {
         $planet[$value] -= $design[$value];
         if ($planet[$value] < 0) {
             $status[] = 'Not enough ' . $value . '.';
         }
     }
     if (!empty($design['mineralspread'])) {
         $mineralnames = array(0 => 'fe', 1 => 'o', 2 => 'si', 3 => 'mg', 4 => 'ni', 5 => 's', 6 => 'he', 7 => 'h');
         foreach ($design['mineralspread'] as $key => $value) {
             $mineral = $value / 100 * $design['minerals'];
             $planet['minerals'][$key] -= $mineral;
             if ($planet['minerals'][$key] < 0) {
                 $status[] = 'Not enough ' . $mineralnames[$key] . '.';
             }
         }
     }
     if (!empty($status)) {
         if ($output_mode == 'javascript') {
             echo 'alert(\'' . implode("\n", $status) . '\'); varUpgrading = false; varError = true;';
             exit;
         }
         $this->smarty->append('status', $status);
         $this->overview();
         exit;
     }
     $completion = $design['time'] * $_SESSION['round_speed'] * ((100 - $planet['researchbonus']) / 100);
     $warptime = request_variable('warptime');
     if (!is_null($warptime)) {
         data::initialize();
         $data_planet =& $this->data->planet($planet_id);
         if ($data_planet['warptime_research'] > $completion) {
             $data_planet['warptime_research'] -= $completion;
             $completion = 0;
         } else {
             $completion -= $data_planet['warptime_research'];
             $data_planet['warptime_research'] = 0;
         }
         $this->data->save();
     }
     $insert_design = array('round_id' => $_SESSION['round_id'], 'kingdom_id' => $_SESSION['kingdom_id'], 'planet_id' => $planet_id, 'type' => 3, 'design_id' => $design_id, 'attribute' => $attribute, 'number' => $type, 'start' => microfloat(), 'completion' => microfloat() + $completion);
     $db_result = $this->sql->execute('tasks', $insert_design);
     $this->sql->set(array(array('planets', 'researching', 1), array('planets', 'workers', $planet['workers']), array('planets', 'energy', $planet['energy']), array('planets', 'minerals', serialize($planet['minerals']))));
     $this->sql->where(array('planets', 'planet_id', $planet_id));
     $this->sql->limit(1);
     $db_result = $this->sql->execute();
     if ($output_mode == 'javascript') {
         echo 'varUpgrading = true; varError = false;';
         exit;
     }
     $_SESSION['status'][] = 'Upgrade successfully started.';
     redirect('designs.php');
 }
function register()
{
    global $smarty;
    $timezones = array(-12, -11, -10, -9, -8, -7, -6, -5, -4, -3.5, -3, -2, -1, 0, 1, 2, 3, 3.5, 4, 4.5, 5, 5.5, 6, 6.5, 7, 8, 9, 9.5, 10, 11, 12, 13);
    $smarty->assign('timezones', $timezones);
    if (!isset($_POST['fn'])) {
        $smarty->display('register.tpl');
        exit;
    }
    $username = strtolower($_POST['username']);
    $password = $_POST['password'];
    $password_confirm = $_POST['password_confirm'];
    $email = $_POST['email'];
    $preferences['decimal_symbol'] = $_POST['decimal_symbol'][0];
    $preferences['thousands_seperator'] = $_POST['thousands_seperator'][0];
    $preferences['timezone'] = (int) $_POST['timezone'];
    $preferences['timestamp_format'] = $_POST['timestamp_format'];
    if (isset($_POST['forumaccount'])) {
        $forumaccount = true;
        mysql_select_db('zimzatik2');
        $db_query = "\n\t\t\t\tSELECT \n\t\t\t\t\t`username`, \n\t\t\t\t\t`user_password`, \n\t\t\t\t\t`user_regdate`, \n\t\t\t\t\t`user_email`\n\t\t\t\tFROM `phpbb_users` \n\t\t\t\tWHERE \n\t\t\t\t\t`username` = '" . mysql_real_escape_string($username) . "' AND \n\t\t\t\t\t`user_password` = '" . md5($password) . "' AND \n\t\t\t\t\t`user_active` = '1' \n\t\t\t\tLIMIT 1";
        $db_result = mysql_query($db_query);
        if (!$db_result || mysql_num_rows($db_result) == 0) {
            $status[] = 'Username and password did not match any active forum accounts. If your forum account has not been activated yet, please do so and try again.';
        } else {
            $db_row = mysql_fetch_array($db_result, MYSQL_ASSOC);
            $username = $db_row['username'];
            $password = $db_row['user_password'];
            $email = $db_row['user_email'];
            $regdate = $db_row['user_regdate'];
        }
        mysql_select_db('zimzatik');
    } else {
        $forumaccount = false;
    }
    $email_regex = '/[-_\\d\\w]+@((\\.|)[-_\\d\\w]{2,})+(\\.[\\w]{2,})+/';
    if (strlen($username) > 25 && !$forumaccount) {
        $status[] = 'Username longer than maximum length';
    }
    if ($password != $password_confirm && !$forumaccount) {
        $status[] = 'Passwords do not match. Please re-enter and try again.';
    } elseif (strlen($password) > 100 || strlen($password) < 4) {
        $status[] = 'Password longer than 100 characters or shorter than 4 characters. Please try a shorter/longer password and try again.';
    }
    if (strlen($email) > 255 && !$forumaccount) {
        $status[] = 'Your email is longer than our database can handle. If it is your valid email address please contact the administrator.';
    } elseif (preg_match($email_regex, $email) == 0 && !$forumaccount) {
        $status[] = 'Your email address did not validate. If it is a valid email address please contact the administrator.';
    }
    if (strlen($preferences['timestamp_format']) > 14) {
        $status[] = 'The timestamp format you entered was longer than acceptable. Please shorten it and try again.';
    }
    if (!empty($status)) {
        $smarty->assign('username', $username);
        $smarty->assign('email', $email);
        $smarty->assign('preferences', $preferences);
        $smarty->append('status', $status);
        $smarty->display('register.tpl');
        exit;
    }
    $db_query = "\n\t\t\tSELECT \n\t\t\t\t`username`, \n\t\t\t\t`email`, \n\t\t\t\t`activated` \n\t\t\tFROM `users` \n\t\t\tWHERE \n\t\t\t\t`username` = '" . mysql_real_escape_string($username) . "' OR \n\t\t\t\t`email` = '" . mysql_real_escape_string($email) . "' LIMIT 2";
    $db_result = mysql_query($db_query);
    while ($db_row = mysql_fetch_array($db_result, MYSQL_ASSOC)) {
        if ($db_row['username'] == $username) {
            $status[] = 'Username already taken. Please enter a different one and try again.';
        }
        if ($db_row['email'] == $email) {
            $status[] = 'That email address is already registered under another username.';
            if ($db_row['activated'] == 0) {
                $status[] = 'Please do not create more than one account.';
            }
        }
    }
    if (strlen($status) > 0) {
        $smarty->assign('username', $username);
        $smarty->assign('email', $email);
        $smarty->assign('preferences', $preferences);
        $smarty->append('status', $status);
        $smarty->display('register.tpl');
        exit;
    }
    if ($forumaccount) {
        $activation = 0;
    } else {
        $activation = md5(rand(0, 35000) . '+' . rand(0, 35000));
    }
    $db_query = "\n\t\t\tINSERT INTO `users` \n\t\t\t(`username`, `password`, `preferences`, `email`, `lastlogin`, `created`, `activated`) VALUES \n\t\t\t(\n\t\t\t\t'" . mysql_real_escape_string($username) . "', \n\t\t\t\t";
    if ($forumaccount) {
        $db_query .= "'" . mysql_real_escape_string($password) . "', ";
    } else {
        $db_query .= "'" . md5($password) . "', ";
    }
    $db_query .= "\n\t\t\t\t'" . mysql_real_escape_string(serialize($preferences)) . "', \n\t\t\t\t'" . mysql_real_escape_string($email) . "', \n\t\t\t\t'0', \n\t\t\t\t'" . microfloat() . "', \n\t\t\t\t'" . $activation . "'\n\t\t\t)";
    $db_result = mysql_query($db_query);
    if ($forumaccount) {
        $smarty->append('status', 'Your account has been imported successfully. You can now use the username and password from the forum in the game. Please note that if you change your forum password it will not change your game password.');
    } else {
        $message = 'Welcome to Imperial Kingdoms! You\'re only one step away from joining the action. Click on or manually go to the following URL and your account will be ready for you to use.

http://www.imperialkingdoms.com/register.php?fn=confirm&username='******'&activation=' . urlencode($activation) . '

We look forward to seeing you in our community.

---

If you think you have received this email in error simply ignore it. If you continue to receive unsolicited messages please contact us to have your email blacklisted.';
        $message = wordwrap($message, 70);
        $headers = 'From: Imperial Kingdoms <*****@*****.**>' . "\r\n" . 'Reply-To: Imperial Kingdoms Administration <*****@*****.**>' . "\r\n" . 'X-Mailer: PHP/' . phpversion() . "\r\n\r\n";
        $result = mail($email, 'Imperial Kingdoms Confirmation Code', $message, $headers);
        if ($result != true) {
            $smarty->append('status', 'NOTE: Your confirmation email was not successfully sent. Please contact an administrator at <a href="mailto:admin@imperialkingdoms.com">admin@imperialkingdoms.com</a>');
        } else {
            $smarty->append('status', 'Your confirmation code has been sent to ' . htmlspecialchars($email, ENT_QUOTES) . ' and should arrive within a few minutes. If it hasn\'t arrived in 15 minutes check your junk folder for it. Hotmail accounts may have to wait several hours.');
        }
    }
    $smarty->assign('success', true);
    $smarty->display('register.tpl');
}
 function post_process()
 {
     $subject = trim(request_variable('subject', NULL, ''));
     $message = trim(request_variable('message', NULL, ''));
     $forum_topic_id = abs((int) request_variable('forum_topic_id', NULL, 0));
     if (empty($_REQUEST['message'])) {
         $this->smarty->append('status', 'No message entered.');
         if ($forum_topic_id == 0) {
             $this->smarty->assign('subject', htmlentities($subject));
             $this->topics();
         } else {
             $this->messages();
         }
         exit;
     }
     if ($forum_topic_id == 0) {
         if (strlen($subject) < 3 || strlen($subject) > 64) {
             $this->smarty->assign('message', htmlentities($message));
             $this->smarty->assign('subject', htmlentities($subject));
             $this->smarty->append('status', 'No subject entered.');
             $this->topics();
             exit;
         } else {
             $topicinsert = array('round_id' => $_SESSION['round_id'], 'kingdom_id' => $_SESSION['kingdom_id'], 'lastposter_id' => $_SESSION['player_id'], 'subject' => $subject, 'time_lastpost' => microfloat());
             $db_query = $this->sql->insert('forum_topics', $topicinsert);
             $db_result = mysql_query($db_query);
             $forum_topic_id = mysql_insert_id();
         }
     } else {
         $db_query = "SELECT * FROM `forum_topics` WHERE `forum_topic_id` = '" . $forum_topic_id . "' AND `kingdom_id` = '" . $_SESSION['kingdom_id'] . "' LIMIT 1";
         $db_result = mysql_query($db_query);
         if (!$db_result || mysql_num_rows($db_result) == 0) {
             error(__FILE__, __LINE__, 'DB_DATA', 'Could not select valid forum_topic_id');
         }
         $db_row = mysql_fetch_array($db_result, MYSQL_ASSOC);
         $db_query = "\n\t\t\t\t\tUPDATE `forum_topics` \n\t\t\t\t\tSET \n\t\t\t\t\t\t`lastposter_id` = '" . $_SESSION['player_id'] . "', \n\t\t\t\t\t\t`replies` = `replies` + '1', \n\t\t\t\t\t\t`time_lastpost` = '" . microfloat() . "' \n\t\t\t\t\tWHERE `forum_topic_id` = '" . $forum_topic_id . "' \n\t\t\t\t\tLIMIT 1";
         $db_result = mysql_query($db_query);
     }
     $messageinsert = array('forum_topic_id' => $forum_topic_id, 'round_id' => $_SESSION['round_id'], 'kingdom_id' => $_SESSION['kingdom_id'], 'poster_id' => $_SESSION['player_id'], 'message' => $message, 'posttime' => microfloat(), 'marked' => array());
     $db_result = $this->sql->execute('forum_messages', $messageinsert);
     $db_query = "\n\t\t\t\tUPDATE `players` \n\t\t\t\tSET `forum` = '1' \n\t\t\t\tWHERE \n\t\t\t\t\t`round_id` = '" . $_SESSION['round_id'] . "' AND \n\t\t\t\t\t`kingdom_id` = '" . $_SESSION['kingdom_id'] . "' AND \n\t\t\t\t\t`player_id` <> '" . $_SESSION['player_id'] . "' AND \n\t\t\t\t\t`rank` > '0'";
     $db_result = mysql_query($db_query);
     $this->smarty->append('status', 'Message posted.');
     $this->messages();
     exit;
 }
 function cancel()
 {
     if (empty($_REQUEST['tasks'])) {
         $_SESSION['status'][] = 'No building task specified.';
         redirect('buildings.php?fn=buildings_constructions');
     }
     if (!is_array($_REQUEST['tasks'])) {
         $tasks = array((int) $_REQUEST['tasks'] => true);
     } else {
         foreach ($_REQUEST['tasks'] as $task_id => $value) {
             if ((int) $task_id > 0) {
                 $tasks[(int) $task_id] = true;
             }
         }
     }
     $buildings_array = array();
     $this->sql->where(array(array('tasks', 'task_id', array_keys($tasks), 'IN'), array('tasks', 'round_id', $_SESSION['round_id']), array('tasks', 'type', TASK_BUILD), array('tasks', 'planet_id', $this->planet_id)));
     $this->sql->limit(count($tasks));
     $db_result = $this->sql->execute();
     while ($db_row = mysql_fetch_array($db_result, MYSQL_ASSOC)) {
         $tasks[$db_row['task_id']] = $db_row;
         $buildings_array[$db_row['building_id']] = true;
     }
     $planet =& $this->data->planet($this->planet_id);
     $buildings = $this->data->building(array_keys($buildings_array));
     $now = microfloat();
     foreach ($tasks as $task_id => $task) {
         $building_id = $task['building_id'];
         $percentage = sqrt(($task['completion'] - $now) / ($task['completion'] - $task['start']));
         foreach (array('food', 'workers', 'energy') as $resource) {
             if (!empty($buildings[$building_id][$resource])) {
                 $planet[$resource] += $task['number'] * $task['planning'] * $buildings[$building_id][$resource] * $percentage;
             }
         }
         if ($buildings[$building_id]['minerals'] == 0) {
             continue;
         }
         foreach ($buildings[$building_id]['mineralspread'] as $key => $value) {
             if ($value == 0) {
                 continue;
             }
             $mineral = $value / 100 * $buildings[$building_id]['minerals'] * $task['number'] * $task['planning'] * $percentage;
             $planet['minerals'][$key] += $mineral;
         }
     }
     $db_query = "\n\t\t\t\tDELETE FROM `tasks` \n\t\t\t\tWHERE \n\t\t\t\t\t`task_id` IN ('" . implode("', '", array_keys($tasks)) . "') AND \n\t\t\t\t\t`round_id` = '" . $_SESSION['round_id'] . "' AND \n\t\t\t\t\t`type` = '" . TASK_BUILD . "' AND \n\t\t\t\t\t`planet_id` = '" . $this->planet_id . "' \n\t\t\t\tLIMIT " . count($tasks);
     $db_result = mysql_query($db_query);
     if (mysql_affected_rows() == count($tasks)) {
         $status[] = 'All specified tasks stopped.';
     } else {
         $status[] = 'Some specified tasks were not stopped.';
     }
     $this->data->save();
     $_SESSION['status'][] = $status;
     redirect('buildings.php?fn=buildings_constructions');
 }
function news_playerstats()
{
    $playerstats = array();
    // Recent Players in the last 48 hours
    $playerstats['active_time'] = 172800 * $_SESSION['round_speed'];
    $db_query = "\n\t\t\tSELECT COUNT(*) AS 'recentplayers' \n\t\t\tFROM `players` \n\t\t\tWHERE \n\t\t\t\t`round_id` = '" . $_SESSION['round_id'] . "' AND \n\t\t\t\t`lastactive` > '" . (microfloat() - $playerstats['active_time']) . "' AND \n\t\t\t\t`npc` = 0 AND \n\t\t\t\t`user_id` > 0";
    $db_result = mysql_query($db_query);
    $db_row = mysql_fetch_array($db_result, MYSQL_ASSOC);
    $playerstats['recentplayers'] = $db_row['recentplayers'];
    // Total Players in round
    $db_query = "\n\t\t\tSELECT COUNT(*) AS 'totalplayers' \n\t\t\tFROM `players` \n\t\t\tWHERE \n\t\t\t\t`round_id` = '" . $_SESSION['round_id'] . "' AND \n\t\t\t\t`npc` = 0 AND \n\t\t\t\t`user_id` > 0";
    $db_result = mysql_query($db_query);
    $db_row = mysql_fetch_array($db_result, MYSQL_ASSOC);
    $playerstats['totalplayers'] = $db_row['totalplayers'];
    $playerstats['active_time'] = format_time(timeparser($playerstats['active_time']));
    return $playerstats;
}
 function modify_destination()
 {
     if (empty($this->group_type) || empty($this->group_id)) {
         error(__FILE__, __LINE__, 'DATA', 'Null type or group id.');
     }
     if ($this->group_type != 'navy') {
         error(__FILE__, __LINE__, 'INVALID_GROUP_TYPE', 'Invalid group type for this function.');
     }
     if (empty($_POST['destination'])) {
         error(__FILE__, __LINE__, 'INVALID_INPUT', 'Invalid input specified for this function');
     }
     $destination = $_POST['destination'];
     if (!empty($destination['planet_id'])) {
         $planet_id = abs((int) $destination['planet_id']);
         $planet =& $this->data->planet($planet_id);
         $player =& $this->data->player($planet['player_id']);
         $group =& $this->data->group('navy', $this->group_id);
         $this->sql->select(array(array('quadrants', 'x', 'x_quadrant'), array('quadrants', 'y', 'y_quadrant'), array('starsystems', 'x', 'x_starsystem'), array('starsystems', 'y', 'y_starsystem')));
         $this->sql->where(array(array('quadrants', 'quadrant_id', $planet['quadrant_id']), array('starsystems', 'starsystem_id', $planet['starsystem_id'])));
         $this->sql->limit(1);
         $db_result = $this->sql->execute();
         $db_row = mysql_fetch_array($db_result, MYSQL_ASSOC);
         $starsystem = array('x' => $db_row['x_starsystem'], 'y' => $db_row['y_starsystem']);
         $quadrant = array('x' => $db_row['x_quadrant'], 'y' => $db_row['y_quadrant']);
         if (empty($group['units'])) {
             $_SESSION['status'][] = 'That group isn\'t going anywhere. You need at least one unit in a group to send it somewhere.';
             redirect('groups.php?fn=groups_view&group_id=' . $this->group_id . '&group_type=' . $this->group_type . '&group_view=' . $this->group_view);
         }
         if ($planet['kingdom_id'] != $_SESSION['kingdom_id']) {
             $kingdom =& $this->data->kingdom($_SESSION['kingdom_id']);
             //					 print_r($kingdom);
             if (!isset($kingdom['enemies'][$planet['kingdom_id']]) && !isset($kingdom['allies'][$planet['kingdom_id']])) {
                 $status[] = 'You must declare war before sending fleets to attack, or an alliance to assist.';
                 $_SESSION['status'][] = $status;
                 redirect('groups.php?fn=groups_view&group_id=' . $this->group_id . '&group_type=' . $this->group_type . '&group_view=' . $this->group_view);
             }
         }
         $this->sql->select(array('navyblueprints', 'speed'));
         $this->sql->where(array('navyblueprints', 'navyblueprint_id', array_keys($group['units']), 'IN'));
         $this->sql->orderby(array('navyblueprints', 'speed', 'ASC'));
         $this->sql->limit(1);
         $db_result_speed = $this->sql->execute();
         $db_row_speed = mysql_fetch_array($db_result_speed, MYSQL_ASSOC);
         if ($db_row_speed['speed'] == 0) {
             $_SESSION['status'][] = 'That group isn\'t going anywhere. Your group can\'t go anywhere if there are stationary units in it.';
             redirect('groups.php?fn=groups_view&group_id=' . $this->group_id . '&group_type=' . $this->group_type . '&group_view=' . $this->group_view);
         } elseif ($db_row_speed['speed'] > 1) {
             $group['speed'] = (400 - $db_row_speed['speed']) / 400;
         } else {
             $group['speed'] = 1;
         }
         if ($group['x_current'] != $group['x_destination'] || $group['y_current'] != $group['y_destination']) {
             $this->sql->select(array('tasks', 'completion'));
             $this->sql->where(array('tasks', 'group_id', $this->group_id));
             $this->sql->limit(1);
             $existing_result = $this->sql->execute();
             if (mysql_num_rows($existing_result) > 0) {
                 $existingtask = mysql_fetch_array($existing_result, MYSQL_ASSOC);
                 //						 $temp['x'] = $group['x_destination'] - $group['x_current'];
                 //						 $temp['y'] = $group['y_destination'] - $group['y_current'];
                 //						 $temp['distance'] = sqrt(($temp['x'] * $temp['x']) + ($temp['y'] * $temp['y']));
                 $temp['distance'] = plot_distance(array($group['x_current'], $group['y_current']), array($group['x_destination'], $group['y_destination']));
                 $temp['time'] = $temp['distance'] * (1200 * $_SESSION['round_speed']) * $group['speed'];
                 $temp['now'] = microfloat();
                 $temp['completed'] = ($temp['time'] - ($existingtask['completion'] - $temp['now'])) / $temp['time'];
                 $group['x_current'] += $temp['completed'] * ($group['x_destination'] - $group['x_current']);
                 $group['y_current'] += $temp['completed'] * ($group['y_destination'] - $group['y_current']);
                 $db_query = "DELETE FROM `tasks` WHERE `group_id` = '" . $this->group_id . "'";
                 $db_result = mysql_query($db_query);
             }
         }
         $x[0] = $group['x_current'];
         $y[0] = $group['y_current'];
         $x[1] = $quadrant['x'] * 49 + $starsystem['x'] * 7 + $planet['x'];
         $y[1] = $quadrant['y'] * 49 + $starsystem['y'] * 7 + $planet['y'];
         $group['planet_id'] = $planet['planet_id'];
     } else {
         $_SESSION['status'][] = 'Invalid input specified for this function.';
         redirect('groups.php?fn=groups_view&group_view=' . $this->group_view . '&group_id=' . $this->group_id . '&group_type=' . $this->group_type);
     }
     $distance = plot_distance(array($x[0], $y[0]), array($x[1], $y[1]));
     $time = $distance * (1200 * $_SESSION['round_speed']) * $group['speed'];
     $minimum_time = 7200 * $_SESSION['round_speed'];
     if ($time < $minimum_time) {
         $time = $minimum_time;
     }
     $group['x_destination'] = $x[1];
     $group['y_destination'] = $y[1];
     if ($planet['kingdom_id'] != $_SESSION['kingdom_id']) {
         // Set combat alert
         $this->sql->set(array('players', 'combat', 1));
         $this->sql->where(array('players', 'kingdom_id', $planet['kingdom_id']));
         $this->sql->execute();
     }
     $now = microfloat();
     $insert_task = array('round_id' => $_SESSION['round_id'], 'kingdom_id' => $_SESSION['kingdom_id'], 'player_id' => $_SESSION['player_id'], 'group_id' => $this->group_id, 'type' => TASK_NAVY, 'start' => $now, 'completion' => $now + $time);
     if (!empty($group['planet_id'])) {
         $insert_task['planet_id'] = $group['planet_id'];
         $insert_task['target_kingdom_id'] = $planet['kingdom_id'];
         $round = $this->data->round($_SESSION['round_id']);
         $db_query = "SELECT `completion` FROM `combat` WHERE `planet_id` = '" . $group['planet_id'] . "' LIMIT 1";
         $db_result = mysql_query($db_query);
         if ($db_result && $db_result > 0) {
             $db_row = mysql_fetch_array($db_result, MYSQL_ASSOC);
             $next_combat = $db_row['completion'];
         } else {
             $this->sql->select(array('tasks', 'completion'));
             $this->sql->where(array('tasks', 'planet_id', $db_row['planet_id']));
             $this->sql->orderby(array('tasks', 'completion', 'asc'));
             $this->sql->limit(1);
             $db_result = $this->sql->execute();
             if (mysql_num_rows($db_result) > 0) {
                 $db_row = mysql_fetch_array($db_result, MYSQL_ASSOC);
                 $next_combat = $db_row['completion'];
             } else {
                 $next_combat = $insert_task['completion'] + $round['combattick'] - 0.01;
             }
         }
         $next_update = ($next_combat - $insert_task['completion']) / $round['combattick'];
         $insert_task['completion'] += (ceil($next_update) - $next_update) * $round['combattick'];
     }
     $this->sql->execute('tasks', $insert_task);
     $this->data->save();
     $status[] = 'Successfully set destination.';
     if (!empty($status)) {
         $_SESSION['status'][] = $status;
     }
     redirect('groups.php?fn=groups_view&group_id=' . $this->group_id . '&group_type=' . $this->group_type . '&group_view=' . $this->group_view);
 }
 function commission()
 {
     if (isset($_POST['mode']) && $_POST['mode'] == 'js') {
         $this->output_mode = 'javascript';
     } else {
         $this->output_mode = '';
     }
     $units = abs((int) request_variable('units', 'post'));
     if (empty($units) || empty($this->unit_id) || empty($this->unit_type)) {
         $status[] = 'Must commission at least one unit.';
     }
     if ($this->commission_errorcheck($status)) {
         return;
     }
     $planet = $this->data->planet($this->planet_id);
     $unit = $this->data->blueprint($this->unit_type, $this->unit_id);
     if ($unit['kingdom_id'] != $planet['kingdom_id']) {
         $status[] = 'You do not own the blueprint to this unit.';
     }
     if ($this->commission_errorcheck($status)) {
         return;
     }
     if (empty($planet['production'][$this->unit_type][$unit[$this->unit_type . 'concept_id']])) {
         $status[] = 'No buildings to produce this unit.';
     }
     $resources = array('workers', 'energy');
     foreach ($resources as $value) {
         if ($planet[$value] - $unit[$value] * $units < 0) {
             $status[] = 'Not enough ' . $value . '.';
         }
     }
     if (!empty($unit['mineralspread'])) {
         $mineralnames = unserialize(MINERALS_ARRAY);
         foreach ($unit['mineralspread'] as $key => $value) {
             if ($planet['minerals'][$key] - $value / 100 * $unit['minerals'] * $units < 0) {
                 $status[] = 'Not enough ' . $mineralnames[$key] . '.';
             }
         }
     }
     if ($this->commission_errorcheck($status)) {
         return;
     }
     $planet =& $this->data->planet($this->planet_id);
     $resources = array('workers', 'energy');
     foreach ($resources as $value) {
         $planet[$value] -= $unit[$value] * $units;
     }
     if (!empty($unit['mineralspread'])) {
         foreach ($unit['mineralspread'] as $key => $value) {
             $planet['minerals'][$key] -= $value / 100 * $unit['minerals'] * $units;
         }
     }
     $completion = $units * ($unit['time'] * $_SESSION['round_speed']) / $planet['production'][$this->unit_type][$unit[$this->unit_type . 'concept_id']];
     $warptime = request_variable('warptime');
     if (!is_null($warptime) && $planet['player_id'] == $_SESSION['player_id']) {
         if ($planet['warptime_construction'] > $completion) {
             $planet['warptime_construction'] -= $completion;
             $completion = 0;
         } else {
             $completion -= $planet['warptime_construction'];
             $planet['warptime_construction'] = 0;
         }
     }
     $now = microfloat();
     $db_query = "SELECT `completion` FROM `tasks` WHERE `planet_id` = '" . $this->planet_id . "' AND `type` = '" . TASK_UNIT . "' AND `attribute` = '" . $this->unit_type . "' AND `planning` = '" . $unit[$this->unit_type . 'concept_id'] . "' ORDER BY `completion` DESC LIMIT 1";
     $db_result = mysql_query($db_query);
     if (mysql_num_rows($db_result) > 0) {
         $db_row = mysql_fetch_array($db_result, MYSQL_ASSOC);
         $start = $db_row['completion'];
     } else {
         $start = $now;
     }
     // Add the task.
     $task_insert = array('round_id' => $_SESSION['round_id'], 'kingdom_id' => $_SESSION['kingdom_id'], 'planet_id' => $this->planet_id, 'type' => TASK_UNIT, 'unit_id' => $this->unit_id, 'attribute' => $this->unit_type, 'number' => $units, 'planning' => $unit[$this->unit_type . 'concept_id'], 'completion' => $start + $completion, 'start' => $start);
     $this->sql->execute('tasks', $task_insert);
     $this->data->save();
     if ($output_mode == 'javascript') {
         echo 'varCommissioned = true; varError = false;';
         exit;
     }
     $this->smarty->append('status', 'The unit is being commissioned.');
     $this->overview();
     exit;
 }
 function research()
 {
     // FIXME
     $concept_id = $this->concept_id;
     $planet_id = $this->planet_id;
     if (isset($_POST['mode']) && $_POST['mode'] == 'js') {
         $output_mode = 'javascript';
     } else {
         $output_mode = '';
     }
     $this->output_mode = $output_mode;
     $status = array();
     permissions_check(PERMISSION_PLANET, $planet_id, 'research');
     $kingdom =& $this->data->kingdom($_SESSION['kingdom_id']);
     if (!isset($kingdom['concepts'][$concept_id])) {
         $status[] = 'The concept you selected does not exist, has already been researched, or is outside of your grasp.';
         $this->research_checkerror($status);
     }
     $db_query = "SELECT `planet_id` FROM `tasks` WHERE `kingdom_id` = '" . $_SESSION['kingdom_id'] . "' AND `type` IN ('" . TASK_RESEARCH . "', '" . TASK_UPGRADE . "') AND (`planet_id` = '" . $planet_id . "' OR `concept_id` = '" . $concept_id . "') LIMIT 2";
     $db_result = mysql_query($db_query);
     while ($db_row = mysql_fetch_array($db_result, MYSQL_ASSOC)) {
         if ($db_row['planet_id'] == $planet_id) {
             $status[] = 'That planet is already researching something.';
         } else {
             $status[] = 'That concept is already being researched elsewhere';
         }
     }
     $this->research_checkerror($status);
     $planet =& $this->data->planet($planet_id);
     $concept = $this->data->concept($concept_id);
     $score = 0;
     $resources = array('workers' => SCORE_WORKERS, 'energy' => SCORE_ENERGY);
     foreach ($resources as $key => $value) {
         $score += $concept[$key] * $value;
         $planet[$key] -= $concept[$key];
         $kingdom[$key] -= $concept[$key];
         if ($planet[$key] < 0) {
             $status[] = 'Not enough ' . $key . '.';
         }
     }
     if (!empty($concept['mineralspread'])) {
         $mineralnames = array(0 => 'fe', 1 => 'o', 2 => 'si', 3 => 'mg', 4 => 'ni', 5 => 's', 6 => 'he', 7 => 'h');
         foreach ($concept['mineralspread'] as $key => $value) {
             $mineral = $value / 100 * $concept['minerals'];
             $score += $mineral * SCORE_MINERALS;
             $planet['minerals'][$key] -= $mineral;
             if ($planet['minerals'][$key] < 0) {
                 $status[] = 'Not enough ' . $mineralnames[$key] . '.';
             }
         }
         $kingdom['minerals'] -= $concept['minerals'];
     }
     $this->research_checkerror($status);
     $player =& $this->data->player($planet['player_id']);
     $research_bonus = $planet['researchbonus'] < 85 ? $planet['researchbonus'] : 85;
     $completion = $concept['time'] * $_SESSION['round_speed'] * ((100 - $research_bonus) / 100);
     $planet['researching']++;
     $planet['score'] -= $score;
     $player['score'] -= $score;
     $warptime = request_variable('warptime');
     if (!is_null($warptime)) {
         if ($planet['warptime_research'] > $completion) {
             $planet['warptime_research'] -= $completion;
             $completion = 0;
         } else {
             $completion -= $planet['warptime_research'];
             $planet['warptime_research'] = 0;
         }
     }
     $now = microfloat();
     $task_insert = array('round_id' => $_SESSION['round_id'], 'kingdom_id' => $_SESSION['kingdom_id'], 'player_id' => $planet['player_id'], 'planet_id' => $planet['planet_id'], 'type' => TASK_RESEARCH, 'concept_id' => $this->concept_id, 'completion' => $now + $completion, 'start' => $now);
     $this->sql->execute('tasks', $task_insert);
     $this->data->save();
     if ($output_mode == 'javascript') {
         echo 'varResearching = true; varError = false;';
         exit;
     }
     if ($completion == 0) {
         $_SESSION['status'][] = 'Research successfully completed.';
     } else {
         $_SESSION['status'][] = 'Research successfully started.';
     }
     redirect('research.php');
 }
function info()
{
    global $smarty;
    if (empty($_REQUEST['round_id'])) {
        error(__FILE__, __LINE__, 'INVALID_ID', 'Invalid Round ID');
    }
    $smarty->assign('content', 'info');
    $round_id = abs((int) $_REQUEST['round_id']);
    $db_query = "\n\t\t\tSELECT \n\t\t\t\t`round_id`, \n\t\t\t\t`round_engine`, \n\t\t\t\t`name`, \n\t\t\t\t`description`, \n\t\t\t\t`starttime`, \n\t\t\t\t`stoptime`, \n\t\t\t\t`starsystems`, \n\t\t\t\t`planets`, \n\t\t\t\t`resistance`, \n\t\t\t\t`speed`, \n\t\t\t\t`resourcetick`, \n\t\t\t\t`combattick` \n\t\t\tFROM `rounds` \n\t\t\tWHERE `round_id` = '" . $round_id . "' \n\t\t\tLIMIT 1";
    $db_result = mysql_query($db_query);
    $round = mysql_fetch_array($db_result, MYSQL_ASSOC);
    $round['speed'] /= 1000;
    // Dynamic attack limit based on elapsed time of current round
    $end_time = 3456000 * $round['speed'];
    $current_time = microfloat() - $round['starttime'];
    $attack_limit = 1 - $current_time / $end_time;
    if ($attack_limit < 0) {
        $attack_limit = 0;
    }
    $round['attack_limit'] = round($attack_limit * 100, 2);
    $round['description'] = nl2br($round['description']);
    $round['starttime'] = format_timestamp($round['starttime']);
    $round['stoptime'] = format_timestamp($round['stoptime']);
    $round['resistance'] = format_number($round['resistance']);
    $round['resourcetick'] = format_time(timeparser($round['resourcetick'] / 1000));
    $round['combattick'] = format_time(timeparser($round['combattick'] / 1000));
    $smarty->assign('round', $round);
}
function soft_reset_round()
{
    global $sql;
    $round_id = $_REQUEST['round_id'];
    $db_query = "SELECT * FROM `rounds` WHERE `round_id` = '" . $round_id . "'";
    $db_result = mysql_query($db_query);
    $round = mysql_fetch_array($db_result, MYSQL_ASSOC);
    $tables = $t = 'players';
    $warptime = (microfloat() - $round['starttime']) * 0.75;
    $sql->set(array(array($t, 'npc', 0), array($t, 'warptime', $warptime), array($t, 'score', 0), array($t, 'score_peak', 0)));
    $sql->where(array($t, 'round_id', $round_id));
    $sql->execute();
    $sql->select(array(array($t, 'player_id'), array($t, 'kingdom_id'), array($t, 'rank')));
    $sql->where(array($t, 'round_id', $round_id));
    $db_result = $sql->execute();
    while ($db_row = mysql_fetch_array($db_result, MYSQL_ASSOC)) {
        $kingdoms[$db_row['kingdom_id']]['members'][$db_row['player_id']] = $db_row['rank'];
    }
    function addbuilding($buildings, $building, $buildingcount)
    {
        if ($building == 9) {
            // Zero-G
            $buildings[9] = $buildingcount;
            $buildings[1] = $buildingcount * 15;
            $buildings[10] = $buildingcount * 20;
            $buildings[14] = $buildingcount * 10;
        } else {
            // HydroCrane
            $buildings[8] = $buildingcount;
            $buildings[10] = $buildingcount * 15;
            $buildings[14] = $buildingcount * 25;
        }
        return $buildings;
    }
    $db_query = "SELECT `player_id` FROM `players` WHERE `round_id` = '" . $round_id . "' GROUP BY `kingdom_id` HAVING COUNT(`kingdom_id`) = 1";
    $db_result = mysql_query($db_query);
    while ($db_row = mysql_fetch_array($db_result, MYSQL_ASSOC)) {
        $player_id = $db_row['player_id'];
        $buildings = array(8 => 0, 9 => 0);
        $db_query = "SELECT `planet_id`, `buildings` FROM `planets` WHERE `player_id` = '" . $player_id . "'";
        $db_result = mysql_query($db_query);
        while ($db_row = mysql_fetch_array($db_result, MYSQL_ASSOC)) {
            $players[$player_id][$db_row['planet_id']] = true;
            $db_row['buildings'] = unserialize($db_row['buildings']);
            if (!empty($db_row['buildings'][8]) && $db_row['buildings'][8] > $buildings[8]) {
                $buildings[8] = $db_row['buildings'][8];
            }
            if (!empty($db_row['buildings'][9]) && $db_row['buildings'][9] > $buildings[9]) {
                $buildings[9] = $db_row['buildings'][9];
            }
        }
        if ($buildings[8] != 0 || $buildings[9] != 0) {
            $bonus = $building == 8 ? 'buildingbonus' : 'researchbonus';
            $building = $buildings[8] > $buildings[9] ? 8 : 9;
            $planetcount = count($players[$player_id]);
            $buildingcount = round(30 / $planetcount);
            $planetbuildings = addbuilding(unserialize($round['buildings']), $building, $buildingcount);
        } else {
            $bonus = 'researchbonus';
            $buildingcount = 0;
            $planetbuildings = unserialize($round['buildings']);
        }
        $sql->set(array(array('planets', 'buildings', serialize($planetbuildings)), array('planets', $bonus, $buildingcount)));
        $sql->where(array('planets', 'player_id', $player_id));
        $sql->execute();
    }
    $t = 'planets';
    $mineralstock = array(0 => 20, 1 => 20, 2 => 15, 3 => 15, 4 => 10, 5 => 10, 6 => 5, 7 => 5);
    foreach ($mineralstock as $key => $value) {
        $mineralsremaining[$key] = $round['minerals'] * ($value / 100);
    }
    $sql->set(array(array($t, 'cranes', 1), array($t, 'planning', 1), array($t, 'researching', 0), array($t, 'buildingbonus', 0), array($t, 'researchbonus', 0), array($t, 'production', 'a:0:{}'), array($t, 'units', 'a:0:{}'), array($t, 'food', $round['food']), array($t, 'foodrate', 0), array($t, 'workers', $round['workers']), array($t, 'workersrate', 0), array($t, 'energy', $round['energy']), array($t, 'energyrate', 0), array($t, 'minerals', serialize(array(0 => 0, 1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0, 7 => 0))), array($t, 'mineralsrate', 0), array($t, 'mineralsremaining', serialize($mineralsremaining)), array($t, 'resistance', 0), array($t, 'score', 0), array($t, 'score_peak', 0)));
    $sql->where(array($t, 'round_id', $round_id));
    $sql->execute();
    $sql->select(array(array($t, 'planet_id'), array($t, 'player_id'), array($t, 'kingdom_id')));
    $sql->where(array($t, 'round_id', $round_id));
    $db_result = $sql->execute();
    while ($db_row = mysql_fetch_array($db_result, MYSQL_ASSOC)) {
        $kingdoms[$db_row['kingdom_id']]['planets'][$db_row['planet_id']] = true;
    }
    $t = 'kingdoms';
    $sql->set(array(array($t, 'buildings', $round['buildings']), array($t, 'units', 'a:0:{}'), array($t, 'concepts', $round['concepts']), array($t, 'researched', 'a:0:{}'), array($t, 'foodrate', 0), array($t, 'workersrate', 0), array($t, 'energyrate', 0), array($t, 'mineralsrate', 0), array($t, 'score', 0), array($t, 'score_peak', 0)));
    $sql->where(array($t, 'round_id', $round_id));
    $sql->execute();
    foreach ($kingdoms as $kingdom_id => $sections) {
        if (empty($sections['planets'])) {
            $sections['planets'] = array();
        }
        if (empty($sections['members'])) {
            $sections['members'] = array();
        }
        $planets = count($sections['planets']);
        $sql->set(array(array($t, 'planets', serialize($sections['planets'])), array($t, 'members', serialize($sections['members'])), array($t, 'food', $round['food'] * $planets), array($t, 'workers', $round['workers'] * $planets), array($t, 'energy', $round['energy'] * $planets), array($t, 'minerals', 0)));
        $sql->where(array($t, 'kingdom_id', $kingdom_id));
        $sql->execute();
    }
    $names = file(dirname(__FILE__) . '/names_planets.txt');
    foreach (array('players' => 'player_id', 'kingdoms' => 'kingdom_id', 'planets' => 'planet_id') as $t => $id) {
        if ($t == 'planets') {
            $sql->select(array(array($t, 'player_id'), array($t, 'kingdom_id')));
        }
        $sql->select(array($t, $id));
        $sql->where(array($t, 'name', '[Empty]'));
        $db_result = $sql->execute();
        while ($db_row = mysql_fetch_array($db_result, MYSQL_ASSOC)) {
            if ($t == 'planets' && empty($db_row['player_id']) && empty($db_row['kingdom_id'])) {
                $sql->set(array($t, 'name', ''));
            } else {
                $sql->set(array($t, 'name', trim($names[rand(0, count($names))])));
            }
            $sql->where(array($t, $id, $db_row[$id]));
            $sql->execute();
        }
    }
    $tables = array('combat', 'combatreports', 'tasks');
    foreach (array('army', 'navy', 'weapon') as $type) {
        $tables[] = $type . 'blueprints';
        $tables[] = $type . 'designs';
        if ($type != 'weapon') {
            $tables[] = $type . 'groups';
        }
    }
    foreach ($tables as $t) {
        $db_query = "DELETE FROM `" . $t . "` WHERE `round_id` = '" . $round_id . "'";
        $db_result = mysql_query($db_query);
    }
}
function planet_massmanage()
{
    global $smarty, $sql, $data;
    // get all planets owned by this player
    // picture, name, food storage & rate, worker storage & rate, energy storage & rate, mineral storage & rate,
    // [ ] The Past	  1.2K  +8   1.1K  +40   872  +48   0  0   Derrick   1h, 38m
    $available_planning = $available_cranes = 0;
    // Retrieve all of the player's planets
    $player = $data->player($_SESSION['player_id']);
    $planet_ids = $player['planets'];
    $planet_ids = array_keys($planet_ids);
    $planets = $data->planet($planet_ids);
    if (!empty($planets)) {
        $db_query = "\n\t\t\t\tSELECT \n\t\t\t\t\tt.`planet_id`, \n\t\t\t\t\tb.`name`, \n\t\t\t\t\tMIN(t.`completion`) as 'completion' \n\t\t\t\tFROM \n\t\t\t\t\t`tasks` t, \n\t\t\t\t\t`buildings` b \n\t\t\t\tWHERE \n\t\t\t\t\tt.`planet_id` IN ('" . implode("', '", array_keys($planets)) . "') AND \n\t\t\t\t\tb.`building_id` = t.`building_id` \n\t\t\t\tGROUP BY t.`planet_id` \n\t\t\t\tLIMIT " . count($planets);
        $db_result = $sql->query($db_query);
        while ($db_row = mysql_fetch_array($db_result, MYSQL_ASSOC)) {
            $planets[$db_row['planet_id']]['construction'] = array('name' => strshort($db_row['name'], 15), 'completion' => format_time(timeparser($db_row['completion'] - microfloat())));
        }
        $db_query = "\n\t\t\t\tSELECT \n\t\t\t\t\tt.`planet_id`, \n\t\t\t\t\tc.`name`, \n\t\t\t\t\tMIN(t.`completion`) as 'completion' \n\t\t\t\tFROM \n\t\t\t\t\t`tasks` t, \n\t\t\t\t\t`concepts` c \n\t\t\t\tWHERE \n\t\t\t\t\tt.`planet_id` IN ('" . implode("', '", array_keys($planets)) . "') AND \n\t\t\t\t\tc.`concept_id` = t.`concept_id` \n\t\t\t\tGROUP BY t.`planet_id` \n\t\t\t\tLIMIT " . count($planets);
        $db_result = $sql->query($db_query);
        while ($db_row = mysql_fetch_array($db_result, MYSQL_ASSOC)) {
            $planets[$db_row['planet_id']]['research'] = array('name' => strshort($db_row['name'], 15), 'completion' => format_time(timeparser($db_row['completion'] - microfloat())));
        }
    }
    // Sort planets by cranes and then score, desc.
    $sort_key = array('cranes' => array('busy_planets' => array(), 'idle_planets' => array()), 'score' => array('busy_planets' => array(), 'idle_planets' => array()));
    $idle_planets = $busy_planets = array();
    foreach ($planets as $planet_id => $planet) {
        if (!empty($planet['minerals'])) {
            $planet['minerals'] = array_sum($planet['minerals']);
        } else {
            $planet['minerals'] = 0;
        }
        $resource_deficiency = 0;
        foreach (array('food', 'workers', 'energy', 'minerals') as $resource) {
            if ($resource_deficiency != 0) {
                $planet[$resource . 'deficiency'] = $planet[$resource . 'rate'];
            }
            $planet[$resource . 'rate'] += $resource_deficiency;
            if ($planet[$resource . 'rate'] < 0 && $planet[$resource] < abs($planet[$resource . 'rate'])) {
                $resource_deficiency = $planet[$resource . 'rate'] + $planet[$resource];
            }
            $planet[$resource] = format_number($planet[$resource], true);
            $planet[$resource . 'rate'] = format_number($planet[$resource . 'rate'], true, true);
        }
        if ($planet['planning'] > $available_planning && $planet['cranes'] > 0) {
            $available_planning = $planet['planning'];
        }
        if ($planet['cranes'] > $available_cranes) {
            $available_cranes = $planet['cranes'];
        }
        $planets[$planet['planet_id']] = $planet;
        if ($planet['cranes'] == 0) {
            $busy_planets[$planet['planet_id']] =& $planets[$planet['planet_id']];
            $sort_key['cranes']['busy_planets'][$planet_id] = $planet['cranes'];
            $sort_key['score']['busy_planets'][$planet_id] = $planet['score'];
        } else {
            $idle_planets[$planet['planet_id']] =& $planets[$planet['planet_id']];
            $sort_key['cranes']['idle_planets'][$planet_id] = $planet['cranes'];
            $sort_key['score']['idle_planets'][$planet_id] = $planet['score'];
        }
    }
    array_multisort($sort_key['cranes']['busy_planets'], SORT_DESC, $sort_key['score']['busy_planets'], SORT_DESC, $busy_planets);
    array_multisort($sort_key['cranes']['idle_planets'], SORT_DESC, $sort_key['score']['idle_planets'], SORT_DESC, $idle_planets);
    $kingdom = $data->kingdom($_SESSION['kingdom_id']);
    $db_query = "SELECT `building_id`, `name` FROM `buildings` WHERE `building_id` IN ('" . implode("', '", array_keys($kingdom['buildings'])) . "') ORDER BY `name` ASC";
    $db_result = $sql->query($db_query);
    $buildings = array();
    while ($db_row = mysql_fetch_array($db_result, MYSQL_ASSOC)) {
        $buildings[$db_row['building_id']] = $db_row['name'];
    }
    $smarty->assign('available_cranes', $available_cranes);
    $smarty->assign('available_planning', $available_planning);
    $smarty->assign('buildings', $buildings);
    $smarty->assign('planets', $planets);
    $smarty->assign('idle_planets', $idle_planets);
    $smarty->assign('idle_planet_count', count($idle_planets));
    $smarty->assign('busy_planets', $busy_planets);
    $smarty->display('planet_massmanage.tpl');
}
 function vote()
 {
     if (empty($_REQUEST['proposition_id'])) {
         error(__FILE__, __LINE__, 'ID_UNSPECIFIED', 'Unspecified proposition id');
     }
     $votes = array('for', 'against', 'neutral');
     if (!in_array($_REQUEST['vote'], $votes)) {
         error(__FILE__, __LINE__, 'VOTE_INVALID', 'Invalid vote');
     }
     $proposition_id = (int) $_REQUEST['proposition_id'];
     $vote = $_REQUEST['vote'];
     $this->sql->where(array(array('propositions', 'proposition_id', $proposition_id), array('propositions', 'round_id', $_SESSION['round_id']), array('propositions', 'kingdom_id', $_SESSION['kingdom_id'])));
     $this->sql->limit(1);
     $db_query = $this->sql->generate();
     $db_result = mysql_query($db_query);
     if (!$db_result || mysql_num_rows($db_result) == 0) {
         error(__FILE__, __LINE__, 'ID_INVALID', 'Invalid proposition id');
     }
     $proposition = mysql_fetch_array($db_result, MYSQL_ASSOC);
     if ($proposition['status'] != 0) {
         error(__FILE__, __LINE__, 'VOTE_INVALID', 'Invalid vote');
     }
     $proposition['voted'] = unserialize($proposition['voted']);
     if (!empty($proposition['voted'][$_SESSION['player_id']])) {
         error(__FILE__, __LINE__, 'VOTE_DUPE', 'Vote already placed');
     }
     $proposition['voted'][$_SESSION['player_id']] = true;
     $db_query = "\n\t\t\t\tSELECT COUNT(*) AS 'members' \n\t\t\t\tFROM `players` \n\t\t\t\tWHERE \n\t\t\t\t\t`kingdom_id` = '" . $_SESSION['kingdom_id'] . "' AND \n\t\t\t\t\t`rank` >= '" . RANK_SENATOR . "' AND \n\t\t\t\t\t`lastactive` >= " . (microfloat() - $_SESSION['round_speed'] * 172800);
     $db_result = mysql_query($db_query);
     $db_row = mysql_fetch_array($db_result, MYSQL_ASSOC);
     $proposition[$vote]++;
     $this->sql->set(array(array('propositions', $vote, $proposition[$vote]), array('propositions', 'voted', serialize($proposition['voted']))));
     $this->sql->where(array('propositions', 'proposition_id', $proposition_id));
     $this->sql->limit(1);
     $twothirds = 2 / 3;
     // for
     if ($db_row['members'] * $twothirds <= $proposition['for'] + $proposition['neutral'] * 0.5) {
         $this->sql->set(array('propositions', 'status', 1));
         $flag = 'for';
     } elseif ($db_row['members'] * $twothirds < $proposition['against'] + $proposition['neutral'] * 0.5) {
         $this->sql->set(array('propositions', 'status', 2));
         $flag = 'against';
     } elseif ($db_row['members'] == $proposition['for'] + $proposition['against'] + $proposition['neutral']) {
         $this->sql->set(array('propositions', 'status', 3));
         $flag = 'neutral';
     }
     $db_result = $this->sql->execute();
     if (!empty($flag)) {
         $types = array(PROPOSITION_DESCRIPTION => 'description', PROPOSITION_AVATAR => 'avatar', PROPOSITION_PROMOTE => 'promote', PROPOSITION_DEMOTE => 'demote', PROPOSITION_EXECUTE => 'execute', PROPOSITION_WAR => 'war', PROPOSITION_PEACE => 'peace');
         $proposition_fn = $types[$proposition['type']];
         $this->{$proposition_fn}($flag);
     }
     $_SESSION['status'][] = 'Vote counted.';
     redirect('propositions.php?fn=propositions_info&proposition_id=' . $proposition_id);
 }
 function selectplanets()
 {
     /*
     	What do we want to do about teams vs solo players?
     	What about teams with less than 'planet' players
     	
     	How about give all players all five planets then give 'planet' planet codes.
     	New players could take over planets with a code.
     	That would require allowing planets with owners to be given away using the planet code system.
     	
     	Another idea is to give solo and team creators one planet and 'planet - 1 codes.
     	New or existing players can then redeem any number of codes, with each only being used once.
     	I like this idea. It uses the existing system and the only modification needed will be to allow code redemption in-game.
     	
     	What about giving out a code that can used to join a team and be given a planet from existing players?
     	There would need to be some way to make sure it was only used for the original 'planet' planets.
     	No, it would still be possible to abuse it. Go with the second idea.
     */
     // If they are creating a team give them all of the planets?
     if ($this->kingdom['mode'] == 'createteam' || $this->kingdom['mode'] == 'jointeam') {
         $this->planets = 1;
     }
     // Check for available planets and create kingdom
     if ($this->kingdom['mode'] == 'independant' || $this->kingdom['mode'] == 'createteam') {
         // Grab a starsystem that's available.
         if ($this->kingdom['mode'] == 'createteam') {
             $this->starsystem_id = $this->availablestarsystem('createteam');
         } else {
             $this->starsystem_id = $this->availablestarsystem($this->planets);
         }
         // If zero was returned nothing is available.
         if ($this->starsystem_id == 0) {
             if ($this->kingdom['mode'] == 'createteam') {
                 $status[] = 'There is no more room in this round for new teams.<br />If you really want in this round, try creating an independant kingdom or finding a team with an available planet.';
             } elseif ($this->kingdom['mode'] == 'independant' && $this->planets > $this->round['min_planets']) {
                 $status[] = 'There is no more room in this round for an independant kingdom with ' . $this->planets . ' planets. Try asking for less planets, or find a team with an available planet.';
             } else {
                 $status[] = 'There is no more room in this round for independant kingdoms.<br />If you really want in this round, try finding a team with an available planet.';
             }
             $this->smarty->append('status', $status);
             return $this->returnform();
         } else {
             if ($this->kingdom['mode'] == 'createteam') {
                 $db_query = "UPDATE `starsystems` SET `available` = '0' WHERE `starsystem_id` = '" . $this->starsystem_id . "' LIMIT 1";
                 $db_result = mysql_query($db_query);
             } else {
                 $db_query = "UPDATE `starsystems` SET `available` = `available` - '" . $this->planets . "' WHERE `starsystem_id` = '" . $this->starsystem_id . "' LIMIT 1";
                 $db_result = mysql_query($db_query);
             }
         }
         $this->new_kingdom();
     } elseif ($this->kingdom['mode'] == 'jointeam') {
         $this->sql->select(array(array('planets', 'planet_id'), array('kingdoms', 'kingdom_id'), array('kingdoms', 'members'), array('kingdoms', 'planets')));
         $this->sql->where(array(array('planets', 'player_id', 0), array('planets', 'code', $this->planet['code']), array('kingdoms', 'kingdom_id', array('planets', 'kingdom_id')), array('kingdoms', 'round_id', $_SESSION['round_id']), array('planets', 'round_id', $_SESSION['round_id'])));
         $this->sql->limit(1);
         $db_query = $this->sql->generate();
         $db_result = mysql_query($db_query);
         if (mysql_num_rows($db_result) == 0) {
             $status[] = 'The planet code does not match any on file, or the planet has already been claimed.';
             $this->smarty->append('status', $status);
             return $this->returnform();
         }
         $db_row = mysql_fetch_array($db_result, MYSQL_ASSOC);
         $this->kingdom['kingdom_id'] = $db_row['kingdom_id'];
         $this->kingdom['members'] = unserialize($db_row['members']);
         $this->kingdom['planets'] = unserialize($db_row['planets']);
         $this->player['planets'][$db_row['planet_id']] = true;
     }
     $warptime = (microfloat() - $this->round['starttime']) * $this->round['warptime'];
     $player_insert = array('round_id' => $_SESSION['round_id'], 'user_id' => $_SESSION['user_id'], 'name' => $this->player['name'], 'kingdom_id' => $this->kingdom['kingdom_id']);
     if ($this->npc) {
         $player_insert['npc'] = 1;
         $player_insert['user_id'] = 0;
     }
     $db_query = $this->sql->insert('players', $player_insert);
     $db_result = mysql_query($db_query);
     $this->player['player_id'] = mysql_insert_id();
     $this->sql->set(array(array('planets', 'name', $this->planet['name']), array('planets', 'kingdom_id', $this->kingdom['kingdom_id']), array('planets', 'player_id', $this->player['player_id']), array('planets', 'status', PLANETSTATUS_OCCUPIED), array('planets', 'lastupdated', microfloat()), array('planets', 'warptime_construction', $warptime), array('planets', 'warptime_research', $warptime)));
     $this->sql->where(array('planets', 'planet_id', array_keys($this->player['planets']), 'IN'));
     $db_query = $this->sql->generate();
     $db_result = mysql_query($db_query);
     $db_query = "\n\t\t\t\tSELECT \n\t\t\t\t\tSUM(`food`) AS 'food', \n\t\t\t\t\tSUM(`foodrate`) AS 'foodrate', \n\t\t\t\t\tSUM(`workers`) AS 'workers', \n\t\t\t\t\tSUM(`workersrate`) AS 'workersrate', \n\t\t\t\t\tSUM(`energy`) AS 'energy', \n\t\t\t\t\tSUM(`energyrate`) AS 'energyrate' \n\t\t\t\tFROM `planets` \n\t\t\t\tWHERE `planet_id` IN ('" . implode("', '", array_keys($this->player['planets'])) . "') \n\t\t\t\tLIMIT " . count($this->player['planets']);
     $db_result = $this->sql->query($db_query);
     $resource_sums = mysql_fetch_array($db_result, MYSQL_ASSOC);
     $db_query = "\n\t\t\t\tUPDATE `kingdoms` \n\t\t\t\tSET \n\t\t\t\t\t`food` = `food` + '" . $resource_sums['food'] . "', \n\t\t\t\t\t`foodrate` = `foodrate` + '" . $resource_sums['foodrate'] . "', \n\t\t\t\t\t`workers` = `workers` + '" . $resource_sums['workers'] . "', \n\t\t\t\t\t`workersrate` = `workersrate` + '" . $resource_sums['workersrate'] . "', \n\t\t\t\t\t`energy` = `energy` + '" . $resource_sums['energy'] . "', \n\t\t\t\t\t`energyrate` = `energyrate` + '" . $resource_sums['energyrate'] . "' \n\t\t\t\tWHERE `kingdom_id` = '" . $this->kingdom['kingdom_id'] . "' \n\t\t\t\tLIMIT 1";
     $db_result = $this->sql->query($db_query);
     $this->kingdom['planets'] = $this->kingdom['planets'] + $this->player['planets'];
     $this->planet['planet_id'] = array_rand($this->player['planets']);
     $this->player['planet_current'] = $this->planet['planet_id'];
     $this->kingdom['members'][$this->player['player_id']] = true;
     $this->sql->set(array(array('kingdoms', 'members', serialize($this->kingdom['members'])), array('kingdoms', 'planets', serialize($this->kingdom['planets']))));
     $this->sql->where(array('kingdoms', 'kingdom_id', $this->kingdom['kingdom_id']));
     $this->sql->limit(1);
     $db_query = $this->sql->generate();
     $db_result = mysql_query($db_query);
     $this->sql->set(array('players', 'planets', serialize($this->player['planets'])));
     $this->sql->where(array('players', 'player_id', $this->player['player_id']));
     $this->sql->limit(1);
     $db_query = $this->sql->generate();
     $db_result = mysql_query($db_query);
     if ($this->kingdom['mode'] == 'createteam') {
         // planet['planet_id'] is a randomly selected planet id that the player owns.
         // Since this is a team creator there was only one planet to select.
         unset($this->planet['planets'][$this->planet['planet_id']]);
         $mail_body = 'Below are your planet codes. You can give these to other players to join your kingdom or players already in your kingdom, including yourself, to claim more than one planet. To claim another planet visit the Options - Planet page.' . "\n\n";
         foreach ($this->planet['planets'] as $key => $value) {
             $this->sql->set(array(array('planets', 'code', $value), array('planets', 'kingdom_id', $this->kingdom['kingdom_id']), array('planets', 'status', PLANETSTATUS_RESERVED)));
             $this->sql->where(array('planets', 'planet_id', $key));
             $this->sql->execute();
             $mail_body .= '[b]P#' . $key . ':[/b] ' . $value . "\n";
         }
         $mail_insert = array('round_id' => $_SESSION['round_id'], 'to_player_id' => $this->player['player_id'], 'from_player_id' => $this->player['player_id'], 'time' => microfloat(), 'subject' => 'Planet Codes', 'body' => $mail_body);
         $this->sql->execute('mail', $mail_insert);
         $this->sql->set(array('players', 'mail', 1));
         $this->sql->where(array('players', 'player_id', $this->player['player_id']));
         $this->sql->execute();
     } elseif ($this->kingdom['mode'] == 'jointeam') {
         // Set new member's rank to senator.
         $this->sql->set(array('players', 'rank', RANK_SENATOR));
         $this->sql->where(array('players', 'player_id', $this->player['player_id']));
         $this->sql->limit(1);
         $db_query = $this->sql->generate();
         $db_result = mysql_query($db_query);
     }
     if ($this->kingdom['mode'] == 'independant' && $this->round['bonus'] != 0) {
         $buildingcount = round(30 / $this->planets);
         if ($this->planet['bonus'] == 0) {
             // Zero-G
             $buildings[9] = $buildingcount;
             $buildings[1] = $buildingcount * 15;
             $buildings[10] = $buildingcount * 20;
             $buildings[14] = $buildingcount * 10;
             $researchbonus = $buildingcount;
             $buildingbonus = 0;
         } else {
             // HydroCrane
             $buildings[8] = $buildingcount;
             $buildings[10] = $buildingcount * 15;
             $buildings[14] = $buildingcount * 25;
             $buildingbonus = $buildingcount;
             $researchbonus = 0;
         }
         $this->sql->set(array(array('planets', 'buildings', serialize($buildings)), array('planets', 'researchbonus', $researchbonus), array('planets', 'buildingbonus', $buildingbonus)));
         $this->sql->where(array('planets', 'player_id', $this->player['player_id']));
         $this->sql->execute();
     }
     if (!$this->npc) {
         $this->sql->select(array('users', 'style'));
         $this->sql->where(array('users', 'user_id', $_SESSION['user_id']));
         $db_result = $this->sql->execute();
         $db_row = mysql_fetch_array($db_result, MYSQL_ASSOC);
         $_SESSION['style'] = $db_row['style'];
         $_SESSION['player_id'] = $this->player['player_id'];
         $_SESSION['kingdom_id'] = $this->kingdom['kingdom_id'];
         $_SESSION['planet_id'] = $this->planet['planet_id'];
         $this->createnpc();
     }
     redirect('main.php');
 }
function getrounds()
{
    global $smarty, $sql;
    $rounds = array();
    if (!$_SESSION['admin']) {
        $db_query = "\n\t\t\t\tSELECT \n\t\t\t\t\t`round_id`, \n\t\t\t\t\t`name`, \n\t\t\t\t\t`starttime`, \n\t\t\t\t\t`stoptime` \n\t\t\t\tFROM `rounds` \n\t\t\t\tWHERE \n\t\t\t\t\t`stoptime` > '" . microfloat() . "' AND \n\t\t\t\t\t`starttime` <= '" . microfloat() . "' AND \n\t\t\t\t\t`public` >= '1' \n\t\t\t\tORDER BY `starttime` ASC";
    } else {
        // Get all current rounds
        $db_query = "\n\t\t\t\tSELECT \n\t\t\t\t\t`round_id`, \n\t\t\t\t\t`name`, \n\t\t\t\t\t`starttime`, \n\t\t\t\t\t`stoptime` \n\t\t\t\tFROM `rounds` \n\t\t\t\tWHERE \n\t\t\t\t\t`stoptime` > '" . microfloat() . "' OR \n\t\t\t\t\t`public` = '0' \n\t\t\t\tORDER BY `starttime` ASC";
    }
    $db_result = mysql_query($db_query);
    while ($db_row = mysql_fetch_array($db_result, MYSQL_ASSOC)) {
        $temp = array();
        // Count the seconds until stop
        $seconds = $db_row['stoptime'] - time();
        $temp['started'] = true;
        // Merge the time arrays
        $temp += timeparser($seconds);
        $seconds = $db_row['stoptime'] - $db_row['starttime'];
        $db_row['starttime'] = $temp;
        $temp = array();
        $temp = timeparser($seconds);
        $db_row['stoptime'] = $temp;
        $rounds[] = $db_row;
    }
    if (count($rounds) == 1) {
        $_POST['round_id'] = $rounds[0]['round_id'];
        selectround();
        exit;
    }
    $smarty->assign('rounds', $rounds);
    $smarty->display('login_selectround.tpl');
}
function status_player()
{
    global $smarty, $sql, $data;
    if (!empty($_REQUEST['player_id'])) {
        $player_id = (int) $_REQUEST['player_id'];
    } else {
        $player_id = $_SESSION['player_id'];
    }
    $data->updater->update(0, 0, $player_id);
    $player = $data->player($player_id);
    if (empty($player)) {
        error(__FILE__, __LINE__, 'DATA', 'Invalid kingdom selected.');
    }
    $display['player_id'] = $player['player_id'];
    $display['kingdom_id'] = $player['kingdom_id'];
    $display['name'] = $player['name'];
    $display['image'] = $player['image'];
    $display['description'] = nl2br(htmlspecialchars($player['description']));
    $display['planet_count'] = count($player['planets']);
    $display['score'] = format_number($player['score']);
    if ($player['score_peak'] > $player['score']) {
        $display['score_peak'] = format_number($player['score_peak']);
    }
    if (microfloat() - $player['lastactive'] < 900) {
        $display['on'] = true;
    }
    $kingdom = $data->kingdom($player['kingdom_id']);
    if (empty($kingdom)) {
        error(__FILE__, __LINE__, 'DATA', 'Invalid kingdom selected.');
    }
    $display['kingdom'] = array('score' => format_number($kingdom['score']), 'kingdom_id' => $kingdom['kingdom_id'], 'name' => $kingdom['name']);
    $smarty->assign('player', $display);
    $smarty->display('status_player.tpl');
}
 function updater()
 {
     if (!isset($_SESSION['player_id']) || !empty($_SESSION['admin'])) {
         return;
     }
     $player =& $this->data->player($_SESSION['player_id']);
     $kingdom =& $this->data->kingdom($_SESSION['kingdom_id']);
     $player['lastactive'] = microfloat();
     $kingdom['last_active'] = microfloat();
 }