<?php
/*
.:----------- www.VTDN.com -----------:.
----------------------------------------
.: File: functions.servers.php        :.
.: Client: Fragzz Network             :.
----------------------------------------
.:------------------------------------:.


The Contents of this file are subject to the VTDN General License, which can be found at:
http://www.vtdn.com/index.php?page=general_license
You may NOT use this file EXCEPT in compliance with the License.

The Contents of this file are Copyright ©2002 Vision Tech Design. All rights reserved.
Developers: Chris Adams

You MAY make changes to this file, but doing so will make any support offered for this file
VOID. This file may not be distributed to ANYONE.

*/
?><?

function addserver ($username,$password,$slots,$branding,$public,$boxid,$caption '',$orderid '') {
    global 
$DB$LOGIN;
    
    if(empty(
$username) || empty($password) || empty($slots) || empty($boxid)) {
        die();
    }
    if(!empty(
$orderid)) {
        
$pending_id $orderid;
        if(
$DB->exists("s_pending_db","server_pending_id = '".$pending_id."'")) {
            
$order_data unserialize($DB->get_data("s_pending_db","order_data","server_pending_id",$pending_id));
            
$player_id $DB->get_data("s_pending_db","player_id","server_pending_id",$pending_id);
            
$account_id $DB->get_data("s_pending_db","account_id","server_pending_id",$pending_id);

            
$DB->query("INSERT INTO s_subscription_db VALUES ('','".$player_id."','".$account_id."','".time()."','".date('d')."','".$order_data["desc"]."','".$order_data["total"]."');") or trigger_error('Subscription add failed: '.$DB->error(),E_USER_ERROR);
            
$subscription_id mysql_insert_id();

            
//$DB->query("DELETE FROM s_pending_db WHERE server_pending_id = '".$pending_id."';") or trigger_error($DB->error(),E_USER_ERROR);
        
}
        else {
            die(
"\nOrder ID NOT FOUND. Subscription entries not added.\n");
        }
    }
    else {
        
$pending_id 0;
    }

    
$sql1 $DB->query("INSERT INTO s_db VALUES ('','0','0','0','true','false');") or die('Error: Couldn\'t insert into s_db');
    
$server_id mysql_insert_id();

    
$sql2 $DB->query("INSERT INTO s_internal_db VALUES ('','$server_id','".$username."','".$password."','0','".$slots."','".$branding."','".$public."','".$caption."','".$subscription_id."','','0','','".$boxid."','');") or die("Error: Couldn't insert into s_internal_db: ".mysql_error());


    
$sql22 $DB->query("SELECT ip FROM s_ip_db WHERE server_box_id = '".$boxid."' ORDER BY ip ASC LIMIT 1") or die(mysql_error());
    
$ip $DB->result($sql22,0);

    
$box = new boxControl;
    
$box->ip $ip;
    
$box->connect();
    echo 
$box->command('init '.$username);
    echo 
$box->command('stop '.$username);
    
$box->disconnect();
    unset(
$box);

    return 
true;
}

function 
addconfig ($USERNAME,$cfg_id) {
    global 
$DB;
    
    
$q1 $DB->query("SELECT * FROM s_config_db WHERE server_config_id = '".$cfg_id."';") or die(mysql_error());
    
$cfg_info $DB->fetch_array($q1);
    
    
$q2 $DB->query("SELECT * FROM s_gametype_db WHERE server_gametype_id = '".$cfg_info["gametype"]."';") or die(mysql_error());
    
$gametype_details $DB->fetch_array($q2);
    
$cfg_path $gametype_details["cfg_path"];

    
$server_path '/servers/'.$USERNAME;

    
$init_code $gametype_details["initialise_code"];
    if(!
file_exists('/servers/'.$USERNAME.'/'.$cfg_path)) {
        eval(
$init_code);
    }


    
$sql1 $DB->query("SELECT A.server_addon_id, A.initialise_code FROM s_addon_values_db AS V JOIN s_addon_db AS A ON V.server_addon_id = A.server_addon_id WHERE V.server_config_id = '".$cfg_id."' ORDER BY A.order ASC") or trigger_error($DB->error(),E_USER_ERROR);
    while(
$addons $DB->fetch_array($sql1)) {
        if(!empty(
$addons["initialise_code"])) {
            eval(
stripslashes($addons["initialise_code"]));
        }
    }

    
$newcfg '/servers/'.$USERNAME.'/'.$cfg_path.$cfg_id.'.cfg';
    
$new_file fopen($newcfg,'w');
    
$result fwrite($new_file,stripslashes($cfg_info["config_data"]));
    
fclose($new_file);
    
    
system('/usr/bin/fragzzPanel_chmod_cfg 774 '.$USERNAME.'/'.$cfg_path);

    return 
true;
}

