function military_overview()
{
    global $data, $smarty, $sql;
    $incomingfleets = array();
    $combatlocations = array();
    $declarations = array();
    $microtime = microfloat();
    $sql->select(array(array('planets', 'planet_id'), array('planets', 'name', 'planetname'), array('navygroups', 'navygroup_id'), array('navygroups', 'name', 'navygroupname'), array('tasks', 'kingdom_id'), array('tasks', 'completion', 'time')));
    $sql->where(array(array('navygroups', 'round_id', $_SESSION['round_id']), array('navygroups', 'navygroup_id', array('tasks', 'group_id')), array('planets', 'round_id', $_SESSION['round_id']), array('planets', 'planet_id', array('tasks', 'planet_id')), array('tasks', 'round_id', $_SESSION['round_id']), array('tasks', 'type', 5), array('tasks', 'kingdom_id', array('tasks', 'target_kingdom_id'), '<>')));
    $db_query = $sql->generate();
    $db_query .= " AND (`tasks`.`kingdom_id` = '" . $_SESSION['kingdom_id'] . "' OR `tasks`.`target_kingdom_id` = '" . $_SESSION['kingdom_id'] . "') ORDER BY `planets`.`planet_id` ASC, `tasks`.`completion` ASC";
    $db_result = mysql_query($db_query);
    if (mysql_num_rows($db_result) > 0) {
        while ($db_row = mysql_fetch_array($db_result, MYSQL_ASSOC)) {
            if ($db_row['kingdom_id'] == $_SESSION['kingdom_id']) {
                $db_row['direction'] = 'Outgoing';
            } else {
                $db_row['direction'] = 'Incoming';
            }
            unset($db_row['kingdom_id'], $db_row['target_kingdom_id']);
            $db_row['time'] = format_time(timeparser($db_row['time'] - $microtime));
            $incomingfleets[] = $db_row;
        }
    }
    $typearray = array('army', 'navy');
    foreach ($typearray as $type) {
        $sql->property('DISTINCT');
        $sql->select(array(array('planets', 'planet_id'), array('planets', 'name', 'planetname'), array('combat', 'completion')));
        $sql->where(array(array($type . 'groups', 'kingdom_id', array('planets', 'kingdom_id'), '!='), array($type . 'groups', 'planet_id', array('planets', 'planet_id')), array($type . 'groups', 'units', 'a:0:{}', '<>'), array('combat', 'planet_id', array('planets', 'planet_id'))));
        if ($type == 'navy') {
            $sql->where(array(array('navygroups', 'x_current', array('navygroups', 'x_destination')), array('navygroups', 'y_current', array('navygroups', 'y_destination'))));
        }
        $db_query = $sql->generate();
        $db_query .= " AND (`" . $type . "groups`.`kingdom_id` = '" . $_SESSION['kingdom_id'] . "' OR `planets`.`kingdom_id` = '" . $_SESSION['kingdom_id'] . "') ORDER BY `combat`.`completion` ASC";
        $db_result = mysql_query($db_query);
        if (mysql_num_rows($db_result) > 0) {
            $location_restarts = array();
            while ($db_row = mysql_fetch_array($db_result, MYSQL_ASSOC)) {
                $db_row['time'] = format_time(timeparser($db_row['completion'] - $microtime));
                $combatlocations[$db_row['planet_id']] = $db_row;
                // If the update hasn't finished after 30 seconds, it has died.
                if ($db_row['completion'] < $microtime + 30) {
                    $location_restarts[] = $db_row['planet_id'];
                }
            }
            // Restart any dead combats.
            if (!empty($location_restarts)) {
                $db_query = "UPDATE `combat` SET `beingupdated` = '0' WHERE `planet_id` IN ('" . implode("', '", $location_restarts) . "')";
                $db_result = mysql_query($db_query);
            }
        }
    }
    $sort_function = create_function('$a,$b', 'if ($a[\'completion\'] == $b[\'completion\']) return 0; return ($a[\'completion\'] < $b[\'completion\']) ? -1 : 1;');
    usort($combatlocations, $sort_function);
    // Declarations
    military_declarations();
    $smarty->assign('incomingfleets', $incomingfleets);
    $smarty->assign('combatlocations', $combatlocations);
    $smarty->display('military_overview.tpl');
}
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 options_round()
{
    global $smarty;
    if (empty($_SESSION['admin']) || $_SESSION['admin'] != true) {
        $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;
    }
    $smarty->assign('rounds', $rounds);
    $smarty->display('options_round.tpl');
}
function blueprints_info()
{
    global $smarty, $sql;
    $type = isset($_REQUEST['type']) ? $_REQUEST['type'] : '';
    $blueprint_id = isset($_REQUEST['blueprint_id']) ? $_REQUEST['blueprint_id'] : '';
    if (!in_array($type, array('army', 'navy', 'weapon')) || empty($blueprint_id)) {
        error(__FILE__, __LINE__, 'INVALID_ID/TYPE', 'Invalid type and/or blueprint_id');
    }
    $sql->where(array($type . 'blueprints', $type . 'blueprint_id', $blueprint_id));
    $sql->limit(1);
    $db_result = $sql->execute();
    if (mysql_num_rows($db_result) == 0) {
        error(__FILE__, __LINE__, 'INVALID_ID', 'Invalid blueprint_id');
    }
    $blueprint = mysql_fetch_array($db_result, MYSQL_ASSOC);
    if ($blueprint['kingdom_id'] != $_SESSION['kingdom_id']) {
        error(__FILE__, __LINE__, 'INVALID_ACCESS', 'You do not have permission to access that blueprint.');
    }
    $blueprint['mineralspread'] = unserialize($blueprint['mineralspread']);
    $blueprint['resources']['time'] = format_time(timeparser($blueprint['time'] * $_SESSION['round_speed']));
    $blueprint['resources']['workers'] = format_number($blueprint['workers'], true);
    $blueprint['resources']['energy'] = format_number($blueprint['energy'], true);
    if (!empty($blueprint['mineralspread'])) {
        $mineralnames = array(0 => 'fe', 1 => 'o', 2 => 'si', 3 => 'mg', 4 => 'ni', 5 => 's', 6 => 'he', 7 => 'h');
        foreach ($blueprint['mineralspread'] as $key => $value) {
            $resources['minerals'][$mineralnames[$key]] = format_number($blueprint['minerals'] / $value, true);
        }
        $blueprint['resources']['minerals'] = $resources['minerals'];
    }
    if ($type == 'weapon') {
        $blueprint['targets'] = unserialize($blueprint['targets']);
    } else {
        $blueprint['weapons'] = unserialize($blueprint['weapons']);
    }
    blueprints_stats($type, $blueprint_id);
    $smarty->assign('type', $type);
    $smarty->assign('blueprint', $blueprint);
    $smarty->display('blueprints_info.tpl');
}
 function info()
 {
     $designs['main'] = array('army', 'navy', 'weapon');
     $designs['army'] = array('attack', 'defense', 'armor', 'hull', 'weaponsload');
     $designs['navy'] = array('attack', 'defense', 'armor', 'hull', 'weaponsload', 'cargo', 'speed');
     $designs['weapon'] = array('accuracy', 'areadamage', 'rateoffire', 'power', 'damage');
     foreach ($designs['main'] as $value) {
         if (!empty($_REQUEST[$value . 'design_id'])) {
             $design_id = (int) $_REQUEST[$value . 'design_id'];
             $design_name = $value;
             break;
         }
     }
     if (empty($design_name)) {
         error(__FILE__, __LINE__, 'DATA_NULL', 'Null design selected');
     }
     $db_query = "\n\t\t\t\tSELECT * \n\t\t\t\tFROM `" . $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']);
     $upgrades = array();
     foreach ($designs[$design_name] as $value) {
         // =IF(C1 < $B$2; ROUNDDOWN(C1 + (($B$4 / 100) * C1) + $B$3); "")
         if ($design[$value . '_base'] < $design[$value . '_max']) {
             $increment = floor($design[$value . '_per'] / 100 * $design[$value . '_base'] + $design[$value . '_inc']);
             if ($design[$value . '_base'] + $increment > $design[$value . '_max']) {
                 $increment = $design[$value . '_max'] - $design[$value . '_base'];
             }
             $sizeincrement = floor($design[$value . '_size'] / 100 * $design['size_base'] + $design[$value . '_sizeinc']);
             if ($design['size_base'] + $sizeincrement > $design['size_max']) {
                 $sizeincrement = $design['size_max'] - $design['size_base'];
             }
             if ($value == 'weaponsload') {
                 $upgrades[$value]['name'] = 'Weapon Load';
             } else {
                 $upgrades[$value]['name'] = ucfirst($value);
             }
             $upgrades[$value]['current'] = $design[$value . '_base'];
             $upgrades[$value]['increase'] = $increment;
             $upgrades[$value]['sizeincrease'] = $sizeincrement;
         }
     }
     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) {
             $resources['resources']['minerals'][$mineralnames[$key]] = format_number($design['minerals'] * ($value / 100), true);
         }
     }
     $resources['name'] = $design['name'];
     $resources['design_id'] = $design_id;
     $resources['type'] = $design_name;
     $resources['resources']['time'] = format_time(timeparser($design['time'] * $_SESSION['round_speed']));
     $resources['resources']['workers'] = $design['workers'];
     $resources['resources']['energy'] = $design['energy'];
     $resources['upgrades'] = $upgrades;
     research_planets();
     $this->smarty->assign('design', $resources);
     $this->smarty->display('designs_info.tpl');
     exit;
 }
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 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 info()
 {
     $planet = $this->data->planet($this->planet_id);
     //$designs['army'] = array('attack', 'defense', 'armor', 'hull', 'weapons', 'size');
     //$designs['navy'] = array('attack', 'defense', 'armor', 'hull', 'weapons', 'cargo', 'speed', 'size');
     $unit = $this->data->blueprint($this->unit_type, $this->unit_id);
     $unit['name'] = htmlentities($unit['name']);
     if (!empty($planet['production'][$this->unit_type][$unit[$this->unit_type . 'concept_id']])) {
         $unit['resources']['time'] = format_time(timeparser($unit['time'] * $_SESSION['round_speed'] / $planet['production'][$this->unit_type][$unit[$this->unit_type . 'concept_id']]));
     }
     $unit['resources']['workers'] = format_number($unit['workers'], true);
     $unit['resources']['energy'] = format_number($unit['energy'], true);
     if (!empty($unit['mineralspread'])) {
         $mineralnames = unserialize(MINERALS_ARRAY);
         foreach ($unit['mineralspread'] as $key => $value) {
             $resources['minerals'][$mineralnames[$key]] = format_number($unit['minerals'] / $value, true);
         }
         $unit['resources']['minerals'] = $resources['minerals'];
     }
     if ($unit['kingdom_id'] == $_SESSION['kingdom_id']) {
         blueprints_stats($this->unit_type, $this->unit_id);
     }
     research_planets();
     $this->smarty->assign('unit', $unit);
     $this->smarty->assign('unit_type', $this->unit_type);
     $this->smarty->assign('unit_id', $this->unit_id);
     $this->smarty->display('units_info.tpl');
 }
 function overview()
 {
     $grouplist = array();
     $this->sql->select(array(array($this->group_type . 'groups', $this->group_type . 'group_id', 'group_id'), array($this->group_type . 'groups', 'name'), array($this->group_type . 'groups', 'planet_id'), array($this->group_type . 'groups', 'units')));
     $this->sql->where(array(array($this->group_type . 'groups', 'round_id', $_SESSION['round_id']), array($this->group_type . 'groups', 'kingdom_id', $_SESSION['kingdom_id']), array($this->group_type . 'groups', 'player_id', $_SESSION['player_id'])));
     $this->sql->orderby(array($this->group_type . 'groups', 'planet_id', 'ASC'));
     if ($this->group_type == 'army') {
         $this->sql->select(array(array($this->group_type . 'groups', 'navygroup_id'), array($this->group_type . 'groups', 'size')));
         $this->sql->orderby(array($this->group_type . 'groups', 'size', 'DESC'));
     } else {
         $this->sql->select(array(array($this->group_type . 'groups', 'x_current'), array($this->group_type . 'groups', 'y_current'), array($this->group_type . 'groups', 'x_destination'), array($this->group_type . 'groups', 'y_destination'), array($this->group_type . 'groups', 'cargo_current'), array($this->group_type . 'groups', 'cargo_max')));
         $this->sql->orderby(array(array($this->group_type . 'groups', 'cargo_current', 'DESC'), array($this->group_type . 'groups', 'cargo_max', 'DESC')));
     }
     $this->sql->orderby(array($this->group_type . 'groups', $this->group_type . 'group_id', 'ASC'));
     $db_result = $this->sql->execute();
     while ($db_row = mysql_fetch_array($db_result, MYSQL_ASSOC)) {
         $db_row['units'] = unserialize($db_row['units']);
         $grouplist[$db_row['group_id']] = array('name' => htmlentities($db_row['name']), 'units' => array_sum($db_row['units']));
         if ($this->group_type == 'army') {
             $locations = array('planet', 'navygroup');
             foreach ($locations as $value) {
                 if (empty($db_row[$value . '_id'])) {
                     continue;
                 }
                 $this->sql->select(array($value . 's', 'name'));
                 $this->sql->where(array($value . 's', $value . '_id', $db_row[$value . '_id']));
                 $location_result = $this->sql->execute();
                 $location_row = mysql_fetch_array($location_result, MYSQL_ASSOC);
                 $location = strtoupper($value[0]) . '#' . $db_row[$value . '_id'] . ' ' . strshort(htmlentities($location_row['name']), 10);
                 break;
             }
             $grouplist[$db_row['group_id']]['location'] = $location;
             $grouplist[$db_row['group_id']]['size'] = format_number($db_row['size'], true);
         } else {
             $coordinates = map_coordinate($db_row['x_destination'], $db_row['y_destination']);
             $this->sql->select(array(array('planets', 'planet_id'), array('planets', 'name')));
             $this->sql->where(array(array('quadrants', 'round_id', $_SESSION['round_id']), array('starsystems', 'round_id', $_SESSION['round_id']), array('planets', 'round_id', $_SESSION['round_id']), array('quadrants', 'x', $coordinates['quadrant']['x']), array('quadrants', 'y', $coordinates['quadrant']['y']), array('starsystems', 'x', $coordinates['starsystem']['x']), array('starsystems', 'y', $coordinates['starsystem']['y']), array('planets', 'x', $coordinates['planet']['x']), array('planets', 'y', $coordinates['planet']['y']), array('planets', 'starsystem_id', array('starsystems', 'starsystem_id')), array('planets', 'quadrant_id', array('quadrants', 'quadrant_id')), array('planets', 'planet_id', $db_row['planet_id'])));
             $this->sql->limit(1);
             $location_result = $this->sql->execute();
             if (mysql_num_rows($location_result) > 0) {
                 $location_row = mysql_fetch_array($location_result, MYSQL_ASSOC);
                 $grouplist[$db_row['group_id']]['location'] = 'P#' . $location_row['planet_id'] . ' ' . strshort($location_row['name'], 15);
             } else {
                 $grouplist[$db_row['group_id']]['location'] = '(' . $coordinates['quadrant']['x'] . ', ' . $coordinates['quadrant']['y'] . '), ' . '(' . $coordinates['starsystem']['x'] . ', ' . $coordinates['starsystem']['y'] . '), ' . '(' . $coordinates['planet']['x'] . ', ' . $coordinates['planet']['y'] . ')';
             }
             if ($db_row['x_current'] != $db_row['x_destination'] || $db_row['y_current'] != $db_row['y_destination']) {
                 $this->sql->select(array('tasks', 'completion'));
                 $this->sql->where(array(array('tasks', 'type', 5), array('tasks', 'group_id', $db_row['group_id'])));
                 $this->sql->limit(1);
                 $location_result = $this->sql->execute();
                 $location_row = mysql_fetch_array($location_result, MYSQL_ASSOC);
                 $grouplist[$db_row['group_id']]['location'] .= ' ' . format_time(timeparser($location_row['completion'] - microfloat()));
                 $grouplist[$db_row['group_id']]['transit'] = true;
             }
             $grouplist[$db_row['group_id']]['size'] = format_number($db_row['cargo_current'], true) . '/' . format_number($db_row['cargo_max'], true);
         }
     }
     $this->smarty->assign('type', $this->group_type);
     $this->smarty->assign('groups', $grouplist);
     $this->smarty->display('groups_overview.tpl');
 }
 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 info()
 {
     // FIXME
     $concept_id = $this->concept_id;
     $this->planets();
     $concept = $this->data->concept($this->concept_id);
     if (empty($concept)) {
         error(__FILE__, __LINE__, 'DATA', 'Invalid concept selected');
     }
     $grant_types = array(array(0 => 'concepts', 1 => 'concept_id', 2 => 'Concept'), array(0 => 'buildings', 1 => 'building_id', 2 => 'Building'), array(0 => 'armyconcepts', 1 => 'armyconcept_id', 2 => 'Army Unit'), array(0 => 'navyconcepts', 1 => 'navyconcept_id', 2 => 'Navy Unit'), array(0 => 'weaponconcepts', 1 => 'weaponconcept_id', 2 => 'Weapon'));
     foreach ($grant_types as $value) {
         if (!empty($concept['grants'][$value[0]])) {
             $db_query = "SELECT `name` FROM `" . $value[0] . "` WHERE `" . $value[1] . "` IN ('" . implode("', '", array_keys($concept['grants'][$value[0]])) . "')";
             $db_result = mysql_query($db_query);
             while ($db_row = mysql_fetch_array($db_result, MYSQL_ASSOC)) {
                 $grants[] = array('type' => $value[2], 'name' => $db_row['name']);
             }
         }
     }
     $concept['grants'] = $grants;
     $mineralnames = array(0 => 'fe', 1 => 'o', 2 => 'si', 3 => 'mg', 4 => 'ni', 5 => 's', 6 => 'he', 7 => 'h');
     foreach ($concept['mineralspread'] as $key => $value) {
         $concept['resources']['minerals'][$mineralnames[$key]] = format_number($concept['minerals'] * ($value / 100), true);
     }
     $concept['resources']['time'] = format_time(timeparser($concept['time'] * $_SESSION['round_speed']));
     $concept['resources']['workers'] = format_number($concept['workers'], true);
     $concept['resources']['energy'] = format_number($concept['energy'], true);
     unset($concept['minerals'], $concept['mineralspread'], $concept['time'], $concept['workers'], $concept['energy']);
     research_planets();
     $this->smarty->assign('concept', $concept);
     $this->smarty->display('research_info.tpl');
 }
