function exec_ogp_module()
{
    global $db;
    echo "<h2>" . get_lang('game_monitor') . "</h2>";
    $refresh = new refreshed(100000);
    set_time_limit(0);
    $stats_servers_online = 0;
    $stats_servers = 0;
    $stats_players = 0;
    $stats_maxplayers = 0;
    $isAdmin = $db->isAdmin($_SESSION['user_id']);
    if ($isAdmin) {
        $server_homes = $db->getIpPorts();
    } else {
        $server_homes = $db->getIpPortsForUser($_SESSION['user_id']);
    }
    if ($server_homes === FALSE) {
        // If there are no games, then there can not be any mods either.
        print_failure(get_lang('no_game_homes_assigned'));
        if ($isAdmin) {
            echo "<p><a href='?m=user_games&amp;p=assign&amp;user_id={$_SESSION['user_id']}'>" . get_lang('assign_game_homes') . "</a></p>";
        }
        return;
    }
    if (empty($_GET['home_id-mod_id-ip-port'])) {
        unset($_GET['home_id-mod_id-ip-port']);
    }
    if (empty($_GET['home_id'])) {
        unset($_GET['home_id']);
    }
    if ($_GET['home_cfg_id'] == get_lang('game_type')) {
        unset($_GET['home_cfg_id']);
    }
    create_home_selector_game_type($_GET['m'], $_GET['p'], $server_homes);
    if (!isset($_GET['home_id-mod_id-ip-port']) and !isset($_GET['home_id']) and !isset($_GET['home_cfg_id'])) {
        create_home_selector_address($_GET['m'], $_GET['p'], $server_homes);
        $show_all = TRUE;
    } else {
        create_home_selector_address($_GET['m'], $_GET['p'], $server_homes);
        create_home_selector($_GET['m'], $_GET['p'], "show_all");
        $show_all = FALSE;
    }
    require "protocol/lgsl/lgsl_protocol.php";
    ?>
		<form>
			<b><?php 
    print_lang('search');
    ?>
:</b>
			<input type="text" id="search">
		</form>
	<?php 
    $info = $db->getUser($_SESSION['users_login']);
    $chk_expire = $info['user_expires'];
    $exptime = read_expire($chk_expire);
    $time_to_expire = str_replace('hr', 'hours', $exptime);
    if ($exptime != "X") {
        ?>
		<span style="color:black;font-weight:bold;">
		 <center>
			<?php 
        echo print_lang('account_expiration');
        ?>
: <span style="color:green;"><?php 
        echo date("l, F jS, Y, H:i:s", $chk_expire) . " ( " . $time_to_expire . ")";
        ?>
</span>
		 </center>
		</span>
	<?php 
    }
    ?>
		<table id="servermonitor" class="tablesorter">
		<thead> 
		<tr> 
			<th style="width:16px;background-position: center;"></th> 
			<th style="width:16px;background-position: center;"></th> 
			<th><?php 
    print_lang('server_name');
    ?>
</th> 
			<th><?php 
    print_lang('address');
    ?>
</th> 
			<th><?php 
    print_lang('owner');
    ?>
</th> 
			<th>
			  <?php 
    print_lang('operations');
    ?>
			  <img style="border:0;height:15px;" id="action-stop" src="images/stop.png"/>
			  <img style="border:0;height:15px;" id="action-restart" src="images/restart.png"/>
			  <img style="border:0;height:15px;" id="action-start" src="images/start.png"/>
			</th>
		</tr> 
		</thead> 
		<tbody> 
	<?php 
    foreach ($server_homes as $server_home) {
        $stats_servers++;
        //Unset variables.
        if (isset($_GET['home_id-mod_id-ip-port'])) {
            $pieces = explode("-", $_GET['home_id-mod_id-ip-port']);
            $post_home_id = $pieces[0];
            $post_mod_id = $pieces[1];
            $post_ip = $pieces[2];
            $post_port = $pieces[3];
        }
        if ($show_all or isset($_GET['home_id']) and $_GET['home_id'] == $server_home['home_id'] or isset($_GET['home_id-mod_id-ip-port']) and $server_home['home_id'] == $post_home_id and $server_home['mod_id'] == $post_mod_id and $post_ip == $server_home['ip'] and $post_port == $server_home['port'] or isset($_GET['home_cfg_id']) and $_GET['home_cfg_id'] == $server_home['home_cfg_id']) {
            unset($map, $trclass, $first, $second, $onlineT, $ts3opt, $offlineT, $halfT, $ministart, $player_list, $groupsus, $name, $mod_name, $SrvCtrl, $lite_fm, $manager, $user, $pos, $ftp, $addonsmanager, $ctrlChkBoxes);
            //End
            if ($isAdmin) {
                $server_home['access_rights'] = "ufpet";
            } else {
                $home_info = $db->getUserGameHome($_SESSION['user_id'], $server_home['home_id']);
                $server_home['access_rights'] = $home_info['access_rights'];
            }
            $litefm_installed = $db->isModuleInstalled('litefm');
            $ftp_installed = $db->isModuleInstalled('ftp');
            $addonsmanager_installed = $db->isModuleInstalled('addonsmanager');
            $mysql_installed = $db->isModuleInstalled('mysql');
            if ($server_home['mod_name'] == "none" or $server_home['mod_name'] == "None") {
                $mod_name = "";
            } elseif ($server_home['mod_name'] != $server_home['game_name']) {
                $mod_name = " ( " . $server_home['mod_name'] . " )";
            }
            $get_size = "<table align='left' class='monitorbutton' ><tr>" . "<td align='middle' class='size' id='" . $server_home["home_id"] . "'>" . "<img style='border:0;height:40px;vertical-align:middle;' src='images/file_size.png' title='" . get_lang('get_size') . "'/>\n<br /><span style='font-weight:bold;'>" . get_lang('get_size') . "</span></td></tr></table>";
            $manager = "<a href='?m=user_games&amp;p=edit&amp;home_id=" . $server_home['home_id'] . "'>\n" . "<table align='left' class='monitorbutton' ><tr><td align='middle' >" . "<img style='border:0;height:40px;vertical-align:middle;' src='images/edit.png' title='" . get_lang('edit') . "'/>\n<br />" . get_lang('edit') . "\n</td></tr></table></a>";
            // Only show the filemanager link when the litefm is installed.
            if (preg_match("/f/", $server_home['access_rights']) > 0 && $litefm_installed) {
                $lite_fm = "<a href='?m=litefm&amp;home_id=" . $server_home['home_id'] . "'>\n" . "<table align='left' class='monitorbutton' ><tr><td align='middle' >" . "<img style='border:0;height:40px;vertical-align:middle;' src='images/txt.png' title='" . get_lang('file_manager') . "'/>\n<br />" . get_lang('file_manager') . "\n</td></tr></table></a>";
            }
            if (preg_match("/t/", $server_home['access_rights']) > 0 && $ftp_installed) {
                $ftp = "<a href='?m=ftp&amp;home_id=" . $server_home['home_id'] . "'>\n" . "<table align='left' class='monitorbutton' ><tr><td align='middle' >" . "<img style='border:0;height:40px;vertical-align:middle;' src='images/ftp.png' title='" . get_lang('ftp') . "'/>\n<br>" . get_lang('ftp') . "\n</td></tr></table></a>";
            }
            if ($addonsmanager_installed) {
                $addons = $db->resultQuery("SELECT DISTINCT addon_id FROM OGP_DB_PREFIXaddons NATURAL JOIN OGP_DB_PREFIXconfig_homes WHERE home_cfg_id=" . $server_home['home_cfg_id']);
                $addons_qty = count($addons);
                if ($addons and $addons_qty >= 1) {
                    $addonsmanager = "<a href='?m=addonsmanager&amp;p=user_addons&amp;home_id=" . $server_home['home_id'] . "&amp;ip=" . $server_home['ip'] . "&amp;port=" . $server_home['port'] . "'>\n" . "<table align='left' class='monitorbutton' ><tr><td align='middle' >" . "<img style='border:0;height:40px;vertical-align:middle;' src='modules/administration/images/addons_manager.png' title='" . get_lang('addons') . "'/>\n<br />" . get_lang('addons') . "\n<b style='font-size:0.9em' >(" . $addons_qty . ")</td></tr></table></a>";
                }
            }
            if ($mysql_installed) {
                $mysql_dbs = $db->resultQuery("SELECT db_id FROM OGP_DB_PREFIXmysql_databases WHERE enabled=1 AND home_id=" . $server_home['home_id']);
                if (!empty($mysql_dbs)) {
                    $mysql = "<a href='?m=mysql&p=user_db&home_id=" . $server_home['home_id'] . "'>\n" . "<table align='left' class='monitorbutton' ><tr><td align='middle' >" . "<img style='border:0;height:40px;vertical-align:middle;' src='modules/administration/images/mysql_admin.png' title='" . get_lang('mysql_databases') . "'/>\n<br />" . get_lang('mysql_databases') . "\n</td></tr></table></a>\n";
                }
            }
            $mod_result = $db->getHomeMods($server_home['home_id']);
            if ($mod_result === FALSE) {
                print_failure(get_lang('fail_no_mods'));
                if ($isAdmin) {
                    $manager .= "<a href='?m=user_games&amp;p=edit&amp;home_id=" . $server_home['home_id'] . "'>" . get_lang('configure_mods') . "</a>";
                }
                continue;
            }
            $server_xml = read_server_config(SERVER_CONFIG_LOCATION . "/" . $server_home['home_cfg_file']);
            $master_server_home_id = $db->getMasterServer($server_home['remote_server_id'], $server_home['home_cfg_id']);
            if ($master_server_home_id != FALSE) {
                if (!$db->getGameHomeWithoutMods($master_server_home_id)) {
                    $db->setMasterServer("remove", $master_server_home_id, $server_home['home_cfg_id'], $server_home['remote_server_id']);
                    $master_server_home_id = FALSE;
                }
            }
            if ($server_xml) {
                if (preg_match("/u/", $server_home['access_rights']) > 0) {
                    // In case game is compatible with steam we offer a way to use steam with the updates.
                    if ($server_xml->installer == "steamcmd") {
                        if ($master_server_home_id != FALSE and $master_server_home_id != $server_home['home_id']) {
                            $manager .= "<form name='steam_master_" . $server_home['home_id'] . "_" . $server_home['mod_id'] . "_" . str_replace(".", "", $server_home['ip']) . "_" . $server_home['port'] . "' action='?m=gamemanager&amp;p=update&amp;home_id=" . $server_home['home_id'] . "&amp;mod_id=" . $server_home['mod_id'] . "&amp;update=update' method='POST' >\n" . "<table align='left' class='monitorbutton' >\n" . "<tr><td align='middle' onclick='document.steam_master_" . $server_home['home_id'] . "_" . $server_home['mod_id'] . "_" . str_replace(".", "", $server_home['ip']) . "_" . $server_home['port'] . ".submit()' ><img style='border:0;height:40px;vertical-align:middle;' src='images/master.png' />" . "<br /><span style='font-weight:bold;'>" . get_lang('update_from_local_master_server') . "</span><input id='master" . $server_home['home_id'] . "' type='hidden' name='master_server_home_id' value='" . $master_server_home_id . "' /></td></tr>\n</table>\n</form>";
                        }
                        $manager .= "<form name='steam_" . $server_home['home_id'] . "_" . $server_home['mod_id'] . "_" . str_replace(".", "", $server_home['ip']) . "_" . $server_home['port'] . "' action='?m=gamemanager&amp;p=update&amp;home_id=" . $server_home['home_id'] . "&amp;mod_id=" . $server_home['mod_id'] . "&amp;update=update' method='POST' >\n" . "<table align='left' class='monitorbutton' >\n" . "<tr><td align='middle' onclick='document.steam_" . $server_home['home_id'] . "_" . $server_home['mod_id'] . "_" . str_replace(".", "", $server_home['ip']) . "_" . $server_home['port'] . ".submit()' ><img style='border:0;height:40px;vertical-align:middle;' src='images/steam.png' />" . "<br /><span style='font-weight:bold;'>" . get_lang('install_update_steam') . "</span></td></tr>\n</table>\n</form>";
                    } else {
                        $manager .= "<a href='?m=gamemanager&amp;p=update_manual&amp;home_id=" . $server_home['home_id'] . "&amp;mod_id=" . $server_home['mod_id'] . "&amp;update=update'>\n" . "<table align='left' class='monitorbutton' ><tr><td align='middle' >" . "<img style='border:0;height:40px;vertical-align:middle;' src='images/install.png' title='" . get_lang('install_update_manual') . "'/>\n<br>" . get_lang('install_update_manual') . "\n</td></td></table></a>";
                        $sync_name = get_sync_name($server_xml);
                        $sync_list = @file("modules/gamemanager/rsync.list", FILE_IGNORE_NEW_LINES);
                        $master_server_home_id = $db->getMasterServer($server_home['remote_server_id'], $server_home['home_cfg_id']);
                        if (in_array($sync_name, $sync_list) or $master_server_home_id != FALSE and $master_server_home_id != $server_home['home_id']) {
                            $manager .= "<a href='?m=gamemanager&amp;p=rsync_install&amp;home_id=" . $server_home['home_id'] . "&amp;mod_id=" . $server_home['mod_id'] . "&amp;update=update'>\n" . "<table align='left' class='monitorbutton' ><tr><td align='middle' >" . "<img style='border:0;height:40px;vertical-align:middle;' src='images/rsync.png' title='" . get_lang('rsync_install') . "'/>\n<br />" . get_lang('rsync_install') . "\n</td></td></table></a>";
                        }
                    }
                }
            }
            if ($isAdmin) {
                if ($server_xml->control_protocol == 'rcon' or $server_xml->control_protocol == 'lcon' or $server_xml->control_protocol == 'rcon2' or @$server_xml->gameq_query_name == 'minecraft') {
                    $manager .= "<form name='rcon_preset" . $server_home['home_id'] . "' action='home.php?m=gamemanager&amp;p=rcon_presets&amp;home_id=" . $server_home['home_id'] . "&amp;mod_id=" . $server_home['mod_id'] . "' method='POST'>\n" . "<table align='left' class='monitorbutton' >\n" . "<tr>\n" . "<td align='middle' onclick='document.rcon_preset" . $server_home['home_id'] . ".submit()' ><img style='border:0;height:40px;vertical-align:middle;' src='images/rcon_preset.png' /><br /><span style='font-weight:bold;'>" . get_lang('rcon_presets') . "</span></td>\n" . "</tr>\n" . "</table>\n" . "</form>";
                }
            }
            $xml_installer = $server_xml->installer;
            // If query name does not exist use mod key instead.
            if ($server_xml->protocol == "gameq") {
                $query_name = $server_xml->gameq_query_name;
            } elseif ($server_xml->protocol == "lgsl") {
                $query_name = $server_xml->lgsl_query_name;
            } elseif ($server_xml->mods->mod['key'] == "none" or $server_xml->mods->mod['key'] == "None") {
                $query_name = "none";
            } else {
                $query_name = $server_xml->mods->mod['key'];
            }
            if ($server_xml->mods->mod['key'] == "none" or $server_xml->mods->mod['key'] == "None") {
                $mod = "none";
            } else {
                $mod = $server_xml->mods->mod['key'];
            }
            //----------+ getting the lgsl image icon
            $icon_paths = array("images/icons/{$mod}.png", "images/icons/{$query_name}.png", "protocol/lgsl/other/icon_unknown.gif");
            $icon_path = get_first_existing_file($icon_paths);
            //Properties for all servers
            if (isset($post_home_id) && $post_home_id == $server_home['home_id'] or isset($_GET['home_id']) && $_GET['home_id'] == $server_home['home_id']) {
                $trclass = " expandme";
            }
            $groupusers = $db->getGroupUsersByHomeId($server_home['home_id']);
            if ($groupusers) {
                $groupsus = "<b>" . get_lang('group_users') . "</b><br>";
                foreach ($groupusers as $groupu) {
                    $groupsus .= $groupu['users_login'] . "<br>";
                }
            } else {
                $groupsus = "";
            }
            $view_log = "<a href='?m=gamemanager&amp;p=log&amp;home_id-mod_id-ip-port=" . $server_home['home_id'] . "-" . $server_home['mod_id'] . "-" . $server_home['ip'] . "-" . $server_home['port'] . "'>\n" . "<table align='left' class='monitorbutton' ><tr><td align='middle' >" . "<img style='border:0;height:40px;vertical-align:middle;' src='images/log.png' title='" . get_lang('view_log') . "'/>\n<br>" . get_lang('view_log') . "\n</td></tr></table></a>";
            $btns = $view_log . @$ftp . @$lite_fm . @$addonsmanager;
            //End
            $remote = new OGPRemoteLibrary($server_home['agent_ip'], $server_home['agent_port'], $server_home['encryption_key'], $server_home['timeout']);
            $host_stat = $remote->status_chk();
            if ($host_stat === 1) {
                if ($server_home['use_nat'] == 1) {
                    $query_ip = $server_home['agent_ip'];
                } else {
                    $query_ip = $server_home['ip'];
                }
                $address = $query_ip . ":" . $server_home['port'];
                $screen_running = $remote->is_screen_running(OGP_SCREEN_TYPE_HOME, $server_home['home_id']) === 1;
                $update_in_progress = $remote->is_screen_running(OGP_SCREEN_TYPE_UPDATE, $server_home['home_id']) === 1;
                if ($screen_running) {
                    // Check if the screen running the server is running.
                    $status = "online";
                    $order = 1;
                    if ($server_xml->protocol == "lgsl") {
                        $get_q_and_s = lgsl_port_conversion((string) $query_name, $server_home['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'];
                        $address = "<a href='" . lgsl_software_link($query_name, $query_ip, $c_port, $q_port, $s_port) . "'>" . $query_ip . ":" . $server_home['port'] . "</a>";
                    }
                    if ($server_xml->protocol == "teamspeak3") {
                        $address = "<a href='ts3server://" . $query_ip . ":" . $server_home['port'] . "'>" . $query_ip . ":" . $server_home['port'] . "</a>";
                    }
                    if ($server_xml->protocol == "gameq" and $server_xml->installer == 'steamcmd') {
                        $address = "<a href='steam://connect/" . $query_ip . ":" . $server_home['port'] . "'>" . $query_ip . ":" . $server_home['port'] . "</a>";
                    }
                    $pos = $refresh->add("home.php?m=gamemanager&p=ref_servermonitor&type=cleared&server_home=" . $server_home['home_id'] . "&ip=" . $server_home['ip'] . "&port=" . $server_home['port']);
                    if ($server_xml->protocol == "teamspeak3") {
                        require 'protocol/TeamSpeak3/functions.php';
                    }
                    $startup_file_exists = $remote->rfile_exists("startups/" . $server_home['ip'] . "-" . $server_home['port']) === 1;
                    $ctrlChkBoxes .= '<div id="server_icon" class="action-stop' . $server_home['home_id'] . '" >
									 <div>
									 <input id="action-stop" class="action-stop' . $server_home['home_id'] . '" name="action-' . $server_home['home_id'] . '" value="stop-' . $server_home['home_id'] . '-' . $server_home['mod_id'] . '-' . $server_home['ip'] . '-' . $server_home['port'] . '" type="radio"><img style="border:0;height:15px;" src="images/stop.png"/></div><div>&nbsp;' . get_lang('stop_server') . '</div></div>';
                    if ($startup_file_exists) {
                        $ctrlChkBoxes .= '<div id="server_icon" class="action-restart' . $server_home['home_id'] . '" >
										 <div>
										 <input id="action-restart" class="action-restart' . $server_home['home_id'] . '" name="action-' . $server_home['home_id'] . '" value="restart-' . $server_home['home_id'] . '-' . $server_home['mod_id'] . '-' . $server_home['ip'] . '-' . $server_home['port'] . '" type="radio"><img style="border:0;height:15px;" src="images/restart.png"/></div><div>&nbsp;' . get_lang('restart_server') . '</div></div>';
                    }
                    $stats_servers_online++;
                } else {
                    $status = "offline";
                    if ($db->getLastParam($server_home['home_id']) != FALSE) {
                        if ($update_in_progress) {
                            $ctrlChkBoxes .= '<div id="server_icon" class="action-start' . $server_home['home_id'] . '" >&nbsp;' . get_lang('update_in_progress') . '</div>';
                        } else {
                            $ctrlChkBoxes .= '<div id="server_icon" class="action-start' . $server_home['home_id'] . '" >
											 <div>
											 <input id="action-start" class="action-start' . $server_home['home_id'] . '" name="action-' . $server_home['home_id'] . '" value="start-' . $server_home['home_id'] . '-' . $server_home['mod_id'] . '-' . $server_home['ip'] . '-' . $server_home['port'] . '" type="radio"><img style="border:0;height:15px;" src="images/start.png"/></div><div>&nbsp;' . get_lang('start_server') . '</div></div>';
                        }
                    }
                    $order = 3;
                    ob_start();
                    require 'modules/gamemanager/mini_start.php';
                    $ministart = ob_get_contents();
                    ob_end_clean();
                    if ($update_in_progress) {
                        $offlineT = '<div id="server_icon" class="action-start' . $server_home['home_id'] . '" >&nbsp;' . get_lang('update_in_progress') . '</div>';
                    } else {
                        $offlineT = $ministart;
                    }
                }
            } else {
                $status = "offline";
                $order = 3;
                $address = "<span style='color:darkred;font-weight:bold;'>Agent Offline</span>";
            }
            $user = $db->getUserById($server_home['user_id_main']);
            // Template
            @($first = "<tr class='maintr{$trclass}'>");
            $first .= "<td class='collapsible'><span class='hidden'>{$order}</span><a></a>" . "<img src='images/{$status}.png' />" . "</td>";
            $first .= "<td>" . "<span class='hidden'>{$mod}</span><img src='{$icon_path}' />" . "</td>";
            $first .= "<td class='collapsible'><a></a><b>" . $server_home['home_name'] . "</b>{$mod_name}</td>";
            $first .= "<td>" . $address . "</td>";
            $first .= "<td>" . $user['users_login'] . "</td>";
            $first .= "<td style='width:328px;padding:0px;'>{$ctrlChkBoxes}</td>";
            $first .= "</tr>";
            $second = "<tr class='expand-child'>";
            @($second .= "<td colspan='4'>" . $refresh->getdiv($pos, "width:100%;") . "{$offlineT}</td>");
            $second .= "<td width='80'>{$groupsus}</td>";
            @($second .= "<td>{$btns}{$manager}<br>{$mysql}<br>{$get_size}<br>{$ts3opt}</td>");
            $second .= "</tr>";
            //Echo them all
            echo "{$first}{$second}";
        }
    }
    echo "</tbody>";
    echo "<tfoot style='border:1px solid grey;'>\n\t\t\t<tr>\n\t\t\t  <td colspan='6' >\n\t\t\t\t<div class='bloc' >\n\t\t\t\t<img src='images/magnifglass.png' /> " . get_lang('statistics') . ": {$stats_servers_online}/{$stats_servers} " . get_lang('servers') . "\n</div>\n\t\t\t\t<div class='right bloc' >\n\t\t\t\t  <label>" . get_lang('execute_selected_server_operations') . "</label>\n\t\t\t\t  <input id='execute_operations' type='submit' value='" . get_lang('execute_operations') . "' >\n\n\t\t\t\t</div>\n\t\t\t  </td>\n\t\t\t</tr>\n\t\t  </tfoot>";
    echo "</table>";
    ?>
	<script type="text/javascript">
			$(document).ready(function() 
				{ 
					<?php 
    echo $refresh->build("8000");
    ?>
					$('input#search').quicksearch('table#servermonitor tbody tr.maintr');
					$("#servermonitor")
						.collapsible("td.collapsible", {collapse: true})
						.tablesorter({sortList: [[0,0], [1,0]] , widgets: ['zebra','repeatHeaders']})
						; 
				} 
			);
			
			$("div#server_icon").click(function(){
				var id = $(this).attr('class');
				if($("input[type=radio]."+id).attr('checked') == 'checked')
				{
					$("input[type=radio]."+id).prop('checked', false);
				}
				else
				{
					$("input[type=radio]."+id).prop('checked', true);
				}
			});
						
			$('.size').click(function(){
				var $id = $(this).attr('id');
				$.get( "home.php?m=user_games&type=cleared&p=get_size&home_id="+$id, function( data ) {
					$('#'+$id+".size").text( data );
					$('#'+$id+".size").css("font-size", "16pt");
				});
			});
			
			$('#execute_operations').click(function(){
				var addpost = {};
				$('input[type=radio]:checked').each(function( ){
					var name = $(this).attr('name');
					var value = $(this).val();
					addpost[ name ] = value;
				});
				
				$('.right.bloc').html('<img src="images/loading.gif" />');
				
				$.ajax({
				type: "POST",
				url: "home.php?m=gamemanager&p=game_monitor",
				data: addpost,
				complete: function(){ 
					document.location.reload(); 
				}
				});
			});
			
			$('img#action-stop').click(function(){
				$('input[type=radio]#action-stop').each(function( ){
					if( this.checked )
					{
						$(this).attr('checked', false);
					}
					else
					{
						$(this).attr('checked', true);
					}
				});
			});
			
			$('img#action-restart').click(function(){
				$('input[type=radio]#action-restart').each(function( ){
					if( this.checked )
					{
						$(this).attr('checked', false);
					}
					else
					{
						$(this).attr('checked', true);
					}
				});
			});
			
			$('img#action-start').click(function(){
				$('input[type=radio]#action-start').each(function( ){
					if( this.checked )
					{
						$(this).attr('checked', false);
					}
					else
					{
						$(this).attr('checked', true);
					}
				});
			});
		</script>
	<?php 
}
function exec_ogp_module()
{
    global $db, $view;
    $home_id = $_GET['home_id'];
    $isAdmin = $db->isAdmin($_SESSION['user_id']);
    if ($isAdmin) {
        $home_info = $db->getGameHome($home_id);
        $custom_fileds_access_enabled = TRUE;
    } else {
        $home_info = $db->getUserGameHome($_SESSION['user_id'], $home_id);
        $custom_fileds_access_enabled = preg_match("/c/", $home_info['access_rights']) > 0 ? TRUE : FALSE;
    }
    if (!$home_info or !$custom_fileds_access_enabled) {
        return;
    }
    $server_xml = read_server_config(SERVER_CONFIG_LOCATION . $home_info['home_cfg_file']);
    include 'includes/lib_remote.php';
    $remote = new OGPRemoteLibrary($home_info['agent_ip'], $home_info['agent_port'], $home_info['encryption_key']);
    echo "<h2>" . get_lang('editing_home_called') . " \"" . $home_info['home_name'] . "\"</h2>";
    echo "<p>";
    echo "<a href='?m=gamemanager&p=game_monitor&home_id={$home_id}'>&lt;&lt; " . get_lang('back_to_game_monitor') . "</a>";
    if ($isAdmin) {
        echo "  &nbsp; ";
        echo "<a href='?m=user_games'>&lt;&lt; " . get_lang('back_to_game_servers') . "</a>";
    }
    echo "  &nbsp; ";
    echo "<a href='?m=user_games&p=edit&home_id={$home_id}'>&lt;&lt; " . get_lang('back_to_edit_server') . "</a>";
    echo "</p>";
    if (isset($_POST['update_settings'])) {
        $save_field = $_POST['fields'];
        $db->changeCustomFields($home_info['home_id'], json_encode($save_field));
        print_success(get_lang('settings_updated'));
        $view->refresh("?m=user_games&p=custom_fields&home_id=" . $home_id);
    }
    $ft = new FormTable();
    $ft->start_form("", "post", "autocomplete=\"off\"");
    $ft->start_table();
    foreach ($server_xml->custom_fields->field as $field) {
        renderCustomFields($field, $home_info['home_id']);
    }
    $ft->end_table();
    $ft->add_button("submit", "update_settings", get_lang('update_settings'));
    $ft->end_form();
}
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 = isset($_REQUEST['home_id']) ? $_REQUEST['home_id'] : "";
    $mod_id = isset($_REQUEST['mod_id']) ? $_REQUEST['mod_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 || preg_match("/u/", $home_info['access_rights']) != 1) {
        print_failure(get_lang('no_rights'));
        echo "<table class='center'><tr><td><a href='?m=gamemanager&amp;p=game_monitor&amp;home_id=" . $home_info['home_id'] . "'><< " . get_lang('back') . "</a></td></tr></table>";
        return;
    }
    $game_type = $home_info['game_key'];
    echo "<h2>Updating game server <em>" . $home_info['home_name'] . "</em></h2>";
    $server_xml = read_server_config(SERVER_CONFIG_LOCATION . "/" . $home_info['home_cfg_file']);
    if ($server_xml->installer != "steamcmd") {
        print_failure(get_lang('xml_steam_error'));
        return;
    }
    $remote = new OGPRemoteLibrary($home_info['agent_ip'], $home_info['agent_port'], $home_info['encryption_key']);
    $host_stat = $remote->status_chk();
    if ($remote->is_screen_running(OGP_SCREEN_TYPE_HOME, $home_id) == 1) {
        print_failure(get_lang('server_running_cant_update'));
        return;
    }
    $log_txt = '';
    $update_active = $remote->get_log(OGP_SCREEN_TYPE_UPDATE, $home_id, clean_path($home_info['home_path']), $log_txt);
    $modkey = $home_info['mods'][$mod_id]['mod_key'];
    $mod_xml = xml_get_mod($server_xml, $modkey);
    if (!$mod_xml) {
        print_failure(get_lang_f('mod_key_not_found_from_xml', $modkey));
        return;
    }
    if ($update_active === 0) {
        print_failure(get_lang('agent_offline'));
        echo "<meta http-equiv='refresh' content='5'>";
        return;
    } else {
        if ($_REQUEST['update'] == 'update' && $update_active != 1) {
            $installer_name = $modkey;
            if (isset($mod_xml->installer_name)) {
                $installer_name = $mod_xml->installer_name;
            }
            $mod_cfg_id = $home_info['mod_cfg_id'];
            $game_mod_precmd = $db->resultQuery("SELECT DISTINCT precmd FROM OGP_DB_PREFIXgame_mods WHERE mod_id='{$mod_id}'");
            if ($game_mod_precmd[0]['precmd'] === NULL or empty($game_mod_precmd[0]['precmd'])) {
                $config_mod_precmd = $db->resultQuery("SELECT DISTINCT def_precmd FROM OGP_DB_PREFIXconfig_mods WHERE mod_cfg_id='{$mod_cfg_id}'");
                if ($config_mod_precmd[0]['def_precmd'] === NULL or empty($config_mod_precmd[0]['def_precmd'])) {
                    $precmd = "";
                } else {
                    $precmd = $config_mod_precmd[0]['def_precmd'];
                }
            } else {
                $precmd = $game_mod_precmd[0]['precmd'];
            }
            $game_mod_postcmd = $db->resultQuery("SELECT DISTINCT postcmd FROM OGP_DB_PREFIXgame_mods WHERE mod_id='{$mod_id}'");
            if ($game_mod_postcmd[0]['postcmd'] === NULL or empty($game_mod_postcmd[0]['postcmd'])) {
                $config_mod_postcmd = $db->resultQuery("SELECT DISTINCT def_postcmd FROM OGP_DB_PREFIXconfig_mods WHERE mod_cfg_id='{$mod_cfg_id}'");
                if ($config_mod_postcmd[0]['def_postcmd'] === NULL or empty($config_mod_postcmd[0]['def_postcmd'])) {
                    $postcmd = "";
                } else {
                    $postcmd = $config_mod_postcmd[0]['def_postcmd'];
                }
            } else {
                $postcmd = $game_mod_postcmd[0]['postcmd'];
            }
            $exec_folder_path = clean_path($home_info['home_path'] . "/" . $server_xml->exe_location);
            $exec_path = clean_path($exec_folder_path . "/" . $server_xml->server_exec_name);
            if (isset($_REQUEST['master_server_home_id'])) {
                $ms_home_id = $_REQUEST['master_server_home_id'];
                $ms_info = $db->getGameHome($ms_home_id);
                $steam_out = $remote->masterServerUpdate($home_id, $home_info['home_path'], $ms_home_id, $ms_info['home_path'], $exec_folder_path, $exec_path, $precmd, $postcmd);
            } else {
                if (preg_match("/win32/", $server_xml->game_key) or preg_match("/win64/", $server_xml->game_key)) {
                    $cfg_os = "windows";
                } elseif (preg_match("/linux/", $server_xml->game_key)) {
                    $cfg_os = "linux";
                }
                $settings = $db->getSettings();
                // Some games like L4D2 require anonymous login
                if ($mod_xml->installer_login) {
                    $login = $mod_xml->installer_login;
                    $pass = '';
                } else {
                    $login = $settings['steam_user'];
                    $pass = $settings['steam_pass'];
                }
                $modname = ($installer_name == '90' and !preg_match("/(cstrike|valve)/", $modkey)) ? $modkey : '';
                $betaname = isset($mod_xml->betaname) ? $mod_xml->betaname : '';
                $betapwd = isset($mod_xml->betapwd) ? $mod_xml->betapwd : '';
                $steam_out = $remote->steam_cmd($home_id, $home_info['home_path'], $installer_name, $modname, $betaname, $betapwd, $login, $pass, $settings['steam_guard'], $exec_folder_path, $exec_path, $precmd, $postcmd, $cfg_os);
            }
            if ($steam_out === 0) {
                print_failure(get_lang('failed_to_start_steam_update'));
                return;
            } else {
                if ($steam_out === 1) {
                    print_success(get_lang('update_started'));
                } else {
                    if ($host_stat === 0) {
                        print_failure(get_lang('agent_offline'));
                        $view->refresh("?m=gamemanager&amp;p=update&amp;update=refresh&amp;home_id={$home_id}&amp;mod_id={$mod_id}", 5);
                        return;
                    }
                    echo "Installing Steam... wait.";
                    $steamcmdtrue = isset($_REQUEST['steamcmd']) ? "&amp;steamcmd=true" : "";
                    $view->refresh("?m=gamemanager&amp;p=update&amp;update=update&amp;home_id={$home_id}&amp;mod_id={$mod_id}{$steamcmdtrue}", 5);
                    return;
                }
            }
        } else {
            if (isset($_POST['stop_update_x'])) {
                $stop_update = sprintf("screen -S OGP_UPDATE_%09d -X quit", $home_id);
                $remote->exec("{$stop_update}");
            }
            $update_complete = false;
            if ($update_active == 1) {
                echo "<p class='note'>" . get_lang('update_in_progress') . "</p>\n";
                echo "<form method=POST><input type='image' name='stop_update' onsubmit='submit-form();' src='modules/administration/images/remove.gif'>" . get_lang('stop_update') . "</input></form>";
            } else {
                echo "<meta http-equiv='refresh' content='60'>";
                print_success(get_lang('update_completed'));
                echo "<table class='center'><tr><td><a href='?m=gamemanager&amp;p=game_monitor&amp;home_id=" . $home_info['home_id'] . "'><< " . get_lang('back') . "</a></td></tr></table>";
                $update_complete = true;
            }
            if (empty($log_txt)) {
                $log_txt = get_lang('not_available');
            }
            echo "<pre>" . $log_txt . "</pre>\n";
            if ($update_complete) {
                return;
            }
        }
    }
    echo "<p><a href=\"?m=gamemanager&amp;p=update&amp;update=refresh&amp;home_id={$home_id}&amp;mod_id={$mod_id}\">";
    echo get_lang('refresh_steam_status') . "</a></p>";
    $view->refresh("?m=gamemanager&amp;p=update&amp;update=refresh&amp;home_id={$home_id}&amp;mod_id={$mod_id}", 5);
    return;
}
function exec_ogp_module()
{
    global $db, $settings;
    $isAdmin = $db->isAdmin($_SESSION['user_id']);
    $OnlineServers = "";
    $OnlineServersTitle = "";
    if (isset($settings['welcome_title']) && $settings['welcome_title'] == "1") {
        if (isset($settings['welcome_title_message']) && !empty($settings['welcome_title_message'])) {
            echo "<div>" . $settings['welcome_title_message'] . "</div>";
        }
    }
    $OnlineServersTitle .= get_lang('online_servers');
    $player_list = "";
    if ($isAdmin) {
        $server_homes = $db->getIpPorts();
    } else {
        $OnlineServersTitle = "Open Game Panel";
        $OnlineServers .= "<p>" . get_lang("welcome_text") . "</p><br><b>" . get_lang('online_servers') . ":</b><br><br>";
        $server_homes = $db->getIpPortsForUser($_SESSION['user_id']);
    }
    require_once "includes/refreshed.php";
    $refresh = new refreshed();
    if (!$server_homes) {
        $OnlineServers .= "<p class='failure'>" . get_lang('no_games_to_monitor') . "</p>";
        if ($isAdmin) {
            //$OnlineServers .= "<p class='note'>".get_lang('add_games_in').
            //"&nbsp;<a href='?m=user_games&amp;p=add'>".get_lang('game_servers')."</a></p>";
            $OnlineServers .= "<p class='note'>" . get_lang_f("add_games_in", "<a href='?m=user_games&amp;p=add'>" . get_lang('game_servers') . "</a>") . "</p>";
        }
    } else {
        if (isset($settings['old_dashboard_behavior']) and $settings['old_dashboard_behavior'] == 1) {
            $serverslist = $refresh->add("home.php?m=dashboard&p=query_ref&show=servers&type=cleared");
            $playerslist = $refresh->add("home.php?m=dashboard&p=query_ref&show=players&type=cleared");
            $OnlineServers .= $refresh->getdiv($serverslist);
            $player_list .= $refresh->getdiv($playerslist);
        } else {
            $player_list = "";
            $stats_servers = 0;
            $stats_servers_online = 0;
            $stats_players = 0;
            $stats_maxplayers = 0;
            $onlinePlayers = "";
            $OnlineServers .= "<table style='width:100%;' class='online_servers'>";
            require_once "protocol/lgsl/lgsl_protocol.php";
            foreach ($server_homes as $server_home) {
                $remote_server_id = $server_home['remote_server_id'];
                $rserver = $db->getRemoteServerById($remote_server_id);
                // Count the number of servers.
                $stats_servers++;
                // Remember to clear the old value here.
                $message = "";
                $remote = new OGPRemoteLibrary($server_home['agent_ip'], $server_home['agent_port'], $server_home['encryption_key']);
                $host_stat = $remote->status_chk();
                if ($host_stat === 1) {
                    // Check if the screen running the server is running.
                    $screen_running = $remote->is_screen_running(OGP_SCREEN_TYPE_HOME, $server_home['home_id']) === 1;
                    $server_xml = read_server_config(SERVER_CONFIG_LOCATION . "/" . $server_home['home_cfg_file']);
                    if ($screen_running) {
                        // Check if the screen running the server is running.
                        if ($server_home['use_nat'] == 1) {
                            $ip = $server_home['agent_ip'];
                        } else {
                            $ip = $server_home['ip'];
                        }
                        $port = $server_home['port'];
                        $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'];
                        if ($server_xml->protocol == "lgsl") {
                            $address = "<a href='" . lgsl_software_link($server_xml->lgsl_query_name, $ip, $c_port, $q_port, $s_port) . "'>" . $ip . ":" . $port . "</a>";
                        }
                        if ($server_xml->protocol == "teamspeak3") {
                            $address = "<a href='ts3server://{$ip}:{$port}'>{$ip}:{$port}</a>";
                        } elseif ($server_xml->protocol == "gameq" and $server_xml->installer == "steam") {
                            $address = "<a href='steam://connect/{$ip}:{$port}'>{$ip}:{$port}</a>";
                        } elseif ($server_xml->protocol == "gameq" or !isset($server_xml->protocol)) {
                            $address = "{$ip}:{$port}";
                        }
                        $OnlineServers .= "<tr><td><div class='name' ><a href='?m=gamemanager&amp;p=game_monitor&amp;home_id-mod_id-ip-port=" . $server_home['home_id'] . "-" . $server_home['mod_id'] . "-" . $server_home['ip'] . "-" . $server_home['port'] . "' ><img style='border:0;height:12px;' src='images/magnifglass.png'/>" . $server_home['home_name'] . "</a></div> | ";
                        $OnlineServers .= "<div id='gamelink' >{$address}</div>";
                        $OnlineServers .= "</td></tr>";
                        $stats_servers_online++;
                    }
                }
                unset($map, $player_list, $status, $ip, $port, $players, $playersmax, $name, $map, $mod, $xml_mod, $qport, $address, $maplocation);
            }
            $OnlineServers .= "</table>";
            $OnlineServers .= "<center>" . get_lang('statistics') . ":<br>{$stats_servers_online}/{$stats_servers} " . get_lang('online_servers') . "</center>";
        }
    }
    ?>
	<div style="margin-top:20px;">    
	<?php 
    //$title[$id] = "The Title";
    //$content[$id] = "Content of the Widget";
    $title = array();
    $content = array();
    $href = array();
    // Game Monitor
    $title[1] = get_lang('game_monitor');
    $content[1] = '<img src="themes/' . $settings['theme'] . '/images/icons/game_monitor.png" style="width:48px;float:right;margin:0 0 0 8px" />' . get_lang('dashboard_game_monitor_text');
    $href[1] = 'home.php?m=gamemanager&p=game_monitor';
    // Online Server
    $title[2] = $OnlineServersTitle;
    $content[2] = $OnlineServers;
    $href[2] = null;
    // Currently Online
    $title[3] = get_lang('currently_online');
    $content[3] = $player_list;
    $href[3] = null;
    // FTP
    $title[4] = get_lang('ftp');
    $content[4] = '<img src="themes/' . $settings['theme'] . '/images/icons/folder.png" style="width:48px;float:right;margin:0 0 0 8px" />' . get_lang('dashboard_ftp_text');
    $href[4] = 'home.php?m=ftp';
    // Support
    $title[5] = get_lang('support');
    $content[5] = '<img src="themes/' . $settings['theme'] . '/images/icons/support.png" style="width:48px;float:right;margin:0 0 0 8px" />' . get_lang('dashboard_support_text');
    $href[5] = 'http://www.opengamepanel.org/forum';
    $columns = array();
    $columns[1]['column_id'] = 1;
    $columns[2]['column_id'] = 2;
    $columns[3]['column_id'] = 3;
    foreach ($columns as $column) {
        echo '<div class="column ';
        if ($column['column_id'] == 1) {
            echo 'one_fourth';
        } else {
            if ($column['column_id'] == 2) {
                echo 'one_two';
            } else {
                if ($column['column_id'] == 3) {
                    echo 'one_fourth';
                }
            }
        }
        echo '" id="column' . $column['column_id'] . '" >';
        $items = $db->resultQuery("SELECT * FROM OGP_DB_PREFIXwidgets_users WHERE column_id='" . $column['column_id'] . "' AND user_id='" . $_SESSION['user_id'] . "' ORDER BY sort_no");
        if ($items) {
            foreach ($items as $widget) {
                if ((!isset($settings['old_dashboard_behavior']) or $settings['old_dashboard_behavior'] == 0) and $widget['widget_id'] == "3") {
                    continue;
                }
                echo ' 
				<div class="dragbox bloc rounded" id="item' . $widget['widget_id'] . '"> 
					<h4><span class="configure"></span>';
                if (!is_null($title[$widget['widget_id']])) {
                    echo $title[$widget['widget_id']];
                }
                echo '</h4> 
						<div class="dragbox-content" ';
                if (!is_null($href[$widget['widget_id']])) {
                    echo "onclick=\"location.href='" . $href[$widget['widget_id']] . "'\" style=\"cursor:pointer;";
                    if ($widget['collapsed'] == 1) {
                        echo 'display:none;';
                    }
                    echo '"';
                } elseif ($widget['collapsed'] == 1) {
                    echo 'style="display:none;"';
                }
                echo '>';
                if (!is_null($content[$widget['widget_id']])) {
                    echo $content[$widget['widget_id']];
                }
                echo ' 
					</div> 
				</div>';
                unset($widget);
            }
        }
        echo '</div>';
    }
    if ($isAdmin and $db->isModuleInstalled('status')) {
        echo "<h0>Server Status</h0><br>";
        $servers = $db->getRemoteServers();
        echo "<div style='float:left;width:40%;' >\n\t\t\t   <div class='bloc rounded' >\n\t\t\t   <h4>Select remote server</h4>\n\t\t\t    <div>\n\t\t\t\t<br>\n\t\t\t\t<center>\n\t\t\t    <form action='' method='GET'>\n\t\t\t    <input type='hidden' name='m' value='" . $_GET['m'] . "'/>\n\t\t\t    <input type='hidden' name='p' value='" . $_GET['p'] . "'/>\n\t\t\t    <select name='remote_server_id' onchange=" . '"this.form.submit()"' . ">\n";
        foreach ($servers as $server_row) {
            if (!empty($server_row['remote_server_id']) and !isset($_GET['remote_server_id']) or !empty($server_row['remote_server_id']) and empty($_GET['remote_server_id'])) {
                $_GET['remote_server_id'] = $server_row['remote_server_id'];
            }
            if (isset($_GET['remote_server_id']) and $_GET['remote_server_id'] == $server_row['remote_server_id']) {
                $rhost_id = $_GET['remote_server_id'];
                $remote_server = $db->getRemoteServer($rhost_id);
                $remote = new OGPRemoteLibrary($remote_server['agent_ip'], $remote_server['agent_port'], $remote_server['encryption_key']);
                $host_stat = $remote->status_chk();
                if ($host_stat === 1) {
                    $checked = "selected='selected'";
                } else {
                    $checked = '';
                    $_GET['remote_server_id'] = 'webhost';
                }
            } else {
                $checked = '';
            }
            echo "<option value='" . $server_row['remote_server_id'] . "' {$checked} >" . $server_row['remote_server_name'] . "</option>\n";
        }
        if (function_exists('exec')) {
            $checked = (isset($_GET['remote_server_id']) and $_GET['remote_server_id'] == 'webhost') ? "selected='selected'" : "";
            echo "<option value='webhost' {$checked} >Webhost Status</option>";
        }
        echo "\t</select>\n\t\t\t    </form>\n\t\t\t\t</center>\n\t\t\t\t<br><br>\n\t\t\t    </div>\n\t\t\t   </div>\n\t\t\t  </div>\n";
        if (isset($_GET['remote_server_id']) and $_GET['remote_server_id'] == "webhost") {
            unset($_GET['remote_server_id']);
        }
        if (isset($_GET['remote_server_id']) && !empty($_GET['remote_server_id'])) {
            $remote_server = "&remote_server_id=" . $_GET['remote_server_id'];
        } else {
            $remote_server = "";
        }
        if ($isAdmin and $db->isModuleInstalled('status') and (isset($_GET['remote_server_id']) or function_exists('exec'))) {
            $status = $refresh->add("home.php?m=status&type=cleared" . $remote_server);
            echo $refresh->getdiv($status);
        }
    }
    ?>
	
<script type="text/javascript">
var userAgent = navigator.userAgent.toLowerCase(),
	browser   = '',
	version   = 0;

$.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase());