function 
gut_out ($from,$to,$del true) {
    if(
$del == true) {
        
system('rm -rf '.$to);
    }
    
system('mkdir '.$to);
    
system('ln -s '.$from.'/* '.$to.'/');
    return 
true;
}

function 
copy_out ($from,$to,$extra " --reply=no",$del true) {
    if(
$del == true) {
        
system('rm -rf '.$to);
    }
    
system('mkdir '.$to);
    
system('cp '.$from.'/* '.$to.'/ -r'.$extra);
    return 
true;
}


function 
next_available($box,$start,$jump 1) {
    global 
$DB;

    
$found false;
    
$current $start;
    
$sql1 $DB->query("SELECT ip FROM s_ip_db WHERE server_box_id = '$box';");
    while(
$ipd $DB->fetch_array($sql1)) {
        
$ips[] = $ipd[0];
    }
    
$useip 0;

    while (
$found == false) {
        
$q $DB->query("SELECT server_reserved_id FROM s_reserved_db WHERE ip = '".$ips[$useip]."' && port = '$current'");
        if (
$DB->num_rows($q) != 0) {
            
$useip++;
            if(!isset(
$ips[$useip])) {
                
$useip 0;
                
$current++;
            }
        }
        else {
            
$use = array('ip' => $ips[$useip], 'port' => $current);
            
$found true;
        }
    }

    return 
$use;
}

