Clean up environment

This commit is contained in:
fanyx 2022-06-26 17:39:27 +02:00
parent d07e4ec6dc
commit 839b000ef1
12 changed files with 3 additions and 3290 deletions

6
.gitignore vendored
View File

@ -1,4 +1,4 @@
/scripts
.gitignore
docker-compose.yml
/.tmp
/.tmp
.env
.env-mysql

View File

@ -1,2 +0,0 @@
# TODO's
- test runs

View File

@ -1,135 +0,0 @@
#!/bin/bash
#
set -e
if [[ "$(id -u)" = "0" ]]; then
chown -R trackmania /opt/tmserver
exec su-exec trackmania "$0"
fi
# Change dir to /opt/tmserver
cd /opt/tmserver
# Evaluate all the available environment variables
if [[ -z "${SERVER_LOGIN}" ]]; then
echo "Server account login is missing. Server cannot start."
echo "Please set environment variable SERVER_LOGIN."
exit 9
fi
if [[ -z "${SERVER_LOGIN_PASSWORD}" ]]; then
echo "Server account password is missing. Server cannot start."
echo "Please set environment variable SERVER_LOGIN_PASSWORD."
exit 9
fi
if [[ -z "${SERVER_PORT}" ]]; then
echo "No server port was set. Defaulting to port 2350"
export SERVER_PORT="2350"
fi
if [[ -z "${SERVER_P2P_PORT}" ]]; then
echo "No server peer2peer port was set. Defaulting to port 3450"
export SERVER_P2P_PORT="3450"
fi
if [[ -z "${SERVER_SA_PASSWORD}" ]]; then
echo "No SuperAdmin password was set. Generating a random one. You can change it afterwards but it's also not that important"
echo "Might aswell leave it as randomly generated"
export SERVER_SA_PASSWORD=$(pwgen -s 12)
echo "SuperAdmin password: ${SERVER_SA_PASSWORD}"
echo "Please write this down or pipe the docker logs to a file."
fi
if [[ -z "${SERVER_ADM_PASSWORD}" ]]; then
echo "No Admin password was set. Generating a random one. You can change it afterwards but it's also not that important"
echo "Might aswell leave it as randomly generated"
export SERVER_ADM_PASSWORD=$(pwgen -s 12)
echo "Admin password: ${SERVER_ADM_PASSWORD}"
echo "Please write this down or pipe the docker logs to a file."
fi
if [[ -z "${SERVER_NAME}" ]]; then
echo "No server name was set. Defaulting to 'Trackmania Server'"
export SERVER_NAME="Trackmania Server"
fi
if [[ -z "${SERVER_COMMENT}" ]]; then
echo "No server description was set. Defaulting to 'This is a Trackmania Server'"
export SERVER_COMMENT="This is a Trackmania Server"
fi
if [[ -z "${GAMEMODE}" ]]; then
echo "No gamemode was specified. Defaulting to TimeAttack."
export GAMEMODE="1"
fi
if [[ -z "${CHATTIME}" ]]; then
echo "No chat timeout was specified. Defaulting to 10000 ms."
export CHATTIME="10000"
fi
if [[ -z "${FINISHTIMEOUT}" ]]; then
echo "No finish timeout was specified. Defaulting to adaptive mode."
export FINISHTIMEOUT="1"
fi
if [[ -z "${DISABLERESPAWN}" ]]; then
echo "Respawns were not specified. Defaulting to enabled."
export DISABLERESPAWN="0"
fi
if [[ -z "${ROUNDS_POINTSLIMIT}" ]]; then
echo "No points limit was specified for rounds mode. Defaulting to 30."
export ROUNDS_POINTSLIMIT="30"
fi
if [[ -z "${TIMEATTACK_LIMIT}" ]]; then
echo "No time limit was specified for time attack mode. Defaulting to 180000 ms."
export TIMEATTACK_LIMIT="180000"
fi
if [[ -z "${TEAM_POINTSLIMIT}" ]]; then
echo "No points limit was specified for team mode. Defaulting to 50."
export TEAM_POINTSLIMIT="50"
fi
if [[ -z "${TEAM_MAXPOINTS}" ]]; then
echo "No number of maximum points per round was specified for team mode. Defaulting to 6."
export TEAM_MAXPOINTS="6"
fi
if [[ -z "${LAPS_NBLAPS}" ]]; then
echo "No number of laps was specified for laps mode. Defaulting to 5."
export LAPS_NBLAPS="5"
fi
if [[ -z "${LAPS_TIMELIMIT}" ]]; then
echo "No time limit was specified for laps mode. Defaulting to no limit."
export LAPS_TIMELIMIT="0"
fi
echo "Evaluation over"
echo "Checking for custom playlist"
CUSTOM_PLAYLIST='playlist/playlist.txt'
TEMPLATE_FILE='GameData/Tracks/MatchSettings/_playlist.txt'
TEMPLATE_FILE_TEMP='GameData/Tracks/MatchSettings/_playlist.txt.tmp'
PLAYLIST_FILE_TEMP='GameData/Tracks/MatchSettings/playlist.txt.tmp'
cp $TEMPLATE_FILE $PLAYLIST_FILE_TEMP
if [[ -f 'playlist/playlist.txt' ]]; then
count=1
while read l; do
xmlstarlet ed -s /playlist -t elem -n challenge $PLAYLIST_FILE_TEMP > $TEMPLATE_FILE_TEMP
xmlstarlet ed -s "/playlist/challenge[${count}]" -t elem -n file -v "${l}" $TEMPLATE_FILE_TEMP > $PLAYLIST_FILE_TEMP
count=$((count+1))
done < $CUSTOM_PLAYLIST
else
xmlstarlet ed -s /playlist -t elem -n challenge $PLAYLIST_FILE_TEMP > $TEMPLATE_FILE_TEMP
xmlstarlet ed -s "playlist/challenge[1]" -t elem -n file -v "Challenges/Nadeo/A01-Race.Challenge.Gbx" $TEMPLATE_FILE_TEMP > $PLAYLIST_FILE_TEMP
fi
echo "Evaluating custom playlist over"
echo "Substition in config files"
#Trackmania Files
envsubst < GameData/Config/_config.txt > GameData/Config/config.txt
envsubst < $PLAYLIST_FILE_TEMP > GameData/Tracks/MatchSettings/playlist.txt
exec "./TrackmaniaServer" "/nodaemon" "/internet" "/game_settings=MatchSettings/playlist.txt" "/dedicated_cfg=config.txt"

View File

@ -1,92 +0,0 @@
<?xml version="1.0" encoding="utf-8" ?>
<dedicated>
<authorization_levels>
<level>
<name>SuperAdmin</name>
<password>$SERVER_SA_PASSWORD</password>
</level>
<level>
<name>Admin</name>
<password>$SERVER_ADM_PASSWORD</password>
</level>
<level>
<name>User</name>
<password>User</password>
</level>
</authorization_levels>
<masterserver_account>
<login>$SERVER_LOGIN</login>
<password>$SERVER_LOGIN_PASSWORD</password>
<validation_key></validation_key>
</masterserver_account>
<server_options>
<name>$SERVER_NAME</name>
<comment>$SERVER_COMMENT</comment>
<hide_server>0</hide_server> <!-- value is 0 (always shown), 1 (always hidden), 2 (hidden from nations) -->
<max_players>32</max_players>
<password>$SERVER_PASSWORD</password>
<max_spectators>32</max_spectators>
<password_spectator></password_spectator>
<ladder_mode>forced</ladder_mode> <!-- value between 'inactive', 'forced' (or '0', '1') -->
<ladder_serverlimit_min>0</ladder_serverlimit_min> <!-- Those values will be clamped to the limits authorized on http://official.trackmania.com/tmf-ladderserver/ -->
<ladder_serverlimit_max>50000</ladder_serverlimit_max>
<enable_p2p_upload>True</enable_p2p_upload>
<enable_p2p_download>True</enable_p2p_download>
<callvote_timeout>60000</callvote_timeout>
<callvote_ratio>0.5</callvote_ratio> <!-- default ratio. value in [0..1], or -1 to forbid. -->
<callvote_ratios>
<voteratio command="Ban" ratio="0.65"/>
<!-- commands can be "Ban", "Kick", "ChallengeRestart", "NextChallenge", ... -->
</callvote_ratios>
<allow_challenge_download>True</allow_challenge_download>
<autosave_replays>False</autosave_replays>
<autosave_validation_replays>False</autosave_validation_replays>
<referee_password></referee_password>
<referee_validation_mode>0</referee_validation_mode> <!-- value is 0 (only validate top3 players), 1 (validate all players) -->
<use_changing_validation_seed>False</use_changing_validation_seed>
</server_options>
<system_config>
<connection_uploadrate>512</connection_uploadrate> <!-- Kbps (kilo bits per second) -->
<connection_downloadrate>8192</connection_downloadrate> <!-- Kbps -->
<force_ip_address></force_ip_address>
<server_port>$SERVER_PORT</server_port>
<server_p2p_port>$SERVER_P2P_PORT</server_p2p_port>
<client_port>0</client_port>
<bind_ip_address></bind_ip_address>
<use_nat_upnp></use_nat_upnp>
<p2p_cache_size>600</p2p_cache_size>
<xmlrpc_port>5000</xmlrpc_port>
<xmlrpc_allowremote>True</xmlrpc_allowremote> <!-- If you specify an ip adress here, it'll be the only accepted adress. this will improve security. -->
<blacklist_url></blacklist_url>
<guestlist_filename></guestlist_filename>
<blacklist_filename></blacklist_filename>
<packmask>stadium</packmask>
<allow_spectator_relays>False</allow_spectator_relays>
<!-- <minimum_client_build>2009-10-01</minimum_client_build> -->
<!-- <disable_coherence_checks>laps</disable_coherence_checks> -->
<use_proxy>False</use_proxy>
<proxy_login></proxy_login>
<proxy_password></proxy_password>
</system_config>
</dedicated>

View File

@ -1,39 +0,0 @@
<?xml version="1.0" encoding="utf-8" ?>
<playlist>
<gameinfos>
<game_mode>$GAMEMODE</game_mode>
<chat_time>$CHATTIME</chat_time>
<finishtimeout>$FINISHTIMEOUT</finishtimeout>
<allwarmupduration>0</allwarmupduration>
<disablerespawn>$DISABLERESPAWN</disablerespawn>
<forceshowallopponents>0</forceshowallopponents>
<rounds_pointslimit>$ROUNDS_POINTSLIMIT</rounds_pointslimit>
<rounds_usenewrules>0</rounds_usenewrules>
<rounds_forcedlaps>0</rounds_forcedlaps>
<rounds_pointslimitnewrules>5</rounds_pointslimitnewrules>
<team_pointslimit>$TEAM_POINTSLIMIT</team_pointslimit>
<team_maxpoints>$TEAM_MAXPOINTS</team_maxpoints>
<team_usenewrules>0</team_usenewrules>
<team_pointslimitnewrules>5</team_pointslimitnewrules>
<timeattack_limit>$TIMEATTACK_LIMIT</timeattack_limit>
<timeattack_synchstartperiod>0</timeattack_synchstartperiod>
<laps_nblaps>$LAPS_NBLAPS</laps_nblaps>
<laps_timelimit>$LAPS_TIMELIMIT</laps_timelimit>
<cup_pointslimit>100</cup_pointslimit>
<cup_roundsperchallenge>5</cup_roundsperchallenge>
<cup_nbwinners>3</cup_nbwinners>
<cup_warmupduration>2</cup_warmupduration>
</gameinfos>
<filter>
<is_lan>1</is_lan>
<is_internet>1</is_internet>
<is_solo>0</is_solo>
<is_hotseat>0</is_hotseat>
<sort_index>7</sort_index>
<random_map_order>0</random_map_order>
<force_default_gamemode>0</force_default_gamemode>
</filter>
<startindex>0</startindex>
</playlist>

View File