// Is this a version of IE?
if ($.browser.msie) {
  userAgent = $.browser.version;
  userAgent = userAgent.substring(0,userAgent.indexOf('.'));
  version = userAgent;
  browser = "Internet Explorer";
}

// Is this a version of Chrome?
if ($.browser.chrome) {
  userAgent = userAgent.substring(userAgent.indexOf('chrome/') + 7);
  userAgent = userAgent.substring(0,userAgent.indexOf('.'));
  version = userAgent;
  // If it is chrome then jQuery thinks it's safari so we have to tell it it isn't
  $.browser.safari = false;
  browser = "Chrome";
}

// Is this a version of Safari?
if ($.browser.safari) {
  userAgent = userAgent.substring(userAgent.indexOf('safari/') + 7);
  userAgent = userAgent.substring(0,userAgent.indexOf('.'));
  version = userAgent;
  browser = "Safari";
}

// Is this a version of Mozilla?
if ($.browser.mozilla) {
	//Is it Firefox?
	if (navigator.userAgent.toLowerCase().indexOf('firefox') != -1) {
		userAgent = userAgent.substring(userAgent.indexOf('firefox/') + 8);
		userAgent = userAgent.substring(0,userAgent.indexOf('.'));
		version = userAgent;
		browser = "Firefox"
	}
	// If not then it must be another Mozilla
	else {
	  browser = "Mozilla (not Firefox)"
	}
}

