}
if ($num_of_servers < $numberservers_to_skip_query) {
    $query_cache_life = (isset($settings['query_cache_life']) and is_numeric($settings['query_cache_life'])) ? $settings['query_cache_life'] : 30;
    $ip_id = $server_home['ip_id'];
    $statusCache = $db->getServerStatusCache($ip_id, $port);
    if (!empty($statusCache) and date('YmdHis', $statusCache['date_timestamp'] + $query_cache_life) >= date('YmdHis')) {
        $results = $statusCache;
    } else {
        require_once 'protocol/GameQ/GameQ.php';
        $port = $server_home['port'];
        if ($server_home['use_nat'] == 1) {
            $ip = $server_home['agent_ip'];
        } else {
            $ip = $server_home['ip'];
        }
        $query_port = get_query_port($server_xml, $port);
        $gq = new GameQ();
        $servers = array(array('id' => 'server', 'type' => (string) $server_xml->gameq_query_name, 'host' => $ip . ":" . $query_port));
        $gq->addServers($servers);
        $gq->setOption('timeout', 4);
        $gq->setOption('debug', FALSE);
        $gq->setFilter('normalise');
        $results = $gq->requestData();
        $db->saveServerStatusCache($ip_id, $port, $results);
    }
    if ($results['server']['gq_online'] == 1) {
        $xml_mod = xml_get_mod($server_xml, $results['server']['gq_mod']);
        $status = "online";
        // Some functions to print the results
        $players = $results['server']['gq_numplayers'];
        $playersmax = $results['server']['gq_maxplayers'];
function exec_ogp_module()
{
    global $db;
    global $view;
    $home_cfg_id = isset($_REQUEST['home_cfg_id']) ? $_REQUEST['home_cfg_id'] : "";
    $home_id = isset($_REQUEST['home_id']) ? $_REQUEST['home_id'] : "";
    $addon_id = isset($_REQUEST['addon_id']) ? $_REQUEST['addon_id'] : "";
    $isAdmin = $db->isAdmin($_SESSION['user_id']);
    if ($isAdmin) {
        $home_info = $db->getGameHome($home_id);
    } else {
        $home_info = $db->getUserGameHome($_SESSION['user_id'], $home_id);
    }
    if ($home_info === FALSE) {
        print_failure(get_lang('no_rights'));
        echo create_back_button("addonsmanager", "user_addons");
        return;
    }
    $server_xml = read_server_config(SERVER_CONFIG_LOCATION . "/" . $home_info['home_cfg_file']);
    $state = isset($_REQUEST['state']) ? $_REQUEST['state'] : "";
    $pid = isset($_REQUEST['pid']) ? $_REQUEST['pid'] : -1;
    if (!empty($state)) {
        $remote = new OGPRemoteLibrary($home_info['agent_ip'], $home_info['agent_port'], $home_info['encryption_key']);
        $addons_rows = $db->resultQuery("SELECT url, path, post_script FROM OGP_DB_PREFIXaddons WHERE addon_id=" . $addon_id);
        $addon_info = $addons_rows[0];
        $url = $addon_info['url'];
        $filename = basename($url);
        #### This makes replacements to the bash script:
        if (isset($addon_info['post_script']) and !empty($addon_info['post_script']) and $addon_info['post_script'] != "") {
            $check_passed = FALSE;
            $address_at_post = $_POST['ip'] . ":" . $_POST['port'];
            $ip_ports = $db->getHomeIpPorts($home_info["home_id"]);
            foreach ($ip_ports as $ip_port) {
            }
            $address_owned = $ip_port['ip'] . ":" . $ip_port['port'];
            if ($address_owned == $address_at_post) {
                $check_passed = TRUE;
                break;
            }
            $ip = $ip_port['ip'];
            $port = $ip_port['port'];
            $home_info["ip"] = $check_passed ? $_POST['ip'] : $ip;
            $home_info["port"] = $check_passed ? $_POST['port'] : $port;
            if (isset($server_xml->gameq_query_name)) {
                $home_info["query_port"] = get_query_port($server_xml, $home_info['port']);
            } elseif (isset($server_xml->lgsl_query_name)) {
                $get_q_and_s = lgsl_port_conversion((string) $server_xml->lgsl_query_name, $home_info['port'], "", "");
                $home_info["query_port"] = $get_q_and_s['1'];
            }
            $home_info["incremental"] = $db->incrementalNumByHomeId($home_info["home_id"], $home_info["mod_cfg_id"], $home_info["remote_server_id"]);
            $post_script = preg_replace("/\\%home_path\\%/i", $home_info["home_path"], $addon_info['post_script']);
            $post_script = preg_replace("/\\%home_name\\%/i", $home_info["home_name"], $post_script);
            $post_script = preg_replace("/\\%control_password\\%/i", $home_info["control_password"], $post_script);
            $post_script = preg_replace("/\\%max_players\\%/i", $home_info["max_players"], $post_script);
            $post_script = preg_replace("/\\%ip\\%/i", $home_info["ip"], $post_script);
            $post_script = preg_replace("/\\%port\\%/i", $home_info["port"], $post_script);
            $post_script = preg_replace("/\\%query_port\\%/i", $home_info["query_port"], $post_script);
            $post_script = preg_replace("/\\%incremental\\%/i", $home_info["incremental"], $post_script);
        } else {
            $post_script = "";
        }
        #### end of replacememnts
        if ($state == "start" and $addon_id != "") {
            $pid = $remote->start_file_download($addon_info['url'], $home_info['home_path'] . "/" . $addon_info['path'], $filename, "uncompress", $post_script);
        }
        $headers = get_headers($url, 1);
        $download_available = !$headers ? FALSE : TRUE;
        // Check if any error occured
        if ($download_available) {
            $bytes = is_array($headers['Content-Length']) ? $headers['Content-Length'][1] : $headers['Content-Length'];
            // Display the File Size
            $totalsize = $bytes / 1024;
            clearstatcache();
        }
        $kbytes = $remote->rsync_progress($home_info['home_path'] . "/" . $addon_info['path'] . "/" . $filename);
        list($totalsize, $mbytes, $pct) = explode(";", do_progress($kbytes, $totalsize));
        $totalmbytes = round($totalsize / 1024, 2);
        $pct = $pct > 100 ? 100 : $pct;
        echo "<h2>" . $home_info['home_name'] . "</h2>";
        echo '<div class="dragbox bloc rounded" style="background-color:#dce9f2;" >
				<h4>' . get_lang('install') . " " . $filename . " {$mbytes}MB/{$totalmbytes}MB</h4>\n\t\t\t  <div style='background-color:#dce9f2;' >\n\t\t\t  ";
        $bar = '';
        for ($i = 1; $i <= $pct; $i++) {
            $bar .= '<img style="width:0.92%;vertical-align:middle;" src="images/progressBar.png">';
        }
        echo "<center>{$bar} <b style='vertical-align:top;display:inline;font-size:1.2em;color:red;' >{$pct}%</b></center>\n\t\t\t\t</div>\n\t\t\t  </div>";
        if (($pct == "100" or !$download_available) and $post_script != "") {
            $log_retval = $remote->get_log("post_script", $pid, clean_path($home_info['home_path'] . "/" . $server_xml->exe_location), $script_log);
            if ($log_retval == 0) {
                print_failure(get_lang('agent_offline'));
            } elseif ($log_retval == 1 || $log_retval == 2) {
                echo "<pre class='log'>" . $script_log . "</pre>";
            } elseif ($remote->is_screen_running("post_script", $pid) == 1) {
                print_failure(get_lang_f('unable_to_get_log', $log_retval));
            }
        }
        if ($pct == "100" or !$download_available or $download_available and $pct == "-" and $pid > 0) {
            if (!$download_available) {
                print_failure(get_lang('failed_to_start_file_download'));
            } elseif ($remote->is_file_download_in_progress($pid) === 1) {
                print_success(get_lang_f('wait_while_decompressing', $filename));
                echo "<p><a href=\"?m=addonsmanager&amp;p=addons&amp;state=refresh&amp;home_id=" . $home_id . "&addon_id={$addon_id}&amp;pid={$pid}\">" . get_lang('refresh') . "</a></p>";
                $view->refresh("?m=addonsmanager&amp;p=addons&amp;state=refresh&amp;home_id=" . $home_id . "&addon_id={$addon_id}&amp;pid={$pid}", 5);
            } elseif ($remote->is_file_download_in_progress($pid) === 0 and $remote->is_screen_running("post_script", $pid) === 0) {
                print_success(get_lang('addon_installed_successfully'));
                $view->refresh("?m=addonsmanager&amp;p=user_addons&amp;home_id=" . $home_id, 10);
                return;
            }
        } else {
            echo "<p><a href=\"?m=addonsmanager&amp;p=addons&amp;state=refresh&amp;home_id=" . $home_id . "&addon_id={$addon_id}&amp;pid={$pid}\">" . get_lang('refresh') . "</a></p>";
            $view->refresh("?m=addonsmanager&amp;p=addons&amp;state=refresh&amp;home_id=" . $home_id . "&addon_id={$addon_id}&amp;pid={$pid}", 5);
        }
    } elseif (!empty($_GET['addon_type'])) {
        ?>
			<h2><?php 
        echo $home_info['home_name'] . "&nbsp;" . get_lang($_GET['addon_type']);
        ?>
</h2>
            <table class='center'>
			<form action='?m=addonsmanager&amp;p=addons<?php 
        echo "&amp;ip=" . $_GET['ip'] . "&amp;port=" . $_GET['port'];
        ?>
' method='post'>
            <input type='hidden' name='home_id' value='<?php 
        echo "{$home_id}";
        ?>
' />
            <input type='hidden' name='state' value='start' />
            <tr><td align='right'><?php 
        print_lang('game_name');
        ?>
: </td><td align='left'><?php 
        echo "{$home_info['game_name']}";
        ?>
</td></tr>
            <tr><td align='right'><?php 
        print_lang('directory');
        ?>
: </td><td align='left'><?php 
        echo "{$home_info['home_path']}";
        ?>
</td></tr>
            <tr><td align='right'><?php 
        print_lang('remote_server');
        ?>
: </td>
            <td align='left'><?php 
        echo "{$home_info['remote_server_name']} ({$home_info['agent_ip']}:{$home_info['agent_port']})";
        ?>
</td></tr>
            <tr><td align='right'><?php 
        print_lang('select_addon');
        ?>
: </td>
            <td align='left'>
			<select name="addon_id">
			<?php 
        $addons = $db->resultQuery("SELECT addon_id, name FROM OGP_DB_PREFIXaddons WHERE addon_type='" . $_GET['addon_type'] . "' AND home_cfg_id=" . $home_cfg_id);
        foreach ($addons as $addon) {
            ?>
			<option value="<?php 
            echo $addon['addon_id'];
            ?>
"><?php 
            echo $addon['name'];
            ?>
</option>
			<?php 
        }
        ?>
			</select>
			</td></tr>
            <tr><td colspan='2' class='info'>&nbsp;</td></tr>
            <td align='left'>
			&nbsp;
			</td></tr><tr><td align="right">
            <input type="submit" name="update" value="<?php 
        print_lang('install');
        ?>
" />
            </form></td><td>
			<form action="" method="get">
			<input type="hidden" name="m" value="addonsmanager" />
            <input type="hidden" name="p" value="user_addons" />
			<input type="hidden" name="home_id" value="<?php 
        echo "{$home_id}";
        ?>
" />
			<input type="submit" value="<?php 
        print_lang('back');
        ?>
" />
			</form>
			</td></tr>
			</table>
<?php 
    }
    return;
}
function exec_ogp_module()
{
    global $db;
    global $view;
    $home_id = $_REQUEST['home_id'];
    $isAdmin = $db->isAdmin($_SESSION['user_id']);
    if ($isAdmin) {
        $home_info = $db->getGameHome($home_id);
    } else {
        $home_info = $db->getUserGameHome($_SESSION['user_id'], $home_id);
    }
    if ($home_info == FALSE) {
        print_failure(get_lang('no_rights_to_start_server'));
        echo "<table class='center'><tr><td><a href='?m=gamemanager&amp;p=game_monitor&amp;home_id-mod_id-ip-port=" . $home_info['home_id'] . "-" . $home_info['mod_id'] . "-" . $_REQUEST['ip'] . "-" . $_REQUEST['port'] . "'><< " . get_lang('back') . "</a></td></tr></table>";
        return;
    }
    $mod_id = $_REQUEST['mod_id'];
    if (!array_key_exists($mod_id, $home_info['mods'])) {
        print_failure("Unable to retrieve mod information from database.");
        return;
    }
    echo "<h2>";
    echo empty($home_info['home_name']) ? get_lang('not_available') : $home_info['home_name'];
    echo "</h2>";
    require_once 'includes/lib_remote.php';
    $remote = new OGPRemoteLibrary($home_info['agent_ip'], $home_info['agent_port'], $home_info['encryption_key']);
    $server_xml = read_server_config(SERVER_CONFIG_LOCATION . "/" . $home_info['home_cfg_file']);
    if (!$server_xml) {
        echo "<table class='center'><tr><td><a href='?m=gamemanager&amp;p=game_monitor&amp;home_id-mod_id-ip-port=" . $home_info['home_id'] . "-" . $home_info['mod_id'] . "-" . $_REQUEST['ip'] . "-" . $_REQUEST['port'] . "'><< " . get_lang('back') . "</a></td></tr></table>";
        return;
    }
    // It compares ip and port on POST with the pair on DB for security reasons (URL HACKING)
    $home_id = $home_info['home_id'];
    $ip_info = $db->getHomeIpPorts($home_id);
    foreach ($ip_info as $ip_ports_row) {
        if ($ip_ports_row['ip'] == $_REQUEST['ip'] && $ip_ports_row['port'] == $_REQUEST['port']) {
            $ip = $ip_ports_row['ip'];
            $port = $ip_ports_row['port'];
        }
    }
    if (!isset($ip) or !isset($port)) {
        echo "<h2>" . get_lang_f('ip_port_pair_not_owned') . "</h2>";
        echo "<table class='center'><tr><td><a href='?m=gamemanager&amp;p=game_monitor&amp;home_id-mod_id-ip-port={$home_id}-{$mod_id}-{$ip}-{$port}'><< " . get_lang('back') . "</a></td></tr></table>";
        return;
    }
    if (isset($server_xml->console_log)) {
        $log_retval = $remote->remote_readfile($home_info['home_path'] . '/' . $server_xml->console_log, $home_log);
    } else {
        $log_retval = $remote->get_log(OGP_SCREEN_TYPE_HOME, $home_info['home_id'], clean_path($home_info['home_path'] . "/" . $server_xml->exe_location), $home_log);
    }
    function getLastLines($string, $n = 1)
    {
        $lines = explode("\n", $string);
        $lines = array_slice($lines, -$n);
        return implode("\n", $lines);
    }
    $home_log = getLastLines($home_log, 40);
    if ($log_retval > 0) {
        if ($log_retval == 2) {
            print_failure(get_lang('server_not_running_log_found'));
        }
        echo "<pre style='background:black;color:white;'>" . $home_log . "</pre>";
        if ($log_retval == 2) {
            return;
        }
    } else {
        print_failure(get_lang_f('unable_to_get_log', $log_retval));
    }
    // If game is not supported by lgsl we skip the lgsl checks and
    // assume successfull start.
    if ($home_info['use_nat'] == 1) {
        $query_ip = $home_info['agent_ip'];
    } else {
        $query_ip = $ip;
    }
    $running = $remote->is_screen_running(OGP_SCREEN_TYPE_HOME, $home_info['home_id']);
    if ($server_xml->lgsl_query_name) {
        require 'protocol/lgsl/lgsl_protocol.php';
        $get_q_and_s = lgsl_port_conversion((string) $server_xml->lgsl_query_name, $port, "", "");
        //Connection port
        $c_port = $get_q_and_s['0'];
        //query port
        $q_port = $get_q_and_s['1'];
        //software port
        $s_port = $get_q_and_s['2'];
        $data = lgsl_query_live((string) $server_xml->lgsl_query_name, $query_ip, $c_port, $q_port, $s_port, "sa");
        if ($data['b']['status'] == "0") {
            $running = FALSE;
        }
    } elseif ($server_xml->gameq_query_name) {
        require 'protocol/GameQ/GameQ.php';
        $query_port = get_query_port($server_xml, $port);
        $servers = array(array('id' => 'server', 'type' => (string) $server_xml->gameq_query_name, 'host' => $query_ip . ":" . $query_port));
        $gq = new GameQ();
        $gq->addServers($servers);
        $gq->setOption('timeout', 4);
        $gq->setOption('debug', FALSE);
        $gq->setFilter('normalise');
        $game = $gq->requestData();
        if (!$game['server']['gq_online']) {
            $running = FALSE;
        }
    }
    if (!$running) {
        if (!isset($_GET['retry'])) {
            $retry = 0;
        } else {
            $retry = $_GET['retry'];
        }
        if ($retry >= 5) {
            echo "<p>" . get_lang('server_running_not_responding') . "\n\t\t\t<a href=?m=gamemanager&amp;p=stop&amp;home_id=" . $home_info['home_id'] . "&amp;ip=" . $ip . "&amp;port=" . $port . ">" . get_lang('already_running_stop_server') . ".</a></p>";
            echo "<table class='center'><tr><td><a href='?m=gamemanager&amp;p=game_monitor&amp;home_id-mod_id-ip-port={$home_id}-{$mod_id}-{$ip}-{$port}'><< " . get_lang('back') . "</a></td></tr></table>";
        }
        echo "</b>Retry #" . $retry . ".</b>";
        $retry++;
        print "<p class='note'>" . get_lang('starting_server') . "</p>";
        $view->refresh("?m=gamemanager&amp;p=start&amp;refresh&amp;ip={$ip}&amp;port={$port}&amp;home_id={$home_id}&amp;mod_id={$mod_id}&amp;retry=" . $retry, 3);
        return;
    }
    print_success(get_lang('server_started'));
    $ip_id = $db->getIpIdByIp($ip);
    $db->delServerStatusCache($ip_id, $port);
    $view->refresh("?m=gamemanager&amp;p=game_monitor&amp;home_id-mod_id-ip-port={$home_id}-{$mod_id}-{$ip}-{$port}");
    return;
}
                $data['status'] = "ONLINE WITH PASSWORD";
            }
        }
        $db->saveServerStatusCache($ip_id, $port, $data);
    }
    if ($data['status'] == 'ONLINE' or $data['status'] == 'ONLINE WITH PASSWORD') {
        $status = "online";
        $stats_players += $data['s']['players'];
        // COUNT VISIBLE NUMBER OF PLAYERS
        $stats_maxplayers += $data['s']['playersmax'];
        // COUNT VISIBLE NUMBER OF SLOTS
        $players = $data['s']['players'];
        $playersmax = $data['s']['playersmax'];
        $name = $data['s']['name'];
        $map = preg_replace("/[^a-z0-9_]/", "_", strtolower($data['s']['map']));
        $mod = preg_replace("/[^a-z0-9_]/", "_", strtolower($data['s']['game']));
        $xml_mod = xml_get_mod($server_xml, $data['s']['game']);
        $qport = get_query_port($server_xml, $server_home['port']);
        $address = "<a href='" . lgsl_software_link($server_xml->lgsl_query_name, $ip, $c_port, $q_port, $s_port) . "'>" . $ip . ":" . $port . "</a>";
        if ($data['s']['players'] > 0) {
            $player_list = print_player_list($data['p'], $players, $playersmax);
        }
        $playersList = $data['p'];
        $maplocation = get_map_path($query_name, $mod, $map);
    } else {
        $status = "half";
    }
} else {
    $status = "half";
    $notifications = get_lang_f('queries_disabled_by_setting_disable_queries_after', $numberservers_to_skip_query, $num_of_servers);
}
 *
 */