@ -1,867 +0,0 @@
<?php
/* vim: set noexpandtab tabstop=2 softtabstop=2 shiftwidth=2: */
/*
IXR - The Incutio XML-RPC Library - (c) Incutio Ltd 2002
Version 1.61 - Simon Willison, 11th July 2003 (htmlentities -> htmlspecialchars)
Site: http://scripts.incutio.com/xmlrpc/
Manual: http://scripts.incutio.com/xmlrpc/manual.php
Made available under the Artistic License: http://www.opensource.org/licenses/artistic-license.php
Modified to support protocol 'GbxRemote 2' ('GbxRemote 1')
This version is for BigEndian machines. For LittleEndian (e.g. Intel PC)
machines use the original GbxRemote.inc.php instead.
Release 2007-09-22 - Slig:
Modified to support >256KB received data (and now >2MB data produce a specific error message)
Modified readCB() to wait the initial timeout only before first read packet
Modified readCB() to return true if there is data to get with getCBResponses()
Modified to support amd64 (for $recvhandle)
Modified IXR_ClientMulticall_Gbx->addCall() to fit Aseco 0.6.1
Added IXR_Client_Gbx->bytes_sent & bytes_received counters
Fix for a changed feature since php5.1.1 about reference parameter assignment (was used in stream_select)
Workaround for stream_select return value bug with amd64
Release 2008-01-20 - Slig / Xymph / Assembler Maniac:
Workaround for fread delay bug in some cases
Added resetError method (by Xymph)
Some comments and strings code cleanup (by Xymph)
Fix stream_set_timeout($this->socket,...) (thx to CavalierDeVache)
Added a default timeout value to function readCB($timeout)
Changed calls with timeout on a stream to use microseconds instead of seconds (by AM)
Removed IXR_Client_Gbx->bytes_sent & bytes_received counters - not used (by AM)
Release 2008-02-05 - Slig:
Changed some socket read/write timeouts back to seconds to avoid 'transport error'
Changed max data received from 2MB to 4MB
Release 2008-05-20 - Xymph:
Prevented unpack() warnings in query method when the connection dies
Changed resetError method to assign 'false' for correct isError method
Tweaked some 'transport error' messages
Release 2009-04-08 - Gou1:
Added method IXR_Client_Gbx::queryIgnoreResult()
Added methods IXR_Client_Gbx::sendRequest() & IXR_Client_Gbx::getResult()
IXR_Client_Gbx::queryIgnoreResult checks if the request is larger than 512KB to avoid errors
If larger than 512KB and method is system.multicall, try to divide the request into
two separate requests with two separate IXR_Client_Gbx::queryIgnoreResult() calls
Release 2009-06-03 - Xymph:
Suppress possible repetitive CRT warning at stream_select
*/
if (!defined('LF')) {
define('LF', "\n");
}
class IXR_Value {
public $data;
public $type;
function IXR_Value ($data, $type = false) {
$this->data = $data;
if (!$type) {
$type = $this->calculateType();
}
$this->type = $type;
if ($type == 'struct') {
// Turn all the values in the array into new IXR_Value objects
foreach ($this->data as $key => $value) {
$this->data[$key] = new IXR_Value($value);
}
}
if ($type == 'array') {
for ($i = 0, $j = count($this->data); $i < $j; $i++) {
$this->data[$i] = new IXR_Value($this->data[$i]);
}
}
}
function calculateType() {
if ($this->data === true || $this->data === false) {
return 'boolean';
}
if (is_integer($this->data)) {
return 'int';
}
if (is_double($this->data)) {
return 'double';
}
// Deal with IXR object types base64 and date
if (is_object($this->data) && is_a($this->data, 'IXR_Date')) {
return 'date';
}
if (is_object($this->data) && is_a($this->data, 'IXR_Base64')) {
return 'base64';
}
// If it is a normal PHP object convert it into a struct
if (is_object($this->data)) {
$this->data = get_object_vars($this->data);
return 'struct';
}
if (!is_array($this->data)) {
return 'string';
}
// We have an array - is it an array or a struct?
if ($this->isStruct($this->data)) {
return 'struct';
} else {
return 'array';
}
}
function getXml() {
// Return XML for this value
switch ($this->type) {
case 'boolean':
return '<boolean>' . ($this->data ? '1' : '0') . '</boolean>';
break;
case 'int':
return '<int>' . $this->data . '</int>';
break;
case 'double':
return '<double>' . $this->data . '</double>';
break;
case 'string':
return '<string>' . htmlspecialchars($this->data) . '</string>';
break;
case 'array':
$return = '<array><data>' . LF;
foreach ($this->data as $item) {
$return .= ' <value>' . $item->getXml() . '</value>' . LF;
}
$return .= '</data></array>';
return $return;
break;
case 'struct':
$return = '<struct>' . LF;
foreach ($this->data as $name => $value) {
$return .= ' <member><name>' . $name . '</name><value>';
$return .= $value->getXml() . '</value></member>' . LF;
}
$return .= '</struct>';
return $return;
break;
case 'date':
case 'base64':
return $this->data->getXml();
break;
}
return false;
}
function isStruct($array) {
// Nasty function to check if an array is a struct or not
$expected = 0;
foreach ($array as $key => $value) {
if ((string)$key != (string)$expected) {
return true;
}
$expected++;
}
return false;
}
}
class IXR_Message {
public $message;
public $messageType; // methodCall / methodResponse / fault
public $faultCode;
public $faultString;
public $methodName;
public $params;
// Current variable stacks
protected $_arraystructs = array(); // Stack to keep track of the current array/struct
protected $_arraystructstypes = array(); // Stack to keep track of whether things are structs or array
protected $_currentStructName = array(); // A stack as well
protected $_param;
protected $_value;
protected $_currentTag;
protected $_currentTagContents;
// The XML parser
protected $_parser;
function IXR_Message ($message) {
$this->message = $message;
}
function parse() {
// first remove the XML declaration
$this->message = preg_replace('/<\?xml(.*)?\?'.'>/', '', $this->message);
if (trim($this->message) == '') {
return false;
}
$this->_parser = xml_parser_create();
// Set XML parser to take the case of tags into account
xml_parser_set_option($this->_parser, XML_OPTION_CASE_FOLDING, false);
// Set XML parser callback functions
xml_set_object($this->_parser, $this);
xml_set_element_handler($this->_parser, 'tag_open', 'tag_close');
xml_set_character_data_handler($this->_parser, 'cdata');
if (!xml_parse($this->_parser, $this->message)) {
/* die(sprintf('GbxRemote XML error: %s at line %d',
xml_error_string(xml_get_error_code($this->_parser)),
xml_get_current_line_number($this->_parser))); */
return false;
}
xml_parser_free($this->_parser);
// Grab the error messages, if any
if ($this->messageType == 'fault') {
$this->faultCode = $this->params[0]['faultCode'];
$this->faultString = $this->params[0]['faultString'];
}
return true;
}
function tag_open($parser, $tag, $attr) {
$this->currentTag = $tag;
switch ($tag) {
case 'methodCall':
case 'methodResponse':
case 'fault':
$this->messageType = $tag;
break;
// Deal with stacks of arrays and structs
case 'data': // data is to all intents and purposes more interesting than array
$this->_arraystructstypes[] = 'array';
$this->_arraystructs[] = array();
break;
case 'struct':
$this->_arraystructstypes[] = 'struct';
$this->_arraystructs[] = array();
break;
}
}
function cdata($parser, $cdata) {
$this->_currentTagContents .= $cdata;
}
function tag_close($parser, $tag) {
$valueFlag = false;
switch ($tag) {
case 'int':
case 'i4':
$value = (int)trim($this->_currentTagContents);
$this->_currentTagContents = '';
$valueFlag = true;
break;
case 'double':
$value = (double)trim($this->_currentTagContents);
$this->_currentTagContents = '';
$valueFlag = true;
break;
case 'string':
$value = (string)trim($this->_currentTagContents);
$this->_currentTagContents = '';
$valueFlag = true;
break;
case 'dateTime.iso8601':
$value = new IXR_Date(trim($this->_currentTagContents));
// $value = $iso->getTimestamp();
$this->_currentTagContents = '';
$valueFlag = true;
break;
case 'value':
// If no type is indicated, the type is string
if (trim($this->_currentTagContents) != '') {
$value = (string)$this->_currentTagContents;
$this->_currentTagContents = '';
$valueFlag = true;
}
break;
case 'boolean':
$value = (boolean)trim($this->_currentTagContents);
$this->_currentTagContents = '';
$valueFlag = true;
break;
case 'base64':
$value = base64_decode($this->_currentTagContents);
$this->_currentTagContents = '';
$valueFlag = true;
break;
// Deal with stacks of arrays and structs
case 'data':
case 'struct':
$value = array_pop($this->_arraystructs);
array_pop($this->_arraystructstypes);
$valueFlag = true;
break;
case 'member':
array_pop($this->_currentStructName);
break;
case 'name':
$this->_currentStructName[] = trim($this->_currentTagContents);
$this->_currentTagContents = '';
break;
case 'methodName':
$this->methodName = trim($this->_currentTagContents);
$this->_currentTagContents = '';
break;
}
if ($valueFlag) {
/*
if (!is_array($value) && !is_object($value)) {
$value = trim($value);
}
*/
if (count($this->_arraystructs) > 0) {
// Add value to struct or array
if ($this->_arraystructstypes[count($this->_arraystructstypes)-1] == 'struct') {
// Add to struct
$this->_arraystructs[count($this->_arraystructs)-1][$this->_currentStructName[count($this->_currentStructName)-1]] = $value;
} else {
// Add to array
$this->_arraystructs[count($this->_arraystructs)-1][] = $value;
}
} else {
// Just add as a paramater
$this->params[] = $value;
}
}
}
}
class IXR_Request {
public $method;
public $args;
public $xml;
function IXR_Request($method, $args) {
$this->method = $method;
$this->args = $args;
$this->xml = '<?xml version="1.0" encoding="utf-8" ?><methodCall><methodName>' . $this->method . '</methodName><params>';
foreach ($this->args as $arg) {
$this->xml .= '<param><value>';
$v = new IXR_Value($arg);
$this->xml .= $v->getXml();
$this->xml .= '</value></param>' . LF;
}
$this->xml .= '</params></methodCall>';
}
function getLength() {
return strlen($this->xml);
}
function getXml() {
return $this->xml;
}
}
class IXR_Error {
public $code;
public $message;
function IXR_Error($code, $message) {
$this->code = $code;
$this->message = $message;
}
function getXml() {
$xml = <<<EOD
<methodResponse>
<fault>
<value>
<struct>
<member>
<name>faultCode</name>
<value><int>{$this->code}</int></value>
</member>
<member>
<name>faultString</name>
<value><string>{$this->message}</string></value>
</member>
</struct>
</value>
</fault>
</methodResponse>
EOD;
return $xml;
}
}
class IXR_Date {
public $year;
public $month;
public $day;
public $hour;
public $minute;
public $second;
function IXR_Date($time) {
// $time can be a PHP timestamp or an ISO one
if (is_numeric($time)) {
$this->parseTimestamp($time);
} else {
$this->parseIso($time);
}
}
function parseTimestamp($timestamp) {
$this->year = date('Y', $timestamp);
$this->month = date('Y', $timestamp);
$this->day = date('Y', $timestamp);
$this->hour = date('H', $timestamp);
$this->minute = date('i', $timestamp);
$this->second = date('s', $timestamp);
}
function parseIso($iso) {
$this->year = substr($iso, 0, 4);
$this->month = substr($iso, 4, 2);
$this->day = substr($iso, 6, 2);
$this->hour = substr($iso, 9, 2);
$this->minute = substr($iso, 12, 2);
$this->second = substr($iso, 15, 2);
}
function getIso() {
return $this->year.$this->month.$this->day.'T'.$this->hour.':'.$this->minute.':'.$this->second;
}
function getXml() {
return '<dateTime.iso8601>'.$this->getIso().'</dateTime.iso8601>';
}
function getTimestamp() {
return mktime($this->hour, $this->minute, $this->second, $this->month, $this->day, $this->year);
}
}
class IXR_Base64 {
public $data;
function IXR_Base64($data) {
$this->data = $data;
}
function getXml() {
return '<base64>'.base64_encode($this->data).'</base64>';
}
}
//////////////////////////////////////////////////////////
// Nadeo modifications //
// (many thanks to slig for adding callback support) //
//////////////////////////////////////////////////////////
class IXR_Client_Gbx {
public $socket;
public $message = false;
public $cb_message = array();
public $reqhandle;
public $protocol = 0;
// Storage place for an error message
public $error = false;
function bigEndianTest() {
list($endiantest) = array_values(unpack('L1L', pack('V', 1)));
if ($endiantest == 1) {
echo "Machine reports itself as LittleEndian, float handling will work correctly with unpack\r\n";
echo "Use original GbxRemote.inc.php instead of GbxRemote.bem.php\r\n";
die('App Terminated');
return false;
}
return true;
} // bigEndianTest
function IXR_Client_Gbx() {
$this->socket = false;
$this->reqhandle = 0x80000000;
}
function InitWithIp($ip, $port) {
if (!$this->bigEndianTest()) {
$this->error = new IXR_Error(-32999, 'endian error - script doesn\'t match machine type');
return false;
}
// open connection
$this->socket = @fsockopen($ip, $port, $errno, $errstr);
if (!$this->socket) {
$this->error = new IXR_Error(-32300, "transport error - could not open socket (error: $errno, $errstr)");
return false;
}
// handshake
$array_result = big_endian_unpack('Vsize', fread($this->socket, 4));
$size = $array_result['size'];
if ($size > 64) {
$this->error = new IXR_Error(-32300, 'transport error - wrong lowlevel protocol header');
return false;
}
$handshake = fread($this->socket, $size);
if ($handshake == 'GBXRemote 1') {
$this->protocol = 1;
} else if ($handshake == 'GBXRemote 2') {
$this->protocol = 2;
} else {
$this->error = new IXR_Error(-32300, 'transport error - wrong lowlevel protocol version');
return false;
}
return true;
}
function Init($port) {
return $this->InitWithIp('localhost', $port);
}
function Terminate() {
if ($this->socket) {
fclose($this->socket);
$this->socket = false;
}
}
protected function sendRequest(IXR_Request $request) {
$xml = $request->getXml();
@stream_set_timeout($this->socket, 20); // timeout 20 s (to write the request)
// send request
$this->reqhandle++;
if ($this->protocol == 1) {
$bytes = pack('Va*', strlen($xml), $xml);
} else {
$bytes = pack('VVa*', strlen($xml), $this->reqhandle, $xml);
}
$bytes_to_write = strlen($bytes);
while ($bytes_to_write > 0) {
$r = fwrite($this->socket, $bytes);
if ($r === false || $r == 0) {
// connection interrupted
return false; // or die?
}
$bytes_to_write -= $r;
if ($bytes_to_write == 0)
break;
$bytes = substr($bytes, $r);
}
return true;
}
protected function getResult() {
$contents = '';
$contents_length = 0;
do {
$size = 0;
$recvhandle = 0;
@stream_set_timeout($this->socket, 20); // timeout 20 s (to read the reply header)
// Get result
if ($this->protocol == 1) {
$contents = fread($this->socket, 4);
if (strlen($contents) == 0) {
$this->error = new IXR_Error(-32700, 'transport error - connection interrupted!');
return false;
}
$array_result = big_endian_unpack('Vsize', $contents);
$size = $array_result['size'];
$recvhandle = $this->reqhandle;
} else {
$contents = fread($this->socket, 8);
if (strlen($contents) == 0) {
$this->error = new IXR_Error(-32700, 'transport error - connection interrupted!');
return false;
}
$array_result = big_endian_unpack('Vsize/Vhandle', $contents);
$size = $array_result['size'];
$recvhandle = $array_result['handle'];
// -- amd64 support --
$bits = sprintf('%b', $recvhandle);
if (strlen($bits) == 64) {
$recvhandle = bindec(substr($bits, 32));
}
}
if ($recvhandle == 0 || $size == 0) {
$this->error = new IXR_Error(-32700, 'transport error - connection interrupted!');
return false;
}
if ($size > 4096*1024) {
$this->error = new IXR_Error(-32700, "transport error - answer too big ($size)");
return false;
}
$contents = '';
$contents_length = 0;
@stream_set_timeout($this->socket, 0, 10000); // timeout 10 ms (for successive reads until end)
while ($contents_length < $size) {
$contents .= fread($this->socket, $size-$contents_length);
$contents_length = strlen($contents);
}
if (($recvhandle & 0x80000000) == 0) {
// this is a callback, not our answer! handle= $recvhandle, xml-rpc= $contents
// just add it to the message list for the user to read
$new_cb_message = new IXR_Message($contents);
if ($new_cb_message->parse() && $new_cb_message->messageType != 'fault') {
array_push($this->cb_message, array($new_cb_message->methodName, $new_cb_message->params));
}
}
} while ((int)$recvhandle != (int)$this->reqhandle);
$this->message = new IXR_Message($contents);
if (!$this->message->parse()) {
// XML error
$this->error = new IXR_Error(-32700, 'parse error. not well formed');
return false;
}
// Is the message a fault?
if ($this->message->messageType == 'fault') {
$this->error = new IXR_Error($this->message->faultCode, $this->message->faultString);
return false;
}
// Message must be OK
return true;
}
function query() {
$args = func_get_args();
$method = array_shift($args);
if (!$this->socket || $this->protocol == 0) {
$this->error = new IXR_Error(-32300, 'transport error - Client not initialized');
return false;
}
$request = new IXR_Request($method, $args);
// Check if request is larger than 512 Kbytes
if ($request->getLength() > 512*1024-8) {
$this->error = new IXR_Error(-32700, 'transport error - request too large!');
return false;
}
// Send request
$ok = $this->sendRequest($request);
if (!$ok) {
$this->error = new IXR_Error(-32700, 'transport error - connection interrupted');
return false;
}
// Get result
return $this->getResult();
}
// Non-blocking query method: doesn't read the response
function queryIgnoreResult() {
$args = func_get_args();
$method = array_shift($args);
if (!$this->socket || $this->protocol == 0) {
$this->error = new IXR_Error(-32300, 'transport error - Client not initialized');
return false;
}
$request = new IXR_Request($method, $args);
// Check if the request is greater than 512 Kbytes to avoid errors
// If the method is system.multicall, make two calls (possibly recursively)
if ($request->getLength() > 512*1024-8) {
if ($method = 'system.multicall' && isset($args[0])) {
$count = count($args[0]);
// If count is 1, query cannot be reduced
if ($count < 2) {
$this->error = new IXR_Error(-32700, 'transport error - request too large!');
return false;
}
$length = floor($count/2);
$args1 = array_slice($args[0], 0, $length);
$args2 = array_slice($args[0], $length, ($count-$length));
$res1 = $this->queryIgnoreResult('system.multicall', $args1);
$res2 = $this->queryIgnoreResult('system.multicall', $args2);
return ($res1 && $res2);
}
// If the method is not a multicall, just stop
else {
$this->error = new IXR_Error(-32700, 'transport error - request too large!');
return false;
}
}
// Send request
$ok = $this->sendRequest($request);
if (!$ok) {
$this->error = new IXR_Error(-32700, 'transport error - connection interrupted');
return false;
}
}
function readCB($timeout = 2000) { // timeout 2 ms
if (!$this->socket || $this->protocol == 0) {
$this->error = new IXR_Error(-32300, 'transport error - Client not initialized');
return false;
}
if ($this->protocol == 1)
return false;
$something_received = count($this->cb_message)>0;
$contents = '';
$contents_length = 0;
@stream_set_timeout($this->socket, 0, 10000); // timeout 10 ms (to read available data)
// (assignment in arguments is forbidden since php 5.1.1)
$read = array($this->socket);
$write = NULL;
$except = NULL;
$nb = @stream_select($read, $write, $except, 0, $timeout);
// workaround for stream_select bug with amd64
if ($nb !== false)
$nb = count($read);
while ($nb !== false && $nb > 0) {
$timeout = 0; // we don't want to wait for the full time again, just flush the available data
$size = 0;
$recvhandle = 0;
// Get result
$contents = fread($this->socket, 8);
if (strlen($contents) == 0) {
$this->error = new IXR_Error(-32700, 'transport error - connection interrupted!');
return false;
}
$array_result = big_endian_unpack('Vsize/Vhandle', $contents);
$size = $array_result['size'];
$recvhandle = $array_result['handle'];
if ($recvhandle == 0 || $size == 0) {
$this->error = new IXR_Error(-32700, 'transport error - connection interrupted!');
return false;
}
if ($size > 4096*1024) {
$this->error = new IXR_Error(-32700, "transport error - answer too big ($size)");
return false;
}
$contents = '';
$contents_length = 0;
while ($contents_length < $size) {
$contents .= fread($this->socket, $size-$contents_length);
$contents_length = strlen($contents);
}
if (($recvhandle & 0x80000000) == 0) {
// this is a callback. handle= $recvhandle, xml-rpc= $contents
//echo 'CALLBACK('.$contents_length.')[ '.$contents.' ]' . LF;
$new_cb_message = new IXR_Message($contents);
if ($new_cb_message->parse() && $new_cb_message->messageType != 'fault') {
array_push($this->cb_message, array($new_cb_message->methodName, $new_cb_message->params));
}
$something_received = true;
}
// (assignment in arguments is forbidden since php 5.1.1)
$read = array($this->socket);
$write = NULL;
$except = NULL;
$nb = @stream_select($read, $write, $except, 0, $timeout);
// workaround for stream_select bug with amd64
if ($nb !== false)
$nb = count($read);
}
return $something_received;
}
function getResponse() {
// methodResponses can only have one param - return that
return $this->message->params[0];
}
function getCBResponses() {
// (look at the end of basic.php for an example)
$messages = $this->cb_message;
$this->cb_message = array();
return $messages;
}
function isError() {
return is_object($this->error);
}
function resetError() {
$this->error = false;
}
function getErrorCode() {
return $this->error->code;
}
function getErrorMessage() {
return $this->error->message;
}
}
class IXR_ClientMulticall_Gbx extends IXR_Client_Gbx {
public $calls = array();
function addCall($methodName, $args) {
$struct = array('methodName' => $methodName, 'params' => $args);
$this->calls[] = $struct;
return (count($this->calls) - 1);
}
function multiquery($ignoreResult = false) {
// Prepare multicall, then call the parent::query() (or queryIgnoreResult) method
if ($ignoreResult) {
$result = parent::queryIgnoreResult('system.multicall', $this->calls);
} else {
$result = parent::query('system.multicall', $this->calls);
}
$this->calls = array(); // reset for next calls
return $result;
}
}
/**
* The following code is a workaround for php's unpack function which
* does not have the capability of unpacking double precision floats
* that were packed in the opposite byte order of the current machine.
*/
function big_endian_unpack($format, $data) {
$ar = unpack($format, $data);
$vals = array_values($ar);
$f = explode('/', $format);
$i = 0;
foreach ($f as $f_k => $f_v) {
$repeater = intval(substr($f_v, 1));
if ($repeater == 0)
$repeater = 1;
if ($f_v{1} == '*') {
$repeater = count($ar) - $i;
}
if ($f_v{0} != 'd') {
$i += $repeater;
continue;
}
$j = $i + $repeater;
for ($a = $i; $a < $j; ++$a) {
$p = pack('d', $vals[$i]);
$p = strrev($p);
list($vals[$i]) = array_values(unpack('d1d', $p));
++$i;
}
}
$a = 0;
foreach ($ar as $ar_k => $ar_v) {
$ar[$ar_k] = $vals[$a];
++$a;
}
return $ar;
}
?>