// Is this a version of Opera?
if ($.browser.opera) {
	userAgent = userAgent.substring(userAgent.indexOf('version/') + 8);
	userAgent = userAgent.substring(0,userAgent.indexOf('.'));
	version = userAgent;
	browser = "Opera";
}

// Now you have two variables, browser and version
// which have the right info
$(document).ready(
	function(){  
		$('.dragbox')  
		.each(function(){  
			$(this).hover(function(){  
				$(this).find('h4').addClass('collapse'); 
			}, function(){  
			$(this).find('h4').removeClass('collapse');  
			})  
			.find('h4').hover(function(){  
				$(this).find('.configure').css('visibility', 'visible'); 
			}, function(){  
				$(this).find('.configure').css('visibility', 'hidden');  
			})  
			.click(function(){  
				$(this).siblings('.dragbox-content').toggle();  
				//Save state on change of collapse state of panel  
				updateWidgetData();  
			})  
			.end()  
			.find('.configure').css('visibility', 'hidden');  
		});  
	  
		$('.column').sortable({  
			connectWith: '.column',  
			handle: 'h4',  
			cursor: 'move',  
			placeholder: 'placeholder',  
			forcePlaceholderSize: true,  
			opacity: 0.4,   
			start: function(event, ui){
				//Firefox, Safari/Chrome fire click event after drag is complete, fix for that
				if(browser == "Firefox" || browser == "Mozilla (not Firefox)" || browser == "Safari") 
					$(ui.item).find('.dragbox-content').toggle();
			},
			stop: function(){  
				updateWidgetData();  
			}
		})  
		.disableSelection();  
	}  
);
function updateWidgetData(){  
	var items=[];  
	$('.column').each(function(){  
		var columnId=$(this).attr('id');  
		$('.dragbox', this).each(function(i){  
			var collapsed=0;  
			if($(this).find('.dragbox-content').css('display')=="none")  
				collapsed=1;  
			//Create Item object for current panel  
			var item={  
				id: $(this).attr('id'),  
				collapsed: collapsed,  
				order : i,  
				column: columnId  
			};  
			//Push item object into items array  
			items.push(item);  
		});  
	});  
	//Assign items array to sortorder JSON variable  
	var sortorder={ items: items };  
	//Pass sortorder variable to server using ajax to save state  
	$.post('home.php?m=dashboard&p=updateWidgets', 'data='+$.toJSON(sortorder), function(response){ 
		if(response.indexOf("success") < 0){
			$("#console").html('<h0><div class="Failed">Failed to save you\'r operation! Please contact OGP...</div></h0>').hide().fadeIn(1000);  
		}
	});  
}