function 
apply_config($server_id$USERNAME$server_config_id) {
    global 
$DB;
    global 
$LOGIN;
    global 
$SITE;

    if(
$USERNAME == 'demo') {
        return 
false;
    }
    else {
        if(!empty(
$server_config_id)) {
            
$current_addons $DB->get_data('s_internal_db','current_addons','server_id',$server_id);
            
$current_addons unserialize(stripslashes($current_addons));
            foreach(
$current_addons as $addon_id) {
                
$remove_code $DB->get_data('s_addon_db','remove_code','server_addon_id',$addon_id);
                eval(
stripslashes($remove_code));

                unset(
$remove_code);
                unset(
$addon_id);
            }

            
$box_id $DB->get_data('s_internal_db','current_box','server_id',$server_id);
            
$new_config $DB->fetch_array($DB->query("SELECT * FROM s_config_db WHERE server_config_id = '".$server_config_id."'"));
            
$new_gametype $DB->fetch_array($DB->query("SELECT * FROM s_gametype_db WHERE server_gametype_id = '".$new_config['gametype']."'"));

            
$CFG $server_config_id.'.cfg';
            if(
$new_config["player_slots"] > 0) {
                
$MAXPLAYERS $new_config["player_slots"];
            }
            else {
                
$MAXPLAYERS $DB->get_data('s_internal_db','player_slots','server_id',$server_id);    
            }
            
$MAP $new_config["map"];

            
$sql1 $DB->query("SELECT ip, port FROM s_reserved_db WHERE gametype = '".$new_config['gametype']."' && server_id = '".$server_id."';") or trigger_error(mysql_error(),E_USER_ERROR);
            if(
$DB->num_rows($sql1) == 0) {
                if(
$DB->get_data('s_db','fragzz','server_id',$server_id) == 'true') {
                    if(
$new_gametype['port_increment'] == '11') {
                        
$new_gametype['default_port'] = $new_gametype['default_port'] + 18;
                    }
                    else {
                        
$new_gametype["default_port"] = $new_gametype["default_port"] + 15;
                    }
                }

                
$ip_result next_available($box_id,$new_gametype["default_port"],$new_gametype["port_increment"]);
                
$IP $ip_result["ip"];
                
$PORT $ip_result["port"];
                
$DB->query("INSERT INTO s_reserved_db VALUES ('','".$server_id."','".$new_config['gametype']."','".$IP."','".$PORT."','true','".time()."');") or trigger_error('Couldn\'t switch: '.mysql_error(),E_USER_ERROR);
            }
            else {
                
$IP $DB->result($sql1,0,"ip");
                
$PORT $DB->result($sql1,0,"port");
            }

            
$PORT1 $PORT 1;
            
$PORT2 $PORT 2;
            
$PORT3 $PORT 3;
            
$PORT4 $PORT 4;
            
$PORT5 $PORT 5;
            
$PORT10 $PORT 10;
            
$PORT500 $PORT 500;
            
$PORT1000 $PORT 1000;
            
$PORT2000 $PORT 2000;


            
$DB->query("UPDATE s_reserved_db SET inuse = 'true', lastused = '".time()."' WHERE server_id = '".$server_id."' && ip = '".$IP."' && port = '".$PORT."';") or trigger_error("Warning: Couldn't set new reservation in use",E_USER_WARNING);

            
$DB->query("UPDATE s_reserved_db SET inuse = 'false' WHERE inuse = 'true' && server_id = '".$server_id."' && ip != '".$IP."' && port != '".$PORT."';") or trigger_error("Warning: Couldn't remove old reservation",E_USER_WARNING);

            if(
$new_gametype["server_gametype_id"] == 11) {
                
$RUNUSERNAME 'root';
            }
            else {
                
$RUNUSERNAME $USERNAME;
            }

            
$is_fragzz $DB->get_data('s_db','fragzz','server_id',$server_id);
            if(
$is_fragzz == "true") {
                
$adjustment "-10";
            }
            else {
                
$adjustment "-20";
            }

            
$server_path "/servers/".$USERNAME;
            
$cfg_path $new_gametype["cfg_path"];

            
$init_code $new_gametype["initialise_code"];
            if(!
file_exists($server_path.'/'.$cfg_path)) {
                eval(
$init_code);
            }
            
            
$apply_code $new_gametype["apply_code"];
            if(!empty(
$apply_code)) {
                eval(
$apply_code);
            }

            eval(
"\$new_gametype['binary_arguments'] = \"".$new_gametype['binary_arguments']."\";");


            
$current_addons = array();
            
$sql1 $DB->query("SELECT A.server_addon_id, A.binary_arguments, A.initialise_code, A.apply_code, A.addon_type FROM s_addon_values_db AS V JOIN s_addon_db AS A ON V.server_addon_id = A.server_addon_id WHERE V.server_config_id = '".$new_config["server_config_id"]."' ORDER BY A.order ASC") or trigger_error($DB->error(),E_USER_ERROR);
            while(
$addons $DB->fetch_array($sql1)) {
                
$current_addons[] = $addons["server_addon_id"];
                if(!empty(
$addons["apply_code"])) {
                    eval(
stripslashes($addons["apply_code"]));
                }
                if(
$addons["addon_type"] == 'core') {
                    
$new_gametype["binary_arguments"] = $addons["binary_arguments"] . ' ' $new_gametype["binary_arguments"];
                }
                else {
                    
$new_gametype["binary_arguments"] = $new_gametype["binary_arguments"] . ' ' $addons["binary_arguments"];
                }
            }

            
$current_addons serialize($current_addons);
            
$DB->query("UPDATE s_internal_db SET current_config = '".$new_config["server_config_id"]."', current_addons = '".addslashes($current_addons)."' WHERE server_id = '".$server_id."';");

            
system('/usr/bin/fragzzPanel_chmod_cfg 774 '.$USERNAME.'/'.$cfg_path);
            
$config_file fopen($server_path.'/'.$cfg_path.$new_config["server_config_id"].'.cfg','w');
            
fwrite($config_file,stripslashes($new_config["config_data"])."\n");

            
$sql1 $DB->query("SELECT O.server_option_id, O.output, O.format_string, V.value, O.space FROM s_option_values_db AS V JOIN s_option_db AS O ON V.server_option_id = O.server_option_id WHERE V.server_config_id = '".$new_config["server_config_id"]."' ORDER BY O.order ASC") or trigger_error($DB->error(),E_USER_ERROR);
            while(
$options $DB->fetch_array($sql1)) {
                if(
$options["value"] != "" $DB->get_data('s_option_db','always_include','server_option_id',$options[0]) == 'true') {
                    
$value $options["value"];
                    eval(
"\$options[\"format_string\"] = \"".str_replace('"','\"',$options["format_string"])."\";");
                    if(
$options["output"] == "config") {
                        
fwrite($config_file,$options["format_string"]);
                    }
                    elseif(
$options["output"] == "command") {
                        if(
$options["space"] == 'true') {
                            
$char ' ';
                        }
                        else {
                            
$char '';
                        }
                        
$new_gametype["binary_arguments"] = $new_gametype["binary_arguments"] . $char $options["format_string"];
                    }
                }
            }

            if(
$new_gametype["engine"] == 'ut') {
                if(
$new_gametype["binary_arguments"] == 'server') {
                    die(
'No map was set. Please edit your current configuration and set a map.');
                }
                else {
                    
//$new_gametype["binary_arguments"] = trim($new_gametype['binary_arguments'])."?maxplayers=".$MAXPLAYERS." ini=".$CFG." multihome=".$IP." port=".$PORT;
                
}
            }
            
            if(
$new_gametype["engine"] == 'hl') {
                if(
$DB->get_data('s_internal_db','player_slots','server_id',$server_id) > 15) {
                    
$new_gametype["binary_arguments"] = $new_gametype["binary_arguments"] . " +sys_ticrate 600";
                }
                else {
                    
$new_gametype["binary_arguments"] = $new_gametype["binary_arguments"] . " +sys_ticrate 500";
                }                    
            }

            
$server_cfg_f fopen("/servers/".$USERNAME."/run",'w');
            
$new_run_file '#!/bin/sh
HOME="/servers/'
.$USERNAME.'"
USERNAME="'
.$USERNAME.'"
DISPLAY=localhost:0
TERM=xterm
LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH
BINARY="'
.$new_gametype["binary_path"].'"
EXTRA="'
.$new_gametype["binary_arguments"].'"';

if (
$new_gametype["change_dir"] != 'false') {
$new_run_file .= '
DIR="'
.$new_gametype["change_dir"].'"

cd $DIR'
;
}

$new_run_file .= '
exec nice --adjustment='
.$adjustment.' envdir /servers/$USERNAME/env setuidgid '.$RUNUSERNAME.' $BINARY $EXTRA 2>&1';
            
fwrite($server_cfg_f,$new_run_file);
            
fclose($server_cfg_f);

            
fclose($config_file);

            if(
$new_config["gametype"] == '9') {
                
system('rm -rf '.$server_path.'/hl/'.$selected_mod.'/server.cfg');
                
system('ln -s '.$server_path.'/hl/'.$selected_mod.'/'.$new_config["server_config_id"].'.cfg '.$server_path.'/hl/'.$selected_mod.'/server.cfg');
            }

            if(
$new_config["gametype"] == '27') {
                
system('rm -rf '.$server_path.'/steam-hl/'.$selected_mod.'/server.cfg');
                
system('ln -s '.$server_path.'/steam-hl/'.$selected_mod.'/'.$new_config["server_config_id"].'.cfg '.$server_path.'/steam-hl/'.$selected_mod.'/server.cfg');
            }

            eval(
"\$mapcycle_path = \"".$new_gametype["mapcycle_path"]."\";");
            if(!empty(
$mapcycle_path)) {
                
$map_file fopen("/servers/".$USERNAME."/".$mapcycle_path,"w");
                
fwrite($map_file,$new_config['mapcycle_data']);
                
fclose($map_file);
            }

            
system('chmod +x '."/servers/".$USERNAME."/run");

            
$DB->query("UPDATE s_db SET gametype = '".$new_config['gametype']."', ip = '".$IP."', port = '".$PORT."' WHERE server_id = '".$server_id."';") or trigger_error($DB->error(),E_USER_ERROR);

            
$GLOBALS["IP"] = $IP;
            
$GLOBALS["PORT"] = $PORT;

            return 
true;
        }
        else {
            return 
false;
        }
    }
}