View File

@ -1,830 +0,0 @@
<?php
/* vim: set noexpandtab tabstop=2 softtabstop=2 shiftwidth=2: */
/*
IXR - The Incutio XML-RPC Library - (c) Incutio Ltd 2002
Version 1.61 - Simon Willison, 11th July 2003 (htmlentities -> htmlspecialchars)
Site: http://scripts.incutio.com/xmlrpc/
Manual: http://scripts.incutio.com/xmlrpc/manual.php
Made available under the Artistic License: http://www.opensource.org/licenses/artistic-license.php
Modified to support protocol 'GbxRemote 2' ('GbxRemote 1')
This version is for LittleEndian (e.g. Intel PC) machines.
For BigEndian machines use GbxRemote.bem.php as GbxRemote.inc.php instead.
Release 2007-09-22 - Slig:
Modified to support >256KB received data (and now >2MB data produce a specific error message)
Modified readCB() to wait the initial timeout only before first read packet
Modified readCB() to return true if there is data to get with getCBResponses()
Modified to support amd64 (for $recvhandle)
Modified IXR_ClientMulticall_Gbx->addCall() to fit Aseco 0.6.1
Added IXR_Client_Gbx->bytes_sent & bytes_received counters
Fix for a changed feature since php5.1.1 about reference parameter assignment (was used in stream_select)
Workaround for stream_select return value bug with amd64
Release 2008-01-20 - Slig / Xymph / Assembler Maniac:
Workaround for fread delay bug in some cases
Added resetError method (by Xymph)
Some comments and strings code cleanup (by Xymph)
Fix stream_set_timeout($this->socket,...) (thx to CavalierDeVache)
Added a default timeout value to function readCB($timeout)
Changed calls with timeout on a stream to use microseconds instead of seconds (by AM)
Removed IXR_Client_Gbx->bytes_sent & bytes_received counters - not used (by AM)
Release 2008-02-05 - Slig:
Changed some socket read/write timeouts back to seconds to avoid 'transport error'
Changed max data received from 2MB to 4MB
Release 2008-05-20 - Xymph:
Prevented unpack() warnings in query method when the connection dies
Changed resetError method to assign 'false' for correct isError method
Tweaked some 'transport error' messages
Release 2009-04-08 - Gou1:
Added method IXR_Client_Gbx::queryIgnoreResult()
Added methods IXR_Client_Gbx::sendRequest() & IXR_Client_Gbx::getResult()
IXR_Client_Gbx::queryIgnoreResult checks if the request is larger than 512KB to avoid errors
If larger than 512KB and method is system.multicall, try to divide the request into
two separate requests with two separate IXR_Client_Gbx::queryIgnoreResult() calls
Release 2009-06-03 - Xymph:
Suppress possible repetitive CRT warning at stream_select
*/
if (!defined('LF')) {
define('LF', "\n");
}
class IXR_Value {
public $data;
public $type;
function IXR_Value ($data, $type = false) {
$this->data = $data;
if (!$type) {
$type = $this->calculateType();
}
$this->type = $type;
if ($type == 'struct') {
// Turn all the values in the array into new IXR_Value objects
foreach ($this->data as $key => $value) {
$this->data[$key] = new IXR_Value($value);
}
}
if ($type == 'array') {
for ($i = 0, $j = count($this->data); $i < $j; $i++) {
$this->data[$i] = new IXR_Value($this->data[$i]);
}
}
}
function calculateType() {
if ($this->data === true || $this->data === false) {
return 'boolean';
}
if (is_integer($this->data)) {
return 'int';
}
if (is_double($this->data)) {
return 'double';
}
// Deal with IXR object types base64 and date
if (is_object($this->data) && is_a($this->data, 'IXR_Date')) {
return 'date';
}
if (is_object($this->data) && is_a($this->data, 'IXR_Base64')) {
return 'base64';
}
// If it is a normal PHP object convert it into a struct
if (is_object($this->data)) {
$this->data = get_object_vars($this->data);
return 'struct';
}
if (!is_array($this->data)) {
return 'string';
}
// We have an array - is it an array or a struct?
if ($this->isStruct($this->data)) {
return 'struct';
} else {
return 'array';
}
}
function getXml() {
// Return XML for this value
switch ($this->type) {
case 'boolean':
return '<boolean>' . ($this->data ? '1' : '0') . '</boolean>';
break;
case 'int':
return '<int>' . $this->data . '</int>';
break;
case 'double':
return '<double>' . $this->data . '</double>';
break;
case 'string':
return '<string>' . htmlspecialchars($this->data) . '</string>';
break;
case 'array':
$return = '<array><data>' . LF;
foreach ($this->data as $item) {
$return .= ' <value>' . $item->getXml() . '</value>' . LF;
}
$return .= '</data></array>';
return $return;
break;
case 'struct':
$return = '<struct>' . LF;
foreach ($this->data as $name => $value) {
$return .= ' <member><name>' . $name . '</name><value>';
$return .= $value->getXml() . '</value></member>' . LF;
}
$return .= '</struct>';
return $return;
break;
case 'date':
case 'base64':
return $this->data->getXml();
break;
}
return false;
}
function isStruct($array) {
// Nasty function to check if an array is a struct or not
$expected = 0;
foreach ($array as $key => $value) {
if ((string)$key != (string)$expected) {
return true;
}
$expected++;
}
return false;
}
}
class IXR_Message {
public $message;
public $messageType; // methodCall / methodResponse / fault
public $faultCode;
public $faultString;
public $methodName;
public $params;
// Current variable stacks
protected $_arraystructs = array(); // Stack to keep track of the current array/struct
protected $_arraystructstypes = array(); // Stack to keep track of whether things are structs or array
protected $_currentStructName = array(); // A stack as well
protected $_param;
protected $_value;
protected $_currentTag;
protected $_currentTagContents;
// The XML parser
protected $_parser;
function IXR_Message ($message) {
$this->message = $message;
}
function parse() {
// first remove the XML declaration
$this->message = preg_replace('/<\?xml(.*)?\?'.'>/', '', $this->message);
if (trim($this->message) == '') {
return false;
}
$this->_parser = xml_parser_create();
// Set XML parser to take the case of tags into account
xml_parser_set_option($this->_parser, XML_OPTION_CASE_FOLDING, false);
// Set XML parser callback functions
xml_set_object($this->_parser, $this);
xml_set_element_handler($this->_parser, 'tag_open', 'tag_close');
xml_set_character_data_handler($this->_parser, 'cdata');
if (!xml_parse($this->_parser, $this->message)) {
/* die(sprintf('GbxRemote XML error: %s at line %d',
xml_error_string(xml_get_error_code($this->_parser)),
xml_get_current_line_number($this->_parser))); */
return false;
}
xml_parser_free($this->_parser);
// Grab the error messages, if any
if ($this->messageType == 'fault') {
$this->faultCode = $this->params[0]['faultCode'];
$this->faultString = $this->params[0]['faultString'];
}
return true;
}
function tag_open($parser, $tag, $attr) {
$this->currentTag = $tag;
switch ($tag) {
case 'methodCall':
case 'methodResponse':
case 'fault':
$this->messageType = $tag;
break;
// Deal with stacks of arrays and structs
case 'data': // data is to all intents and purposes more interesting than array
$this->_arraystructstypes[] = 'array';
$this->_arraystructs[] = array();
break;
case 'struct':
$this->_arraystructstypes[] = 'struct';
$this->_arraystructs[] = array();
break;
}
}
function cdata($parser, $cdata) {
$this->_currentTagContents .= $cdata;
}
function tag_close($parser, $tag) {
$valueFlag = false;
switch ($tag) {
case 'int':
case 'i4':
$value = (int)trim($this->_currentTagContents);
$this->_currentTagContents = '';
$valueFlag = true;
break;
case 'double':
$value = (double)trim($this->_currentTagContents);
$this->_currentTagContents = '';
$valueFlag = true;
break;
case 'string':
$value = (string)trim($this->_currentTagContents);
$this->_currentTagContents = '';
$valueFlag = true;
break;
case 'dateTime.iso8601':
$value = new IXR_Date(trim($this->_currentTagContents));
// $value = $iso->getTimestamp();
$this->_currentTagContents = '';
$valueFlag = true;
break;
case 'value':
// If no type is indicated, the type is string
if (trim($this->_currentTagContents) != '') {
$value = (string)$this->_currentTagContents;
$this->_currentTagContents = '';
$valueFlag = true;
}
break;
case 'boolean':
$value = (boolean)trim($this->_currentTagContents);
$this->_currentTagContents = '';
$valueFlag = true;
break;
case 'base64':
$value = base64_decode($this->_currentTagContents);
$this->_currentTagContents = '';
$valueFlag = true;
break;
// Deal with stacks of arrays and structs
case 'data':
case 'struct':
$value = array_pop($this->_arraystructs);
array_pop($this->_arraystructstypes);
$valueFlag = true;
break;
case 'member':
array_pop($this->_currentStructName);
break;
case 'name':
$this->_currentStructName[] = trim($this->_currentTagContents);
$this->_currentTagContents = '';
break;
case 'methodName':
$this->methodName = trim($this->_currentTagContents);
$this->_currentTagContents = '';
break;
}
if ($valueFlag) {
/*
if (!is_array($value) && !is_object($value)) {
$value = trim($value);
}
*/
if (count($this->_arraystructs) > 0) {
// Add value to struct or array
if ($this->_arraystructstypes[count($this->_arraystructstypes)-1] == 'struct') {
// Add to struct
$this->_arraystructs[count($this->_arraystructs)-1][$this->_currentStructName[count($this->_currentStructName)-1]] = $value;
} else {
// Add to array
$this->_arraystructs[count($this->_arraystructs)-1][] = $value;
}
} else {
// Just add as a paramater
$this->params[] = $value;
}
}
}
}
class IXR_Request {
public $method;
public $args;
public $xml;
function IXR_Request($method, $args) {
$this->method = $method;
$this->args = $args;
$this->xml = '<?xml version="1.0" encoding="utf-8" ?><methodCall><methodName>' . $this->method . '</methodName><params>';
foreach ($this->args as $arg) {
$this->xml .= '<param><value>';
$v = new IXR_Value($arg);
$this->xml .= $v->getXml();
$this->xml .= '</value></param>' . LF;
}
$this->xml .= '</params></methodCall>';
}
function getLength() {
return strlen($this->xml);
}
function getXml() {
return $this->xml;
}
}
class IXR_Error {
public $code;
public $message;
function IXR_Error($code, $message) {
$this->code = $code;
$this->message = $message;
}
function getXml() {
$xml = <<<EOD
<methodResponse>
<fault>
<value>
<struct>
<member>
<name>faultCode</name>
<value><int>{$this->code}</int></value>
</member>
<member>
<name>faultString</name>
<value><string>{$this->message}</string></value>
</member>
</struct>
</value>
</fault>
</methodResponse>
EOD;
return $xml;
}
}
class IXR_Date {
public $year;
public $month;
public $day;
public $hour;
public $minute;
public $second;
function IXR_Date($time) {
// $time can be a PHP timestamp or an ISO one
if (is_numeric($time)) {
$this->parseTimestamp($time);
} else {
$this->parseIso($time);
}
}
function parseTimestamp($timestamp) {
$this->year = date('Y', $timestamp);
$this->month = date('Y', $timestamp);
$this->day = date('Y', $timestamp);
$this->hour = date('H', $timestamp);
$this->minute = date('i', $timestamp);
$this->second = date('s', $timestamp);
}
function parseIso($iso) {
$this->year = substr($iso, 0, 4);
$this->month = substr($iso, 4, 2);
$this->day = substr($iso, 6, 2);
$this->hour = substr($iso, 9, 2);
$this->minute = substr($iso, 12, 2);
$this->second = substr($iso, 15, 2);
}
function getIso() {
return $this->year.$this->month.$this->day.'T'.$this->hour.':'.$this->minute.':'.$this->second;
}
function getXml() {
return '<dateTime.iso8601>'.$this->getIso().'</dateTime.iso8601>';
}
function getTimestamp() {
return mktime($this->hour, $this->minute, $this->second, $this->month, $this->day, $this->year);
}
}
class IXR_Base64 {
public $data;
function IXR_Base64($data) {
$this->data = $data;
}
function getXml() {
return '<base64>'.base64_encode($this->data).'</base64>';
}
}
//////////////////////////////////////////////////////////
// Nadeo modifications //
// (many thanks to slig for adding callback support) //
//////////////////////////////////////////////////////////
class IXR_Client_Gbx {
public $socket;
public $message = false;
public $cb_message = array();
public $reqhandle;
public $protocol = 0;
// Storage place for an error message
public $error = false;
function bigEndianTest() {
list($endiantest) = array_values(unpack('L1L', pack('V', 1)));
if ($endiantest != 1) {
echo "Machine reports itself as BigEndian, float handling must be altered\r\n";
echo "Overwrite GbxRemote.inc.php with GbxRemote.bem.php\r\n";
die('App Terminated');
return false;
}
return true;
} // bigEndianTest
function IXR_Client_Gbx() {
$this->socket = false;
$this->reqhandle = 0x80000000;
}
function InitWithIp($ip, $port) {
if (!$this->bigEndianTest()) {
$this->error = new IXR_Error(-32999, 'endian error - script doesn\'t match machine type');
return false;
}
// open connection
$this->socket = @fsockopen($ip, $port, $errno, $errstr);
if (!$this->socket) {
$this->error = new IXR_Error(-32300, "transport error - could not open socket (error: $errno, $errstr)");
return false;
}
// handshake
$array_result = unpack('Vsize', fread($this->socket, 4));
$size = $array_result['size'];
if ($size > 64) {
$this->error = new IXR_Error(-32300, 'transport error - wrong lowlevel protocol header');
return false;
}
$handshake = fread($this->socket, $size);
if ($handshake == 'GBXRemote 1') {
$this->protocol = 1;
} else if ($handshake == 'GBXRemote 2') {
$this->protocol = 2;
} else {
$this->error = new IXR_Error(-32300, 'transport error - wrong lowlevel protocol version');
return false;
}
return true;
}
function Init($port) {
return $this->InitWithIp('localhost', $port);
}
function Terminate() {
if ($this->socket) {
fclose($this->socket);
$this->socket = false;
}
}
protected function sendRequest(IXR_Request $request) {
$xml = $request->getXml();
@stream_set_timeout($this->socket, 20); // timeout 20 s (to write the request)
// send request
$this->reqhandle++;
if ($this->protocol == 1) {
$bytes = pack('Va*', strlen($xml), $xml);
} else {
$bytes = pack('VVa*', strlen($xml), $this->reqhandle, $xml);
}
$bytes_to_write = strlen($bytes);
while ($bytes_to_write > 0) {
$r = fwrite($this->socket, $bytes);
if ($r === false || $r == 0) {
// connection interrupted
return false; // or die?
}
$bytes_to_write -= $r;
if ($bytes_to_write == 0)
break;
$bytes = substr($bytes, $r);
}
return true;
}
protected function getResult() {
$contents = '';
$contents_length = 0;
do {
$size = 0;
$recvhandle = 0;
@stream_set_timeout($this->socket, 20); // timeout 20 s (to read the reply header)
// Get result
if ($this->protocol == 1) {
$contents = fread($this->socket, 4);
if (strlen($contents) == 0) {
$this->error = new IXR_Error(-32700, 'transport error - connection interrupted!');
return false;
}
$array_result = unpack('Vsize', $contents);
$size = $array_result['size'];
$recvhandle = $this->reqhandle;
} else {
$contents = fread($this->socket, 8);
if (strlen($contents) == 0) {
$this->error = new IXR_Error(-32700, 'transport error - connection interrupted!');
return false;
}
$array_result = unpack('Vsize/Vhandle', $contents);
$size = $array_result['size'];
$recvhandle = $array_result['handle'];
// -- amd64 support --
$bits = sprintf('%b', $recvhandle);
if (strlen($bits) == 64) {
$recvhandle = bindec(substr($bits, 32));
}
}
if ($recvhandle == 0 || $size == 0) {
$this->error = new IXR_Error(-32700, 'transport error - connection interrupted!');
return false;
}
if ($size > 4096*1024) {
$this->error = new IXR_Error(-32700, "transport error - answer too big ($size)");
return false;
}
$contents = '';
$contents_length = 0;
@stream_set_timeout($this->socket, 0, 10000); // timeout 10 ms (for successive reads until end)
while ($contents_length < $size) {
$contents .= fread($this->socket, $size-$contents_length);
$contents_length = strlen($contents);
}
if (($recvhandle & 0x80000000) == 0) {
// this is a callback, not our answer! handle= $recvhandle, xml-rpc= $contents
// just add it to the message list for the user to read
$new_cb_message = new IXR_Message($contents);
if ($new_cb_message->parse() && $new_cb_message->messageType != 'fault') {
array_push($this->cb_message, array($new_cb_message->methodName, $new_cb_message->params));
}
}
} while ((int)$recvhandle != (int)$this->reqhandle);
$this->message = new IXR_Message($contents);
if (!$this->message->parse()) {
// XML error
$this->error = new IXR_Error(-32700, 'parse error. not well formed');
return false;
}
// Is the message a fault?
if ($this->message->messageType == 'fault') {
$this->error = new IXR_Error($this->message->faultCode, $this->message->faultString);
return false;
}
// Message must be OK
return true;
}
function query() {
$args = func_get_args();
$method = array_shift($args);
if (!$this->socket || $this->protocol == 0) {
$this->error = new IXR_Error(-32300, 'transport error - Client not initialized');
return false;
}
$request = new IXR_Request($method, $args);
// Check if request is larger than 512 Kbytes
if ($request->getLength() > 512*1024-8) {
$this->error = new IXR_Error(-32700, 'transport error - request too large!');
return false;
}
// Send request
$ok = $this->sendRequest($request);
if (!$ok) {
$this->error = new IXR_Error(-32700, 'transport error - connection interrupted');
return false;
}
// Get result
return $this->getResult();
}
// Non-blocking query method: doesn't read the response
function queryIgnoreResult() {
$args = func_get_args();
$method = array_shift($args);
if (!$this->socket || $this->protocol == 0) {
$this->error = new IXR_Error(-32300, 'transport error - Client not initialized');
return false;
}
$request = new IXR_Request($method, $args);
// Check if the request is greater than 512 Kbytes to avoid errors
// If the method is system.multicall, make two calls (possibly recursively)
if ($request->getLength() > 512*1024-8) {
if ($method = 'system.multicall' && isset($args[0])) {
$count = count($args[0]);
// If count is 1, query cannot be reduced
if ($count < 2) {
$this->error = new IXR_Error(-32700, 'transport error - request too large!');
return false;
}
$length = floor($count/2);
$args1 = array_slice($args[0], 0, $length);
$args2 = array_slice($args[0], $length, ($count-$length));
$res1 = $this->queryIgnoreResult('system.multicall', $args1);
$res2 = $this->queryIgnoreResult('system.multicall', $args2);
return ($res1 && $res2);
}
// If the method is not a multicall, just stop
else {
$this->error = new IXR_Error(-32700, 'transport error - request too large!');
return false;
}
}
// Send request
$ok = $this->sendRequest($request);
if (!$ok) {
$this->error = new IXR_Error(-32700, 'transport error - connection interrupted');
return false;
}
}
function readCB($timeout = 2000) { // timeout 2 ms
if (!$this->socket || $this->protocol == 0) {
$this->error = new IXR_Error(-32300, 'transport error - Client not initialized');
return false;
}
if ($this->protocol == 1)
return false;
$something_received = count($this->cb_message)>0;
$contents = '';
$contents_length = 0;
@stream_set_timeout($this->socket, 0, 10000); // timeout 10 ms (to read available data)
// (assignment in arguments is forbidden since php 5.1.1)
$read = array($this->socket);
$write = NULL;
$except = NULL;
$nb = @stream_select($read, $write, $except, 0, $timeout);
// workaround for stream_select bug with amd64
if ($nb !== false)
$nb = count($read);
while ($nb !== false && $nb > 0) {
$timeout = 0; // we don't want to wait for the full time again, just flush the available data
$size = 0;
$recvhandle = 0;
// Get result
$contents = fread($this->socket, 8);
if (strlen($contents) == 0) {
$this->error = new IXR_Error(-32700, 'transport error - connection interrupted!');
return false;
}
$array_result = unpack('Vsize/Vhandle', $contents);
$size = $array_result['size'];
$recvhandle = $array_result['handle'];
if ($recvhandle == 0 || $size == 0) {
$this->error = new IXR_Error(-32700, 'transport error - connection interrupted!');
return false;
}
if ($size > 4096*1024) {
$this->error = new IXR_Error(-32700, "transport error - answer too big ($size)");
return false;
}
$contents = '';
$contents_length = 0;
while ($contents_length < $size) {
$contents .= fread($this->socket, $size-$contents_length);
$contents_length = strlen($contents);
}
if (($recvhandle & 0x80000000) == 0) {
// this is a callback. handle= $recvhandle, xml-rpc= $contents
//echo 'CALLBACK('.$contents_length.')[ '.$contents.' ]' . LF;
$new_cb_message = new IXR_Message($contents);
if ($new_cb_message->parse() && $new_cb_message->messageType != 'fault') {
array_push($this->cb_message, array($new_cb_message->methodName, $new_cb_message->params));
}
$something_received = true;
}
// (assignment in arguments is forbidden since php 5.1.1)
$read = array($this->socket);
$write = NULL;
$except = NULL;
$nb = @stream_select($read, $write, $except, 0, $timeout);
// workaround for stream_select bug with amd64
if ($nb !== false)
$nb = count($read);
}
return $something_received;
}
function getResponse() {
// methodResponses can only have one param - return that
return $this->message->params[0];
}
function getCBResponses() {
// (look at the end of basic.php for an example)
$messages = $this->cb_message;
$this->cb_message = array();
return $messages;
}
function isError() {
return is_object($this->error);
}
function resetError() {
$this->error = false;
}
function getErrorCode() {
return $this->error->code;
}
function getErrorMessage() {
return $this->error->message;
}
}
class IXR_ClientMulticall_Gbx extends IXR_Client_Gbx {
public $calls = array();
function addCall($methodName, $args) {
$struct = array('methodName' => $methodName, 'params' => $args);
$this->calls[] = $struct;
return (count($this->calls) - 1);
}
function multiquery($ignoreResult = false) {
// Prepare multicall, then call the parent::query() (or queryIgnoreResult) method
if ($ignoreResult) {
$result = parent::queryIgnoreResult('system.multicall', $this->calls);
} else {
$result = parent::query('system.multicall', $this->calls);
}
$this->calls = array(); // reset for next calls
return $result;
}
}
?>