$(document).ready(function(){ 
	<?php 
    echo $refresh->build("20000");
    ?>
});
</script>
<?php 
}
function exec_ogp_module()
{
    global $db;
    $isAdmin = $db->isAdmin($_SESSION['user_id']);
    $submit = isset($_REQUEST['submit']) ? $_REQUEST['submit'] : "";
    $home_id = $_GET['home_id'];
    $enabled_mods = $db->getHomeMods($home_id);
    if ($isAdmin and isset($_POST['change_home_cfg_id'])) {
        if (!empty($enabled_mods)) {
            foreach ($enabled_mods as $enabled_rows) {
                $db->delGameMod($enabled_rows['mod_id']);
            }
        }
        $home_cfg_id = $game_home['home_cfg_id'];
        $new_home_cfg_id = $_POST['home_cfg_id'];
        if ($db->updateHomeCfgId($home_id, $new_home_cfg_id)) {
            print_success(get_lang('successfully_changed_game_server'));
            $db->logger(get_lang('successfully_changed_game_server') . " HOME ID:{$home_id} - " . get_lang('change_game_type') . ":old home_cfg_id:{$home_cfg_id}, new home_cfg_id:{$new_home_cfg_id}");
        }
        $enabled_mods = $db->getHomeMods($home_id);
    }
    if ($isAdmin) {
        $game_home = $db->getGameHome($_GET['home_id']);
    } else {
        $game_home = $db->getUserGameHome($_SESSION['user_id'], $_GET['home_id']);
    }
    if (!$game_home and !$isAdmin) {
        return;
    }
    $home_info = $db->getGameHomeWithoutMods($home_id);
    $server_xml = read_server_config(SERVER_CONFIG_LOCATION . $home_info['home_cfg_file']);
    include 'includes/lib_remote.php';
    $remote = new OGPRemoteLibrary($home_info['agent_ip'], $home_info['agent_port'], $home_info['encryption_key']);
    $ftp_installed = $db->isModuleInstalled('ftp');
    $screen_running = $remote->is_screen_running(OGP_SCREEN_TYPE_HOME, $home_info['home_id']) === 1;
    if ($isAdmin) {
        $game_home['access_rights'] = "ufpet";
    }
    echo "<h2>" . get_lang('editing_home_called') . " \"" . $home_info['home_name'] . "\"</h2>";
    if (isset($_REQUEST['change_name'])) {
        $server_name = $_POST['server_name'];
        if ($db->changeHomeName($home_id, $server_name) === TRUE) {
            print_success(get_lang('successfully_changed_game_server'));
            $db->logger(get_lang('successfully_changed_game_server') . " HOME ID:{$home_id} - " . get_lang('game_server_name') . ":{$server_name}");
        } else {
            print_failure("Name update failed.");
        }
    } elseif (isset($_REQUEST['change_control_password'])) {
        $control_password = $_POST['control_password'];
        if ($db->changeHomeControlPassword($home_id, $control_password) === TRUE) {
            print_success(get_lang('control_password_updated_successfully'));
            $db->logger(get_lang('control_password_updated_successfully') . " HOME ID:{$home_id} - " . get_lang('game_control_password') . ":{$control_password}");
        } else {
            print_failure(get_lang('control_password_update_failed'));
        }
    } elseif (isset($_REQUEST['change_ftp_login']) && preg_match("/t/", $game_home['access_rights']) > 0) {
        // Is FTP Module Installed?
        if ($ftp_installed) {
            if ($db->IsFtpEnabled($home_id) or $isAdmin) {
                $post_ftp_login = trim($_POST['ftp_login']);
                $host_stat = $remote->status_chk();
                $user_exists = FALSE;
                $host_online = FALSE;
                if ($host_stat === 1) {
                    $host_online = TRUE;
                    $ftp_accounts_list = $remote->ftp_mgr("list");
                    $ftp_accounts = explode("\n", $ftp_accounts_list);
                    foreach ($ftp_accounts as $ftp_account) {
                        if ($ftp_account != "") {
                            list($ftp_login, $ftp_path) = explode("\t", $ftp_account);
                            $ftp_login = trim($ftp_login);
                            if ($ftp_login == $post_ftp_login) {
                                $user_exists = TRUE;
                                break;
                            }
                        }
                    }
                }
                if ($host_online and !$user_exists) {
                    $old_login = isset($home_info['ftp_login']) ? $home_info['ftp_login'] : $home_id;
                    $change_login_delete_old = $remote->ftp_mgr("userdel", $old_login);
                    if ($change_login_delete_old !== 0) {
                        $change_login_add_new = $remote->ftp_mgr("useradd", $post_ftp_login, $home_info['ftp_password'], $home_info['home_path']);
                    }
                    if (isset($change_login_add_new) and $change_login_add_new !== 0) {
                        if ($db->changeFtpLogin($home_id, $post_ftp_login) === TRUE) {
                            print_success(get_lang('successfully_changed_game_server'));
                            $db->logger(get_lang('successfully_changed_game_server') . " HOME ID:{$home_id} - " . get_lang('server_ftp_login') . ":{$post_ftp_login}");
                        }
                    } else {
                        print_failure(get_lang('error_ocurred_on_remote_server') . " " . get_lang('ftp_login_can_not_be_changed'));
                    }
                } else {
                    print_failure(get_lang('error_ocurred_on_remote_server') . " " . get_lang('ftp_login_can_not_be_changed'));
                }
            }
        }
    } elseif (isset($_REQUEST['change_ftp_password']) && preg_match("/t/", $game_home['access_rights']) > 0) {
        // Is FTP Module Installed?
        if ($ftp_installed) {
            if ($db->IsFtpEnabled($home_id) or $isAdmin) {
                $ftp_password = $_POST['ftp_password'];
                $ftp_login = isset($home_info['ftp_login']) ? $home_info['ftp_login'] : $home_id;
                $change_passwd_on_remote = $remote->ftp_mgr("passwd", $ftp_login, $ftp_password);
                if ($change_passwd_on_remote !== 0) {
                    if ($db->changeFtpPassword($home_id, clean_path($ftp_password)) === TRUE) {
                        print_success(get_lang('successfully_changed_game_server'));
                        $db->logger(get_lang('successfully_changed_game_server') . " HOME ID:{$home_id} - " . get_lang('server_ftp_password') . ":{$ftp_password}");
                    }
                } else {
                    print_failure(get_lang('error_ocurred_on_remote_server') . " " . get_lang('ftp_password_can_not_be_changed'));
                }
            }
        }
    } elseif (isset($_POST["force_mod_id"])) {
        $force_mod_id = $_POST['force_mod_id'];
        $ip_id = $_POST['ip_id'];
        $port = $_POST['port'];
        if ($db->forceModAtAddress($ip_id, $port, $force_mod_id)) {
            print_success(get_lang('successfully_assigned_mod_to_address'));
            $db->logger(get_lang('successfully_assigned_mod_to_address'));
        } else {
            print_failure("Failed to assign mod to address.");
        }
    } elseif ($isAdmin) {
        if (isset($_REQUEST['create_ftp'])) {
            $login = isset($home_info['ftp_login']) ? $home_info['ftp_login'] : $home_id;
            $create_ftp = $remote->ftp_mgr("useradd", $login, $home_info['ftp_password'], $home_info['home_path']);
            if ($create_ftp === 0) {
                print_failure(get_lang('error_ocurred_on_remote_server') . " " . get_lang('ftp_can_not_be_switched_on'));
            } else {
                $db->changeFtpStatus('enabled', $home_id);
                print_success(get_lang('successfully_changed_game_server'));
                $db->logger(get_lang('successfully_changed_game_server') . " HOME ID:{$home_id} - " . get_lang('change_ftp_account_status') . ":enabled");
            }
        } else {
            if (isset($_REQUEST['delete_ftp'])) {
                $login = isset($home_info['ftp_login']) ? $home_info['ftp_login'] : $home_id;
                $delete_ftp = $remote->ftp_mgr("userdel", $login);
                if ($delete_ftp === 0) {
                    print_failure(get_lang('error_ocurred_on_remote_server') . " " . get_lang('ftp_can_not_be_switched_off'));
                } else {
                    $db->changeFtpStatus('disabled', $home_id);
                    print_success(get_lang('successfully_changed_game_server'));
                    $db->logger(get_lang('successfully_changed_game_server') . " HOME ID:{$home_id} - " . get_lang('change_ftp_account_status') . ":disabled");
                }
            } else {
                if (isset($_REQUEST['change_user_id_main'])) {
                    $user_id_main = $_POST['user_id_main'];
                    if (isset($_POST['deleteoldassigns'])) {
                        $db->unassignHomeFrom("user", $home_info['user_id_main'], $home_id);
                        $home_groups = $db->getGroupsForHome($home_info['home_id']);
                        if (isset($home_groups)) {
                            foreach ($home_groups as $home_group) {
                                $db->unassignHomeFrom("group", $home_group['group_id'], $home_id);
                            }
                        }
                    }
                    $old_home = $db->getUserGameHome($home_info['user_id_main'], $home_id);
                    if ($db->changeUserIdMain($home_id, clean_path($user_id_main)) === TRUE && $db->assignHomeTo("user", $user_id_main, $home_id, $old_home['access_rights']) === TRUE) {
                        print_success(get_lang('successfully_changed_game_server'));
                        $db->logger(get_lang('successfully_changed_game_server') . " HOME ID:{$home_id} - " . get_lang('change_user_id_main') . ":{$user_id_main}");
                    }
                } else {
                    if (isset($_REQUEST['change_home'])) {
                        $home_path = $_POST['home_path'];
                        if ($db->changeHomePath($home_id, clean_path($home_path)) === TRUE) {
                            if ($ftp_installed) {
                                if ($db->IsFtpEnabled($home_id)) {
                                    $login = isset($home_info['ftp_login']) ? $home_info['ftp_login'] : $home_id;
                                    $delte_old_ftp_account = $remote->ftp_mgr("userdel", $login);
                                    if ($delte_old_ftp_account !== 0) {
                                        $create_new_ftp_account = $remote->ftp_mgr("useradd", $login, $home_info['ftp_password'], $home_path);
                                    }
                                    if (isset($create_new_ftp_account) and $create_new_ftp_account !== 0) {
                                        print_success(get_lang('successfully_changed_game_server'));
                                        $db->logger(get_lang('successfully_changed_game_server') . " HOME ID:{$home_id} - " . get_lang('home_path') . ":{$home_path}");
                                    } else {
                                        print_failure(get_lang('error_ocurred_on_remote_server') . " " . get_lang('ftp_login_can_not_be_changed'));
                                    }
                                } else {
                                    print_success(get_lang('successfully_changed_game_server'));
                                    $db->logger(get_lang('successfully_changed_game_server') . " HOME ID:{$home_id} - " . get_lang('home_path') . ":{$home_path}");
                                }
                            } else {
                                print_success(get_lang('successfully_changed_game_server'));
                                $db->logger(get_lang('successfully_changed_game_server') . " HOME ID:{$home_id} - " . get_lang('home_path') . ":{$home_path}");
                            }
                        }
                    } else {
                        if (isset($_REQUEST['master_server'])) {
                            if (isset($_POST['add'])) {
                                $action = "add";
                            } else {
                                $action = "remove";
                            }
                            if ($db->setMasterServer($action, $home_id, $home_info['home_cfg_id'], $home_info['remote_server_id']) === TRUE) {
                                print_success(get_lang('successfully_changed_game_server'));
                                $db->logger(get_lang('successfully_changed_game_server') . " HOME ID:{$home_id} - " . get_lang('set_as_master_server') . ":{$action}");
                            }
                        }
                    }
                }
            }
        }
        if (isset($_REQUEST['add_mod'])) {
            $mod_cfg_id = $_POST['mod_cfg_id'];
            if ($db->addModToGameHome($home_id, $mod_cfg_id) === FALSE) {
                print_failure(get_lang_f('failed_to_assing_mod_to_home', $mod_cfg_id));
            } else {
                print_success(get_lang_f('successfully_assigned_mod_to_home', $mod_cfg_id));
                $db->logger(get_lang_f('successfully_assigned_mod_to_home', $mod_cfg_id) . " [HOME ID:{$home_id}]");
            }
        } else {
            if ($submit == "delete_mod") {
                $mod_id = $_GET['mod_id'];
                if ($db->delGameMod($mod_id) === TRUE) {
                    print_success(get_lang('successfully_removed_mod'));
                }
                $db->logger(get_lang('successfully_removed_mod') . " [MOD ID:{$mod_id} HOME ID:{$home_id}]");
            } else {
                if (isset($_REQUEST['set_options'])) {
                    $maxplayers = 0 + @$_POST['maxplayers'];
                    $cliopts = $_POST['cliopts'];
                    $cpus = $_POST['cpus'];
                    $nice = $_POST['nice'];
                    $mod_cfg_id = $_POST['mod_cfg_id'];
                    $db->updateGameModParams($maxplayers, $cliopts, $cpus, $nice, $home_id, $mod_cfg_id);
                    print_success(get_lang("successfully_modified_mod"));
                    $db->logger(get_lang('successfully_modified_mod') . " [MOD CFG ID:{$mod_cfg_id} HOME ID:{$home_id}]");
                    echo "<meta http-equiv='refresh' content='2'>";
                }
            }
        }
    }
    $home_info = $db->getGameHomeWithoutMods($home_id);
    $custom_fileds_access_enabled = preg_match("/c/", $game_home['access_rights']) > 0 ? TRUE : FALSE;
    echo "<p>";
    echo "<a href='?m=gamemanager&p=game_monitor&home_id={$home_id}'>&lt;&lt; " . get_lang('back_to_game_monitor') . "</a>";
    if ($isAdmin) {
        echo " &nbsp; ";
        echo "<a href='?m=user_games'>&lt;&lt; " . get_lang('back_to_game_servers') . "</a>";
        $custom_fileds_access_enabled = TRUE;
    }
    if (isset($server_xml->custom_fields) and $custom_fileds_access_enabled) {
        echo " &nbsp; <a href='?m=user_games&p=custom_fields&home_id=" . $home_id . "'>" . get_lang('go_to_custom_fields') . " &gt;&gt;</a>";
    }
    echo "</p>";
    echo "<table class='center'>";
    if ($isAdmin) {
        // Form to change game type
        echo "<tr><td rowspan='2' class='right'>" . get_lang('game_type') . ":</td><td class='left'>";
        echo "<form action='?m=user_games&p=edit&home_id=" . $home_id . "' method='post'>";
        $game_cfgs = $db->getGameCfgs();
        $host_stat = $remote->status_chk();
        if ($host_stat === 1) {
            $os = $remote->what_os();
        } else {
            $os = "Unknown OS";
        }
        echo "<select name='home_cfg_id' >";
        // Linux 64 bits + wine
        if (preg_match("/Linux/", $os) and preg_match("/64/", $os) and preg_match("/wine/", $os)) {
            foreach ($game_cfgs as $row) {
                if (preg_match("/linux/", $row['game_key'])) {
                    $selected = $home_info['home_cfg_id'] == $row['home_cfg_id'] ? 'selected="selected"' : "";
                    echo "<option value='" . $row['home_cfg_id'] . "' {$selected}>" . $row['game_name'];
                    if (preg_match("/64/", $row['game_key'])) {
                        echo " (64 bit)";
                    }
                    echo "</option>\n";
                }
            }
            echo "<option style='background:black;color:white;' value=''>" . get_lang('wine_games') . ":</option>\n";
            foreach ($game_cfgs as $row) {
                if (preg_match("/win/", $row['game_key'])) {
                    $selected = $home_info['home_cfg_id'] == $row['home_cfg_id'] ? 'selected="selected"' : "";
                    echo "<option value='" . $row['home_cfg_id'] . "' {$selected}>" . $row['game_name'];
                    if (preg_match("/64/", $row['game_key'])) {
                        echo " (64 bit)";
                    }
                    echo "</option>\n";
                }
            }
        } elseif (preg_match("/Linux/", $os) and preg_match("/64/", $os)) {
            foreach ($game_cfgs as $row) {
                if (preg_match("/linux/", $row['game_key'])) {
                    $selected = $home_info['home_cfg_id'] == $row['home_cfg_id'] ? 'selected="selected"' : "";
                    echo "<option value='" . $row['home_cfg_id'] . "' {$selected}>" . $row['game_name'];
                    if (preg_match("/64/", $row['game_key'])) {
                        echo " (64 bit)";
                    }
                    echo "</option>\n";
                }
            }
        } elseif (preg_match("/Linux/", $os) and preg_match("/wine/", $os)) {
            foreach ($game_cfgs as $row) {
                if (preg_match("/linux32/", $row['game_key'])) {
                    $selected = $home_info['home_cfg_id'] == $row['home_cfg_id'] ? 'selected="selected"' : "";
                    echo "<option value='" . $row['home_cfg_id'] . "' {$selected}>" . $row['game_name'] . "</option>\n";
                }
            }
            echo "<option style='background:black;color:white;' value=''>" . get_lang('wine_games') . "</option>\n";
            foreach ($game_cfgs as $row) {
                if (preg_match("/win32/", $row['game_key'])) {
                    $selected = $home_info['home_cfg_id'] == $row['home_cfg_id'] ? 'selected="selected"' : "";
                    echo "<option value='" . $row['home_cfg_id'] . "' {$selected}>" . $row['game_name'] . "</option>\n";
                }
            }
        } elseif (preg_match("/Linux/", $os)) {
            foreach ($game_cfgs as $row) {
                if (preg_match("/linux32/", $row['game_key'])) {
                    $selected = $home_info['home_cfg_id'] == $row['home_cfg_id'] ? 'selected="selected"' : "";
                    echo "<option value='" . $row['home_cfg_id'] . "' {$selected}>" . $row['game_name'] . "</option>\n";
                }
            }
        } elseif (preg_match("/CYGWIN/", $os) and preg_match("/64/", $os)) {
            foreach ($game_cfgs as $row) {
                if (preg_match("/win/", $row['game_key'])) {
                    $selected = $home_info['home_cfg_id'] == $row['home_cfg_id'] ? 'selected="selected"' : "";
                    echo "<option value='" . $row['home_cfg_id'] . "' {$selected}>" . $row['game_name'];
                    if (preg_match("/64/", $row['game_key'])) {
                        echo " (64 bit)";
                    }
                    echo "</option>\n";
                }
            }
        } elseif (preg_match("/CYGWIN/", $os)) {
            foreach ($game_cfgs as $row) {
                if (preg_match("/win32/", $row['game_key'])) {
                    $selected = $home_info['home_cfg_id'] == $row['home_cfg_id'] ? 'selected="selected"' : "";
                    echo "<option value='" . $row['home_cfg_id'] . "' {$selected}>" . $row['game_name'] . "</option>\n";
                }
            }
        } elseif ($os == "Unknown OS") {
            foreach ($game_cfgs as $row) {
                $selected = $home_info['home_cfg_id'] == $row['home_cfg_id'] ? 'selected="selected"' : "";
                echo "<option value='" . $row['home_cfg_id'] . "' {$selected}>" . $row['game_name'];
                if (preg_match("/64/", $row['game_key'])) {
                    echo " (64 bit)";
                }
                echo "</option>\n";
            }
        }
        echo "</select>\n</td></tr>";
        echo "<tr><td class='left'><input type='submit' name='change_home_cfg_id' value='" . get_lang('change_game_type') . "' />";
        echo "</form></td></tr>";
        echo "<tr><td colspan='2' class='info'>" . get_lang('change_game_type_info') . "</td></tr>";
        // Form to edit main user.
        echo "<tr><td rowspan='3' class='right'>" . get_lang('user_id_main') . ":</td><td class='left'>";
        echo "<form action='?m=user_games&p=edit&home_id=" . $home_id . "' method='post'>";
        echo "<input type='hidden' name='home_id' value=\"{$home_id}\" />\n";
        echo "<select name='user_id_main'>";
        $user = $db->getUserById($home_info['user_id_main']);
        echo "<option value='" . $home_info['user_id_main'] . "'>" . $user['users_login'] . "</option>\n";
        $users = $db->getUserList();
        foreach ($users as $user) {
            // Only users and admins can be assigned homes... not subusers
            if (is_null($user['users_parent'])) {
                if ($home_info['user_id_main'] != $user['user_id']) {
                    echo "<option value='" . $user['user_id'] . "'>" . $user['users_login'] . "</option>\n";
                }
            }
        }
        echo "</select></td></tr>";
        echo "<tr><td><input type='checkbox' name='deleteoldassigns' id='deleteoldassigns' /><label for='deleteoldassigns' >" . get_lang('Delete_old_user_assigned_homes') . "</label></td></tr>";
        echo "<tr><td class='left'><input type='submit' name='change_user_id_main' value='" . get_lang('change_user_id_main') . "' />";
        echo "</form></td></tr>";
        echo "<tr><td colspan='2' class='info'>" . get_lang('change_user_id_main_info') . "</td></tr>";
        // Form to edit game path.
        echo "<tr><td class='right'>" . get_lang('home_path') . ":</td><td class='left'>";
        echo "<form action='?m=user_games&p=edit&home_id=" . $home_id . "' method='post'>";
        echo "<input type='hidden' name='home_id' value=\"{$home_id}\" />\n";
        echo "<input type='text' size='30' name='home_path' value=" . $home_info['home_path'] . " />";
        echo "<input type='submit' name='change_home' value='" . get_lang('change_home') . "' />";
        echo "</form></td></tr>";
        echo "<tr><td colspan='2' class='info'>" . get_lang('change_home_info') . "</td></tr>";
    }
    // Form to edit game name
    echo "<tr><td class='right'>" . get_lang('game_server_name') . ":</td><td class='left'>";
    echo "<form action='?m=user_games&p=edit&home_id=" . $home_id . "' method='post'>";
    echo "<input type='hidden' name='home_id' value=\"{$home_id}\" />\n";
    echo "<input type='text' size='30' name='server_name' value='" . $home_info['home_name'] . "' />";
    echo "<input type=submit name='change_name' value='" . get_lang('change_name') . "' />";
    echo "</form></td></tr>";
    echo "<tr><td colspan='2' class='info'>" . get_lang('change_name_info') . "</td></tr>";
    // Form to edit control password
    echo "<tr><td class='right'>" . get_lang('game_control_password') . ":</td><td class='left'>";
    echo "<form action='?m=user_games&p=edit&home_id=" . $home_id . "' method='post'>";
    echo "<input type='hidden' name='home_id' value=\"{$home_id}\" />\n";
    echo "<input type='text' size='30' name='control_password' value='" . $home_info['control_password'] . "' />";
    echo "<input type='submit' name='change_control_password' value='" . get_lang('change_control_password') . "' />";
    echo "</form></td></tr>";
    echo "<tr><td colspan='2' class='info'>" . get_lang('change_control_password_info') . "</td></tr>";
    if (preg_match("/t/", $game_home['access_rights']) > 0 && $ftp_installed && $db->IsFtpEnabled($home_id)) {
        // Form to edit control ftp login
        $ftp_login = isset($home_info['ftp_login']) ? $home_info['ftp_login'] : $home_id;
        echo "<tr><td class='right'>" . get_lang('server_ftp_login') . ":</td><td class='left'>";
        echo "<form action='?m=user_games&p=edit&home_id=" . $home_id . "' method='post'>";
        echo "<input type='text' size='30' name='ftp_login' value='" . $ftp_login . "' />";
        echo "<input type='submit' name='change_ftp_login' value='" . get_lang('change_ftp_login') . "' />";
        echo "</form></td></tr>";
        echo "<tr><td  colspan='2' class='info'>" . get_lang('change_ftp_login_info') . "</td></tr>";
        // Form to edit control ftp password
        echo "<tr><td class='right'>" . get_lang('server_ftp_password') . ":</td><td class='left'>";
        echo "<form action='?m=user_games&p=edit&home_id=" . $home_id . "' method='post'>";
        echo "<input type='text' size='30' name='ftp_password' value='" . $home_info['ftp_password'] . "' />";
        echo "<input type='submit' name='change_ftp_password' value='" . get_lang('change_ftp_password') . "' />";
        echo "</form></td></tr>";
        echo "<tr><td  colspan='2' class='info'>" . get_lang('change_ftp_password_info') . "</td></tr>";
    }
    if ($isAdmin && $ftp_installed) {
        // Forms to enable/disable ftp account
        echo "<tr>";
        echo "<td class='right'>" . get_lang('change_ftp_account_status') . ":</td>";
        echo "<td class='left'>";
        if (!$db->IsFtpEnabled($home_id)) {
            echo "<div style='display:block;float:left;' ><form action='?m=user_games&p=edit&home_id=" . $home_id . "' method='post'>";
            echo "<input type='submit' name='create_ftp' value='" . get_lang('ftp_on') . "' />";
            echo "</form></div>";
        } else {
            echo "<div style='display:block;float:left;' ><form action='?m=user_games&p=edit&home_id=" . $home_id . "' method='post'>";
            echo "<input type='submit' name='delete_ftp' value='" . get_lang('ftp_off') . "' />";
            echo "</form></div>";
        }
        echo "</td></tr>";
        echo "<tr><td  colspan='2' class='info'>" . get_lang('change_ftp_account_status_info') . "</td>";
        echo "</tr>";
    }
    if ($isAdmin) {
        $master_server_home_id = $db->getMasterServer($home_info['remote_server_id'], $home_info['home_cfg_id']);
        if ($master_server_home_id != FALSE and $master_server_home_id == $home_id) {
            $checked = 'checked ="checked"';
        } else {
            $checked = "";
        }
        // Form to enable/disable as master server for local update
        echo "</tr><tr><td class='right'>" . get_lang('master_server_for_clon_update') . ":</td><td class='left'>";
        echo "<form action='?m=user_games&p=edit&home_id=" . $home_id . "' method='post'>";
        echo "<input type='checkbox' name='add' {$checked} />";
        echo "<input type='submit' name='master_server' value='" . get_lang('set_as_master_server') . "' />";
        echo "</form></td></tr>";
        echo "<tr><td colspan='2' class='info'>" . get_lang('set_as_master_server_for_local_clon_update') . " (" . get_lang_f('only_available_for', $server_xml->game_name, $home_info['remote_server_name']) . ")</td></tr>";
    }
    echo "</table>";
    if ($isAdmin) {
        $avail_ips = $db->getRemoteServerIPs($home_info['remote_server_id']);
        $ip_array = array();
        if (is_array($avail_ips) && !empty($avail_ips)) {
            echo "<h3>" . get_lang('ips_and_ports') . "</h3>";
            if (!$screen_running) {
                if (isset($_REQUEST['set_ip'])) {
                    $ip_id = $_POST['ip'];
                    $ip_row = $db->resultQuery("SELECT ip FROM OGP_DB_PREFIXremote_server_ips WHERE ip_id=" . $ip_id);
                    $ip = $ip_row['0']['ip'];
                    $port = $_POST['port'];
                    $port = (int) trim($port);
                    $home_id = $_POST['home_id'];
                    if (!isPortValid($port)) {
                        print_failure(get_lang('port_range_error'));
                    } else {
                        if ($db->addGameIpPort($home_id, $ip_id, $port) === FALSE) {
                            print_failure(get_lang_f('ip_port_already_in_use', $ip, $port));
                        } else {
                            print_success(get_lang_f('successfully_assigned_ip_port_to_server_id', $ip, $port, $home_id));
                            $db->logger(get_lang_f('successfully_assigned_ip_port_to_server_id', $ip, $port, $home_id));
                        }
                    }
                }
                if (isset($_REQUEST["delete_ip"])) {
                    $del_ip = $_GET['ip'];
                    $del_port = $_GET['port'];
                    if ($db->delGameIpPort($home_id, $del_ip, $del_port)) {
                        print_success(get_lang('successfully_assigned_ip_port'));
                        $db->logger(get_lang('successfully_assigned_ip_port') . " [unassigned]");
                    } else {
                        print_failure("Failed to unassign ip:port.");
                    }
                }
                echo "<form action='?m=user_games&p=edit&home_id=" . $home_id . "' method='post'>\n";
                echo "<input type='hidden' name='home_id' value=\"{$home_id}\" />\n";
                echo get_lang('ip') . ":<select name='ip' onchange='this.form.submit();'>";
                foreach ($avail_ips as $value) {
                    $selected = (isset($_POST['ip']) and $_POST['ip'] == $value['ip_id']) ? "selected='selected'" : "";
                    echo "<option value='" . $value['ip_id'] . "' {$selected} >" . $value['ip'] . "</option>\n";
                }
                echo "</select>";
                $ip_id = isset($_POST['ip']) ? $_POST['ip'] : $avail_ips[0]['ip_id'];
                $port = $db->getNextAvailablePort($ip_id, $home_info['home_cfg_id']);
                echo " " . get_lang('port') . ":<input type='text' name='port' value='" . $port . "' size='6' />";
                echo "<input type='submit' name='set_ip' value='" . get_lang('set_ip') . "' />";
                echo "</form>";
                $assigned = $db->getHomeIpPorts($home_id);
                if (empty($assigned)) {
                    print_failure(get_lang('no_ip_ports_assigned'));
                } else {
                    foreach ($assigned as $assigned_rows) {
                        $force_mod = "";
                        $align = "center";
                        if (!empty($enabled_mods) and count($enabled_mods) > 1) {
                            $force_mod .= "<td align='left'>\n" . "<form action='?m=user_games&p=edit&home_id=" . $home_id . "' method='post'>\n" . "<input type='hidden' name='ip_id' value=" . $assigned_rows['ip_id'] . " />" . "<input type='hidden' name='port' value=" . $assigned_rows['port'] . " />" . "<select name='force_mod_id' onchange='this.form.submit();'>" . "<option value='0' >" . get_lang('force_mod_on_this_address') . "</option>";
                            foreach ($enabled_mods as $mod) {
                                $selected = $mod['mod_id'] == $assigned_rows['force_mod_id'] ? "selected='selected'" : "";
                                $force_mod .= "<option value='" . $mod['mod_id'] . "' {$selected}>" . $mod['mod_name'] . "</option>";
                            }
                            $force_mod .= "</select>\n</form>\n</td>\n";
                            $align = "right";
                        }
                        echo "<table class='center'><tr><td align='{$align}'>" . $assigned_rows['ip'] . ":" . $assigned_rows['port'] . " <a href='?m=user_games&amp;p=edit&amp;home_id={$home_id}&amp;delete_ip&amp;ip=" . $assigned_rows['ip_id'] . "&amp;port=" . $assigned_rows['port'] . "'>[ " . get_lang('delete') . " ]</a></td>\n" . $force_mod . "</tr>\n</table>\n";
                    }
                }
            } else {
                print_failure(get_lang('server_is_running_change_addresses_not_available'));
            }
        } else {
            print_failure(get_lang('no_ip_addresses_configured') . "<a href='?m=server'>" . get_lang('server_page') . "</a>.");
        }
        echo "<h3>" . get_lang('mods') . "</h3>";
        echo "<p class='info'>" . get_lang('extra_cmd_line_info') . "</p>\n";
        if (empty($enabled_mods)) {
            print_failure(get_lang('note') . ":" . get_lang('note_no_mods'));
            $cpu_count = $remote->cpu_count();
            if ($cpu_count === -1) {
                print_failure(get_lang('warning_agent_offline_defaulting_CPU_count_to_1'));
                $cpu_count = 'NA';
            } else {
                // cpu numbering starts from 0 so lets remove the last cpu.
                $cpu_count -= 1;
            }
            $game_mods = $db->getAvailableModsForGameHome($home_id);
            foreach ($game_mods as $game_mod) {
                if ($game_mod['mod_name'] == "none") {
                    $mod_cfg_id = $game_mod['mod_cfg_id'];
                }
                if ($game_mod['mod_name'] == "None") {
                    $mod_cfg_id = $game_mod['mod_cfg_id'];
                }
            }
            if (isset($mod_cfg_id)) {
                $db->addModToGameHome($home_id, $mod_cfg_id);
                $maxplayers = $server_xml->max_user_amount ? $server_xml->max_user_amount : 0;
                $db->updateGameModParams($maxplayers, '', 'NA', '0', $home_id, $mod_cfg_id);
                echo "<meta http-equiv='refresh' content='0'>";
                return;
            } else {
                echo "<form action='?m=user_games&p=edit&home_id=" . $home_id . "' method='post'>\n";
                echo "<input type='hidden' name='home_id' value=\"{$home_id}\" />\n";
                echo "<p>" . get_lang('available_mods') . ": <select name='mod_cfg_id'>\n";
                foreach ($game_mods as $game_mod) {
                    echo "<option value='" . $game_mod['mod_cfg_id'] . "'>" . $game_mod['mod_name'] . "</option>\n";
                }
                echo "</select>\n";
                echo "<input type='submit' name='add_mod' value='" . get_lang('add_mod') . "' /></p>";
                echo "</form>";
            }
        } else {
            $cpu_count = $remote->cpu_count();
            if ($cpu_count === -1) {
                print_failure(get_lang('warning_agent_offline_defaulting_CPU_count_to_1'));
                $cpu_count = 'NA';
            } else {
                // cpu numbering starts from 0 so lets remove the last cpu.
                $cpu_count -= 1;
            }
            echo "<table class='center'>\n";
            echo "<tr><td></td><td><b>" . get_lang('mod_name') . "</b></td>";
            if ($server_xml->max_user_amount) {
                echo "<td><b>" . get_lang('max_players') . "</b></td>";
            }
            echo "<td><b>" . get_lang('extra_cmd_line_args') . "</b></td><td><b>" . get_lang('cpu_affinity') . "</b></td>";
            echo "<td><b>" . get_lang('nice_level') . "</b></td><td></td></tr>\n";
            foreach ($enabled_mods as $enabled_rows) {
                echo "<form action='?m=user_games&p=edit&home_id=" . $home_id . "' method='post'><tr><td>\n" . "<input type='hidden' name='home_id' value=\"{$home_id}\" />\n" . "<input type='hidden' name='mod_cfg_id' value=\"" . $enabled_rows['mod_cfg_id'] . "\" />\n" . "<a href='?m=user_games&amp;p=edit&amp;mod_id=" . $enabled_rows['mod_id'] . "&amp;home_id={$home_id}&amp;submit=delete_mod'>[ " . get_lang('remove_mod') . " ]</a><br>" . "<a href='?m=user_games&p=install_cmds&home_id={$home_id}&mod_id=" . $enabled_rows['mod_id'] . "'>" . get_lang('mod_install_cmds') . "</a></td>" . "<td>" . $enabled_rows['mod_name'] . "</td>";
                if ($server_xml->max_user_amount) {
                    echo "<td>" . create_drop_box_from_array(range(0, $server_xml->max_user_amount), 'maxplayers', $enabled_rows['max_players'], true) . "</td>";
                }
                echo "<td><input type='text' name='cliopts' size='20' value=\"" . $enabled_rows['extra_params'] . "\" /></td>";
                echo "<td>" . create_drop_box_from_array(array_merge(array('NA'), range(0, $cpu_count)), 'cpus', $enabled_rows['cpu_affinity']) . "</td>";
                echo "<td>" . create_drop_box_from_array(array_merge(range(-19, 19)), 'nice', $enabled_rows['nice']) . "</td>";
                echo "<td><input type='submit' name='set_options' value='" . get_lang('set_options') . "' /></td></tr></form>\n";
            }
            echo "</table>\n";
            $game_mods = $db->getAvailableModsForGameHome($home_id);
            foreach ($game_mods as $game_mod) {
                if ($game_mod['mod_name'] == "none") {
                    $mods_available = 0;
                } elseif ($game_mod['mod_name'] == "None") {
                    $mods_available = 0;
                } else {
                    $mods_available = 1;
                }
            }
            if ($mods_available == 1) {
                echo "<form action='?m=user_games&p=edit&home_id=" . $home_id . "' method='post'>\n";
                echo "<input type='hidden' name='home_id' value=\"{$home_id}\" />\n";
                echo "<p>" . get_lang('available_mods') . ": <select name='mod_cfg_id'>\n";
                foreach ($game_mods as $game_mod) {
                    echo "<option value='" . $game_mod['mod_cfg_id'] . "'>" . $game_mod['mod_name'] . "</option>\n";
                }
                echo "</select>\n";
                echo "<input type='submit' name='add_mod' value='" . get_lang('add_mod') . "' /></p>";
                echo "</form>";
            }
        }
    } else {
        $assigned = $db->getHomeIpPorts($home_id);
        if (!empty($assigned) and !empty($enabled_mods) and count($enabled_mods) > 1) {
            echo "<table class='center'>\n" . "<tr>\n" . "<td colspan='2' align='center'>" . "<h3>" . get_lang('switch_mods') . "</h3>" . "</td>\n" . "</tr>\n";
            foreach ($assigned as $assigned_rows) {
                $force_mod = "<tr>\n<td align='right' style='width:50%' >" . get_lang_f('switch_mod_for_address', $assigned_rows['ip'] . ":" . $assigned_rows['port']) . "</td>\n" . ($force_mod .= "<td align='left' style='width:50%' >\n" . "<form action='?m=user_games&p=edit&home_id=" . $home_id . "' method='post'>\n" . "<input type='hidden' name='ip_id' value=" . $assigned_rows['ip_id'] . " />" . "<input type='hidden' name='port' value=" . $assigned_rows['port'] . " />" . "<select name='force_mod_id' onchange='this.form.submit();'>");
                foreach ($enabled_mods as $mod) {
                    $selected = $mod['mod_id'] == $assigned_rows['force_mod_id'] ? "selected='selected'" : "";
                    $force_mod .= "<option value='" . $mod['mod_id'] . "' {$selected}>" . $mod['mod_name'] . "</option>";
                }
                $force_mod .= "</select>\n</form>\n</td>\n</tr>\n";
            }
            echo $force_mod . "</table>\n";
        }
    }
}
function exec_ogp_module()
{
    global $db;
    require_once 'includes/lib_remote.php';
    $access = FALSE;
    $port = $_REQUEST['port'];
    $ip = $_REQUEST['ip'];
    $server_home = $db->getGameHomeByIP($ip, $port);
    $home_id = $server_home['home_id'];
    // Is user ??
    $users = $db->getUsersByHomeId($home_id);
    if ($users) {
        foreach ($users as $user) {
            if ($user['user_id'] == $_SESSION['user_id']) {
                $access = TRUE;
            }
        }
    }
    // Is group user ??
    $groupusers = $db->getGroupUsersByHomeId($home_id);
    if ($groupusers) {
        foreach ($groupusers as $groupuser) {
            if ($groupuser['user_id'] == $_SESSION['user_id']) {
                $access = TRUE;
            }
        }
    }
    // Is admin ??
    $isAdmin = $db->isAdmin($_SESSION['user_id']);
    if ($isAdmin) {
        $access = TRUE;
    }
    if ($access == FALSE) {
        print_failure("Access Denied!");
        die;
    }
    $server_xml = read_server_config(SERVER_CONFIG_LOCATION . "/" . $server_home['home_cfg_file']);
    $xml_installer = $server_xml->installer;
    $mod = $server_xml->mods->mod['key'];
    if ($server_xml->protocol == "gameq") {
        $query_name = $server_xml->gameq_query_name;
    } elseif ($server_xml->protocol == "lgsl") {
        $query_name = $server_xml->lgsl_query_name;
    } else {
        $query_name = $mod;
    }
    // If query name does not exist use mod key instead.
    //Properties for all servers
    if (isset($_GET['home_id']) && $_GET['home_id'] == $server_home['home_id']) {
        $trclass = "class='expandme'";
    }
    $user = $db->getUserById($server_home['user_id_main']);
    $btns = "<a href='?m=gamemanager&amp;p=gamemanager&amp;home_id=" . $server_home['home_id'] . "'><img src='images/gamemanager.png' style='border:0;height:16px;' />" . get_lang('gamemanager') . "</a>&nbsp;&nbsp;" . "<a href='?m=gamemanager&amp;p=log&amp;home_id=" . $server_home['home_id'] . "'><img style='border:0;height:16px;' src='images/log.png'/>" . get_lang('view_log') . "</a>&nbsp;&nbsp;" . "<a href='?m=ftp&amp;home_id=" . $server_home['home_id'] . "'><img style='border:0;height:16px;' src='images/ftp.png'/>" . get_lang('ftp') . "</a>";
    // Check if the screen running the server is running.
    if ($server_xml->protocol == "gameq") {
        require 'protocol/GameQ/functions.php';
        require_once 'protocol/GameQ/GameQMonitor.php';
    } else {
        if ($server_xml->protocol == "lgsl") {
            require 'protocol/lgsl/functions.php';
            require_once 'protocol/lgsl/LGSLMonitor.php';
        } else {
            if ($server_xml->protocol == "teamspeak3") {
                require_once 'protocol/TeamSpeak3/TS3Monitor.php';
            } else {
                // This is here because some servers are not supported by LGSL/GameQ or
                // because we do not have proper support for them yet.
                // With properly supported games this should not needed.
                // (In a perfect world no one would need an insurance.)
                $status = "online";
                $map = $status;
                $maplocation = get_map_path($query_name, $mod, $map);
                @($notifications .= get_lang("query_protocol_not_supported"));
            }
        }
    }
    @($map_icon = "<img class='mapicon' src='{$maplocation}'/>");
    @($currentmap = $map);
    //Properties for Specific Status
    if ($status == "half" || $status == "online") {
        if ($status == "online") {
            $onlineT = "<div>";
            $onlineT .= "{$map_icon}";
            $onlineT .= "</div>";
            $onlineT .= "<div>";
            @($onlineT .= get_lang('hostname') . ": <marquee class='hostname'>{$name}</marquee><br />");
            @($onlineT .= get_lang('current_map') . ": {$currentmap}");
            $onlineT .= "</div>";
        } else {
            if ($status == "half") {
                @($notifications .= get_lang("failed_querying_server"));
            }
        }
        $remote_server_id = $server_home['remote_server_id'];
        $rserver = $db->getRemoteServerById($remote_server_id);
        $remote = new OGPRemoteLibrary($rserver['agent_ip'], $rserver['agent_port'], $rserver['encryption_key'], $rserver['timeout']);
        $startup_file_exists = $remote->rfile_exists("startups/" . $server_home['ip'] . "-" . $server_home['port']) === 1;
        $SrvCtrl = "<table class='srvctrl'><tr>";
        if ($startup_file_exists) {
            $SrvCtrl .= "<td style='border:0;text-align:center;background:transparent'><a href='?m=gamemanager&amp;p=restart&amp;home_id=" . $server_home['home_id'] . "&amp;mod_id=" . $server_home['mod_id'] . "&amp;ip=" . $server_home['ip'] . "&amp;port=" . $server_home['port'] . "'><img src='images/restart.png' width='64' border='0' alt='" . get_lang('restart_server') . "' /><br><b>" . get_lang('restart_server') . "</b></a></td>";
        }
        $SrvCtrl .= "<td style='border:0;text-align:center;background:transparent'><a href='?m=gamemanager&amp;p=stop&amp;home_id=" . $server_home['home_id'] . "&amp;ip=" . $server_home['ip'] . "&amp;port=" . $server_home['port'] . "'><img src='images/stop.png' width='64' border='0' alt='" . get_lang('stop_server') . "' /><br><b>" . get_lang('stop_server') . "</b></a></td></tr></table>";
    }
    //Echo them all
    echo "<div class='monitor-1'>" . @$onlineT . @$halfT . @$offlineT . "</div>" . "<div class='monitor-2 bloc'>" . @$SrvCtrl . "</div>";
    if (isset($player_list)) {
        echo "<div class='monitor-3'>" . @$player_list . "</div>";
    }
    if (isset($notifications)) {
        echo "<div class='monitor-3 bloc'>" . @$notifications . "</div>";
    }
}
function exec_ogp_module()
{
    global $db, $view;
    $game_cfgs = $db->getGameCfgs();
    echo "<h2>" . get_lang('game_config_setup') . "</h2>\n\n          <p>" . get_lang_f("modify_configs_info", SERVER_CONFIG_LOCATION) . "</p>\n\n\t\t  <form action='?m=config_games' method='post'>\n\n          <p><input id='reset_old_configs' type='checkbox' name='clear_old' value='yes' /><label for='reset_old_configs'>" . get_lang('reset_old_configs') . "</label></p>\n\n          <p class='note'>" . get_lang('note') . ": " . get_lang('config_reset_warning') . "</p>\n\n\t\t  <p><input type='submit' name='reconfig' value='" . get_lang('update_configs') . "' /></p>\n\n          </form>\n";
    if (isset($_REQUEST['reconfig'])) {
        $files = glob(SERVER_CONFIG_LOCATION . "*.xml");
        if (empty($files)) {
            print_failure(get_lang_f("no_configs_found", SERVER_CONFIG_LOCATION));
            return;
        }
        /// \todo remove the clear_old hack when the update on duplicate is completed to database.
        $clear_old = FALSE;
        if (isset($_REQUEST['clear_old']) && $_REQUEST['clear_old'] === 'yes') {
            echo "<p class='info'>" . get_lang('resetting_configs') . "</p>";
            $clear_old = TRUE;
        } else {
            echo "<p class='info'>" . get_lang('updating_configs') . "</p>";
        }
        $db->clearGameCfgs($clear_old);
        foreach ($files as $config_file) {
            $config = read_server_config($config_file);
            if (empty($config)) {
                print_failure(get_lang_f("error_when_handling_file", $config_file));
                continue;
            }
            echo "<p class='info'>" . get_lang_f("updating_config_from_file", $config_file) . "</p>";
            if (!$db->addGameCfg($config)) {
                print_failure(get_lang_f("error_while_adding_cfg_to_db", $config_file));
                continue;
            }
        }
        print_success(get_lang('configs_updated_ok'));
    }
    $game_cfgs = $db->getGameCfgs();
    echo "<table class='center'>\n\n\t\t  <form action='' method='GET'>\n\n\t\t  <input type='hidden' name='m' value='config_games'/>\n\t\t  <tr>\n\n\t\t  <td class='left'>\n\n\t\t  <select name='home_cfg_id' onchange=" . '"this.form.submit()"' . ">\n\n\t\t  <option style='background:black;color:white;' value=''>" . get_lang('select_game') . "</option>\n";
    foreach ($game_cfgs as $row) {
        if (preg_match("/_win/", $row['game_key'])) {
            $os = "(Windows)";
        }
        if (preg_match("/_linux/", $row['game_key'])) {
            $os = "(Linux)";
        }
        if (preg_match("/64/", $row['game_key'])) {
            $arch = "(64bit)";
        } else {
            $arch = "";
        }
        if (isset($_GET['home_cfg_id']) and $row['home_cfg_id'] == $_GET['home_cfg_id']) {
            $selected = "selected='selected'";
        } else {
            $selected = "";
        }
        echo "<option value='" . $row['home_cfg_id'] . "' {$selected} >" . $row['game_name'] . " {$os} {$arch}</option>\n";
        unset($os, $arch);
    }
    echo "</select>\n\n\t\t  </td>\n\n\t\t  </tr>\n\n\t\t  </form>\n\n\t\t  </table>\n";
    if (isset($_GET['home_cfg_id'])) {
        $home_cfg_id = trim($_GET['home_cfg_id']);
        $cfg_info = $db->getGameCfg($home_cfg_id);
        if ($cfg_info !== FALSE) {
            $config_file = SERVER_CONFIG_LOCATION . $cfg_info['home_cfg_file'];
            if (preg_match("/_win/", $cfg_info['game_key'])) {
                $os = "(Windows)";
            }
            if (preg_match("/_linux/", $cfg_info['game_key'])) {
                $os = "(Linux)";
            }
            if (preg_match("/64/", $cfg_info['game_key'])) {
                $arch = "(64bit)";
            } else {
                $arch = "";
            }
            if (isset($_GET['delete'])) {
                if ($db->delGameCfgAndMods($home_cfg_id) === FALSE) {
                    print_failure(get_lang_f('failed_to_delete_config_from_db', $cfg_info['game_name']));
                    $view->refresh('?m=config_games&home_cfg_id=' . $home_cfg_id, 3);
                } elseif (unlink($config_file) === FALSE) {
                    print_failure(get_lang_f('failed_removing_file', $config_file));
                    $view->refresh('?m=config_games&home_cfg_id=' . $home_cfg_id, 3);
                } else {
                    print_success(get_lang_f('removed_game_cfg_from_disk_and_datbase', $cfg_info['game_name'] . " {$os} {$arch}"));
                    $view->refresh('?m=config_games', 3);
                }
            } else {
                echo "<a href='?m=config_games&home_cfg_id=" . $home_cfg_id . "&delete'>" . get_lang_f('delete_game_config_for', $cfg_info['game_name'] . " {$os} {$arch}") . "</a><br>";
                $configs = read_server_config($config_file);
                echo "<table>\n";
                foreach ($configs as $key => $value) {
                    echo "<tr><td><b>{$key}<b></td><td colspan=25 >{$value}</td></tr>\n";
                    foreach ($value as $subkey => $subvalue) {
                        echo "<tr><td><b>{$subkey}<b></td><td>{$subvalue}</td>\n";
                        list($attributes, $attrvalue) = each($subvalue);
                        foreach ($attrvalue as $attrkey => $attrval) {
                            echo "<td><b>{$attrkey}<b></td><td>{$attrval}</td>\n";
                        }
                        echo "</td>";
                        foreach ($subvalue as $option => $options) {
                            echo "<td><b>{$option}<b></td><td>{$options}</td>\n";
                        }
                    }
                    echo "</tr>\n";
                }
                echo "</table>\n";
            }
        }
    }
    if (isset($_GET['xml_config_creator'])) {
        echo "<iframe style='width:100%;height:600px;' frameBorder='0' src='home.php?m=config_games&p=xml_config_creator&type=cleared' ></iframe>";
    } else {
        echo "<br><form action='' method='GET'><input type='hidden' name='m' value='config_games' /><input type='submit' name='xml_config_creator' value='" . get_lang('create_xml_configs') . "'/></form>";
    }
}
function exec_ogp_module()
{
    //update_local_copies(); #Disabled until the rsync_sites.list file from master servers is corrected.
    global $db, $view, $settings;
    if (isset($_REQUEST['url'])) {
        $url = $_REQUEST['url'];
    } else {
        $url = "";
    }
    $home_id = isset($_REQUEST['home_id']) ? $_REQUEST['home_id'] : "";
    $mod_id = isset($_REQUEST['mod_id']) ? $_REQUEST['mod_id'] : "";
    $state = isset($_POST['state']) ? $_POST['state'] : "";
    $update = isset($_GET['update']) ? $_GET['update'] : "";
    $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 || preg_match("/u/", $home_info['access_rights']) != 1) {
        print_failure(get_lang('no_rights'));
        echo create_back_button("gamemanager", "game_monitor");
        return;
    }
    $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 (isset($server_xml->lgsl_query_name)) {
        $lgslname = $server_xml->lgsl_query_name;
        if ($lgslname == "quake3") {
            if ($server_xml->game_name == "Quake 3") {
                $lgslname = "q3";
            }
        }
    } elseif (isset($server_xml->gameq_query_name)) {
        $lgslname = $server_xml->gameq_query_name;
        if ($lgslname == "minecraft") {
            if ($server_xml->game_name == "Minecraft Tekkit") {
                $lgslname = "tekkit";
            } elseif ($server_xml->game_name == "Minecraft Bukkit") {
                $lgslname = "bukkit";
            }
        }
    } elseif (isset($server_xml->protocol)) {
        $lgslname = $server_xml->protocol;
    } else {
        $lgslname = $server_xml->mods->mod['key'];
    }
    if (preg_match("/win32/", $server_xml->game_key) or preg_match("/win64/", $server_xml->game_key)) {
        $os = "windows";
    } elseif (preg_match("/linux/", $server_xml->game_key)) {
        $os = "linux";
    }
    $full_url = $url . "/ogp_game_installer/{$lgslname}/{$os}/";
    echo "<h2>Update {$home_info['home_name']}</h2>";
    if ($remote->is_screen_running(OGP_SCREEN_TYPE_HOME, $home_id) == 1) {
        print_failure(get_lang('server_running_cant_update'));
        return;
    }
    $update_active = $remote->get_log(OGP_SCREEN_TYPE_UPDATE, $home_id, clean_path($home_info['home_path']), $log_txt, 30);
    if ($update_active === 0) {
        print_failure(get_lang('agent_offline'));
        echo "<meta http-equiv='refresh' content='5'>";
        return;
    } elseif ($state == 'start' && $update_active != 1) {
        $mod_cfg_id = $home_info['mod_cfg_id'];
        $game_mod_precmd = $db->resultQuery("SELECT DISTINCT precmd FROM OGP_DB_PREFIXgame_mods WHERE mod_id='{$mod_id}'");
        if ($game_mod_precmd[0]['precmd'] === NULL or empty($game_mod_precmd[0]['precmd'])) {
            $config_mod_precmd = $db->resultQuery("SELECT DISTINCT def_precmd FROM OGP_DB_PREFIXconfig_mods WHERE mod_cfg_id='{$mod_cfg_id}'");
            if ($config_mod_precmd[0]['def_precmd'] === NULL or empty($config_mod_precmd[0]['def_precmd'])) {
                $precmd = "";
            } else {
                $precmd = $config_mod_precmd[0]['def_precmd'];
            }
        } else {
            $precmd = $game_mod_precmd[0]['precmd'];
        }
        $game_mod_postcmd = $db->resultQuery("SELECT DISTINCT postcmd FROM OGP_DB_PREFIXgame_mods WHERE mod_id='{$mod_id}'");
        if ($game_mod_postcmd[0]['postcmd'] === NULL or empty($game_mod_postcmd[0]['postcmd'])) {
            $config_mod_postcmd = $db->resultQuery("SELECT DISTINCT def_postcmd FROM OGP_DB_PREFIXconfig_mods WHERE mod_cfg_id='{$mod_cfg_id}'");
            if ($config_mod_postcmd[0]['def_postcmd'] === NULL or empty($config_mod_postcmd[0]['def_postcmd'])) {
                $postcmd = "";
            } else {
                $postcmd = $config_mod_postcmd[0]['def_postcmd'];
            }
        } else {
            $postcmd = $game_mod_postcmd[0]['postcmd'];
        }
        $exec_folder_path = clean_path($home_info['home_path'] . "/" . $server_xml->exe_location);
        $exec_path = clean_path($exec_folder_path . "/" . $server_xml->server_exec_name);
        if (isset($_REQUEST['master_server_home_id'])) {
            $ms_home_id = $_REQUEST['master_server_home_id'];
            $ms_info = $db->getGameHome($ms_home_id);
            print_success(get_lang_f("starting_copy_with_master_server_named", $ms_info['home_name']));
            $rsync = $remote->masterServerUpdate($home_id, $home_info['home_path'], $ms_home_id, $ms_info['home_path'], $exec_folder_path, $exec_path, $precmd, $postcmd);
            $master = "&amp;master=true";
        } else {
            print_success(get_lang_f("starting_sync_with", $full_url));
            $rsync = $remote->start_rsync_install($home_id, $home_info['home_path'], "{$full_url}", $exec_folder_path, $exec_path, $precmd, $postcmd);
            $master = "";
        }
        if ($rsync === 0) {
            print_failure(get_lang('failed_to_start_rsync_update'));
            return;
        } else {
            if ($rsync === 1) {
                print_success(get_lang('update_started'));
                echo "<p><a href=\"?m=gamemanager&amp;p=rsync_install&amp;update=refresh&amp;home_id={$home_id}&amp;mod_id={$mod_id}{$master}\">";
                echo get_lang('refresh_rsync_status') . "</a></p>";
                $view->refresh("?m=gamemanager&amp;p=rsync_install&amp;update=refresh&amp;home_id={$home_id}&amp;mod_id={$mod_id}{$master}", 5);
                return;
            } elseif ($rsync === 0) {
                print_failure(get_lang('agent_offline'));
                return;
            }
        }
    } elseif ($update_active == 1) {
        echo "<p class='note'></p>\n";
        if (isset($_POST['stop_update_x'])) {
            $stop_update = sprintf("screen -S OGP_UPDATE_%09d -X quit", $home_id);
            $remote->exec("{$stop_update}");
        }
        $update_complete = false;
        echo "<form method=POST><input type='image' name='stop_update' onsubmit='submit-form();' src='modules/administration/images/remove.gif'>" . get_lang('stop_update') . "</input></form>";
        if (empty($log_txt)) {
            $log_txt = get_lang('not_available');
        }
        if (!isset($_GET['master'])) {
            $kbytes = $remote->rsync_progress($home_info['home_path']);
            list($totalsize, $mbytes, $pct) = explode(";", do_progress($kbytes, $lgslname . "/" . $os));
            $totalmbytes = round($totalsize / 1024, 2);
            echo '<div class="dragbox bloc rounded" style="background-color:#dce9f2;" >
					<h4>' . get_lang('update_in_progress') . " {$mbytes}MB/{$totalmbytes}MB</h4>\n\t\t\t\t  <div style='background-color:#dce9f2;' >\n\t\t\t\t  ";
            $bar = '';
            for ($i = 1; $i <= $pct; $i++) {
                $bar .= '<img style="width:0.92%;vertical-align:middle;" src="images/progressBar.png">';
            }
            echo "{$bar} <b style='vertical-align:top;display:inline;font-size:1.2em;color:red;' >{$pct}%</b>\n\t\t\t\t\t</div>\n\t\t\t\t  </div><br>";
        } else {
            echo '<h4>' . get_lang('update_in_progress') . '</h4>';
        }
        echo "<pre>" . $log_txt . "</pre>\n";
        echo "<p><a href=\"?m=gamemanager&amp;p=rsync_install&amp;update=refresh&amp;home_id={$home_id}&amp;mod_id={$mod_id}\">";
        echo get_lang('refresh_rsync_status') . "</a></p>";
        $view->refresh("?m=gamemanager&amp;p=rsync_install&amp;update=refresh&amp;home_id={$home_id}&amp;mod_id={$mod_id}", 5);
        return;
    } elseif ($update != "update") {
        echo "<meta http-equiv='refresh' content='60'>";
        print_success(get_lang('update_completed'));
        echo "<table class='center'><tr><td><a href='?m=gamemanager&amp;p=game_monitor&amp;home_id=" . $home_info['home_id'] . "'><< " . get_lang('back') . "</a></td></tr></table>";
        echo "<pre>" . $log_txt . "</pre>\n";
        echo "<table class='center'><tr><td><a href='?m=gamemanager&amp;p=game_monitor&amp;home_id=" . $home_info['home_id'] . "'><< " . get_lang('back') . "</a></td></tr></table>";
        $update_complete = true;
    } else {
        $rsync_remote_sites = file("modules/gamemanager/rsync_sites.list");
        #load offical rsync sites
        $rsync_local_sites = file("modules/gamemanager/rsync_sites_local.list");
        #load user custom sites
        $settings['rsync_available'] = isset($settings['rsync_available']) ? $settings['rsync_available'] : "1";
        if (is_array($rsync_local_sites) and $settings['rsync_available'] == "1") {
            $rsync_sites = array_merge($rsync_remote_sites, $rsync_local_sites);
            #merge arrays
        } elseif ($settings['rsync_available'] == "2") {
            $rsync_sites = $rsync_remote_sites;
        } elseif ($settings['rsync_available'] == "3") {
            $rsync_sites = $rsync_local_sites;
        }
        #echo "LGSL or GameQ query name is $server_xml->lgsl_query_name$server_xml->gameq_query_name";
        $sync_list = @file("modules/gamemanager/rsync.list", FILE_IGNORE_NEW_LINES);
        if (!is_array($sync_list)) {
            if (!is_file("modules/gamemanager/rsync.list")) {
                print_failure("Trouble accessing http://www.opengamepanel.org/rsync.list");
                print_failure("Make sure allow_fopen_url is set to \"On\" in your php.ini and opengamepanel.org is online");
                print_failure("In the mean time, you can get a local copy of the file by running wget http://www.opengamepanel.org/sync_data/rsync.list -O /path/to/ogpweb/modules/gamemanager/rsync.list");
                return;
            }
            # print_failure("Error loading rsync.list");
            # return;
            $sync_list = @file("modules/gamemanager/rsync.list", FILE_IGNORE_NEW_LINES);
            if (!is_array($sync_list)) {
                print_failure("Failed to open local copy of rsync.list in modules/gamemanager/rsync.list");
                return;
            }
        }
        $master_server_home_id = $db->getMasterServer($home_info['remote_server_id'], $home_info['home_cfg_id']);
        if (in_array($lgslname, $sync_list)) {
            echo "Game type supported<br>\n\t\t\t\t <p class='center'>To add your own rsync site, create modules/gamemanager/rsync_sites_local.list and put a server name on each line.</p><br>\n\t\t\t\t <form action='?m=gamemanager&amp;p=rsync_install' method='post'>\n\t\t\t\t <table class='center'>\n\t\t\t\t <input type='hidden' name='home_id' value='{$home_id}' />\n\t\t\t\t <input type='hidden' name='mod_id' value='{$mod_id}' />\n\t\t\t\t <input type='hidden' name='lgslname' value='{$lgslname}' />\n\t\t\t\t <input type='hidden' name='state' value='start' />\n\t\t\t\t <tr><td align='right'>Game name:</td><td align='left'>{$home_info['game_name']}</td></tr>\n\t\t\t\t <tr><td align='right'>Directory:</td><td align='left'>{$home_info['home_path']}</td></tr>\n\t\t\t\t <tr><td align='right'>Remoteserver:</td>\n\t\t\t\t <td align='left'>{$home_info['remote_server_name']} ({$home_info['agent_ip']}:{$home_info['agent_port']})</td></tr>\n\t\t\t\t <tr><td align='right'>Rsync Server:</td>\n\t\t\t\t <td align='left'>" . create_drop_box_from_array_rsync($rsync_sites, "url") . "<br>";
            if ($master_server_home_id != FALSE and $master_server_home_id != $home_id) {
                echo "<input type='checkbox' name='master_server_home_id' value='{$master_server_home_id}' /><b>" . get_lang('update_from_local_master_server') . "</b>";
            }
            echo "</td></tr></table><p><input type='submit' name='update' value='update' /></p>\n\t\t\t\t </form>";
        } elseif ($master_server_home_id != FALSE and $master_server_home_id != $home_id) {
            $ms_home_info = $db->getGameHome($master_server_home_id);
            echo "<br>\n\t\t\t\t <p class='success'>Master server update available</p><br>\n\t\t\t\t <form action='?m=gamemanager&amp;p=rsync_install' method='post'>\n\t\t\t\t <table class='center'>\n\t\t\t\t <input type='hidden' name='home_id' value='{$home_id}' />\n\t\t\t\t <input type='hidden' name='mod_id' value='{$mod_id}' />\n\t\t\t\t <input type='hidden' name='lgslname' value='{$lgslname}' />\n\t\t\t\t <input type='hidden' name='state' value='start' />\n\t\t\t\t <tr><td align='right'>Game name:</td><td align='left'>{$home_info['game_name']}</td></tr>\n\t\t\t\t <tr><td align='right'>Master Server Name:</td><td align='left'>{$ms_home_info['home_name']}</td></tr>\n\t\t\t\t <tr><td align='right'>Master Server Directory:</td><td align='left'>{$ms_home_info['home_path']}</td></tr>\n\t\t\t\t <tr><td align='right'>Local Directory:</td><td align='left'>{$home_info['home_path']}</td></tr>" . "<input type='hidden' name='master_server_home_id' value='{$master_server_home_id}' />" . "</td></tr></table><p><input type='submit' name='update' value='" . get_lang('update_from_local_master_server') . "' /></p>\n\t\t\t\t </form>";
        } else {
            print_failure("This game type [ {$lgslname} ] is not yet supported with rsync install");
        }
    }
}
Esempio n. 10
0
require_once "resources/security/functions.php";
require_once "resources/security/functions_local.php";
require_once "resources/security/functions_1.php";
checkLogged('login.php');
$username = getValue('userlogin', 'str', 'SESSION', '');
$password = getValue('password', 'str', 'SESSION', '');
//đọc file log lấy ra các query chưa được synchronize
$array_query = read_logs();
if (!$array_query) {
    echo json_encode(array('success' => 1, 'msg' => 'Nothing to sync'));
    die;
}
$array_query = base64_encode(json_encode($array_query));
//var_dump($array_query);
//lấy config
$server_config = read_server_config();
//var_dump($server_config);
//bắn các câu query lên qua curl
//var_dump($array_query);die();
$curl = curl_get_content($server_config['synchronize_url'], array('queries' => $array_query, 'action' => 'syncLogQuery', 'username' => $username, 'password' => $password));
$response = json_decode($curl, 1);
//var_dump($response);die();
if ($response['success'] == 1) {
    $db_delete = new db_execute('TRUNCATE TABLE synchronize_trigger', 1, false);
    $db_exe = new db_execute('INSERT INTO synchronize_trigger VALUES (' . time() . ')', 1, false);
    echo json_encode($response);
    die;
} else {
    echo json_encode($response);
    die;
}
Esempio n. 11
0
    $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'));
    return;
}
$mod_id = $server_home['mod_id'];
if (!array_key_exists($mod_id, $home_info['mods'])) {
    print_failure(get_lang('unable_retrieve_mod_info'));
    return;
}
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) {
    return;
}
$param_access_enabled = preg_match("/p/", $home_info['access_rights']) > 0 ? TRUE : FALSE;
$extra_param_access_enabled = preg_match("/e/", $home_info['access_rights']) > 0 ? TRUE : FALSE;
if (!isset($_POST['start_server'])) {
    $server_exec = clean_path($home_info['home_path'] . "/" . $server_xml->exe_location . "/" . $server_xml->server_exec_name);
    $r = $remote->rfile_exists($server_exec);
    if ($r === 0) {
        print_failure(get_lang_f('game_exec_not_found', $server_exec));
        return;
    } else {
        if ($r === -1) {
            print_failure(get_lang("agent_offline"));
            return;
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);
}
Esempio n. 13
0
function exec_ogp_module()
{
    global $db, $OnlineServers;
    $isAdmin = $db->isAdmin($_SESSION['user_id']);
    $panel_settings = $db->getSettings();
    $settings = $db->getSettings();
    $OnlineServers = "";
    $OnlineServersTitle = "";
    require_once 'includes/lib_remote.php';
    if ($isAdmin) {
        $server_homes = $db->getIpPorts();
    } else {
        $server_homes = $db->getIpPortsForUser($_SESSION['user_id']);
    }
    $player_list = "";
    if (!$server_homes) {
        $OnlineServers .= "";
    } else {
        $stats_servers = 0;
        $stats_servers_online = 0;
        $stats_players = 0;
        $stats_maxplayers = 0;
        $onlinePlayers = "";
        $OnlineServers .= "<table style='width:100%;' class='online_servers'>";
        foreach ($server_homes as $server_home) {
            $remote_server_id = $server_home['remote_server_id'];
            $rserver = $db->getRemoteServerById($remote_server_id);
            // Count the number of servers.
            $stats_servers++;
            // Remember to clear the old value here.
            $message = "";
            $remote = new OGPRemoteLibrary($server_home['agent_ip'], $server_home['agent_port'], $server_home['encryption_key']);
            $host_stat = $remote->status_chk();
            if ($host_stat === 1) {
                // Check if the screen running the server is running.
                $screen_running = $remote->is_screen_running(OGP_SCREEN_TYPE_HOME, $server_home['home_id']) === 1;
                $server_xml = read_server_config(SERVER_CONFIG_LOCATION . "/" . $server_home['home_cfg_file']);
                $id = strlen($server_home['home_name']) > 15 ? "id='scrolldown'" : "";
                if ($screen_running) {
                    // Check if the screen running the server is running.
                    if ($server_xml->protocol == "gameq") {
                        require 'protocol/GameQ/GameQMonitor.php';
                    } else {
                        if ($server_xml->protocol == "lgsl") {
                            require 'protocol/lgsl/LGSLMonitor.php';
                        } else {
                            if ($server_xml->protocol == "teamspeak3") {
                                require 'protocol/TeamSpeak3/TS3Monitor.php';
                            } else {
                                // This is here because some servers are not supported by LGSL/GameQ or
                                // because we do not have proper support for them yet.
                                // With properly supported games this should not needed.
                                // (In a perfect world no one would need an insurance.)
                                $status = "half";
                                if ($server_home['use_nat'] == 1) {
                                    $ip = $server_home['agent_ip'];
                                } else {
                                    $ip = $server_home['ip'];
                                }
                                $port = $server_home['port'];
                                $player_list = "";
                            }
                        }
                    }
                    if ($status == "online") {
                        $OnlineServers .= "<tr><td><div {$id} class='name' ><a href='?m=gamemanager&amp;p=game_monitor&amp;home_id-mod_id-ip-port=" . $server_home['home_id'] . "-" . $server_home['mod_id'] . "-" . $server_home['ip'] . "-" . $server_home['port'] . "' ><img style='border:0;height:12px;' src='images/magnifglass.png'/>" . $server_home['home_name'] . "</a></div>";
                        $OnlineServers .= "<div><div style='font-size:8pt;' >[" . $players . '/' . $playersmax . "]</div> " . $map . '</div>';
                        $OnlineServers .= "<div id='gamelink' >{$address}</div>";
                        $OnlineServers .= "</td></tr>";
                        if ($players >= 1) {
                            $onlinePlayers .= print_player_list($playersList, $players, $playersmax, $server_home['game_name']);
                        }
                        $stats_servers_online++;
                    } elseif ($status == "half") {
                        $OnlineServers .= "<tr><td><div {$id} class='name' ><a href='?m=gamemanager&amp;p=game_monitor&amp;home_id-mod_id-ip-port=" . $server_home['home_id'] . "-" . $server_home['mod_id'] . "-" . $server_home['ip'] . "-" . $server_home['port'] . "' ><img style='border:0;height:12px;' src='images/magnifglass.png'/>" . $server_home['home_name'] . "</a></div>";
                        $OnlineServers .= "<div><div style='font-size:8pt;' ></div> </div>";
                        $OnlineServers .= "<div id='gamelink' >{$ip}:{$port}</div>";
                        $OnlineServers .= "</td></tr>";
                        $stats_servers_online++;
                    }
                }
            }
            unset($map, $player_list, $status, $ip, $port, $players, $playersmax, $name, $map, $mod, $xml_mod, $qport, $address, $maplocation);
        }
        $OnlineServers .= "</table>";
        $OnlineServers .= "<center>" . get_lang('statistics') . ":<br>{$stats_servers_online}/{$stats_servers} \n\t\t" . get_lang('servers') . "<br>{$stats_players}/{$stats_maxplayers} " . get_lang('players') . "</center>";
    }
    if ($_GET['show'] == "servers") {
        echo $OnlineServers;
    }
    if ($_GET['show'] == "players") {
        echo $onlinePlayers;
    }
}
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;
}
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 $db;
    global $view;
    $pieces = explode("-", $_GET['home_id-mod_id-ip-port']);
    $home_id = $pieces[0];
    $mod_id = $pieces[1];
    $ip = $pieces[2];
    $port = $pieces[3];
    $user_id = $_SESSION['user_id'];
    $isAdmin = $db->isAdmin($user_id);
    if ($isAdmin) {
        $home_info = $db->getGameHome($home_id);
    } else {
        $home_info = $db->getUserGameHome($user_id, $home_id);
    }
    if ($home_info === FALSE) {
        print_failure(get_lang('no_access_to_home'));
        return;
    }
    $server_xml = read_server_config(SERVER_CONFIG_LOCATION . "/" . $home_info['home_cfg_file']);
    if (!$server_xml) {
        echo create_back_button($_GET['m'], 'game_monitor&home_id-mod_id-ip-port=' . $_GET['home_id-mod_id-ip-port']);
        return;
    }
    require_once 'includes/lib_remote.php';
    $remote = new OGPRemoteLibrary($home_info['agent_ip'], $home_info['agent_port'], $home_info['encryption_key']);
    $home_log = "";
    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);
    }
    if ($log_retval == 0) {
        print_failure(get_lang('agent_offline'));
        echo create_back_button($_GET['m'], 'game_monitor&home_id-mod_id-ip-port=' . $_GET['home_id-mod_id-ip-port']);
    } elseif ($log_retval == 1 || $log_retval == 2) {
        // Using the refreshed class
        if (isset($_GET['refreshed'])) {
            echo "<pre class='log'>" . $home_log . "</pre>";
        } else {
            echo "<h2>" . $home_info['home_name'] . "</h2>";
            require_once "includes/refreshed.php";
            $control = '<form method="POST" >
						<input type="submit" name="';
            if (isset($_POST['full'])) {
                $height = "100%";
                $control .= 'default" value="-';
            } else {
                $height = "500px";
                $control .= 'full" value="+';
            }
            $control .= '" /></form><br />';
            $intervals = array("4s" => "4000", "8s" => "8000", "30s" => "30000", "2m" => "120000", "5m" => "300000");
            $intSel = '<form action="" method="GET" >
					   <input type="hidden" name="m" value="gamemanager" />
					   <input type="hidden" name="p" value="log" />
					   <input type="hidden" name="home_id-mod_id-ip-port" value="' . $_GET['home_id-mod_id-ip-port'] . '" />' . get_lang('refresh_interval') . ':<select name="setInterval" onchange="this.form.submit();">';
            foreach ($intervals as $interval => $value) {
                $selected = "";
                if (isset($_GET['setInterval']) and $_GET['setInterval'] == $value) {
                    $selected = 'selected="selected"';
                }
                $intSel .= '<option value="' . $value . '" ' . $selected . ' >' . $interval . '</option>';
            }
            $intSel .= "</select></form>";
            $setInterval = $_GET['setInterval'] ? $_GET['setInterval'] : 4000;
            $refresh = new refreshed();
            $pos = $refresh->add("home.php?m=gamemanager&p=log&type=cleared&refreshed&home_id-mod_id-ip-port=" . $_GET['home_id-mod_id-ip-port']);
            echo $refresh->getdiv($pos, "height:" . $height . ";overflow:auto;max-width:1600px;");
            ?>
<script type="text/javascript">$(document).ready(function(){ <?php 
            echo $refresh->build("{$setInterval}");
            ?>
} ); </script><?php 
            echo "<table class='center' ><tr><td>{$intSel}</td><td>{$control}</td></tr></table>";
            if ($remote->is_screen_running(OGP_SCREEN_TYPE_HOME, $home_info['home_id']) != 1) {
                print_failure(get_lang('server_not_running'));
            } else {
                if ($server_xml->control_protocol == 'rcon' or $server_xml->control_protocol == 'rcon2' or @$server_xml->gameq_query_name == "minecraft" or $server_xml->control_protocol == 'lcon' or isset($server_xml->lgsl_query_name) and $server_xml->lgsl_query_name == "7dtd") {
                    require 'modules/gamemanager/rcon.php';
                }
            }
            echo create_back_button($_GET['m'], 'game_monitor&home_id-mod_id-ip-port=' . $_GET['home_id-mod_id-ip-port']);
        }
    } else {
        print_failure(get_lang_f('unable_to_get_log', $log_retval));
        echo create_back_button($_GET['m'], 'game_monitor&home_id-mod_id-ip-port=' . $_GET['home_id-mod_id-ip-port']);
    }
}
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;
                }
            }
        }
    }
}