function 
server_blank ($var)
{
    if (
$var == '' $var == '\n') {
        return 
0;
    } else {
        return 
1;
    } 


function 
fetch_server_list ($extra ''$all false$cache false)
{
    global 
$SITE;
    global 
$DB;

    if(
$all == true) {
        
$querystring "";
        
$sql1 $DB->query("SELECT S.ip, S.port, G.qstat FROM s_db AS S JOIN s_gametype_db AS G ON S.gametype = G.server_gametype_id WHERE S.ip != '' && S.ip != '0' ORDER BY S.fragzz") or trigger_error($DB->error(),E_USER_ERROR);
        
$sql1 mysql_query("SELECT S.ip, S.port, G.qstat, I.current_box FROM s_db AS S JOIN s_internal_db AS I ON S.server_id = I.server_id JOIN s_gametype_db AS G ON S.gametype = G.server_gametype_id WHERE S.external_lists = 'true' && I.status = 'up' && S.port != '0' ORDER BY S.fragzz, S.port ASC;") or die(mysql_error());
    }
    else {
        
$querystring " WHERE I.site_id = '".$SITE->site_id."' && S.ip != '' && S.ip != '0'";
        if (
file_exists('/tmp/serverlist'.$SITE->site_id)) {
            
unlink('/tmp/serverlist'.$SITE->site_id);
            
unlink('/tmp/serverlistout'.$SITE->site_id);
        }
        
$sql1 $DB->query("SELECT S.ip, S.port, G.qstat FROM s_site_db AS I JOIN s_db AS S ON S.server_id = I.server_id LEFT JOIN s_gametype_db AS G ON S.gametype = G.server_gametype_id$querystring ORDER BY S.fragzz") or trigger_error($DB->error(),E_USER_ERROR);
    }
    
    

    while(
$servers $DB->fetch_array($sql1)) {
        if(
$all != true || $DB->get_data('s_box_db','status','server_box_id',$servers["current_box"]) == 'online') {
            
$output .= strtolower($servers[2]).' '.$servers[0].':'.$servers[1]."\n";
        }
    }
    
$file fopen('/tmp/serverlist'.$SITE->site_id,'w');
    
fwrite($file,$output);
    
fclose($file);
    

    
$from '/tmp/serverlist'.$SITE->site_id;
    
$to '/tmp/serverlistout'.$SITE->site_id;

    if(
$cache == false filemtime($to) < time()-$cache) {
        
$data = `qstat -f $from -raw ///$extra -nh > $to`;
    }

    
$data_array file($to);
    if(
is_array($data_array)) {
        foreach (
$data_array AS $key => $value) {
            
$data_array[$key] = preg_replace('[\n]'''$value);
        } 
        
$data_array array_filter($data_array'server_blank');
        foreach(
$data_array AS $key => $value) {
            
$data_array[$key] = explode('///'$value);
        }

        return(
$data_array);
    }
    else {
        return 
false;
    }


function 
server_query_small ($host$gametype$extra '')
{
    global 
$qstat_game_types;
    global 
$DB;

    
$gametype $DB->get_data('s_gametype_db','qstat','server_gametype_id',$gametype);
    
$server server_query($hoststrtolower($gametype));

    foreach(
$server AS $svalue) {
        if (
$svalue[0] == 'PLAYER') {
            
$nick str_replace('@'''substr($svalue[1], 020));
            if (
$nick != $svalue[1]) {
                
$nick "<font name='$svalue[1]'>" $nick "</font>...";
            } 
            
$o .= "<tr><td style='border-top: 1px solid #137FE3'><font size=1>" $nick "</font></td><td style='border-top: 1px solid #137FE3'><font size=1>" $svalue[2] . "</font></td><td style='border-top: 1px solid #137FE3'><font size=1>" $svalue[3] . "</font></td></tr>\n";
        } else {
            
$o .= "<b>" $qstat_game_types[$gametype] . "</b><br>
            <b>" 
$svalue[2] . "</b><br>
            <i>" 
$svalue[1] . "</i><br><hr height=1 noshade>
            Players: " 
$svalue[5] . " / " $svalue[4] . "<br>
            Map: " 
$svalue[3];

            if (
$svalue[5] != '0') {
                
$o .= "<br><br><b>Players</b>
                <hr height=1 noshade>
                <table width=100% cellpadding=2 cellspacing=0 border=0>
                <tr><td><i>nickname</i></td><td><i>frags</i></td><td><i>ping</i></td></tr>"
;
                
$end '</table><br><br>';
            } else {
                
$end '';
            } 
        } 
    } 

    
$o .= $end;
    return 
$o;


function 
hottest_server()
{
    global 
$qstat_game_types;

    
$data fetch_server_list(' -sort n',true);
    
$server server_query($data[0][1], strtolower($data[0][0]), ' -sort F''120');

    foreach(
$server AS $svalue) {
        if (
$svalue[0] == 'PLAYER') {
            
$nick str_replace('@'''substr($svalue[1], 013));
            if (
$nick != $svalue[1]) {
                
$nick "<font name='$svalue[1]'>" $nick "</font>...";
            } 
            
$o .= "<tr><td style='border-top: 1px solid #137FE3'><font size=1>" $nick "</font></td><td style='border-top: 1px solid #137FE3'><font size=1>" $svalue[3] . "</font></td></tr>\n";
        } else {
            
$o .= "$nextserver<b>" $qstat_game_types[$data[0][0]] . "</b><br>
            <b>" 
$data[0][2] . "</b><br>
     &nbs