View File

@ -1,68 +0,0 @@
<?php
header('Content-Type: text/html; charset=utf-8');
require('GbxRemote.inc.php');
echo "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n";
echo "<HTML>\n<HEAD>\n";
echo "\t<TITLE>Trackmania methods</TITLE>\n";
echo "</HEAD>\n<BODY>\n";
echo "<h1>Available methods:</h1>\n";
$client = new IXR_Client_Gbx;
if (!$client->Init(5000)) {
die('An error occurred - ' . $client->getErrorCode() . ':' . $client->getErrorMessage());
}
if (!$client->query('system.listMethods')) {
die('An error occurred - ' . $client->getErrorCode() . ':' . $client->getErrorMessage());
}
$methods = $client->getResponse();
print '<ul>';
foreach ($methods as $m) {
print '<li><b>' . $m . "</b><br/>\n";
if ($client->query('system.methodSignature', $m)) {
$signatures = $client->getResponse();
} else {
print "<font color='red'>{error in signature}</font><br/>\n";
$signatures = array();
}
if ($client->query('system.methodHelp', $m)) {
$help = $client->getResponse();
} else {
$help = "<font color='red'>{no help}</font>";
}
foreach ($signatures as $sig) {
$is_retval = 1;
$is_firstarg = 1;
foreach ($sig as $argtype) {
if ($is_retval) {
print $argtype . ' ' . $m . '(';
$is_retval = 0;
} else {
if (!$is_firstarg) {
print ', ';
}
print $argtype;
$is_firstarg = 0;
}
}
print ")<br/>\n";
}
print "<font color='0x113355'>";
print $help;
print "</font></li>\n";
}
print '</ul>';
$client->Terminate();
echo "\n</BODY>\n</HTML>\n";
flush();
?>