function research_planets()
{
    global $smarty, $sql;
    if (isset($_POST['mode']) && $_POST['mode'] == 'js') {
        $output_mode = 'javascript';
    } else {
        $output_mode = '';
    }
    $planets_permissions = permissions_planets($_SESSION['player_id'], 'research');
    if (!empty($planets_permissions)) {
        $sql->raw(array('where' => "OR `planets`.`planet_id` IN ('" . implode("', '", array_keys($planets_permissions)) . "')"));
    }
    // Player's planets
    $sql->select(array(array('planets', 'planet_id'), array('planets', 'name'), array('planets', 'researching'), array('planets', 'researchbonus'), array('planets', 'warptime_research')));
    $sql->where(array('planets', 'player_id', $_SESSION['player_id']));
    $sql->orderby(array(array('planets', 'researching', 'ASC'), array('planets', 'researchbonus', 'DESC'), array('planets', 'planet_id', 'ASC')));
    $db_query = $sql->generate();
    $db_result = mysql_query($db_query);
    if ($db_result && mysql_num_rows($db_result) > 0) {
        while ($db_row = mysql_fetch_array($db_result, MYSQL_ASSOC)) {
            $db_row['warptime_research'] = format_time(timeparser($db_row['warptime_research']));
            $planets[$db_row['planet_id']] = $db_row;
        }
        $smarty->assign('planets', $planets);
        if ($output_mode == 'javascript') {
            $smarty->assign('output', 'javascript');
            $smarty->display('research_planets.tpl');
            exit;
        }
    }
}
 function info()
 {
     $building = $this->data->building($this->building_id);
     $planet = $this->data->planet($this->planet_id);
     if (empty($building) || empty($planet)) {
         error(__FILE__, __LINE__, 'DATA', 'Invalid building or planet selection');
     }
     $mineralnames = unserialize(MINERALS_ARRAY);
     foreach ($building['mineralspread'] as $key => $value) {
         if ($value > 0) {
             $building['resources']['minerals'][$mineralnames[$key]] = format_number($building['minerals'] * ($value / 100), true);
         } else {
             $building['resources']['minerals'][$mineralnames[$key]] = 0;
         }
     }
     $building['resources']['time'] = format_time(timeparser($building['time'] * $_SESSION['round_speed'] * ((100 - $planet['buildingbonus']) / 100)));
     $building['resources']['workers'] = format_number($building['workers'], true);
     $building['resources']['energy'] = format_number($building['energy'], true);
     $construction_warptime = format_time(timeparser($planet['warptime_construction']));
     $this->smarty->assign('warptime', $construction_warptime);
     $this->smarty->assign('building', $building);
     $this->smarty->assign('available_cranes', $planet['cranes']);
     $this->smarty->assign('available_planning', $planet['planning']);
     $this->smarty->display('buildings_info.tpl');
 }
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 format_time($time = array(), $maxaccuracy = 2)
{
    if (!is_array($time)) {
        $time = timeparser($time);
    }
    $time_str = '';
    $timeaccuracy = 0;
    $timeunits = array(array(0 => 'days', 1 => 'd'), array(0 => 'hours', 1 => 'h'), array(0 => 'minutes', 1 => 'm'), array(0 => 'seconds', 1 => 's'), array(0 => 'milliseconds', 1 => 'ms'));
    foreach ($timeunits as $value) {
        if (!empty($time[$value[0]]) && ($value[0] != 'milliseconds' || $timeaccuracy == 0)) {
            $timeaccuracy++;
            if ($timeaccuracy > 1) {
                $time_str .= $_SESSION['preferences']['thousands_seperator'] . ' ';
            }
            $time_str .= $time[$value[0]] . $value[1];
        }
        if ($timeaccuracy >= $maxaccuracy) {
            break;
        }
    }
    return htmlentities($time_str);
}