if (empty($server_home["ip"])) {
    $server_home["ip"] = $ip;
}
if (empty($server_home["port"])) {
    $server_home["port"] = $port;
}
$server_home["true"] = "";
$last_param = json_decode($db->getLastParam($server_home["home_id"]), True);
$server_home["max_players"] = isset($cli_param_data['PLAYERS']) ? $cli_param_data['PLAYERS'] : $last_param['players'];
$server_home["webhost_ip"] = $_SERVER['SERVER_ADDR'];
$server_home["incremental"] = $db->incrementalNumByHomeId($server_home["home_id"], $server_home["mod_cfg_id"], $server_home["remote_server_id"]);
$server_home["map"] = isset($cli_param_data['MAP']) ? $cli_param_data['MAP'] : $last_param['map'];
if (isset($server_xml->gameq_query_name)) {
    $server_home["query_port"] = get_query_port($server_xml, $server_home['port']);
} elseif (isset($server_xml->lgsl_query_name)) {
    $get_q_and_s = lgsl_port_conversion((string) $server_xml->lgsl_query_name, $server_home['port'], "", "");
    $server_home["query_port"] = $get_q_and_s['1'];
}
$replace_texts = $server_xml->replace_texts->text;
$replace_id = 0;
foreach ($replace_texts as $text => $array) {
    $param = $array['key'];
    $replacements[$replace_id]['info_param'] = $server_home["{$param}"];
    foreach ($array as $key => $value) {
        if ($key == "default") {
            $replacements[$replace_id]['default'] = (string) $value;
        }
        if ($key == "var") {
            $replacements[$replace_id]['var'] = (string) $value;
function exec_ogp_module()
{
    global $view, $db;
    $ip = $_REQUEST['ip'];
    $port = $_REQUEST['port'];
    $home_id = $_REQUEST['home_id'];
    $user_id = $_SESSION['user_id'];
    $home_id = $_REQUEST['home_id'];
    $isAdmin = $db->isAdmin($_SESSION['user_id']);
    if ($isAdmin) {
        $home_info = $db->getGameHome($home_id);
    } else {
        $home_info = $db->getUserGameHome($_SESSION['user_id'], $home_id);
    }
    require_once 'includes/lib_remote.php';
    $remote = new OGPRemoteLibrary($home_info['agent_ip'], $home_info['agent_port'], $home_info['encryption_key']);
    $mod_id = $_REQUEST['mod_id'];
    if ($home_info === FALSE) {
        print_failure(get_lang('no_rights_to_stop_server'));
        return;
    }
    echo "<h2>";
    echo empty($home_info['home_name']) ? get_lang('not_available') : $home_info['home_name'];
    echo "</h2>";
    $server_xml = read_server_config(SERVER_CONFIG_LOCATION . "/" . $home_info['home_cfg_file']);
    if (!$server_xml) {
        echo create_back_button("gamemanager", "game_monitor");
        return;
    }
    $rserver = $db->getRemoteServerById($home_info['remote_server_id']);
    if (empty($rserver)) {
        print_failure("" . get_lang('not_found_server') . " " . $home_info['remote_server_id'] . ".");
    } else {
        if (isset($_REQUEST['refresh'])) {
            if (isset($server_xml->console_log)) {
                $log_retval = $remote->remote_readfile($home_info['home_path'] . '/' . $server_xml->console_log, $home_log);
            } else {
                $log_retval = $remote->get_log(OGP_SCREEN_TYPE_HOME, $home_info['home_id'], clean_path($home_info['home_path'] . "/" . $server_xml->exe_location), $home_log);
            }
            function getLastLines($string, $n = 1)
            {
                $lines = explode("\n", $string);
                $lines = array_slice($lines, -$n);
                return implode("\n", $lines);
            }
            $home_log = getLastLines($home_log, 40);
            if ($log_retval > 0) {
                if ($log_retval == 2) {
                    print_failure(get_lang('server_not_running_log_found'));
                }
                echo "<pre style='background:black;color:white;'>" . $home_log . "</pre>";
                if ($log_retval == 2) {
                    return;
                }
            } else {
                print_failure(get_lang_f('unable_to_get_log', $log_retval));
            }
            // If game is not supported by lgsl we skip the lgsl checks and
            // assume successfull start.
            if ($home_info['use_nat'] == 1) {
                $query_ip = $home_info['agent_ip'];
            } else {
                $query_ip = $ip;
            }
            $running = TRUE;
            if ($server_xml->lgsl_query_name) {
                require 'protocol/lgsl/lgsl_protocol.php';
                $get_q_and_s = lgsl_port_conversion((string) $server_xml->lgsl_query_name, $port, "", "");
                //Connection port
                $c_port = $get_q_and_s['0'];
                //query port
                $q_port = $get_q_and_s['1'];
                //software port
                $s_port = $get_q_and_s['2'];
                $data = lgsl_query_live((string) $server_xml->lgsl_query_name, $query_ip, $c_port, $q_port, $s_port, "sa");
                if ($data['b']['status'] == "0") {
                    $running = FALSE;
                }
            } elseif ($server_xml->gameq_query_name) {
                require 'protocol/GameQ/GameQ.php';
                $query_port = get_query_port($server_xml, $port);
                $servers = array(array('id' => 'server', 'type' => (string) $server_xml->gameq_query_name, 'host' => $query_ip . ":" . $query_port));
                $gq = new GameQ();
                $gq->addServers($servers);
                $gq->setOption('timeout', 4);
                $gq->setOption('debug', FALSE);
                $gq->setFilter('normalise');
                $game = $gq->requestData();
                if (!$game['server']['gq_online']) {
                    $running = FALSE;
                }
            }
            if (!$running) {
                if (!isset($_GET['retry'])) {
                    $retry = 0;
                } else {
                    $retry = $_GET['retry'];
                }
                if ($retry >= 5) {
                    echo "<p>" . get_lang('server_running_not_responding') . "\n\t\t\t\t\t<a href=?m=gamemanager&amp;p=stop&amp;home_id=" . $home_info['home_id'] . "&amp;ip=" . $ip . "&amp;port=" . $port . ">" . get_lang('already_running_stop_server') . ".</a></p>";
                    echo "<table class='center'><tr><td><a href='?m=gamemanager&amp;p=game_monitor&amp;home_id-mod_id-ip-port={$home_id}-{$mod_id}-{$ip}-{$port}'><< " . get_lang('back') . "</a></td></tr></table>";
                }
                echo "</b>Retry #" . $retry . ".</b>";
                $retry++;
                print "<p class='note'>" . get_lang('starting_server') . "</p>";
                $view->refresh("?m=gamemanager&amp;p=start&amp;refresh&amp;ip={$ip}&amp;port={$port}&amp;home_id={$home_id}&amp;mod_id={$mod_id}&amp;retry=" . $retry, 3);
                return;
            }
            print_success(get_lang_f('server_restarted', $home_info['home_name']));
            $ip_id = $db->getIpIdByIp($ip);
            $db->delServerStatusCache($ip_id, $port);
            $view->refresh("?m=gamemanager&amp;p=game_monitor&amp;home_id-mod_id-ip-port=" . $home_info['home_id'] . "-" . $home_info['mod_id'] . "-" . $_REQUEST['ip'] . "-" . $_REQUEST['port']);
            echo "<p>" . get_lang('follow_server_status') . " <a href='?m=gamemanager&amp;p=game_monitor&amp;home_id-mod_id-ip-port=" . $home_info['home_id'] . "-" . $home_info['mod_id'] . "-" . $_REQUEST['ip'] . "-" . $_REQUEST['port'] . "'>" . get_lang('game_monitor') . "</a> " . get_lang('page') . ".</p>";
            return;
        } else {
            if ($server_xml->replace_texts) {
                $server_home = $home_info;
                if (isset($server_xml->lgsl_query_name)) {
                    require_once 'protocol/lgsl/lgsl_protocol.php';
                }
                require_once "modules/gamemanager/cfg_text_replace.php";
            }
            $control_type = isset($server_xml->control_protocol_type) ? $server_xml->control_protocol_type : "";
            $run_dir = isset($server_xml->exe_location) ? $server_xml->exe_location : "";
            $last_param = json_decode($home_info['last_param'], True);
            $cli_param_data['GAME_TYPE'] = $home_info['mods'][$mod_id]['mod_key'];
            $cli_param_data['IP'] = $ip;
            $cli_param_data['PORT'] = $port;
            $cli_param_data['HOSTNAME'] = $home_info['home_name'];
            $cli_param_data['PID_FILE'] = "ogp_game_startup.pid";
            $os = $remote->what_os();
            // Linux
            if (preg_match("/Linux/", $os)) {
                $cli_param_data['BASE_PATH'] = $home_info['home_path'];
                $cli_param_data['HOME_PATH'] = $home_info['home_path'];
                $cli_param_data['SAVE_PATH'] = $home_info['home_path'];
                $cli_param_data['OUTPUT_PATH'] = $home_info['home_path'];
                $cli_param_data['USER_PATH'] = $home_info['home_path'];
            } elseif (preg_match("/CYGWIN/", $os)) {
                $home_path_win = $remote->exec("cygpath -w " . $home_info['home_path']);
                $home_path_win = str_replace("\\", "\\\\", $home_path_win);
                $home_path_win = trim($home_path_win);
                $cli_param_data['BASE_PATH'] = $home_path_win;
                $cli_param_data['HOME_PATH'] = $home_path_win;
                $cli_param_data['SAVE_PATH'] = $home_path_win;
                $cli_param_data['OUTPUT_PATH'] = $home_path_win;
                $cli_param_data['USER_PATH'] = $home_path_win;
            }
            if ($server_xml->protocol == "gameq") {
                $cli_param_data['QUERY_PORT'] = get_query_port($server_xml, $port);
            } elseif ($server_xml->protocol == "lgsl") {
                require 'protocol/lgsl/lgsl_protocol.php';
                $get_ports = lgsl_port_conversion((string) $server_xml->lgsl_query_name, $port, "", "");
                $cli_param_data['QUERY_PORT'] = $get_ports['1'];
            } elseif ($server_xml->protocol == "teamspeak3") {
                $cli_param_data['QUERY_PORT'] = "10011";
            }
            $cli_param_data['MAP'] = empty($last_param['map']) ? "" : $last_param['map'];
            $cli_param_data['PLAYERS'] = empty($last_param['players']) ? $home_info['mods'][$mod_id]['max_players'] : $last_param['players'];
            $start_cmd = "";
            // If the template is empty then these are not needed.
            if ($server_xml->cli_template) {
                $start_cmd = $server_xml->cli_template;
                if ($server_xml->cli_params) {
                    foreach ($server_xml->cli_params->cli_param as $cli) {
                        // If s is found the param is seperated with space
                        $add_space = preg_match("/s/", $cli['options']) > 0 ? " " : "";
                        $cli_value = $cli_param_data[(string) $cli['id']];
                        // If q is found we add quotes around the value.
                        if (preg_match("/q/", $cli['options']) > 0) {
                            $cli_value = "\"" . $cli_value . "\"";
                        }
                        $start_cmd = preg_replace("/%" . $cli['id'] . "%/", $cli['cli_string'] . $add_space . $cli_value, $start_cmd);
                    }
                }
            }
            if ($isAdmin) {
                $home_info['access_rights'] = "ufpet";
            }
            $param_access_enabled = preg_match("/p/", $home_info['access_rights']) > 0 ? TRUE : FALSE;
            if ($param_access_enabled && isset($last_param)) {
                foreach ($server_xml->server_params->param as $param) {
                    foreach ($last_param as $paramKey => $paramValue) {
                        if (!isset($paramValue)) {
                            $paramValue = (string) $param->default;
                        }
                        if ($param['key'] == $paramKey) {
                            if (0 == strlen($paramValue)) {
                                continue;
                            }
                            if ($param['key'] == $paramValue) {
                                // it's a checkbox
                                $new_param = $paramKey;
                            } elseif ($param->option == "ns" or $param->options == "ns") {
                                $new_param = $paramKey . $paramValue;
                            } else {
                                $new_param = $paramKey . ' "' . $paramValue . '"';
                            }
                            if ($param['id'] == NULL || $param['id'] == "") {
                                $start_cmd .= ' ' . $new_param;
                            } else {
                                $start_cmd = preg_replace("/%" . $param['id'] . "%/", $new_param, $start_cmd);
                            }
                        }
                    }
                    $start_cmd = preg_replace("/%" . $param['id'] . "%/", '', $start_cmd);
                }
            }
            $extra_param_access_enabled = preg_match("/e/", $home_info['access_rights']) > 0 ? TRUE : FALSE;
            if (array_key_exists('extra', $last_param) && $extra_param_access_enabled) {
                $extra_default = $last_param['extra'];
            } else {
                $extra_default = $home_info['mods'][$mod_id]['extra_params'];
            }
            $start_cmd .= " " . $extra_default;
            $remote_retval = $remote->remote_restart_server($home_info['home_id'], $ip, $port, $server_xml->control_protocol, $home_info['control_password'], $control_type, $home_info['home_path'], $server_xml->server_exec_name, $run_dir, $start_cmd, $home_info['cpu_affinity'], $home_info['nice']);
            $db->logger(get_lang_f('server_restarted', $home_info['home_name']) . "({$ip}:{$port})");
            if ($remote_retval === 1) {
                print "<p class='note'>" . get_lang('restarting_server') . "</p>";
                $view->refresh("?m=gamemanager&amp;p=restart&amp;refresh&amp;ip={$ip}&amp;port={$port}&amp;home_id={$home_id}&amp;mod_id={$mod_id}", 3);
                return;
            } else {
                if ($remote_retval === -1) {
                    print_failure(get_lang('server_cant_start'));
                    $view->refresh("?m=gamemanager&amp;p=game_monitor&amp;home_id-mod_id-ip-port=" . $home_info['home_id'] . "-" . $home_info['mod_id'] . "-" . $ip . "-" . $port, 3);
                } else {
                    if ($remote_retval === -2) {
                        print_failure(get_lang('server_cant_stop'));
                        $view->refresh("?m=gamemanager&amp;p=game_monitor&amp;home_id-mod_id-ip-port=" . $home_info['home_id'] . "-" . $home_info['mod_id'] . "-" . $ip . "-" . $port, 3);
                    } else {
                        $screen_running = $remote->is_screen_running(OGP_SCREEN_TYPE_HOME, $home_info['home_id']);
                        if ($screen_running == 1) {
                            print "<p class='note'>" . get_lang('restarting_server') . "</p>";
                            $view->refresh("?m=gamemanager&amp;p=restart&amp;refresh&amp;ip={$ip}&amp;port={$port}&amp;home_id={$home_id}&amp;mod_id={$mod_id}", 3);
                            return;
                        } else {
                            print_failure("" . get_lang('error_occured_remote_host') . ".{$remote_retval}");
                            $view->refresh("?m=gamemanager&amp;p=game_monitor&amp;home_id-mod_id-ip-port=" . $home_info['home_id'] . "-" . $home_info['mod_id'] . "-" . $ip . "-" . $port, 3);
                        }
                    }
                }
            }
        }
    }
}
function exec_ogp_module()
{
    global $view, $db;
    require_once 'includes/lib_remote.php';
    $ip = $_REQUEST['ip'];
    $port = $_REQUEST['port'];
    $home_id = $_REQUEST['home_id'];
    $user_id = $_SESSION['user_id'];
    $isAdmin = $db->isAdmin($_SESSION['user_id']);
    if ($isAdmin) {
        $home_info = $db->getGameHome($home_id);
    } else {
        $home_info = $db->getUserGameHome($_SESSION['user_id'], $home_id);
    }
    $home_path = $home_info['home_path'] . "/";
    if ($home_info === FALSE) {
        print_failure(get_lang('no_rights_to_stop_server'));
        return;
    }
    echo "<h2>" . $home_info['home_name'] . "</h2>";
    $server_xml = read_server_config(SERVER_CONFIG_LOCATION . "/" . $home_info['home_cfg_file']);
    if (!$server_xml) {
        echo create_back_button("gamemanager", "game_monitor");
        return;
    }
    $rserver = $db->getRemoteServerById($home_info['remote_server_id']);
    if (empty($rserver)) {
        print_failure("Could not find the remote server with ID " . $home_info['remote_server_id'] . ".");
    } else {
        $remote = new OGPRemoteLibrary($rserver['agent_ip'], $rserver['agent_port'], $rserver['encryption_key']);
        if (isset($server_xml->control_protocol_type)) {
            $control_type = $server_xml->control_protocol_type;
        } else {
            $control_type = "";
        }
        if ($server_xml->protocol == "gameq") {
            $query_port = get_query_port($server_xml, $port);
        } elseif ($server_xml->protocol == "lgsl") {
            require 'protocol/lgsl/lgsl_protocol.php';
            $get_ports = lgsl_port_conversion((string) $server_xml->lgsl_query_name, $port, "", "");
            $query_port = $get_ports['1'];
        } elseif ($server_xml->protocol == "teamspeak3") {
            $query_port = "10011";
        }
        $remote_retval = $remote->remote_stop_server($home_id, $ip, $port, $server_xml->control_protocol, $home_info['control_password'], $control_type, $home_path);
        $db->logger(get_lang_f('server_stopped', $home_info['home_name']) . "({$ip}:{$port})");
        if ($remote_retval === 1) {
            print_success(get_lang_f("server_stopped", $home_info['home_name']));
            if (isset($home_info['ufw_status']) and $home_info['ufw_status'] == "enable") {
                $ip_ports = $db->getHomeIpPorts($home_id);
                foreach ($ip_ports as $ip_port) {
                    if ($server_xml->protocol == "gameq") {
                        $query_port = get_query_port($server_xml, $ip_port['port']);
                    } elseif ($server_xml->protocol == "lgsl") {
                        require 'protocol/lgsl/lgsl_protocol.php';
                        $get_ports = lgsl_port_conversion((string) $server_xml->lgsl_query_name, $ip_port['port'], "", "");
                        $query_port = $get_ports['1'];
                    } elseif ($server_xml->protocol == "teamspeak3") {
                        $query_port = "10011";
                    }
                    $remote->sudo_exec("ufw deny " . $ip_port['port']);
                    if (isset($query_port)) {
                        $remote->sudo_exec("ufw deny " . $query_port);
                    }
                }
            }
        } elseif ($remote_retval === 0) {
            $remote_retval = $remote->remote_stop_server($home_info['home_id'], $ip, $port, $server_xml->control_protocol, "", $control_type, $home_path);
            if ($remote_retval === 1) {
                print_success(get_lang_f("server_stopped", $home_info['home_name']));
                if (isset($home_info['ufw_status']) and $home_info['ufw_status'] == "enable") {
                    $ip_ports = $db->getHomeIpPorts($home_id);
                    foreach ($ip_ports as $ip_port) {
                        if ($server_xml->protocol == "gameq") {
                            $query_port = get_query_port($server_xml, $ip_port['port']);
                        } elseif ($server_xml->protocol == "lgsl") {
                            require 'protocol/lgsl/lgsl_protocol.php';
                            $get_ports = lgsl_port_conversion((string) $server_xml->lgsl_query_name, $ip_port['port'], "", "");
                            $query_port = $get_ports['1'];
                        } elseif ($server_xml->protocol == "teamspeak3") {
                            $query_port = "10011";
                        }
                        $remote->sudo_exec("ufw deny " . $ip_port['port']);
                        if (isset($query_port)) {
                            $remote->sudo_exec("ufw deny " . $query_port);
                        }
                    }
                }
            }
        }
        if ($remote_retval === 0) {
            print_failure(get_lang("agent_offline"));
        } elseif ($remote_retval !== 1) {
            print_failure("Error occurred on the remote host.");
        }
    }
    $view->refresh("?m=gamemanager&amp;p=game_monitor&amp;home_id-mod_id-ip-port=" . $home_info['home_id'] . "-" . $home_info['mod_id'] . "-" . $_REQUEST['ip'] . "-" . $_REQUEST['port'], 3);
}
function exec_operation($action, $home_id, $mod_id, $ip, $port)
{
    global $db;
    $isAdmin = $db->isAdmin($_SESSION['user_id']);
    if ($isAdmin) {
        $home_info = $db->getGameHome($home_id);
    } else {
        $home_info = $db->getUserGameHome($_SESSION['user_id'], $home_id);
    }
    require_once 'includes/lib_remote.php';
    $remote = new OGPRemoteLibrary($home_info['agent_ip'], $home_info['agent_port'], $home_info['encryption_key']);
    if ($home_info === FALSE) {
        return FALSE;
    }
    $home_path = $home_info['home_path'] . "/";
    $server_xml = read_server_config(SERVER_CONFIG_LOCATION . "/" . $home_info['home_cfg_file']);
    if (!$server_xml) {
        return FALSE;
    }
    $rserver = $db->getRemoteServerById($home_info['remote_server_id']);
    if (empty($rserver)) {
        return FALSE;
    } else {
        if ($action != "stop") {
            if ($server_xml->replace_texts) {
                $server_home = $home_info;
                if (isset($server_xml->lgsl_query_name)) {
                    require_once 'protocol/lgsl/lgsl_protocol.php';
                }
                require_once "modules/gamemanager/cfg_text_replace.php";
            }
        }
        if (isset($server_xml->control_protocol_type)) {
            $control_type = $server_xml->control_protocol_type;
        } else {
            $control_type = "";
        }
        $screen_running = $remote->is_screen_running(OGP_SCREEN_TYPE_HOME, $home_info['home_id']);
        if ($action == "stop" and $screen_running) {
            $remote_retval = $remote->remote_stop_server($home_info['home_id'], $ip, $port, $server_xml->control_protocol, $home_info['control_password'], $control_type, $home_path);
            $db->logger(get_lang_f('server_stopped', $home_info['home_name']) . "({$ip}:{$port})");
            if ($remote_retval === -1) {
                return FALSE;
            } else {
                if ($remote_retval === -2) {
                    return FALSE;
                } else {
                    $screen_running = $remote->is_screen_running(OGP_SCREEN_TYPE_HOME, $home_info['home_id']);
                    if ($screen_running == 1) {
                        return FALSE;
                    } else {
                        if (isset($home_info['ufw_status']) and $home_info['ufw_status'] == "enable") {
                            $ip_ports = $db->getHomeIpPorts($home_id);
                            foreach ($ip_ports as $ip_port) {
                                if ($server_xml->protocol == "gameq") {
                                    $query_port = get_query_port($server_xml, $ip_port['port']);
                                } elseif ($server_xml->protocol == "lgsl") {
                                    require 'protocol/lgsl/lgsl_protocol.php';
                                    $get_ports = lgsl_port_conversion((string) $server_xml->lgsl_query_name, $ip_port['port'], "", "");
                                    $query_port = $get_ports['1'];
                                } elseif ($server_xml->protocol == "teamspeak3") {
                                    $query_port = "10011";
                                }
                                $remote->sudo_exec("ufw deny " . $ip_port['port']);
                                if (isset($query_port)) {
                                    $remote->sudo_exec("ufw deny " . $query_port);
                                }
                            }
                        }
                        return TRUE;
                    }
                }
            }
        } elseif ($action == "restart" and $screen_running) {
            $start_cmd = get_sart_cmd($remote, $server_xml, $home_info, $mod_id, $ip, $port);
            $remote_retval = $remote->remote_restart_server($home_info['home_id'], $ip, $port, $server_xml->control_protocol, $home_info['control_password'], $control_type, $home_info['home_path'], $server_xml->server_exec_name, $run_dir, $start_cmd, $home_info['cpu_affinity'], $home_info['nice']);
            $db->logger(get_lang_f('server_restarted', $home_info['home_name']) . "({$ip}:{$port})");
            if ($remote_retval === -1) {
                return FALSE;
            } else {
                if ($remote_retval === -2) {
                    return FALSE;
                } else {
                    $screen_running = $remote->is_screen_running(OGP_SCREEN_TYPE_HOME, $home_info['home_id']);
                    if ($screen_running == 1) {
                        $ip_id = $db->getIpIdByIp($ip);
                        $db->delServerStatusCache($ip_id, $port);
                        return TRUE;
                    } else {
                        return FALSE;
                    }
                }
            }
        } elseif ($action == "start" and !$screen_running) {
            $start_cmd = get_sart_cmd($remote, $server_xml, $home_info, $mod_id, $ip, $port);
            $start_retval = $remote->universal_start($home_info['home_id'], $home_info['home_path'], $server_xml->server_exec_name, $server_xml->exe_location, $start_cmd, $port, $ip, $home_info['mods'][$mod_id]['cpu_affinity'], $home_info['mods'][$mod_id]['nice']);
            $db->logger(get_lang('server_started') . " (" . $home_info['home_name'] . " {$ip}:{$port})");
            if ($start_retval == AGENT_ERROR_NOT_EXECUTABLE) {
                return FALSE;
            } else {
                if ($start_retval <= 0) {
                    return FALSE;
                } else {
                    if (isset($server_home['ufw_status']) and $server_home['ufw_status'] == "enable") {
                        $ip_ports = $db->getHomeIpPorts($home_id);
                        foreach ($ip_ports as $ip_port) {
                            if ($server_xml->protocol == "gameq") {
                                $query_port = get_query_port($server_xml, $ip_port['port']);
                            } elseif ($server_xml->protocol == "lgsl") {
                                require 'protocol/lgsl/lgsl_protocol.php';
                                $get_ports = lgsl_port_conversion((string) $server_xml->lgsl_query_name, $ip_port['port'], "", "");
                                $query_port = $get_ports['1'];
                            } elseif ($server_xml->protocol == "teamspeak3") {
                                $query_port = "10011";
                            }
                            $remote->sudo_exec("ufw allow " . $ip_port['port']);
                            if (isset($query_port)) {
                                $remote->sudo_exec("ufw allow " . $query_port);
                            }
                        }
                    }
                    $ip_id = $db->getIpIdByIp($ip);
                    $db->delServerStatusCache($ip_id, $port);
                    return TRUE;
                }
            }
        }
    }
}