View File

@ -1,264 +0,0 @@
#!/usr/bin/php
<?php
//=====================================================================
// this is a *work-in-progress* sample simplified spectator interface.
//i To be run on the command line "php SpectatorUi.php", see (1) to set the options.
//=====================================================================
require("GbxRemote.inc.php");
// Utility functions
$client = new IXR_Client_Gbx;
function ConnectToServer($Ip='localhost', $Port=5000, $AuthLogin='Admin', $AuthPassword='Admin')
{
global $client;
if (!$client->InitWithIp($Ip, $Port)) {
trigger_error("[".$client->getErrorCode()."] ".$client->getErrorMessage());
}
DoQuerry("Authenticate", $AuthLogin, $AuthPassword);
DoQuerry("EnableCallbacks", True);
}
function DoQuerry($querry /*...*/)
{
global $client;
$args = func_get_args();
if (!call_user_func_array(array($client, 'query'), $args)) {
trigger_error("[".$client->getErrorCode()."] ".$client->getErrorMessage());
exit(1);
}
return $client->getResponse();
}
function TryQuerry($querry /*...*/)
{
global $client;
$args = func_get_args();
if (!call_user_func_array(array($client, 'query'), $args)) {
print ("Warning: '$querry' -> " . "[".$client->getErrorCode()."] ".$client->getErrorMessage());
return False;
}
return $client->getResponse();
}
function XMLEscapeString( $String )
{
return htmlspecialchars( $String, ENT_NOQUOTES ) ;
}
function MwTimeToString($MwTime)
{
if ($MwTime == -1) {
return "???";
} else {
$minutes = floor($MwTime/(1000*60));
$seconds = floor(($MwTime-$minutes*60*1000)/1000);
$millisec = floor(($MwTime - $minutes*60*1000 - $seconds*1000)/10);
return $minutes.":".$seconds.".".$millisec;
}
}
// UI construction:
$ActionChangeSpec = 1*1000;
function MakePlayerFrame($PlayerRanking, $CurTarget, $GameInfos, &$posx, &$posy)
{
global $ActionChangeSpec;
$NickName = XMLEscapeString($PlayerRanking['NickName']);
$Rank = $PlayerRanking['Rank'];
$Score = $PlayerRanking['Score'];
$Time = MwTimeToString($PlayerRanking["BestTime"]);
$PlayerUId = $PlayerRanking['PlayerId'];
$Action = $ActionChangeSpec + $PlayerUId;
$Frame = "<frame posn='$posx $posy 0'>";
$Frame .= "<quad sizen='32 10' posn='-1 1 0' halign='top' valign='left' style='Bgs1InRace' substyle='BgWindow3' action='$Action'/>";
$Frame .= "<quad sizen='30 5' posn='0 0 1' halign='left' valign='top' style='Bgs1InRace' substyle='BgTitle2'/>";
$Frame .= "<label sizen='28 4' posn='1 -3 2' halign='left' valign='center2' style='TextTitle2'>$Rank. $NickName</label>";
if ($GameInfos["GameMode"] == 5) { // Cup Mode
$Limit = $GameInfos["CupPointsLimit"];
if ($Score == $Limit) {
$Frame .= "<label sizen='30 5' posn='0 -5 0' halign='left' style='TextStaticSmall'>\$FF0\$oFinalist!</label>";
} else if ($Score > $Limit) {
$Frame .= "<label sizen='30 5' posn='0 -5 0' halign='left' style='TextStaticSmall'>\$0F0\$oWinner</label>";
} else {
$Frame .= "<label sizen='30 5' posn='0 -5 0' halign='left' style='TextStaticSmall'>Score: \$o$Score </label>";
}
} else if ($GameInfos["GameMode"] == 0) { // Rounds
$Frame .= "<label sizen='30 5' posn='0 -5 0' halign='left' style='TextStaticSmall'>Score: \$o$Score </label>";
} else if ($GameInfos["GameMode"] == 1) { // TimeAttack
$Frame .= "<label sizen='30 5' posn='0 -5 0' halign='left' style='TextStaticSmall'>Best: \$o$Time </label>";
} else {
// mode not supported.
}
if ($PlayerUId == $CurTarget) {
$Frame .= "<label sizen='5 5' posn='28 -5 0' halign='right' style='TextStaticSmall'>\$0F0(target)</label>";
}
$Frame .= "</frame>";
$posy -= 10;
return $Frame;
}
function BuildUiForSpectator($Login, $Target, $Rankings, $GameInfos)
{
$Page = '<?xml version="1.0" encoding="utf-8"?><manialinks>';
// rankings and scores.
$Page .= '<manialink id="0"><frame>';
$posx=-63;
$posy=37;
foreach ($Rankings as $Ranking) {
if ($Ranking['Rank'] == 0)
break; // there aren't 5 players in the top 5, so cut up earlier.
$Page .= MakePlayerFrame($Ranking, $Target, $GameInfos, $posx, $posy);
}
$Page .= '</frame></manialink>';
// customui
$Page .= '<custom_ui>i<challenge_info visible="false"/><net_infos visible="false"/><scoretable visible="false"/></custom_ui>';
$Page .= '</manialinks>';
return $Page;
}
// SpectatorManager
$SpectatorManager_Status = array();
$SpectatorManager_GlobalDirty = False;
function SpectatorManager_Add($Login)
{
global $SpectatorManager_Status, $SpectatorManager_GlobalDirty;
$SpectatorManager_GlobalDirty = True;
$SpectatorManager_Status[$Login]=
array( "uptodate" => False,
"page" => "",
"target" => "" );
}
function SpectatorManager_Remove($Login)
{
global $SpectatorManager_Status, $SpectatorManager_GlobalDirty;
unset($SpectatorManager_Status[$Login]);
}
function SpectatorManager_SetDirtyAll()
{
global $SpectatorManager_Status, $SpectatorManager_GlobalDirty;
$SpectatorManager_GlobalDirty = True;
foreach($SpectatorManager_Status as $s) {
$s["uptodate"] = False;
}
}
function SpectatorManager_Update()
{
global $SpectatorManager_Status, $SpectatorManager_GlobalDirty;
if (!$SpectatorManager_GlobalDirty)
return;
$SpectatorManager_GlobalDirty = False;
$GameInfos = DoQuerry('GetCurrentGameInfo', 1);
$Rankings = DoQuerry('GetCurrentRanking', 5, 0);
foreach($SpectatorManager_Status as $Login => $s) {
if ($s["uptodate"])
continue;
$NewPage = BuildUiForSpectator($Login, $s["target"], $Rankings, $GameInfos);
if ($s["page"] != $NewPage) {
$s["page"] = $NewPage;
DoQuerry('SendDisplayManialinkPageToLogin', $Login, $NewPage, 0, False);
}
$s["uptodate"] = True;
}
}
// Callbacks
function OnManialinkPageAnswer($PlayerUId, $Login, $Answer)
{
global $SpectatorManager_Status, $SpectatorManager_GlobalDirty;
global $ActionChangeSpec;
$Argument = $Answer%1000;
$Action = $Answer - $Argument ;
if ($Action == $ActionChangeSpec) {
$SpectatorManager_Status[$Login]["target"] = $Argument;
$SpectatorManager_Status[$Login]["uptodate"] = False;
$SpectatorManager_GlobalDirty = True;
TryQuerry('ForceSpectatorTargetId', $PlayerUId, $Argument, 0);
}
}
function OnPlayerInfoChanged($PlayerInfo)
{
return;
}
// ------------------------------------------------------
// -- (1) Server Adress here!---------------------------------
// ------------------------------------------------------
ConnectToServer("localhost", 5000, "Admin", "Admin");
// register already connected specs.
$PlayerList = DoQuerry("GetPlayerList", 250, 0, 1);
foreach ($PlayerList as $Player) {
$Login = $Player["Login"];
$IsPureSpec = ($Player["SpectatorStatus"]/100)%10 != 0;
if ($IsPureSpec)
SpectatorManager_Add($Login);
}
while (true) {
// FIXME
Sleep(1);
$client->readCB(5*1000*1000);
$calls = $client->getCBResponses();
if (!empty($calls)) {
foreach ($calls as $call) {
switch($call[0]){
case 'TrackMania.BeginRace':
case 'TrackMania.EndRace':
case 'TrackMania.EndRound':
SpectatorManager_SetDirtyAll();
break;
case 'TrackMania.PlayerManialinkPageAnswer':
OnManialinkPageAnswer($call[1][0], $call[1][1], $call[1][2]);
break;
case 'TrackMania.PlayerConnect':
if ($call[1][1]) // is spectator
SpectatorManager_Add($call[1][0]);
break;
case 'TrackMania.PlayerDisconnect':
SpectatorManager_Remove($call[1][0]);
break;
case 'TrackMania.PlayerInfoChanged':
OnPlayerInfoChanged($call[1][0]);
break;
}
}
}
SpectatorManager_Update();
flush();
}
$client->Terminate();
?>

View File

@ -1,986 +0,0 @@
<?php
header('Content-Type: text/html; charset=utf-8');
require("GbxRemote.inc.php");
// functions.
// Converts trackmania styles to html
function styledString($str) {
preg_match_all('/./u', $str, $dummy);
$_Str = $dummy[0];
$_Style = NULL;
$string = NULL;
$i = 0;
while (true) {
$Char = ReadNextChar($_Str,$_Style);
if ($Char === FALSE) {
break;
}
$string .= "<span style='".$_Style."'>".$Char."</span>";
$i++;
if ($i>100) {
break;
}
}
return $string;
}
// Read a styled string
function ReadNextChar(&$_Str, &$_Style) {
$Char = current($_Str);
next($_Str);
if ($Char == '\r') { // skip \r
return ReadNextChar($_Str, $_Style);
}
if ($Char != '$') { // detect markup start sequence '$'
return $Char;
}
$Char = current($_Str);
next($_Str);
if ($Char === FALSE) {
return 0;
}
$MarkupCode = $Char;
switch ($MarkupCode) {
// color
case '0': case '1': case '2': case '3': case '4': case '5':
case '6': case '7': case '8': case '9': case 'a': case 'b':
case 'c': case 'd': case 'e': case 'f': case 'A': case 'B':
case 'C': case 'D': case 'E': case 'F':
{
$RGB = NULL;
for ($Count = 0; $Count < 3; $Count ++) {
if ($Count > 0) {
$Char = current($_Str);
next($_Str);
if ($Char === FALSE) {
return 0;
}
}
$RGB .= $Char.$Char;
}
$_Style .= "color:#".$RGB.";";
}
break;
// no color
case 'G': case 'g':
$_Style .= "color:;";
break;
// Shodowed / Embossed
case 'S': case 's':
break;
// Italic
case 'I': case 'i':
$_Style .= "font-style:italic;";
break;
// Wide
case 'W': case 'w':
$_Style .= "letter-spacing:1px;";
break;
// Narrow
case 'N': case 'n':
$_Style .= "letter-spacing:-1px;";
break;
// Medium
case 'M': case 'm':
$_Style .= "letter-spacing:0px;";
break;
// underlined
case 'U': case 'u':
$_Style .= "text-decoration:underline;";
break;
// reset all
case 'Z': case 'z':
$_Style = "";
break;
// escaped char.
case '$': case '[':
return $MarkupCode;
default:
// eat silently the character...
break;
};
return ReadNextChar($_Str, $_Style); // tail recursion.
}
function catchError($errno, $errstr, $errfile, $errline){
echo("<p><font color='red'>$errstr (line:$errline)</font></p>");
}
set_error_handler('catchError');
function MwTimeToString($MwTime)
{
if ($MwTime == -1) {
return "???";
} else {
$minutes = floor($MwTime/(1000*60));
return $minutes.":".floor(($MwTime-$minutes*60*1000)/1000);
}
}
function ParseArgument(&$ArgumentValue, $ArgumentName, $DefaultValue)
{
if (array_key_exists($ArgumentName, $_POST)) {
$ArgumentValue = $_POST[$ArgumentName];
} else if (array_key_exists($ArgumentName, $_GET)) {
$ArgumentValue = $_GET[$ArgumentName];
} else {
$ArgumentValue = $DefaultValue;
}
}
// parse the arguments.
ParseArgument( $AuthLogin, 'authLogin', "SuperAdmin" );
ParseArgument( $AuthPassword, 'authPassword', "SuperAdmin" );
ParseArgument( $OldAuthLogin, 'oldAuthLogin', $AuthLogin );
ParseArgument( $OldAuthPassword, 'oldAuthPassword', $AuthPassword );
ParseArgument( $port, 'port', 5000 );
ParseArgument( $MSLogin, 'mslogin', "" );
ParseArgument( $MSPassword, 'mspassword', "" );
if (array_key_exists('action', $_POST)) {
$Action = $_POST['action'];
/*} else if (array_key_exists('action', $_GET))
$Action = $_GET['action'];*/
} else {
$Action="";
}
echo "<center><h1> - Trackmania Forever dedicated server - </h1></center>";
// ----------------------------------------------------------------
// connect
// ----------------------------------------------------------------
$client = new IXR_Client_Gbx;
if (!$client->Init($port)) {
trigger_error("[".$client->getErrorCode()."] ".$client->getErrorMessage());
}
if (!$client->query("Authenticate", $AuthLogin, $AuthPassword)) {
trigger_error("[".$client->getErrorCode()."] ".$client->getErrorMessage());
$AuthLogin = $OldAuthLogin;
$AuthPassword = $OldAuthPassword;
}
else
{
$OldAuthLogin = $AuthLogin;
$OldAuthPassword = $AuthPassword;
}
// ----------------------------------------------------------------
// do the job.
// ----------------------------------------------------------------
$SimpleActions = array('RestartChallenge', 'NextChallenge', 'StopServer', 'QuitGame', 'CleanBanList');
if (in_array($Action, $SimpleActions)) {
if (!$client->query($Action)) {
trigger_error("[".$client->getErrorCode()."] ".$client->getErrorMessage());
}
} else if ($Action == 'SetServerOptions') {
$IsP2PUpload = array_key_exists('IsP2PUpload', $_POST);
$IsP2PDownload = array_key_exists('IsP2PDownload', $_POST);
$AutoSaveReplays = array_key_exists('AutoSaveReplays', $_POST);
$AutoSaveValidationReplays = array_key_exists('AutoSaveValidationReplays', $_POST);
$AllowChallengeDownload = array_key_exists('AllowChallengeDownload', $_POST);
$struct = array( 'Name' => $_POST['ServerName'],
'Comment' => $_POST['ServerComment'],
'Password' => $_POST['ServerPassword'],
'PasswordForSpectator' => $_POST['SpectatorPassword'],
'NextMaxPlayers' => $_POST['NextMaxPlayers']+0,
'NextMaxSpectators' => $_POST['NextMaxSpectators']+0,
'IsP2PUpload' => $IsP2PUpload,
'IsP2PDownload' => $IsP2PDownload,
'NextLadderMode' => $_POST['NextLadderMode']+0,
'NextVehicleNetQuality' => $_POST['NextVehicleNetQuality']+0,
'NextCallVoteTimeOut' => $_POST['NextCallVoteTimeOut']+0,
'CallVoteRatio' => $_POST['CallVoteRatio']+0,
'RefereePassword' => $_POST['RefereePassword'],
'RefereeMode' => $_POST['RefereeMode']+0,
'AllowChallengeDownload' => $AllowChallengeDownload,
'AutoSaveValidationReplays' => $AutoSaveValidationReplays,
'AutoSaveReplays' => $AutoSaveReplays);
if (!$client->query('SetServerOptions', $struct)) {
trigger_error("[".$client->getErrorCode()."] ".$client->getErrorMessage());
}
} else if ($Action == 'StartServerInternet' || $Action == 'StartServerLan') {
$struct = array( 'Login' => $_POST['Login'],
'Password' => $_POST['Password']);
if (!$client->query($Action, $struct)) {
trigger_error("[".$client->getErrorCode()."] ".$client->getErrorMessage());
}
} else if ($Action == 'RemoveChallenge' || $Action == 'AddChallenge' || $Action == 'ChooseNextChallenge') {
if (!$client->query($Action, urldecode($_POST['ChallengeFileName']))) {
trigger_error("[".$client->getErrorCode()."] ".$client->getErrorMessage());
}
} else if ($Action == 'Kick' || $Action == 'Ban' || $Action == 'UnBan' || $Action == 'AddGuest' || $Action == 'RemoveGuest' || $Action == 'BlackList' || $Action == 'UnBlackList') {
if (!$client->query($Action, urldecode($_POST['PlayerLogin']))) {
trigger_error("[".$client->getErrorCode()."] ".$client->getErrorMessage());
}
} else if ($Action == 'SaveMatchSettings' || $Action == 'LoadMatchSettings' || $Action == 'AppendPlaylistFromMatchSettings') {
if (!$client->query($Action, urldecode($_POST['MatchSettingsFileName']))) {
trigger_error("[".$client->getErrorCode()."] ".$client->getErrorMessage());
}
} else if ($Action == 'LoadGuestList' || $Action == 'SaveGuestList' ) {
if (!$client->query($Action, urldecode($_POST['GuestListFileName']))) {
trigger_error("[".$client->getErrorCode()."] ".$client->getErrorMessage());
}
} else if ($Action == 'LoadBlackList' || $Action == 'SaveBlackList' ) {
if (!$client->query($Action, urldecode($_POST['BlackListFileName']))) {
trigger_error("[".$client->getErrorCode()."] ".$client->getErrorMessage());
}
} else if ($Action == 'SetGameInfos') {
$NextRoundsUseNewRules = array_key_exists('NextRoundsUseNewRules', $_POST);
$NextTeamUseNewRules = array_key_exists('NextTeamUseNewRules', $_POST);
$NextDisableRespawn = array_key_exists('NextDisableRespawn', $_POST);
$struct = array( 'GameMode' => $_POST['NextGameMode']+0,
'ChatTime' => $_POST['NextChatTime']+0,
'FinishTimeout' => $_POST['NextFinishTimeout']+0,
'RoundsPointsLimit' => $_POST['NextRoundsPointsLimit']+0,
'RoundsForcedLaps' => $_POST['NextRoundsForcedLaps']+0,
'RoundsUseNewRules' => $NextRoundsUseNewRules,
'RoundsPointsLimitNewRules' => $_POST['NextRoundsPointsLimitNewRules']+0,
'TimeAttackLimit' => $_POST['NextTimeAttackLimit']+0,
'TimeAttackSynchStartPeriod' => $_POST['NextTimeAttackSynchStartPeriod']+0,
'TeamPointsLimit' => $_POST['NextTeamPointsLimit']+0,
'TeamMaxPoints' => $_POST['NextTeamMaxPoints']+0,
'TeamUseNewRules' => $NextTeamUseNewRules,
'TeamPointsLimitNewRules' => $_POST['NextTeamPointsLimitNewRules']+0,
'CupPointsLimit' => $_POST['NextCupPointsLimit']+0,
'CupRoundsPerChallenge' => $_POST['NextCupRoundsPerChallenge']+0,
'CupNbWinners' => $_POST['NextCupNbWinners']+0,
'CupWarmUpDuration' => $_POST['NextCupWarmUpDuration']+0,
'DisableRespawn' => False,
'ForceShowAllOpponents' => False,
'LapsNbLaps' => $_POST['NextLapsNbLaps']+0,
'LapsTimeLimit' => $_POST['NextLapsTimeLimit']+0,
'AllWarmUpDuration' => 0);
if (!$client->query('SetGameInfos', $struct)) {
trigger_error("[".$client->getErrorCode()."] ".$client->getErrorMessage());
}
} else if ($Action == 'ChangeAuthPassword') {
if (!$client->query('ChangeAuthPassword', $_POST['newLogin'], $_POST['newPassword'])) {
trigger_error("[".$client->getErrorCode()."] ".$client->getErrorMessage());
}
else if( $AuthLogin==$_POST['newLogin'] )
{
$AuthLogin = $_POST['newLogin'];
$AuthPassword = $_POST['newLogin'];
$OldAuthLogin = $AuthLogin;
$OldAuthPassword = $AuthPassword;
}
} else if( ($Action == 'ChatSend') || ($Action == 'ChatSendServerMessage') ){
if (!$client->query($Action, urldecode($_POST['ChatText']))) {
trigger_error("[".$client->getErrorCode()."] ".$client->getErrorMessage());
}
} else if($Action == 'SendDisplayManialinkPage'){
$AutoHide = array_key_exists('AutoHide', $_POST);
if (!$client->query($Action, $_POST['Maniacode'], $_POST['TimeOut']+0, $AutoHide)) {
trigger_error("[".$client->getErrorCode()."] ".$client->getErrorMessage());
}
} else if($Action == 'SendDisplayServerMessageToLogin'){
$AutoHide = array_key_exists('AutoHide', $_POST);
if (!$client->query($Action, $_POST['Login'], $_POST['Maniacode'],$_POST['TimeOut']+0, $AutoHide)) {
trigger_error("[".$client->getErrorCode()."] ".$client->getErrorMessage());
}
} else if($Action == 'SendHideManialinkPage'){
if (!$client->query($Action)) {
trigger_error("[".$client->getErrorCode()."] ".$client->getErrorMessage());
}
} else if($Action == 'SendHideManialinkPageToLogin'){
if (!$client->query($Action, $_POST['Login'])) {
trigger_error("[".$client->getErrorCode()."] ".$client->getErrorMessage());
}
}
// ----------------------------------------------------------------
// connection info
// ----------------------------------------------------------------
echo "\n<h3>Connection Status:</h3>\n";
if (!$client->query('GetVersion')) {
trigger_error("[".$client->getErrorCode()."] ".$client->getErrorMessage());
}
else
{
$AuthSuperAdmin = $AuthLogin=="SuperAdmin" ? "selected" : "";
$AuthAdmin = $AuthLogin=="Admin" ? "selected" : "";
$AuthUser = $AuthLogin=="User" ? "selected" : "";
echo <<<END
<form name="input" action="basic.php" method="post">
<table>
<tr><td>Permission Level: </td><td>
<SELECT name="authLogin" >
<OPTION value="SuperAdmin" $AuthSuperAdmin> SuperAdmin </OPTION>
<OPTION value="Admin" $AuthAdmin> Admin </OPTION>
<OPTION value="User" $AuthUser> User </OPTION>
</SELECT>
</td></tr>
<tr><td>Password: </td><td><input type="password" name="authPassword" size=30 value="$AuthPassword"/><td>
</table>
<input type="submit" value="Authenticate">
<input type="hidden" name="oldAuthLogin" value="$OldAuthLogin">
<input type="hidden" name="oldAuthPassword" value="$OldAuthPassword">
<input type="hidden" name="port" value="$port">
</form>
END;
if( $AuthLogin=="SuperAdmin" )
{
echo <<<END
<form name="input" action="basic.php" method="post">
<table><tr>
<td>Set new Password: </td><td><input type="password" name="newPassword" size=30 value=""/><td>
<td> for </td><td>
<SELECT name="newLogin" >
<OPTION value="SuperAdmin"> SuperAdmin </OPTION>
<OPTION value="Admin"> Admin </OPTION>
<OPTION value="User"> User </OPTION>
</SELECT>
</td>
</table>
<input type="submit" name="action" value="ChangeAuthPassword">
<input type="hidden" name="authLogin" value="$AuthLogin">
<input type="hidden" name="authPassword" value="$AuthPassword">
<input type="hidden" name="port" value="$port">
</form>
END;
}
$Version = $client->getResponse();
echo "Connected to " . $Version['Name']. " - " . $Version['Version'] . "<br>";
}
// ----------------------------------------------------------------
// status info
// ----------------------------------------------------------------
echo "\n<h3>Server Status:</h3>\n";
if (!$client->query('GetStatus')) {
trigger_error("[".$client->getErrorCode()."] ".$client->getErrorMessage());
}
else
{
$Status = $client->getResponse();
echo "Status: ".$Status['Name'];
echo <<<END
<form name="input" action="basic.php" method="post">
<input type="submit" value="Refresh">
<input type="hidden" name="authLogin" value="$AuthLogin">
<input type="hidden" name="authPassword" value="$AuthPassword">
<input type="hidden" name="port" value="$port">
</form>
END;
if ($Status['Code'] == 1) {
// ----------------------------------------------------------------
// start server
// ----------------------------------------------------------------
echo <<<END
<form name="input" action="basic.php" method="post">
<table>
<tr><td>Master Server Login: </td><td><input type="text" name="Login" size=30 value="$MSLogin"/> </td></tr>
<tr><td>Master Server Password: </td><td><input type="password" name="Password" size=30 value="$MSPassword"/> </td></tr>
</table>
<input type="submit" name="action" value="StartServerInternet">
<input type="submit" name="action" value="StartServerLan">
<input type="hidden" name="authLogin" value="$AuthLogin">
<input type="hidden" name="authPassword" value="$AuthPassword">
<input type="hidden" name="port" value="$port">
</form>
END;
echo <<<END
<form name="input" action="basic.php" method="post">
<input type="submit" name="action" value="QuitGame">
<input type="hidden" name="authLogin" value="$AuthLogin">
<input type="hidden" name="authPassword" value="$AuthPassword">
<input type="hidden" name="port" value="$port">
</form>
END;
} else if ( ($Status['Code'] == 3) || ($Status['Code'] == 4) || ($Status['Code'] == 5) ) {
if (!$client->query('GetCurrentChallengeInfo')) {
trigger_error("[".$client->getErrorCode()."] ".$client->getErrorMessage());
}
else
{
$CurrentChallengeInfo = $client->getResponse();
echo "Current challenge : " . $CurrentChallengeInfo['UId'] . " - " . styledString($CurrentChallengeInfo['Name']) . " - " . $CurrentChallengeInfo['Author'] . "<BR>";
}
// ----------------------------------------------------------------
// in game actions
// ----------------------------------------------------------------
if( $Status['Code'] == 4 )
{
echo <<<END
<form name="input" action="basic.php" method="post">
<input type="submit" name="action" value="RestartChallenge"/>
<input type="submit" name="action" value="NextChallenge"/>
<input type="submit" name="action" value="StopServer"/>
<input type="submit" name="action" value="QuitGame"/>
<input type="submit" Name="action" Value="CleanBanList"/>
<input type="hidden" name="authLogin" value="$AuthLogin">
<input type="hidden" name="authPassword" value="$AuthPassword">
<input type="hidden" name="port" value="$port">
</form>
END;
}
else
{
echo "<BR>";
}
echo "Players:<BR>";
if (!$client->query('GetPlayerList', 50, 0)) {
trigger_error("[".$client->getErrorCode()."] ".$client->getErrorMessage());
}
else
{
$PlayerList = $client->getResponse();
echo '<TABLE cellspacing=5>';
foreach ($PlayerList as $player) {
$PlayerLogin = $player['Login'];
$PlayerName = styledString($player['NickName']);
$PlayerRanking = $player['LadderRanking'];
$PlayerIsSpectator = ($player['IsSpectator']!=0) ? "Spectator" : "Player";
$PlayerIsInOfficialMode = ($player['IsInOfficialMode']!=0) ? "Official" : "Not Official";
$PlayerTeamId = $player['TeamId'];
if( $PlayerTeamId == -1)
$PlayerTeam = "No Team";
else if( $PlayerTeamId == 0)
$PlayerTeam = "Blue Team";
else
$PlayerTeam = "Red Team";
echo <<<END
<TR><TD>$PlayerLogin</TD><TD>$PlayerName</TD><TD>$PlayerTeam</TD><TD>$PlayerIsSpectator</TD><TD>$PlayerIsInOfficialMode</TD><TD>$PlayerRanking</TD>
<TD><form action="basic.php" method="post"><input type="hidden" name="PlayerLogin" value="$PlayerLogin"><input type="submit" name="action" value="Kick"><input type="hidden" name="authLogin" value="$AuthLogin"><input type="hidden" name="authPassword" value="$AuthPassword"><input type="hidden" name="port" value="$port"></form></TD>
<TD><form action="basic.php" method="post"><input type="hidden" name="PlayerLogin" value="$PlayerLogin"><input type="submit" name="action" value="Ban"><input type="hidden" name="authLogin" value="$AuthLogin"><input type="hidden" name="authPassword" value="$AuthPassword"><input type="hidden" name="port" value="$port"></form></TD></TR>
END;
}
echo "</TABLE><BR>";
}
echo <<<END
<form name="input" action="basic.php" method="post">
<input type="text" name="ChatText" size=70/>
<input type="submit" name="action" value="ChatSend">
<input type="submit" name="action" value="ChatSendServerMessage">
<input type="hidden" name="authLogin" value="$AuthLogin">
<input type="hidden" name="authPassword" value="$AuthPassword">
<input type="hidden" name="port" value="$port">
</form>
END;
$AutoHide = False;
echo <<<END
<form name="input" action="basic.php" method="post">
<table>
<tr><td>Maniacode: </td><td><textarea cols="50" rows="4" name="Maniacode"></textarea> </td></tr>
<tr><td>TimeOut: </td><td><input type="text" name="TimeOut" size=70/> </td></tr>
<tr><td>Login: </td><td><input type="text" name="Login" size=70/> </td></tr>
<tr><td>AutoHide: </td><td><input type="checkbox" name="AutoHide" $AutoHide/> </td></tr>
</table>
<input type="submit" name="action" value="SendDisplayManialinkPage">
<input type="submit" name="action" value="SendDisplayManialinkPageToLogin">
<input type="submit" name="action" value="SendHideManialinkPage">
<input type="submit" name="action" value="SendHideManialinkPageToLogin">
<input type="hidden" name="authLogin" value="$AuthLogin">
<input type="hidden" name="authPassword" value="$AuthPassword">
<input type="hidden" name="port" value="$port">
</form>
END;
echo "Ranking:<BR>";
if (!$client->query('GetCurrentRanking', 50, 0)) {
trigger_error("[".$client->getErrorCode()."] ".$client->getErrorMessage());
}
else
{
$CurrentRanking = $client->getResponse();
echo '<TABLE cellspacing=5>';
foreach ($CurrentRanking as $Ranking) {
$PlayerLogin = $Ranking['Login'];
$PlayerName = styledString($Ranking['NickName']);
$PlayerRank = $Ranking['Rank'];
$PlayerBestTime = $Ranking['BestTime'];
$PlayerScore = $Ranking['Score'];
$PlayerNbrLaps = $Ranking['NbrLapsFinished'];
$PlayerLadderScore = $Ranking['LadderScore'];
echo <<<END
<TR><TD>$PlayerLogin</TD><TD>$PlayerName</TD><TD>$PlayerRank</TD><TD>$PlayerBestTime</TD><TD>$PlayerScore</TD><TD>$PlayerNbrLaps</TD><TD>$PlayerLadderScore</TD></TR>
END;
}
echo "</TABLE><BR>";
}
} else if ($Status['Code'] == 2) {
echo "server busy..<BR><BR>";
}
echo "GuestList:<BR>";
if (!$client->query('GetGuestList', 50, 0)) {
trigger_error("[".$client->getErrorCode()."] ".$client->getErrorMessage());
}
else
{
$GuestList = $client->getResponse();
echo '<TABLE cellspacing=5>';
foreach ($GuestList as $player) {
$PlayerLogin=$player['Login'];
echo <<<END
<TR><TD>$PlayerLogin</TD>
<TD><form action="basic.php" method="post">
<input type="hidden" name="PlayerLogin" value="$PlayerLogin">
<input type="submit" name="action" value="RemoveGuest">
<input type="hidden" name="authLogin" value="$AuthLogin">
<input type="hidden" name="authPassword" value="$AuthPassword">
<input type="hidden" name="port" value="$port">
</form></TD></TR>
END;
}
echo "</TABLE>";
echo <<<END
<form name="input" action="basic.php" method="post">
<input type="text" name="PlayerLogin" size=70/>
<input type="submit" name="action" value="AddGuest">
<input type="hidden" name="authLogin" value="$AuthLogin">
<input type="hidden" name="authPassword" value="$AuthPassword">
<input type="hidden" name="port" value="$port">
</form>
END;
echo <<<END
<form name="input" action="basic.php" method="post">
<input type="text" name="GuestListFileName" size=70/><BR>
<input type="submit" name="action" value="LoadGuestList">
<input type="submit" name="action" value="SaveGuestList">
<input type="hidden" name="authLogin" value="$AuthLogin">
<input type="hidden" name="authPassword" value="$AuthPassword">
<input type="hidden" name="port" value="$port">
</form>
END;
}
echo "BlackList:<BR>";
if (!$client->query('GetBlackList', 50, 0)) {
trigger_error("[".$client->getErrorCode()."] ".$client->getErrorMessage());
}
else
{
$BlackList = $client->getResponse();
echo '<TABLE cellspacing=5>';
foreach ($BlackList as $player) {
$PlayerLogin=$player['Login'];
echo <<<END
<TR><TD>$PlayerLogin</TD>
<TD><form action="basic.php" method="post">
<input type="hidden" name="PlayerLogin" value="$PlayerLogin">
<input type="submit" name="action" value="UnBlackList">
<input type="hidden" name="authLogin" value="$AuthLogin">
<input type="hidden" name="authPassword" value="$AuthPassword">
<input type="hidden" name="port" value="$port">
</form></TD>
END;
}
echo "</TABLE>";
echo <<<END
<TR><form name="input" action="basic.php" method="post">
<TD colspan=4><input type="text" name="PlayerLogin" size=70/></TD>
<TD><input type="submit" name="action" value="BlackList"></TD>
<input type="hidden" name="authLogin" value="$AuthLogin">
<input type="hidden" name="authPassword" value="$AuthPassword">
<input type="hidden" name="port" value="$port">
</form></TD>
END;
echo <<<END
<form name="input" action="basic.php" method="post">
<input type="text" name="BlackListFileName" size=70/><BR>
<input type="submit" name="action" value="LoadBlackList">
<input type="submit" name="action" value="SaveBlackList">
<input type="hidden" name="authLogin" value="$AuthLogin">
<input type="hidden" name="authPassword" value="$AuthPassword">
<input type="hidden" name="port" value="$port">
</form>
END;
}
echo "BanList:<BR>";
if (!$client->query('GetBanList', 50, 0)) {
trigger_error("[".$client->getErrorCode()."] ".$client->getErrorMessage());
}
else
{
$BanList = $client->getResponse();
echo '<TABLE cellspacing=5>';
foreach ($BanList as $player) {
$PlayerLogin=$player['Login'];
echo <<<END
<TR><TD>$PlayerLogin</TD>
<TD><form action="basic.php" method="post">
<input type="hidden" name="PlayerLogin" value="$PlayerLogin">
<input type="submit" name="action" value="UnBan">
<input type="hidden" name="authLogin" value="$AuthLogin">
<input type="hidden" name="authPassword" value="$AuthPassword">
<input type="hidden" name="port" value="$port">
</form></TD></TR>
END;
}
echo "</TABLE>";
echo <<<END
<form name="input" action="basic.php" method="post">
<input type="text" name="PlayerLogin" size=70/>
<input type="submit" name="action" value="Ban">
<input type="hidden" name="authLogin" value="$AuthLogin">
<input type="hidden" name="authPassword" value="$AuthPassword">
<input type="hidden" name="port" value="$port">
</form>
END;
}
}
// ----------------------------------------------------------------
// Server options
// ----------------------------------------------------------------
echo "\n<h3>Server options:</h3>\n";
if (!$client->query('GetServerOptions', 1)) {
trigger_error("[".$client->getErrorCode()."] ".$client->getErrorMessage());
}
else
{
$ServerOptions = $client->getResponse();
$repGetServerName = $ServerOptions['Name'];
$repServerComment = $ServerOptions['Comment'];
$repServerPassword = $ServerOptions['Password'];
$repPasswordForSpectator = $ServerOptions['PasswordForSpectator'];
$repRefereePassword = $ServerOptions['RefereePassword'];
$repRefereeMode = $ServerOptions['RefereeMode'];
$repCurrentMaxPlayer = $ServerOptions['CurrentMaxPlayers'];
$repNextMaxPlayer = $ServerOptions['NextMaxPlayers'];
$repCurrentMaxSpectator = $ServerOptions['CurrentMaxSpectators'];
$repNextMaxSpectator = $ServerOptions['NextMaxSpectators'];
$repP2PUpload = ($ServerOptions['IsP2PUpload']!=0) ? "checked" : " ";
$repP2PDownload = ($ServerOptions['IsP2PDownload']!=0) ? "checked" : " ";
$repCurrentLadderMode = $ServerOptions['CurrentLadderMode'];
$repNextLadderMode = $ServerOptions['NextLadderMode'];
$repCurrentVehicleNetQuality = $ServerOptions['CurrentVehicleNetQuality'];
$repNextVehicleNetQuality = $ServerOptions['NextVehicleNetQuality'];
$repCurrentCallVoteTimeOut = $ServerOptions['CurrentCallVoteTimeOut'];
$repNextCallVoteTimeOut = $ServerOptions['NextCallVoteTimeOut'];
$repCallVoteRatio = $ServerOptions['CallVoteRatio'];
$repAllowChallengeDownload = ($ServerOptions['AllowChallengeDownload']!=0) ? "checked" : " ";
$repAutoSaveReplays = ($ServerOptions['AutoSaveReplays']!=0) ? "checked" : " ";
$repAutoSaveValidationReplays = ($ServerOptions['AutoSaveValidationReplays']!=0) ? "checked" : " ";
if( $repCurrentLadderMode==0 )
$CurrentLadderMode = "Inactive";
else if( $repCurrentLadderMode==1 )
$CurrentLadderMode = "Forced";
else
$CurrentLadderMode = "Undefined";
if( $repNextLadderMode==0 )
{
$NextLadderModeInactive = "selected";
$NextLadderModeForced = "";
}
{
$NextLadderModeInactive = "";
$NextLadderModeForced = "selected";
}
if( $repCurrentVehicleNetQuality==0 )
$CurrentVehicleNetQuality = "Fast";
else if( $repCurrentVehicleNetQuality==1 )
$CurrentVehicleNetQuality = "High";
else
$CurrentLadderMode = "Undefined";
if( $repNextVehicleNetQuality==1 )
{
$NextVehicleNetQualityFast = "";
$NextVehicleNetQualityHigh = "selected";
}
else
{
$NextVehicleNetQualityFast = "selected";
$NextVehicleNetQualityHigh = "";
}
echo <<<END
<form name="input" action="basic.php" method="post">
<table>
<tr><td>Name: </td><td><input type="text" name="ServerName" size=30 value="$repGetServerName"/> </td></tr>
<tr><td>Comment: </td><td><textarea name="ServerComment" cols=40 rows=3> $repServerComment </textarea> </td></tr>
<tr><td>Password: </td><td><input type="text" name="ServerPassword" size=30 value="$repServerPassword"/> </td></tr>
<tr><td>PasswordForSpectator: </td><td><input type="text" name="SpectatorPassword" size=30 value="$repPasswordForSpectator"/> </td></tr>
<tr><td>RefereePassword: </td><td><input type="text" name="RefereePassword" size=30 value="$repRefereePassword"/> </td></tr>
<tr><td>MaxPlayer: </td><td><table><td><input type="text" name="CurrentMaxPlayers" size=10 readonly value="$repCurrentMaxPlayer"/> </td><td> Next Value: </td><td><input type="text" name="NextMaxPlayers" size=10 value="$repNextMaxPlayer"/> </td></table></td></tr>
<tr><td>MaxSpectator: </td><td><table><td><input type="text" name="CurrentMaxSpectators" size=10 readonly value="$repCurrentMaxSpectator"/> </td><td> Next Value: </td><td><input type="text" name="NextMaxSpectators" size=10 value="$repNextMaxSpectator"/> </td></table></td></tr>
<tr><td>P2PUpload: </td><td><input type="checkbox" name="IsP2PUpload" $repP2PUpload/> </td></tr>
<tr><td>P2PDownload: </td><td><input type="checkbox" name="IsP2PDownload" $repP2PDownload/> </td></tr>
<tr><td>LadderMode: </td><td><table><td><input type="text" name="CurrentLadderMode" size=10 readonly value="$CurrentLadderMode"/> </td><td> Next Value: </td><td>
<SELECT name="NextLadderMode" >
<OPTION value="0" $NextLadderModeInactive> Inactive </OPTION>
<OPTION value="1" $NextLadderModeForced> Forced </OPTION>
</SELECT>
</td></table></td></tr>
<tr><td>VehicleNetQuality: </td><td><table><td><input type="text" name="CurrentVehicleNetQuality" size=10 readonly value="$CurrentVehicleNetQuality"/> </td><td> Next Value: </td><td>
<SELECT name="NextVehicleNetQuality" >
<OPTION value="0" $NextVehicleNetQualityFast> Fast </OPTION>
<OPTION value="1" $NextVehicleNetQualityHigh> High </OPTION>
</SELECT>
</td></table></td></tr>
<tr><td>CallVoteTimeOut: </td><td><table><td><input type="text" name="CurrentCallVoteTimeOut" size=10 readonly value="$repCurrentCallVoteTimeOut"/> </td><td> Next Value: </td><td><input type="text" name="NextCallVoteTimeOut" size=10 value="$repNextCallVoteTimeOut"/> </td></table></td></tr>
<tr><td>CallVoteRatio: </td><td><input type="text" name="CallVoteRatio" size=10 value="$repCallVoteRatio"/> </td></tr>
<tr><td>AllowChallengeDownload: </td><td><input type="checkbox" name="AllowChallengeDownload" $repAllowChallengeDownload/> </td></tr>
<tr><td>AutoSaveReplays: </td><td><input type="checkbox" name="AutoSaveReplays" $repAutoSaveReplays/> </td></tr>
<tr><td>AutoSaveValidationReplays: </td><td><input type="checkbox" name="AutoSaveValidationReplays" $repAutoSaveValidationReplays/> </td></tr>
</table>
<input type="submit" name="action" value="SetServerOptions">
<input type="hidden" name="authLogin" value="$AuthLogin">
<input type="hidden" name="authPassword" value="$AuthPassword">
<input type="hidden" name="port" value="$port">
<input type="hidden" name="RefereeMode" value="$repRefereeMode">
</form>
END;
}
// ----------------------------------------------------------------
// Game infos
// ----------------------------------------------------------------
echo "\n<h3>Game infos:</h3>\n";
if (!$client->query('GetGameInfos', 1)) {
trigger_error("[".$client->getErrorCode()."] ".$client->getErrorMessage());
}
else
{
$GameInfos = $client->getResponse();
$CurrentGameInfo = $GameInfos['CurrentGameInfos'];
$NextGameInfo = $GameInfos['NextGameInfos'];
$ChatTime = $CurrentGameInfo['ChatTime'];
$NbChallenge = $CurrentGameInfo['NbChallenge'];
if( $CurrentGameInfo['GameMode']==0 )
$GameMode = "Rounds";
else if( $CurrentGameInfo['GameMode']==1 )
$GameMode = "TimeAttack";
else if( $CurrentGameInfo['GameMode']==2 )
$GameMode = "Team";
else if( $CurrentGameInfo['GameMode']==3 )
$GameMode = "Laps";
else if( $CurrentGameInfo['GameMode']==4 )
$GameMode = "Stunts";
else if( $CurrentGameInfo['GameMode']==5 )
$GameMode = "Cup";
else
$GameMode = "Undefined";
$RoundsPointsLimit = $CurrentGameInfo['RoundsPointsLimit'];
$RoundsPointsLimitNewRules = $CurrentGameInfo['RoundsPointsLimitNewRules'];
$RoundsUseNewRules = ($CurrentGameInfo['RoundsUseNewRules']!=0) ? "True" : "False";
$RoundsForcedLaps = $CurrentGameInfo['RoundsForcedLaps'];
$FinishTimeout = $CurrentGameInfo['FinishTimeout'];
$TimeAttackLimit = $CurrentGameInfo['TimeAttackLimit'];
$TimeAttackSynchStartPeriod = $CurrentGameInfo['TimeAttackSynchStartPeriod'];
$TeamPointsLimit = $CurrentGameInfo['TeamPointsLimit'];
$TeamPointsLimitNewRules = $CurrentGameInfo['TeamPointsLimitNewRules'];
$TeamMaxPoints = $CurrentGameInfo['TeamMaxPoints'];
$TeamUseNewRules = ($CurrentGameInfo['TeamUseNewRules']!=0) ? "True" : "False";
$CupPointsLimit = $CurrentGameInfo['CupPointsLimit'];
$CupRoundsPerChallenge = $CurrentGameInfo['CupRoundsPerChallenge'];
$CupNbWinners = $CurrentGameInfo['CupNbWinners'];
$CupWarmUpDuration = $CurrentGameInfo['CupWarmUpDuration'];
$LapsNbLaps = $CurrentGameInfo['LapsNbLaps'];
$LapsTimeLimit = $CurrentGameInfo['LapsTimeLimit'];
$NextChatTime = $NextGameInfo['ChatTime'];
$NextGameMode0 = $NextGameInfo['GameMode']==0 ? "selected" : "";
$NextGameMode1 = $NextGameInfo['GameMode']==1 ? "selected" : "";
$NextGameMode2 = $NextGameInfo['GameMode']==2 ? "selected" : "";
$NextGameMode3 = $NextGameInfo['GameMode']==3 ? "selected" : "";
$NextGameMode4 = $NextGameInfo['GameMode']==4 ? "selected" : "";
$NextGameMode5 = $NextGameInfo['GameMode']==5 ? "selected" : "";
$NextRoundsPointsLimit = $NextGameInfo['RoundsPointsLimit'];
$NextRoundsPointsLimitNewRules = $NextGameInfo['RoundsPointsLimitNewRules'];
$NextRoundsUseNewRules = ($NextGameInfo['RoundsUseNewRules']!=0) ? "checked" : " ";
$NextRoundsForcedLaps = $NextGameInfo['RoundsForcedLaps'];
$NextFinishTimeout = $NextGameInfo['FinishTimeout'];
$NextTimeAttackLimit = $NextGameInfo['TimeAttackLimit'];
$NextTimeAttackSynchStartPeriod = $NextGameInfo['TimeAttackSynchStartPeriod'];
$NextTeamPointsLimit = $NextGameInfo['TeamPointsLimit'];
$NextTeamPointsLimitNewRules = $NextGameInfo['TeamPointsLimitNewRules'];
$NextTeamMaxPoints = $NextGameInfo['TeamMaxPoints'];
$NextTeamUseNewRules = ($NextGameInfo['TeamUseNewRules']!=0) ? "checked" : " ";
$NextCupPointsLimit = $NextGameInfo['CupPointsLimit'];
$NextCupRoundsPerChallenge = $NextGameInfo['CupRoundsPerChallenge'];
$NextCupNbWinners = $NextGameInfo['CupNbWinners'];
$NextCupWarmUpDuration = $NextGameInfo['CupWarmUpDuration'];
$NextLapsNbLaps = $NextGameInfo['LapsNbLaps'];
$NextLapsTimeLimit = $NextGameInfo['LapsTimeLimit'];
echo <<<END
<form name="input" action="basic.php" method="post">
<table>
<tr><td></td><td>Current</td><td>Next</td></tr>
<tr><td>Mode: </td><td><input type="text" name="GameMode" readonly value="$GameMode"/> </td><td>
<SELECT name="NextGameMode" >
<OPTION value="0" $NextGameMode0> Rounds </OPTION>
<OPTION value="1" $NextGameMode1> TimeAttack </OPTION>
<OPTION value="2" $NextGameMode2> Team </OPTION>
<OPTION value="3" $NextGameMode3> Laps </OPTION>
<OPTION value="4" $NextGameMode4> Stunts </OPTION>
<OPTION value="5" $NextGameMode5> Cup </OPTION>
</SELECT>
</td></tr>
<tr><td>ChatTime: </td><td><input type="text" name="ChatTime" readonly value="$ChatTime"/> </td><td><input type="text" name="NextChatTime" value="$NextChatTime"/> </td></tr>
<tr><td>NbChallenge: </td><td><input type="text" name="NbChallenge" readonly value="$NbChallenge"/> </td></tr>
<tr><td>RoundsPointsLimit: </td><td><input type="text" name="RoundsPointsLimit" readonly value="$RoundsPointsLimit"/> </td><td><input type="text" name="NextRoundsPointsLimit" value="$NextRoundsPointsLimit"/> </td></tr>
<tr><td>RoundsPointsLimitNewRules: </td><td><input type="text" name="RoundsPointsLimitNewRules" readonly value="$RoundsPointsLimitNewRules"/> </td><td><input type="text" name="NextRoundsPointsLimitNewRules" value="$NextRoundsPointsLimitNewRules"/> </td></tr>
<tr><td>RoundsUseNewRules: </td><td><input type="text" name="RoundsUseNewRules" readonly value="$RoundsUseNewRules"/> </td><td><input type="checkbox" name="NextRoundsUseNewRules" $NextRoundsUseNewRules/> </td></tr>
<tr><td>RoundsForcedLaps: </td><td><input type="text" name="RoundsForcedLaps" readonly value="$RoundsForcedLaps"/> </td><td><input type="text" name="NextRoundsForcedLaps" value="$NextRoundsForcedLaps"/> </td></tr>
<tr><td>FinishTimeout: </td><td><input type="text" name="FinishTimeout" readonly value="$FinishTimeout"/> </td><td><input type="text" name="NextFinishTimeout" value="$NextFinishTimeout"/> </td></tr>
<tr><td>TimeAttackLimit: </td><td><input type="text" name="TimeAttackLimit" readonly value="$TimeAttackLimit"/> </td><td><input type="text" name="NextTimeAttackLimit" value="$NextTimeAttackLimit"/> </td></tr>
<tr><td>TimeAttackSynchStartPeriod: </td><td><input type="text" name="TimeAttackSynchStartPeriod" readonly value="$TimeAttackSynchStartPeriod"/> </td><td><input type="text" name="NextTimeAttackSynchStartPeriod" value="$NextTimeAttackSynchStartPeriod"/> </td></tr>
<tr><td>TeamPointsLimit: </td><td><input type="text" name="TeamPointsLimit" readonly value="$TeamPointsLimit"/> </td><td><input type="text" name="NextTeamPointsLimit" value="$NextTeamPointsLimit"/> </td></tr>
<tr><td>TeamPointsLimitNewRules: </td><td><input type="text" name="TeamPointsLimitNewRules" readonly value="$TeamPointsLimitNewRules"/> </td><td><input type="text" name="NextTeamPointsLimitNewRules" value="$NextTeamPointsLimitNewRules"/> </td></tr>
<tr><td>TeamMaxPoints: </td><td><input type="text" name="TeamMaxPoints" readonly value="$TeamMaxPoints"/> </td><td><input type="text" name="NextTeamMaxPoints" value="$NextTeamMaxPoints"/> </td></tr>
<tr><td>TeamUseNewRules: </td><td><input type="text" name="TeamUseNewRules" readonly value="$TeamUseNewRules"/> </td><td><input type="checkbox" name="NextTeamUseNewRules" $NextTeamUseNewRules/> </td></tr>
<tr><td>CupPointsLimit: </td><td><input type="text" name="CupPointsLimit" readonly value="$CupPointsLimit"/> </td><td><input type="text" name="NextCupPointsLimit" value="$NextCupPointsLimit"/> </td></tr>
<tr><td>CupRoundsPerChallenge: </td><td><input type="text" name="CupRoundsPerChallenge" readonly value="$CupRoundsPerChallenge"/> </td><td><input type="text" name="NextCupRoundsPerChallenge" value="$NextCupRoundsPerChallenge"/> </td></tr>
<tr><td>CupNbWinners: </td><td><input type="text" name="CupNbWinners" readonly value="$CupNbWinners"/> </td><td><input type="text" name="NextCupNbWinners" value="$NextCupNbWinners"/> </td></tr>
<tr><td>CupWarmUpDuration: </td><td><input type="text" name="CupWarmUpDuration" readonly value="$CupWarmUpDuration"/> </td><td><input type="text" name="NextCupWarmUpDuration" value="$NextCupWarmUpDuration"/> </td></tr>
<tr><td>LapsNbLaps: </td><td><input type="text" name="LapsNbLaps" readonly value="$LapsNbLaps"/> </td><td><input type="text" name="NextLapsNbLaps" value="$NextLapsNbLaps"/> </td></tr>
<tr><td>LapsTimeLimit: </td><td><input type="text" name="LapsTimeLimit" readonly value="$LapsTimeLimit"/> </td><td><input type="text" name="NextLapsTimeLimit" value="$NextLapsTimeLimit"/> </td></tr>
</table>
<input type="submit" name="action" value="SetGameInfos">
<input type="hidden" name="authLogin" value="$AuthLogin">
<input type="hidden" name="authPassword" value="$AuthPassword">
<input type="hidden" name="port" value="$port">
</form>
END;
}
// ----------------------------------------------------------------
// challenges
// ----------------------------------------------------------------
// debug
echo "\n<h3>Challenges:</h3>\n";
if (!$client->query('GetChallengeList', 50, 0)) {
trigger_error("[".$client->getErrorCode()."] ".$client->getErrorMessage());
}
else
{
$ChallengeList = $client->getResponse();
echo '<TABLE cellspacing=5>';
foreach ($ChallengeList as $challenge) {
$ChallengeUId = $challenge['UId'];
$ChallengeAuthor = $challenge['Author'];
$ChallengeName = styledString($challenge['Name']);
$FileName = $challenge['FileName'];
$FileNameUrl = urlencode($FileName);
$Environnement = $challenge['Environnement'];
$GoldTime = MwTimeToString($challenge['GoldTime']);
$CopperPrice = $challenge['CopperPrice'];
echo <<<END
<TR><TD>$ChallengeName<br>$ChallengeUId</TD><TD>$FileName</TD><TD>$Environnement<br>$ChallengeAuthor</TD><TD>$GoldTime</TD><TD>$CopperPrice</TD>
<TD><form action="basic.php" method="post"><input type="hidden" name="ChallengeFileName" value="$FileName"><input type="submit" name="action" value="RemoveChallenge"><input type="hidden" name="authLogin" value="$AuthLogin"><input type="hidden" name="authPassword" value="$AuthPassword"><input type="hidden" name="port" value="$port"></form></TD>
<TD><form action="basic.php" method="post"><input type="hidden" name="ChallengeFileName" value="$FileName"><input type="submit" name="action" value="ChooseNextChallenge"><input type="hidden" name="authLogin" value="$AuthLogin"><input type="hidden" name="authPassword" value="$AuthPassword"><input type="hidden" name="port" value="$port"></form></TD>
</TR>
END;
}
echo "</TABLE>";
}
echo <<<END
<TR><form name="input" action="basic.php" method="post">
<TD colspan=4><input type="text" name="ChallengeFileName" size=70/></TD>
<TD><input type="submit" name="action" value="AddChallenge"></TD>
<input type="hidden" name="authLogin" value="$AuthLogin">
<input type="hidden" name="authPassword" value="$AuthPassword">
<input type="hidden" name="port" value="$port">
</form></TD>
END;
echo <<<END
<form name="input" action="basic.php" method="post">
<input type="text" name="MatchSettingsFileName" size=70/><BR>
<input type="submit" name="action" value="LoadMatchSettings"/>
<input type="submit" name="action" value="SaveMatchSettings"/>
<input type="submit" name="action" value="AppendPlaylistFromMatchSettings"/>
<input type="hidden" name="authLogin" value="$AuthLogin">
<input type="hidden" name="authPassword" value="$AuthPassword">
<input type="hidden" name="port" value="$port">
</form></TD>
END;
/*
// uncomment to test the callbacks..
echo "<h2>callbacks:</h2><br/>";
if (!$client->query('EnableCallbacks', true)) {
trigger_error("[".$client->getErrorCode()."] ".$client->getErrorMessage());
}
flush();
while (true) {
$client->readCB(5);
$calls = $client->getCBResponses();
if (!empty($calls)) {
foreach ($calls as $call) {
echo "call: ".$call[0]."<br/>";
}
} else {
echo "no calls...<br/>";
}
flush();
}
*/
$client->Terminate();
?>

View File

@ -1,4 +0,0 @@
#!/bin/sh
cd $TMDIR/GameData/Cache/
find . -type f -exec rm {} \;