removed 'application' folder to have everything in the root directory
This commit is contained in:
459
core/Server/Commands.php
Normal file
459
core/Server/Commands.php
Normal file
@ -0,0 +1,459 @@
|
||||
<?php
|
||||
|
||||
namespace ManiaControl\Server;
|
||||
|
||||
use FML\Controls\Quads\Quad_BgRaceScore2;
|
||||
use FML\Controls\Quads\Quad_Icons128x32_1;
|
||||
use FML\Controls\Quads\Quad_Icons64x64_1;
|
||||
use ManiaControl\Admin\AuthenticationManager;
|
||||
use ManiaControl\Callbacks\CallbackListener;
|
||||
use ManiaControl\Callbacks\Callbacks;
|
||||
use ManiaControl\Callbacks\TimerListener;
|
||||
use ManiaControl\Commands\CommandListener;
|
||||
use ManiaControl\Logger;
|
||||
use ManiaControl\ManiaControl;
|
||||
use ManiaControl\Manialinks\ManialinkPageAnswerListener;
|
||||
use ManiaControl\Players\Player;
|
||||
use Maniaplanet\DedicatedServer\Xmlrpc\GameModeException;
|
||||
|
||||
/**
|
||||
* Class offering various Commands related to the Dedicated Server
|
||||
*
|
||||
* @author ManiaControl Team <mail@maniacontrol.com>
|
||||
* @copyright 2014 ManiaControl Team
|
||||
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
|
||||
*/
|
||||
class Commands implements CallbackListener, CommandListener, ManialinkPageAnswerListener, TimerListener {
|
||||
/*
|
||||
* Constants
|
||||
*/
|
||||
const ACTION_SET_PAUSE = 'ServerCommands.SetPause';
|
||||
const ACTION_EXTEND_WARMUP = 'ServerCommands.ExtendWarmup';
|
||||
const ACTION_END_WARMUP = 'ServerCommands.EndWarmup';
|
||||
const ACTION_CANCEL_VOTE = 'ServerCommands.CancelVote';
|
||||
const CB_VOTE_CANCELLED = 'ServerCommands.VoteCancelled';
|
||||
const SETTING_PERMISSION_CANCEL_VOTE = 'Cancel Vote';
|
||||
const SETTING_PERMISSION_SET_PAUSE = 'Set Pause';
|
||||
const SETTING_PERMISSION_HANDLE_WARMUP = 'Handle Warmup';
|
||||
const SETTING_PERMISSION_SHOW_SYSTEMINFO = 'Show SystemInfo';
|
||||
const SETTING_PERMISSION_SHUTDOWN_SERVER = 'Shutdown Server';
|
||||
const SETTING_PERMISSION_CHANGE_SERVERSETTINGS = 'Change ServerSettings';
|
||||
const COMMAND_EXTEND_WARMUP = 'WarmUp_Extend';
|
||||
const COMMAND_FORCE_WARMUP = 'Command_ForceWarmUp';
|
||||
|
||||
/*
|
||||
* Private properties
|
||||
*/
|
||||
/** @var ManiaControl $maniaControl */
|
||||
private $maniaControl = null;
|
||||
private $serverShutdownTime = -1;
|
||||
private $serverShutdownEmpty = false;
|
||||
|
||||
/**
|
||||
* Create a new server commands instance
|
||||
*
|
||||
* @param ManiaControl $maniaControl
|
||||
*/
|
||||
public function __construct(ManiaControl $maniaControl) {
|
||||
$this->maniaControl = $maniaControl;
|
||||
|
||||
// Callbacks
|
||||
$this->maniaControl->getTimerManager()->registerTimerListening($this, 'each5Seconds', 5000);
|
||||
$this->maniaControl->getCallbackManager()->registerCallbackListener(Callbacks::ONINIT, $this, 'handleOnInit');
|
||||
$this->maniaControl->getCallbackManager()->registerCallbackListener(Callbacks::WARMUPSTATUS, $this, 'handleWarmUpStatus');
|
||||
|
||||
// Chat commands
|
||||
$this->maniaControl->getCommandManager()->registerCommandListener('setservername', $this, 'commandSetServerName', true, 'Sets the ServerName.');
|
||||
$this->maniaControl->getCommandManager()->registerCommandListener('setpwd', $this, 'commandSetPwd', true, 'Sets play password.');
|
||||
$this->maniaControl->getCommandManager()->registerCommandListener('setspecpwd', $this, 'commandSetSpecPwd', true, 'Sets spectator password.');
|
||||
$this->maniaControl->getCommandManager()->registerCommandListener('setmaxplayers', $this, 'commandSetMaxPlayers', true, 'Sets the maximum number of players.');
|
||||
$this->maniaControl->getCommandManager()->registerCommandListener('setmaxspectators', $this, 'commandSetMaxSpectators', true, 'Sets the maximum number of spectators.');
|
||||
$this->maniaControl->getCommandManager()->registerCommandListener('shutdownserver', $this, 'commandShutdownServer', true, 'Shuts down the ManiaPlanet server.');
|
||||
$this->maniaControl->getCommandManager()->registerCommandListener('systeminfo', $this, 'commandSystemInfo', true, 'Shows system information.');
|
||||
$this->maniaControl->getCommandManager()->registerCommandListener('cancel', $this, 'commandCancelVote', true, 'Cancels the current vote.');
|
||||
|
||||
// Page actions
|
||||
$this->maniaControl->getManialinkManager()->registerManialinkPageAnswerListener(self::ACTION_SET_PAUSE, $this, 'setPause');
|
||||
$this->maniaControl->getManialinkManager()->registerManialinkPageAnswerListener(self::ACTION_EXTEND_WARMUP, $this, 'commandExtendWarmup');
|
||||
$this->maniaControl->getManialinkManager()->registerManialinkPageAnswerListener(self::ACTION_END_WARMUP, $this, 'commandEndWarmup');
|
||||
$this->maniaControl->getManialinkManager()->registerManialinkPageAnswerListener(self::ACTION_CANCEL_VOTE, $this, 'commandCancelVote');
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle ManiaControl OnInit Callback
|
||||
*/
|
||||
public function handleOnInit() {
|
||||
// Permissions
|
||||
$this->maniaControl->getAuthenticationManager()->definePermissionLevel(self::SETTING_PERMISSION_SHUTDOWN_SERVER, AuthenticationManager::AUTH_LEVEL_SUPERADMIN);
|
||||
$this->maniaControl->getAuthenticationManager()->definePermissionLevel(self::SETTING_PERMISSION_SHOW_SYSTEMINFO, AuthenticationManager::AUTH_LEVEL_SUPERADMIN);
|
||||
$this->maniaControl->getAuthenticationManager()->definePermissionLevel(self::SETTING_PERMISSION_CHANGE_SERVERSETTINGS, AuthenticationManager::AUTH_LEVEL_ADMIN);
|
||||
$this->maniaControl->getAuthenticationManager()->definePermissionLevel(self::SETTING_PERMISSION_SET_PAUSE, AuthenticationManager::AUTH_LEVEL_MODERATOR);
|
||||
$this->maniaControl->getAuthenticationManager()->definePermissionLevel(self::SETTING_PERMISSION_CANCEL_VOTE, AuthenticationManager::AUTH_LEVEL_MODERATOR);
|
||||
$this->maniaControl->getAuthenticationManager()->definePermissionLevel(self::SETTING_PERMISSION_HANDLE_WARMUP, AuthenticationManager::AUTH_LEVEL_MODERATOR);
|
||||
|
||||
$this->updateCancelVoteMenuItem();
|
||||
$this->updateWarmUpMenuItems();
|
||||
}
|
||||
|
||||
/**
|
||||
* Add the cancel vote menu item
|
||||
*/
|
||||
private function updateCancelVoteMenuItem() {
|
||||
$itemQuad = new Quad_Icons64x64_1();
|
||||
$itemQuad->setSubStyle($itemQuad::SUBSTYLE_ArrowRed);
|
||||
$itemQuad->setAction(self::ACTION_CANCEL_VOTE);
|
||||
$this->maniaControl->getActionsMenu()->addMenuItem($itemQuad, false, 30, 'Cancel Vote');
|
||||
}
|
||||
|
||||
/**
|
||||
* Manage the WarmUp related menu items
|
||||
*/
|
||||
private function updateWarmUpMenuItems() {
|
||||
$pauseExists = false;
|
||||
try {
|
||||
$scriptInfos = $this->maniaControl->getClient()->getModeScriptInfo();
|
||||
foreach ($scriptInfos->commandDescs as $param) {
|
||||
if ($param->name === self::COMMAND_FORCE_WARMUP) {
|
||||
$pauseExists = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
$this->maniaControl->getClient()->triggerModeScriptEvent("WarmUp_GetStatus");
|
||||
} catch (GameModeException $e) {
|
||||
}
|
||||
|
||||
// Add pause menu item
|
||||
if ($pauseExists) {
|
||||
$itemQuad = new Quad_Icons128x32_1();
|
||||
$itemQuad->setSubStyle($itemQuad::SUBSTYLE_ManiaLinkSwitch);
|
||||
$itemQuad->setAction(self::ACTION_SET_PAUSE);
|
||||
$this->maniaControl->getActionsMenu()->addAdminMenuItem($itemQuad, 13, 'Pause the current game');
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle the WarmupStatus Callback, and removes or adds the Menu Items for extending / Stopping warmup
|
||||
*
|
||||
* @param $warmupEnabled
|
||||
*/
|
||||
public function handleWarmUpStatus($warmupEnabled) {
|
||||
if ($warmupEnabled) {
|
||||
// Extend WarmUp menu item
|
||||
$itemQuad = new Quad_BgRaceScore2();
|
||||
$itemQuad->setSubStyle($itemQuad::SUBSTYLE_SendScore);
|
||||
$itemQuad->setAction(self::ACTION_EXTEND_WARMUP);
|
||||
$this->maniaControl->getActionsMenu()->addMenuItem($itemQuad, false, 14, 'Extend Warmup');
|
||||
|
||||
// Stop WarmUp menu item
|
||||
$itemQuad = new Quad_Icons64x64_1();
|
||||
$itemQuad->setSubStyle($itemQuad::SUBSTYLE_ArrowGreen);
|
||||
$itemQuad->setAction(self::ACTION_END_WARMUP);
|
||||
$this->maniaControl->getActionsMenu()->addMenuItem($itemQuad, false, 15, 'End Warmup');
|
||||
} else {
|
||||
$this->maniaControl->getActionsMenu()->removeMenuItem(14, false);
|
||||
$this->maniaControl->getActionsMenu()->removeMenuItem(15, false);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle //cancelvote command
|
||||
*
|
||||
* @param array $chatCallback
|
||||
* @param Player $player
|
||||
*/
|
||||
public function commandCancelVote(array $chatCallback, Player $player) {
|
||||
if (!$this->maniaControl->getAuthenticationManager()->checkPermission($player, self::SETTING_PERMISSION_CANCEL_VOTE)
|
||||
) {
|
||||
$this->maniaControl->getAuthenticationManager()->sendNotAllowed($player);
|
||||
return;
|
||||
}
|
||||
|
||||
if ($this->maniaControl->getClient()->cancelVote()
|
||||
) {
|
||||
$this->maniaControl->getChat()->sendInformation($player->getEscapedNickname() . ' cancelled the Vote!');
|
||||
} else {
|
||||
$this->maniaControl->getChat()->sendInformation("There's no vote running currently!", $player);
|
||||
}
|
||||
|
||||
$this->maniaControl->getCallbackManager()->triggerCallback(self::CB_VOTE_CANCELLED, $player);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Extend the WarmUp
|
||||
*
|
||||
* @param array $callback
|
||||
* @param Player $player
|
||||
*/
|
||||
public function commandExtendWarmup(array $callback, Player $player) {
|
||||
if (!$this->maniaControl->getAuthenticationManager()->checkPermission($player, self::SETTING_PERMISSION_HANDLE_WARMUP)
|
||||
) {
|
||||
$this->maniaControl->getAuthenticationManager()->sendNotAllowed($player);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$this->maniaControl->getClient()->triggerModeScriptEvent('WarmUp_Extend', '10');
|
||||
$this->maniaControl->getChat()->sendInformation($player->getEscapedNickname() . ' extended the WarmUp by 10 seconds!');
|
||||
} catch (GameModeException $e) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* End the WarmUp
|
||||
*
|
||||
* @param array $callback
|
||||
* @param Player $player
|
||||
*/
|
||||
public function commandEndWarmup(array $callback, Player $player) {
|
||||
if (!$this->maniaControl->getAuthenticationManager()->checkPermission($player, self::SETTING_PERMISSION_HANDLE_WARMUP)
|
||||
) {
|
||||
$this->maniaControl->getAuthenticationManager()->sendNotAllowed($player);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$this->maniaControl->getClient()->triggerModeScriptEvent('WarmUp_Stop', '');
|
||||
$this->maniaControl->getChat()->sendInformation($player->getEscapedNickname() . ' stopped the WarmUp!');
|
||||
} catch (GameModeException $e) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pause the current game
|
||||
*
|
||||
* @param array $callback
|
||||
* @param Player $player
|
||||
*/
|
||||
public function setPause(array $callback, Player $player) {
|
||||
if (!$this->maniaControl->getAuthenticationManager()->checkPermission($player, self::SETTING_PERMISSION_SET_PAUSE)
|
||||
) {
|
||||
$this->maniaControl->getAuthenticationManager()->sendNotAllowed($player);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
$this->maniaControl->getClient()->sendModeScriptCommands(array('Command_ForceWarmUp' => true));
|
||||
$this->maniaControl->getChat()->sendInformation($player->getEscapedNickname() . ' paused the Game!');
|
||||
} catch (GameModeException $e) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check Stuff each 5 Seconds
|
||||
*/
|
||||
public function each5Seconds() {
|
||||
// TODO: move empty & delayed shutdown code into server class
|
||||
// Empty shutdown
|
||||
if ($this->serverShutdownEmpty) {
|
||||
if ($this->maniaControl->getPlayerManager()->getPlayerCount(false) <= 0
|
||||
) {
|
||||
$this->shutdownServer('empty');
|
||||
}
|
||||
}
|
||||
|
||||
// Delayed shutdown
|
||||
if ($this->serverShutdownTime > 0) {
|
||||
if (time() >= $this->serverShutdownTime) {
|
||||
$this->shutdownServer('delayed');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform server shutdown
|
||||
*
|
||||
* @param string $login
|
||||
*/
|
||||
private function shutdownServer($login = '-') {
|
||||
Logger::logInfo("Server shutdown requested by '{$login}'!");
|
||||
$this->maniaControl->getClient()->stopServer();
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle //systeminfo command
|
||||
*
|
||||
* @param array $chat
|
||||
* @param Player $player
|
||||
*/
|
||||
public function commandSystemInfo(array $chat, Player $player) {
|
||||
if (!$this->maniaControl->getAuthenticationManager()->checkPermission($player, self::SETTING_PERMISSION_SHOW_SYSTEMINFO)
|
||||
) {
|
||||
$this->maniaControl->getAuthenticationManager()->sendNotAllowed($player);
|
||||
return;
|
||||
}
|
||||
$systemInfo = $this->maniaControl->getClient()->getSystemInfo();
|
||||
$message = 'SystemInfo: ip=' . $systemInfo->publishedIp . ', port=' . $systemInfo->port . ', p2pPort=' . $systemInfo->p2PPort . ', title=' . $systemInfo->titleId . ', login=' . $systemInfo->serverLogin . '.';
|
||||
$this->maniaControl->getChat()->sendInformation($message, $player->login);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle //shutdownserver command
|
||||
*
|
||||
* @param array $chat
|
||||
* @param Player $player
|
||||
*/
|
||||
public function commandShutdownServer(array $chat, Player $player) {
|
||||
if (!$this->maniaControl->getAuthenticationManager()->checkPermission($player, self::SETTING_PERMISSION_SHUTDOWN_SERVER)
|
||||
) {
|
||||
$this->maniaControl->getAuthenticationManager()->sendNotAllowed($player);
|
||||
return;
|
||||
}
|
||||
// Check for delayed shutdown
|
||||
$params = explode(' ', $chat[1][2]);
|
||||
if (count($params) >= 2) {
|
||||
$param = $params[1];
|
||||
if (strtolower($param) === 'empty') {
|
||||
$this->serverShutdownEmpty = !$this->serverShutdownEmpty;
|
||||
if ($this->serverShutdownEmpty) {
|
||||
$this->maniaControl->getChat()->sendInformation("The server will shutdown as soon as it's empty!", $player);
|
||||
return;
|
||||
}
|
||||
$this->maniaControl->getChat()->sendInformation("Empty-shutdown cancelled!", $player);
|
||||
return;
|
||||
}
|
||||
$delay = (int)$param;
|
||||
if ($delay <= 0) {
|
||||
// Cancel shutdown
|
||||
$this->serverShutdownTime = -1;
|
||||
$this->maniaControl->getChat()->sendInformation("Delayed shutdown cancelled!", $player);
|
||||
return;
|
||||
}
|
||||
// Trigger delayed shutdown
|
||||
$this->serverShutdownTime = time() + $delay * 60.;
|
||||
$this->maniaControl->getChat()->sendInformation("The server will shut down in {$delay} minutes!", $player);
|
||||
return;
|
||||
}
|
||||
$this->shutdownServer($player->login);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle //setservername command
|
||||
*
|
||||
* @param array $chat
|
||||
* @param Player $player
|
||||
*/
|
||||
public function commandSetServerName(array $chat, Player $player) {
|
||||
if (!$this->maniaControl->getAuthenticationManager()->checkPermission($player, self::SETTING_PERMISSION_CHANGE_SERVERSETTINGS)
|
||||
) {
|
||||
$this->maniaControl->getAuthenticationManager()->sendNotAllowed($player);
|
||||
return;
|
||||
}
|
||||
$params = explode(' ', $chat[1][2], 2);
|
||||
if (count($params) < 2) {
|
||||
$this->maniaControl->getChat()->sendUsageInfo('Usage example: //setservername ManiaPlanet Server', $player);
|
||||
return;
|
||||
}
|
||||
$serverName = $params[1];
|
||||
$this->maniaControl->getClient()->setServerName($serverName);
|
||||
$this->maniaControl->getChat()->sendSuccess("Server name changed to: '{$serverName}'!", $player);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle //setpwd command
|
||||
*
|
||||
* @param array $chatCallback
|
||||
* @param Player $player
|
||||
*/
|
||||
public function commandSetPwd(array $chatCallback, Player $player) {
|
||||
if (!$this->maniaControl->getAuthenticationManager()->checkPermission($player, self::SETTING_PERMISSION_CHANGE_SERVERSETTINGS)
|
||||
) {
|
||||
$this->maniaControl->getAuthenticationManager()->sendNotAllowed($player);
|
||||
return;
|
||||
}
|
||||
$messageParts = explode(' ', $chatCallback[1][2], 2);
|
||||
$password = '';
|
||||
$successMessage = 'Password removed!';
|
||||
if (isset($messageParts[1])) {
|
||||
$password = $messageParts[1];
|
||||
$successMessage = "Password changed to: '{$password}'!";
|
||||
}
|
||||
$this->maniaControl->getClient()->setServerPassword($password);
|
||||
$this->maniaControl->getChat()->sendSuccess($successMessage, $player);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle //setspecpwd command
|
||||
*
|
||||
* @param array $chatCallback
|
||||
* @param Player $player
|
||||
*/
|
||||
public function commandSetSpecPwd(array $chatCallback, Player $player) {
|
||||
if (!$this->maniaControl->getAuthenticationManager()->checkPermission($player, self::SETTING_PERMISSION_CHANGE_SERVERSETTINGS)
|
||||
) {
|
||||
$this->maniaControl->getAuthenticationManager()->sendNotAllowed($player);
|
||||
return;
|
||||
}
|
||||
$messageParts = explode(' ', $chatCallback[1][2], 2);
|
||||
$password = '';
|
||||
$successMessage = 'Spectator password removed!';
|
||||
if (isset($messageParts[1])) {
|
||||
$password = $messageParts[1];
|
||||
$successMessage = "Spectator password changed to: '{$password}'!";
|
||||
}
|
||||
$this->maniaControl->getClient()->setServerPasswordForSpectator($password);
|
||||
$this->maniaControl->getChat()->sendSuccess($successMessage, $player);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle //setmaxplayers command
|
||||
*
|
||||
* @param array $chatCallback
|
||||
* @param Player $player
|
||||
*/
|
||||
public function commandSetMaxPlayers(array $chatCallback, Player $player) {
|
||||
if (!$this->maniaControl->getAuthenticationManager()->checkPermission($player, self::SETTING_PERMISSION_CHANGE_SERVERSETTINGS)
|
||||
) {
|
||||
$this->maniaControl->getAuthenticationManager()->sendNotAllowed($player);
|
||||
return;
|
||||
}
|
||||
$messageParts = explode(' ', $chatCallback[1][2], 2);
|
||||
if (!isset($messageParts[1])) {
|
||||
$this->maniaControl->getChat()->sendUsageInfo('Usage example: //setmaxplayers 16', $player);
|
||||
return;
|
||||
}
|
||||
$amount = $messageParts[1];
|
||||
if (!is_numeric($amount)) {
|
||||
$this->maniaControl->getChat()->sendUsageInfo('Usage example: //setmaxplayers 16', $player);
|
||||
return;
|
||||
}
|
||||
$amount = (int)$amount;
|
||||
if ($amount < 0) {
|
||||
$amount = 0;
|
||||
}
|
||||
|
||||
$this->maniaControl->getClient()->setMaxPlayers($amount);
|
||||
$this->maniaControl->getChat()->sendSuccess("Changed max players to: {$amount}", $player);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle //setmaxspectators command
|
||||
*
|
||||
* @param array $chatCallback
|
||||
* @param Player $player
|
||||
*/
|
||||
public function commandSetMaxSpectators(array $chatCallback, Player $player) {
|
||||
if (!$this->maniaControl->getAuthenticationManager()->checkPermission($player, self::SETTING_PERMISSION_CHANGE_SERVERSETTINGS)
|
||||
) {
|
||||
$this->maniaControl->getAuthenticationManager()->sendNotAllowed($player);
|
||||
return;
|
||||
}
|
||||
$messageParts = explode(' ', $chatCallback[1][2], 2);
|
||||
if (!isset($messageParts[1])) {
|
||||
$this->maniaControl->getChat()->sendUsageInfo('Usage example: //setmaxspectators 16', $player);
|
||||
return;
|
||||
}
|
||||
$amount = $messageParts[1];
|
||||
if (!is_numeric($amount)) {
|
||||
$this->maniaControl->getChat()->sendUsageInfo('Usage example: //setmaxspectators 16', $player);
|
||||
return;
|
||||
}
|
||||
$amount = (int)$amount;
|
||||
if ($amount < 0) {
|
||||
$amount = 0;
|
||||
}
|
||||
|
||||
$this->maniaControl->getClient()->setMaxSpectators($amount);
|
||||
$this->maniaControl->getChat()->sendSuccess("Changed max spectators to: {$amount}", $player);
|
||||
}
|
||||
}
|
89
core/Server/Config.php
Normal file
89
core/Server/Config.php
Normal file
@ -0,0 +1,89 @@
|
||||
<?php
|
||||
|
||||
namespace ManiaControl\Server;
|
||||
|
||||
/**
|
||||
* Model Class holding the Server Config
|
||||
*
|
||||
* @author ManiaControl Team <mail@maniacontrol.com>
|
||||
* @copyright 2014 ManiaControl Team
|
||||
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
|
||||
*/
|
||||
class Config {
|
||||
/*
|
||||
* Public properties
|
||||
*/
|
||||
public $id = null;
|
||||
public $host = null;
|
||||
public $port = null;
|
||||
public $user = null;
|
||||
public $pass = null;
|
||||
|
||||
/**
|
||||
* Create a new server config instance
|
||||
*
|
||||
* @param mixed $id
|
||||
* @param mixed $host
|
||||
* @param mixed $port
|
||||
* @param mixed $user
|
||||
* @param mixed $pass
|
||||
*/
|
||||
public function __construct($id = null, $host = null, $port = null, $user = null, $pass = null) {
|
||||
$this->id = $this->extractConfigData($id);
|
||||
$this->host = $this->extractConfigData($host);
|
||||
$this->port = $this->extractConfigData($port);
|
||||
$this->user = $this->extractConfigData($user);
|
||||
$this->pass = $this->extractConfigData($pass);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract the actual Data from the given Config Param
|
||||
*
|
||||
* @param mixed $configParam
|
||||
* @return string
|
||||
*/
|
||||
private function extractConfigData($configParam) {
|
||||
if (is_array($configParam)) {
|
||||
return (string)reset($configParam);
|
||||
}
|
||||
return (string)$configParam;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the Config Data
|
||||
*
|
||||
* @param string $message
|
||||
* @return bool
|
||||
*/
|
||||
public function validate(&$message = null) {
|
||||
// Host
|
||||
if (!$this->host) {
|
||||
$message = 'Missing Host!';
|
||||
return false;
|
||||
}
|
||||
|
||||
// Port
|
||||
if (!$this->port || $this->port === 'port') {
|
||||
$message = 'Missing Port!';
|
||||
return false;
|
||||
}
|
||||
|
||||
// User
|
||||
if (!$this->user) {
|
||||
$message = 'Missing User!';
|
||||
return false;
|
||||
}
|
||||
if (!in_array($this->user, array('SuperAdmin', 'Admin', 'User'))) {
|
||||
$message = 'Invalid User!';
|
||||
return false;
|
||||
}
|
||||
|
||||
// Pass
|
||||
if (!$this->pass) {
|
||||
$message = 'Missing Pass!';
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
104
core/Server/Directory.php
Normal file
104
core/Server/Directory.php
Normal file
@ -0,0 +1,104 @@
|
||||
<?php
|
||||
|
||||
namespace ManiaControl\Server;
|
||||
|
||||
use ManiaControl\Callbacks\CallbackListener;
|
||||
use ManiaControl\Callbacks\CallbackManager;
|
||||
use ManiaControl\Files\FileUtil;
|
||||
use ManiaControl\ManiaControl;
|
||||
|
||||
/**
|
||||
* Class offering Operations for the Server Directory
|
||||
*
|
||||
* @author ManiaControl Team <mail@maniacontrol.com>
|
||||
* @copyright 2014 ManiaControl Team
|
||||
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
|
||||
*/
|
||||
class Directory implements CallbackListener {
|
||||
/*
|
||||
* Private properties
|
||||
*/
|
||||
/** @var ManiaControl $maniaControl */
|
||||
private $maniaControl = null;
|
||||
|
||||
/**
|
||||
* Construct new server directory instance
|
||||
*
|
||||
* @param ManiaControl $maniaControl
|
||||
*/
|
||||
public function __construct(ManiaControl $maniaControl) {
|
||||
$this->maniaControl = $maniaControl;
|
||||
|
||||
// Callbacks
|
||||
$this->maniaControl->getCallbackManager()->registerCallbackListener(CallbackManager::CB_MP_SERVERSTOP, $this, 'handleServerStopCallback');
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the Maps Folder Path
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getMapsFolder() {
|
||||
return $this->maniaControl->getClient()->getMapsDirectory();
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the Skins Folder Path
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getSkinsFolder() {
|
||||
return $this->maniaControl->getClient()->getSkinsDirectory();
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle Server Stop Callback
|
||||
*/
|
||||
public function handleServerStopCallback() {
|
||||
$this->cleanLogsFolder();
|
||||
$this->cleanCacheFolder();
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean the server logs folder
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private function cleanLogsFolder() {
|
||||
return FileUtil::cleanDirectory($this->getLogsFolder());
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the Logs Folder Path
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getLogsFolder() {
|
||||
return $this->getGameDataFolder() . '..' . DIRECTORY_SEPARATOR . 'Logs' . DIRECTORY_SEPARATOR;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the Game Data Folder Path
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getGameDataFolder() {
|
||||
return $this->maniaControl->getClient()->gameDataDirectory();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
private function cleanCacheFolder() {
|
||||
return FileUtil::cleanDirectory($this->getCacheFolder(), 50);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the Cache Folder Path
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getCacheFolder() {
|
||||
return $this->getGameDataFolder() . '..' . DIRECTORY_SEPARATOR . 'CommonData' . DIRECTORY_SEPARATOR . 'Cache' . DIRECTORY_SEPARATOR;
|
||||
}
|
||||
}
|
138
core/Server/RankingManager.php
Normal file
138
core/Server/RankingManager.php
Normal file
@ -0,0 +1,138 @@
|
||||
<?php
|
||||
|
||||
namespace ManiaControl\Server;
|
||||
|
||||
use ManiaControl\Callbacks\CallbackListener;
|
||||
use ManiaControl\Callbacks\CallbackManager;
|
||||
use ManiaControl\Callbacks\Callbacks;
|
||||
use ManiaControl\ManiaControl;
|
||||
use ManiaControl\Maps\Map;
|
||||
use Maniaplanet\DedicatedServer\Xmlrpc\GameModeException;
|
||||
|
||||
/**
|
||||
* Class managing Rankings
|
||||
*
|
||||
* @author ManiaControl Team <mail@maniacontrol.com>
|
||||
* @copyright 2014 ManiaControl Team
|
||||
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
|
||||
*/
|
||||
class RankingManager implements CallbackListener {
|
||||
/*
|
||||
* Private properties
|
||||
*/
|
||||
private $rankings = array();
|
||||
|
||||
/**
|
||||
* Construct a new ranking manager instance
|
||||
*
|
||||
* @param ManiaControl $maniaControl
|
||||
*/
|
||||
public function __construct(ManiaControl $maniaControl) {
|
||||
$this->maniaControl = $maniaControl;
|
||||
|
||||
// Callbacks
|
||||
$this->maniaControl->getCallbackManager()->registerCallbackListener(CallbackManager::CB_MP_MODESCRIPTCALLBACK, $this, 'handleCallbacks');
|
||||
$this->maniaControl->getCallbackManager()->registerCallbackListener(CallbackManager::CB_MP_MODESCRIPTCALLBACKARRAY, $this, 'handleCallbacks');
|
||||
$this->maniaControl->getCallbackManager()->registerCallbackListener(Callbacks::ONINIT, $this, 'onInit');
|
||||
$this->maniaControl->getCallbackManager()->registerCallbackListener(Callbacks::BEGINMAP, $this, 'handleBeginMap');
|
||||
//TODO won message at end of the map (disable as setting) (and public announce only all %50 (setting) players)
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the Rankings (never call this Method)
|
||||
*/
|
||||
public function onInit() {
|
||||
try {
|
||||
$this->maniaControl->getClient()->triggerModeScriptEvent('LibXmlRpc_GetRankings', '');
|
||||
} catch (GameModeException $e) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle stats on callbacks (never call this Method)
|
||||
*
|
||||
* @param array $callback
|
||||
*/
|
||||
public function handleCallbacks(array $callback) {
|
||||
$callbackName = $callback[1][0];
|
||||
|
||||
//TODO not tested in TrackMania
|
||||
switch ($callbackName) {
|
||||
case 'updateRankings':
|
||||
$this->updateRankings($callback[1][1][0]);
|
||||
break;
|
||||
case 'endRound':
|
||||
case 'beginRound':
|
||||
case 'endMap':
|
||||
case 'endMap1':
|
||||
$this->updateRankings($callback[1]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear the rankings on the Begin of a Map
|
||||
*
|
||||
* @param Map $map
|
||||
*/
|
||||
public function handleBeginMap(Map $map) {
|
||||
$this->rankings = array();
|
||||
}
|
||||
|
||||
/**
|
||||
* Update Game Rankings (never call this Method)
|
||||
*
|
||||
* @param string $data
|
||||
*/
|
||||
public function updateRankings($data) {
|
||||
if (!is_string($data)) {
|
||||
return;
|
||||
}
|
||||
|
||||
//TODO in legacy mode, no data is in parameter -> fetch via method getCurrentRanking
|
||||
|
||||
$scores = explode(';', $data);
|
||||
foreach ($scores as $player) {
|
||||
if (strpos($player, ':') !== false) {
|
||||
$tmp = explode(':', $player);
|
||||
$this->rankings[$tmp[0]] = $tmp[1];
|
||||
}
|
||||
}
|
||||
array_multisort($this->rankings, SORT_DESC, SORT_NUMERIC);
|
||||
|
||||
//TODO if Local Records activated-> sort asc
|
||||
$this->maniaControl->getCallbackManager()->triggerCallback(Callbacks::RANKINGSUPDATED, $this->getRankings());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Rankings
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getRankings() {
|
||||
return $this->rankings;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the Current Leading Players (as Login Array)
|
||||
*
|
||||
* @return array|null
|
||||
*/
|
||||
public function getLeaders() {
|
||||
$leaders = array();
|
||||
$prev = -1;
|
||||
foreach ($this->rankings as $score) {
|
||||
if ($prev !== -1 && $prev < $score) {
|
||||
return $leaders;
|
||||
}
|
||||
// FIXME: $leader doesn't exist
|
||||
array_push($leaders, $leader);
|
||||
$prev = $score;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public function getPlayerRanking() {
|
||||
//TODO complete this
|
||||
}
|
||||
}
|
68
core/Server/ScriptManager.php
Normal file
68
core/Server/ScriptManager.php
Normal file
@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
namespace ManiaControl\Server;
|
||||
|
||||
use ManiaControl\Logger;
|
||||
use ManiaControl\ManiaControl;
|
||||
|
||||
/**
|
||||
* Manager for Game Mode Script related Stuff
|
||||
*
|
||||
* @author ManiaControl Team <mail@maniacontrol.com>
|
||||
* @copyright 2014 ManiaControl Team
|
||||
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
|
||||
*/
|
||||
class ScriptManager {
|
||||
/*
|
||||
* Private properties
|
||||
*/
|
||||
/** @var ManiaControl $maniaControl */
|
||||
private $maniaControl = null;
|
||||
private $isScriptMode = null;
|
||||
|
||||
/**
|
||||
* Construct a new script manager instance
|
||||
*
|
||||
* @param ManiaControl $maniaControl
|
||||
*/
|
||||
public function __construct(ManiaControl $maniaControl) {
|
||||
$this->maniaControl = $maniaControl;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable script callbacks
|
||||
*
|
||||
* @param bool $enable
|
||||
* @return bool
|
||||
*/
|
||||
public function enableScriptCallbacks($enable = true) {
|
||||
if (!$this->isScriptMode()) {
|
||||
return false;
|
||||
}
|
||||
$scriptSettings = $this->maniaControl->getClient()->getModeScriptSettings();
|
||||
|
||||
if (!array_key_exists('S_UseScriptCallbacks', $scriptSettings)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$scriptSettings['S_UseScriptCallbacks'] = (bool)$enable;
|
||||
$actionName = ($enable ? 'en' : 'dis');
|
||||
|
||||
$this->maniaControl->getClient()->setModeScriptSettings($scriptSettings);
|
||||
Logger::logInfo("Script Callbacks successfully {$actionName}abled!");
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether the Server is running in Script Mode
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isScriptMode() {
|
||||
if (is_null($this->isScriptMode)) {
|
||||
$gameMode = $this->maniaControl->getClient()->getGameMode();
|
||||
$this->isScriptMode = ($gameMode === 0);
|
||||
}
|
||||
return $this->isScriptMode;
|
||||
}
|
||||
}
|
459
core/Server/Server.php
Normal file
459
core/Server/Server.php
Normal file
@ -0,0 +1,459 @@
|
||||
<?php
|
||||
|
||||
namespace ManiaControl\Server;
|
||||
|
||||
use ManiaControl\Callbacks\CallbackListener;
|
||||
use ManiaControl\Callbacks\Callbacks;
|
||||
use ManiaControl\Logger;
|
||||
use ManiaControl\ManiaControl;
|
||||
use ManiaControl\Players\Player;
|
||||
use ManiaControl\Utils\CommandLineHelper;
|
||||
use Maniaplanet\DedicatedServer\Xmlrpc\Exception;
|
||||
|
||||
/**
|
||||
* Class providing access to the connected ManiaPlanet Server
|
||||
*
|
||||
* @author ManiaControl Team <mail@maniacontrol.com>
|
||||
* @copyright 2014 ManiaControl Team
|
||||
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
|
||||
*/
|
||||
class Server implements CallbackListener {
|
||||
/*
|
||||
* Constants
|
||||
*/
|
||||
const TABLE_SERVERS = 'mc_servers';
|
||||
const CB_TEAM_MODE_CHANGED = 'Server.TeamModeChanged';
|
||||
|
||||
/*
|
||||
* Public properties
|
||||
*/
|
||||
/** @var Config $config */
|
||||
public $config = null;
|
||||
public $index = -1;
|
||||
public $ip = null;
|
||||
public $port = -1;
|
||||
public $p2pPort = -1;
|
||||
public $login = null;
|
||||
public $titleId = null;
|
||||
/** @var Directory $directory */
|
||||
/** @deprecated see getDirectory() */
|
||||
public $directory = null;
|
||||
/** @var Commands $commands */
|
||||
/** @deprecated see getCommands() */
|
||||
public $commands = null;
|
||||
/** @var UsageReporter $usageReporter */
|
||||
/** @deprecated see getUsageReporter() */
|
||||
public $usageReporter = null;
|
||||
/** @var RankingManager $rankingManager */
|
||||
/** @deprecated see getRankingManager() */
|
||||
public $rankingManager = null;
|
||||
/** @var ScriptManager $scriptManager */
|
||||
/** @deprecated see getScriptManager() */
|
||||
public $scriptManager = null;
|
||||
|
||||
/*
|
||||
* Private properties
|
||||
*/
|
||||
/** @var ManiaControl $maniaControl */
|
||||
private $maniaControl = null;
|
||||
private $teamMode = null;
|
||||
|
||||
/**
|
||||
* Construct a new Server
|
||||
*
|
||||
* @param ManiaControl $maniaControl
|
||||
*/
|
||||
public function __construct(ManiaControl $maniaControl) {
|
||||
$this->maniaControl = $maniaControl;
|
||||
$this->initTables();
|
||||
|
||||
$this->directory = new Directory($maniaControl);
|
||||
$this->commands = new Commands($maniaControl);
|
||||
$this->usageReporter = new UsageReporter($maniaControl);
|
||||
$this->rankingManager = new RankingManager($maniaControl);
|
||||
$this->scriptManager = new ScriptManager($maniaControl);
|
||||
|
||||
// Callbacks
|
||||
$this->maniaControl->getCallbackManager()->registerCallbackListener(Callbacks::ONINIT, $this, 'onInit');
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize necessary Database Tables
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private function initTables() {
|
||||
$mysqli = $this->maniaControl->getDatabase()->getMysqli();
|
||||
$query = "CREATE TABLE IF NOT EXISTS `" . self::TABLE_SERVERS . "` (
|
||||
`index` int(11) NOT NULL AUTO_INCREMENT,
|
||||
`login` varchar(100) NOT NULL,
|
||||
PRIMARY KEY (`index`),
|
||||
UNIQUE KEY `login` (`login`)
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Servers' AUTO_INCREMENT=1;";
|
||||
$statement = $mysqli->prepare($query);
|
||||
if ($mysqli->error) {
|
||||
trigger_error($mysqli->error, E_USER_ERROR);
|
||||
return false;
|
||||
}
|
||||
$statement->execute();
|
||||
if ($statement->error) {
|
||||
trigger_error($statement->error, E_USER_ERROR);
|
||||
return false;
|
||||
}
|
||||
$statement->close();
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the server config
|
||||
*
|
||||
* @return Config
|
||||
*/
|
||||
public function getConfig() {
|
||||
return $this->config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the server directory
|
||||
*
|
||||
* @return Directory
|
||||
*/
|
||||
public function getDirectory() {
|
||||
return $this->directory;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the server commands
|
||||
*
|
||||
* @return Commands
|
||||
*/
|
||||
public function getCommands() {
|
||||
return $this->commands;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the usage reporter
|
||||
*
|
||||
* @return UsageReporter
|
||||
*/
|
||||
public function getUsageReporter() {
|
||||
return $this->usageReporter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the ranking manager
|
||||
*
|
||||
* @return RankingManager
|
||||
*/
|
||||
public function getRankingManager() {
|
||||
return $this->rankingManager;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the script manager
|
||||
*
|
||||
* @return ScriptManager
|
||||
*/
|
||||
public function getScriptManager() {
|
||||
return $this->scriptManager;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load the server configuration from the config XML
|
||||
*
|
||||
* @return Config
|
||||
*/
|
||||
public function loadConfig() {
|
||||
// Server id parameter
|
||||
$serverId = CommandLineHelper::getParameter('-id');
|
||||
|
||||
// Server xml element with given id
|
||||
$serverElement = null;
|
||||
if ($serverId) {
|
||||
$serverElements = $this->maniaControl->getConfig()->xpath("server[@id='{$serverId}']");
|
||||
if (!$serverElements) {
|
||||
$this->maniaControl->quit("No Server configured with the ID '{$serverId}'!", true);
|
||||
}
|
||||
$serverElement = $serverElements[0];
|
||||
} else {
|
||||
$serverElements = $this->maniaControl->getConfig()->xpath('server');
|
||||
if (!$serverElements) {
|
||||
$this->maniaControl->quit('Invalid server configuration (No Server configured).', true);
|
||||
}
|
||||
$serverElement = $serverElements[0];
|
||||
}
|
||||
|
||||
// Get config elements
|
||||
$hostElements = $serverElement->xpath('host');
|
||||
$portElements = $serverElement->xpath('port');
|
||||
$userElements = $serverElement->xpath('user');
|
||||
if (!$userElements) {
|
||||
$userElements = $serverElement->xpath('login');
|
||||
}
|
||||
$passElements = $serverElement->xpath('pass');
|
||||
|
||||
// Create config object
|
||||
$config = new Config($serverId, $hostElements, $portElements, $userElements, $passElements);
|
||||
$message = null;
|
||||
if (!$config->validate($message)) {
|
||||
$this->maniaControl->quit("Your config file doesn't seem to be maintained properly. Please check the server configuration again! {$message}", true);
|
||||
}
|
||||
$this->config = $config;
|
||||
return $this->config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all Servers from the Database
|
||||
*
|
||||
* @return \stdClass[]
|
||||
*/
|
||||
public function getAllServers() {
|
||||
$mysqli = $this->maniaControl->getDatabase()->getMysqli();
|
||||
$query = "SELECT * FROM `" . self::TABLE_SERVERS . "`;";
|
||||
$result = $mysqli->query($query);
|
||||
if (!$result) {
|
||||
trigger_error($mysqli->error);
|
||||
return array();
|
||||
}
|
||||
|
||||
$servers = array();
|
||||
while ($row = $result->fetch_object()) {
|
||||
array_push($servers, $row);
|
||||
}
|
||||
$result->free();
|
||||
|
||||
return $servers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle OnInit Callback
|
||||
*/
|
||||
public function onInit() {
|
||||
$this->updateProperties();
|
||||
}
|
||||
|
||||
/**
|
||||
* Refetch the Server Properties
|
||||
*/
|
||||
private function updateProperties() {
|
||||
// System info
|
||||
$systemInfo = $this->maniaControl->getClient()->getSystemInfo();
|
||||
$this->ip = $systemInfo->publishedIp;
|
||||
$this->port = $systemInfo->port;
|
||||
$this->p2pPort = $systemInfo->p2PPort;
|
||||
$this->login = $systemInfo->serverLogin;
|
||||
$this->titleId = $systemInfo->titleId;
|
||||
|
||||
// Database index
|
||||
$mysqli = $this->maniaControl->getDatabase()->getMysqli();
|
||||
$query = "INSERT INTO `" . self::TABLE_SERVERS . "` (
|
||||
`login`
|
||||
) VALUES (
|
||||
?
|
||||
) ON DUPLICATE KEY UPDATE
|
||||
`index` = LAST_INSERT_ID(`index`);";
|
||||
$statement = $mysqli->prepare($query);
|
||||
if ($mysqli->error) {
|
||||
trigger_error($mysqli->error);
|
||||
return;
|
||||
}
|
||||
$statement->bind_param('s', $this->login);
|
||||
$statement->execute();
|
||||
if ($statement->error) {
|
||||
trigger_error($statement->error);
|
||||
$statement->close();
|
||||
return;
|
||||
}
|
||||
$this->index = $statement->insert_id;
|
||||
$statement->close();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Server Player Info
|
||||
*
|
||||
* @return \Maniaplanet\DedicatedServer\Structures\PlayerDetailedInfo
|
||||
*/
|
||||
public function getInfo() {
|
||||
return $this->maniaControl->getClient()->getDetailedPlayerInfo($this->login);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve Validation Replay for the given Player
|
||||
*
|
||||
* @param string $login
|
||||
* @return string
|
||||
*/
|
||||
public function getValidationReplay($login) {
|
||||
$login = Player::parseLogin($login);
|
||||
try {
|
||||
$replay = $this->maniaControl->getClient()->getValidationReplay($login);
|
||||
} catch (Exception $e) {
|
||||
// TODO temp added 19.04.2014
|
||||
$this->maniaControl->getErrorHandler()->triggerDebugNotice("Exception line 330 Server.php" . $e->getMessage());
|
||||
trigger_error("Couldn't get validation replay of '{$login}'. " . $e->getMessage());
|
||||
return null;
|
||||
}
|
||||
return $replay;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve Ghost Replay for the given Player
|
||||
*
|
||||
* @param string $login
|
||||
* @return string
|
||||
*/
|
||||
public function getGhostReplay($login) {
|
||||
$dataDir = $this->getDirectory()->getGameDataFolder();
|
||||
if (!$this->checkAccess($dataDir)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Build file name
|
||||
$login = Player::parseLogin($login);
|
||||
$map = $this->maniaControl->getMapManager()->getCurrentMap();
|
||||
$gameMode = $this->getGameMode();
|
||||
$time = time();
|
||||
$fileName = "GhostReplays/Ghost.{$login}.{$gameMode}.{$time}.{$map->uid}.Replay.Gbx";
|
||||
|
||||
// Save ghost replay
|
||||
try {
|
||||
$this->maniaControl->getClient()->saveBestGhostsReplay($login, $fileName);
|
||||
} catch (Exception $e) {
|
||||
// TODO temp added 19.04.2014
|
||||
$this->maniaControl->getErrorHandler()->triggerDebugNotice("Exception line 360 Server.php" . $e->getMessage());
|
||||
|
||||
trigger_error("Couldn't save ghost replay. " . $e->getMessage());
|
||||
return null;
|
||||
}
|
||||
|
||||
// Load replay file
|
||||
$ghostReplay = file_get_contents("{$dataDir}Replays/{$fileName}");
|
||||
if (!$ghostReplay) {
|
||||
trigger_error("Couldn't retrieve saved ghost replay.");
|
||||
return null;
|
||||
}
|
||||
return $ghostReplay;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if ManiaControl has Access to the given Directory
|
||||
*
|
||||
* @param string $directory
|
||||
* @return bool
|
||||
*/
|
||||
public function checkAccess($directory) {
|
||||
return (is_dir($directory) && is_writable($directory));
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the current Game Mode
|
||||
*
|
||||
* @param bool $stringValue
|
||||
* @param int $parseValue
|
||||
* @return int | string
|
||||
*/
|
||||
public function getGameMode($stringValue = false, $parseValue = null) {
|
||||
if (is_int($parseValue)) {
|
||||
$gameMode = $parseValue;
|
||||
} else {
|
||||
$gameMode = $this->maniaControl->getClient()->getGameMode();
|
||||
}
|
||||
if ($stringValue) {
|
||||
switch ($gameMode) {
|
||||
case 0:
|
||||
return 'Script';
|
||||
case 1:
|
||||
return 'Rounds';
|
||||
case 2:
|
||||
return 'TimeAttack';
|
||||
case 3:
|
||||
return 'Team';
|
||||
case 4:
|
||||
return 'Laps';
|
||||
case 5:
|
||||
return 'Cup';
|
||||
case 6:
|
||||
return 'Stunts';
|
||||
default:
|
||||
return 'Unknown';
|
||||
}
|
||||
}
|
||||
return $gameMode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for the Server to have the given Status
|
||||
*
|
||||
* @param int $statusCode
|
||||
* @return bool
|
||||
*/
|
||||
public function waitForStatus($statusCode = 4) {
|
||||
$response = $this->maniaControl->getClient()->getStatus();
|
||||
// Check if server has the given status
|
||||
if ($response->code === 4) {
|
||||
return true;
|
||||
}
|
||||
// Server not yet in given status - Wait for it...
|
||||
$waitBegin = time();
|
||||
$maxWaitTime = 50;
|
||||
$lastStatus = $response->name;
|
||||
Logger::log("Waiting for server to reach status {$statusCode}...");
|
||||
Logger::log("Current Status: {$lastStatus}");
|
||||
while ($response->code !== 4) {
|
||||
sleep(1);
|
||||
$response = $this->maniaControl->getClient()->getStatus();
|
||||
if ($lastStatus !== $response->name) {
|
||||
Logger::log("New Status: {$response->name}");
|
||||
$lastStatus = $response->name;
|
||||
}
|
||||
if (time() - $maxWaitTime > $waitBegin) {
|
||||
// It took too long to reach the status
|
||||
Logger::logError("Server couldn't reach status {$statusCode} after {$maxWaitTime} seconds! ");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set whether the Server Runs a Team-Based Mode or not
|
||||
*
|
||||
* @param bool $teamMode
|
||||
*/
|
||||
public function setTeamMode($teamMode = true) {
|
||||
$oldStatus = $this->teamMode;
|
||||
$this->teamMode = (bool)$teamMode;
|
||||
|
||||
// Trigger callback
|
||||
if ($oldStatus !== $this->teamMode | $oldStatus === null) {
|
||||
$this->maniaControl->getCallbackManager()->triggerCallback(self::CB_TEAM_MODE_CHANGED, $teamMode);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the Server Runs a Team-Based Mode
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isTeamMode() {
|
||||
return $this->teamMode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the join link
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getJoinLink() {
|
||||
return 'maniaplanet://#join=' . $this->login . '@' . $this->titleId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the Servers is empty
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isEmpty() {
|
||||
return ($this->maniaControl->getPlayerManager()->getPlayerCount(false) === 0);
|
||||
}
|
||||
}
|
379
core/Server/ServerOptionsMenu.php
Normal file
379
core/Server/ServerOptionsMenu.php
Normal file
@ -0,0 +1,379 @@
|
||||
<?php
|
||||
|
||||
namespace ManiaControl\Server;
|
||||
|
||||
use FML\Components\CheckBox;
|
||||
use FML\Controls\Entry;
|
||||
use FML\Controls\Frame;
|
||||
use FML\Controls\Labels\Label_Text;
|
||||
use FML\Controls\Quad;
|
||||
use FML\Controls\Quads\Quad_Icons64x64_1;
|
||||
use FML\Script\Features\Paging;
|
||||
use FML\Script\Script;
|
||||
use ManiaControl\Admin\AuthenticationManager;
|
||||
use ManiaControl\Callbacks\CallbackListener;
|
||||
use ManiaControl\Callbacks\Callbacks;
|
||||
use ManiaControl\Callbacks\TimerListener;
|
||||
use ManiaControl\Configurator\ConfiguratorMenu;
|
||||
use ManiaControl\Logger;
|
||||
use ManiaControl\ManiaControl;
|
||||
use ManiaControl\Players\Player;
|
||||
use Maniaplanet\DedicatedServer\Structures\ServerOptions;
|
||||
use Maniaplanet\DedicatedServer\Xmlrpc\ServerOptionsException;
|
||||
|
||||
/**
|
||||
* Class offering a Configurator Menu for Server Options
|
||||
*
|
||||
* @author ManiaControl Team <mail@maniacontrol.com>
|
||||
* @copyright 2014 ManiaControl Team
|
||||
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
|
||||
*/
|
||||
class ServerOptionsMenu implements CallbackListener, ConfiguratorMenu, TimerListener {
|
||||
/*
|
||||
* Constants
|
||||
*/
|
||||
const CB_SERVER_OPTION_CHANGED = 'ServerOptionsMenu.OptionChanged';
|
||||
const CB_SERVER_OPTIONS_CHANGED = 'ServerOptionsMenu.OptionsChanged';
|
||||
const SETTING_PERMISSION_CHANGE_SERVER_OPTIONS = 'Change Server Options';
|
||||
const TABLE_SERVER_OPTIONS = 'mc_server_options';
|
||||
const ACTION_PREFIX_OPTION = 'ServerOptionsMenu.';
|
||||
|
||||
/** @deprecated */
|
||||
const CB_SERVERSETTING_CHANGED = self::CB_SERVER_OPTION_CHANGED;
|
||||
/** @deprecated */
|
||||
const CB_SERVERSETTINGS_CHANGED = self::CB_SERVER_OPTIONS_CHANGED;
|
||||
|
||||
/*
|
||||
* Private properties
|
||||
*/
|
||||
/** @var ManiaControl $maniaControl */
|
||||
private $maniaControl = null;
|
||||
|
||||
/**
|
||||
* Construct a new server options menu instance
|
||||
*
|
||||
* @param ManiaControl $maniaControl
|
||||
*/
|
||||
public function __construct(ManiaControl $maniaControl) {
|
||||
$this->maniaControl = $maniaControl;
|
||||
$this->initTables();
|
||||
|
||||
// Callbacks
|
||||
$this->maniaControl->getCallbackManager()->registerCallbackListener(Callbacks::ONINIT, $this, 'onInit');
|
||||
$this->maniaControl->getTimerManager()->registerTimerListening($this, 'saveCurrentServerOptions', 6 * 3600 * 1000);
|
||||
|
||||
// Permissions
|
||||
$this->maniaControl->getAuthenticationManager()->definePermissionLevel(self::SETTING_PERMISSION_CHANGE_SERVER_OPTIONS, AuthenticationManager::AUTH_LEVEL_SUPERADMIN);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize necessary database tables
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private function initTables() {
|
||||
$mysqli = $this->maniaControl->getDatabase()->getMysqli();
|
||||
$query = "CREATE TABLE IF NOT EXISTS `" . self::TABLE_SERVER_OPTIONS . "` (
|
||||
`index` int(11) NOT NULL AUTO_INCREMENT,
|
||||
`serverIndex` int(11) NOT NULL,
|
||||
`optionName` varchar(100) NOT NULL,
|
||||
`optionValue` varchar(500) NOT NULL,
|
||||
`changed` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (`index`),
|
||||
UNIQUE KEY `option` (`serverIndex`, `optionName`)
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Server Options' AUTO_INCREMENT=1;";
|
||||
$statement = $mysqli->prepare($query);
|
||||
if ($mysqli->error) {
|
||||
trigger_error($mysqli->error, E_USER_ERROR);
|
||||
return false;
|
||||
}
|
||||
$statement->execute();
|
||||
if ($statement->error) {
|
||||
trigger_error($statement->error, E_USER_ERROR);
|
||||
return false;
|
||||
}
|
||||
$statement->close();
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @see \ManiaControl\Configurators\ConfiguratorMenu::getTitle()
|
||||
*/
|
||||
public static function getTitle() {
|
||||
return 'Server Options';
|
||||
}
|
||||
|
||||
/**
|
||||
* Save the current server options in case they have been changed by an external tool
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function saveCurrentServerOptions() {
|
||||
$serverOptions = $this->maniaControl->getClient()->getServerOptions();
|
||||
return $this->saveServerOptions($serverOptions);
|
||||
}
|
||||
|
||||
/**
|
||||
* Save the given server options in the database
|
||||
*
|
||||
* @param ServerOptions $serverOptions
|
||||
* @param bool $triggerCallbacks
|
||||
* @return bool
|
||||
*/
|
||||
private function saveServerOptions(ServerOptions $serverOptions, $triggerCallbacks = false) {
|
||||
$mysqli = $this->maniaControl->getDatabase()->getMysqli();
|
||||
$query = "INSERT INTO `" . self::TABLE_SERVER_OPTIONS . "` (
|
||||
`serverIndex`,
|
||||
`optionName`,
|
||||
`optionValue`
|
||||
) VALUES (
|
||||
?, ?, ?
|
||||
) ON DUPLICATE KEY UPDATE
|
||||
`optionValue` = VALUES(`optionValue`);";
|
||||
$statement = $mysqli->prepare($query);
|
||||
if ($mysqli->error) {
|
||||
trigger_error($mysqli->error);
|
||||
return false;
|
||||
}
|
||||
|
||||
$optionName = null;
|
||||
$optionValue = null;
|
||||
$statement->bind_param('iss', $this->maniaControl->getServer()->index, $optionName, $optionValue);
|
||||
|
||||
$serverOptionsArray = $serverOptions->toArray();
|
||||
foreach ($serverOptionsArray as $optionName => $optionValue) {
|
||||
if ($optionValue === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$statement->execute();
|
||||
if ($statement->error) {
|
||||
trigger_error($statement->error);
|
||||
$statement->close();
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($triggerCallbacks) {
|
||||
$this->maniaControl->getCallbackManager()->triggerCallback(self::CB_SERVER_OPTION_CHANGED, array(self::CB_SERVER_OPTION_CHANGED, $optionName, $optionValue));
|
||||
}
|
||||
}
|
||||
|
||||
$statement->close();
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle OnInit callback
|
||||
*/
|
||||
public function onInit() {
|
||||
$this->loadOptionsFromDatabase();
|
||||
}
|
||||
|
||||
/**
|
||||
* Load options from database
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function loadOptionsFromDatabase() {
|
||||
$mysqli = $this->maniaControl->getDatabase()->getMysqli();
|
||||
$serverIndex = $this->maniaControl->getServer()->index;
|
||||
$query = "SELECT * FROM `" . self::TABLE_SERVER_OPTIONS . "`
|
||||
WHERE `serverIndex` = {$serverIndex};";
|
||||
$result = $mysqli->query($query);
|
||||
if ($mysqli->error) {
|
||||
trigger_error($mysqli->error);
|
||||
return false;
|
||||
}
|
||||
|
||||
$oldServerOptions = $this->maniaControl->getClient()->getServerOptions();
|
||||
$newServerOptions = new ServerOptions();
|
||||
|
||||
while ($row = $result->fetch_object()) {
|
||||
$optionName = lcfirst($row->optionName);
|
||||
if (!property_exists($oldServerOptions, $optionName)) {
|
||||
continue;
|
||||
}
|
||||
$newServerOptions->$optionName = $row->optionValue;
|
||||
settype($newServerOptions->$optionName, gettype($oldServerOptions->$optionName));
|
||||
}
|
||||
$result->free();
|
||||
|
||||
$this->fillUpMandatoryOptions($newServerOptions, $oldServerOptions);
|
||||
|
||||
$loaded = false;
|
||||
try {
|
||||
$loaded = $this->maniaControl->getClient()->setServerOptions($newServerOptions);
|
||||
} catch (ServerOptionsException $exception) {
|
||||
$this->maniaControl->getChat()->sendExceptionToAdmins($exception);
|
||||
}
|
||||
|
||||
if ($loaded) {
|
||||
Logger::logInfo('Server Options successfully loaded!');
|
||||
} else {
|
||||
Logger::logError('Error loading Server Options!');
|
||||
}
|
||||
|
||||
return $loaded;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fill up the new server options object with the necessary options based on the old options object
|
||||
*
|
||||
* @param ServerOptions $newServerOptions
|
||||
* @param ServerOptions $oldServerOptions
|
||||
* @return ServerOptions
|
||||
*/
|
||||
private function fillUpMandatoryOptions(ServerOptions &$newServerOptions, ServerOptions $oldServerOptions) {
|
||||
$mandatoryOptions = array('name', 'comment', 'password', 'passwordForSpectator', 'nextCallVoteTimeOut', 'callVoteRatio');
|
||||
foreach ($mandatoryOptions as $optionName) {
|
||||
if (!isset($newServerOptions->$optionName) && isset($oldServerOptions->$optionName)) {
|
||||
$newServerOptions->$optionName = $oldServerOptions->$optionName;
|
||||
}
|
||||
}
|
||||
return $newServerOptions;
|
||||
}
|
||||
|
||||
/**
|
||||
* @see \ManiaControl\Configurators\ConfiguratorMenu::getMenu()
|
||||
*/
|
||||
public function getMenu($width, $height, Script $script, Player $player) {
|
||||
$paging = new Paging();
|
||||
$script->addFeature($paging);
|
||||
$frame = new Frame();
|
||||
|
||||
$serverOptions = $this->maniaControl->getClient()->getServerOptions();
|
||||
$serverOptionsArray = $serverOptions->toArray();
|
||||
|
||||
// Config
|
||||
$pagerSize = 9.;
|
||||
$optionHeight = 5.;
|
||||
$labelTextSize = 2;
|
||||
|
||||
// Pagers
|
||||
$pagerPrev = new Quad_Icons64x64_1();
|
||||
$frame->add($pagerPrev);
|
||||
$pagerPrev->setPosition($width * 0.39, $height * -0.44, 2)->setSize($pagerSize, $pagerSize)->setSubStyle($pagerPrev::SUBSTYLE_ArrowPrev);
|
||||
|
||||
$pagerNext = new Quad_Icons64x64_1();
|
||||
$frame->add($pagerNext);
|
||||
$pagerNext->setPosition($width * 0.45, $height * -0.44, 2)->setSize($pagerSize, $pagerSize)->setSubStyle($pagerNext::SUBSTYLE_ArrowNext);
|
||||
|
||||
$pageCountLabel = new Label_Text();
|
||||
$frame->add($pageCountLabel);
|
||||
$pageCountLabel->setHAlign($pageCountLabel::RIGHT)->setPosition($width * 0.35, $height * -0.44, 1)->setStyle($pageCountLabel::STYLE_TextTitle1)->setTextSize(2);
|
||||
|
||||
$paging->addButton($pagerNext)->addButton($pagerPrev)->setLabel($pageCountLabel);
|
||||
|
||||
// Pages
|
||||
$posY = 0.;
|
||||
$index = 0;
|
||||
$pageFrame = null;
|
||||
|
||||
foreach ($serverOptionsArray as $name => $value) {
|
||||
// Continue on CurrentMaxPlayers...
|
||||
$pos = strpos($name, 'Current'); // TODO: display 'Current...' somewhere
|
||||
if ($pos !== false) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($index % 13 === 0) {
|
||||
$pageFrame = new Frame();
|
||||
$frame->add($pageFrame);
|
||||
$posY = $height * 0.41;
|
||||
$paging->addPage($pageFrame);
|
||||
}
|
||||
|
||||
$optionsFrame = new Frame();
|
||||
$pageFrame->add($optionsFrame);
|
||||
$optionsFrame->setY($posY);
|
||||
|
||||
$nameLabel = new Label_Text();
|
||||
$optionsFrame->add($nameLabel);
|
||||
$nameLabel->setHAlign($nameLabel::LEFT)->setX($width * -0.46)->setSize($width * 0.4, $optionHeight)->setStyle($nameLabel::STYLE_TextCardSmall)->setTextSize($labelTextSize)->setText($name)->setTextColor('fff');
|
||||
|
||||
if (is_bool($value)) {
|
||||
// Boolean checkbox
|
||||
$quad = new Quad();
|
||||
$quad->setPosition($width * 0.23, 0, -0.01)->setSize(4, 4);
|
||||
$checkBox = new CheckBox(self::ACTION_PREFIX_OPTION . $name, $value, $quad);
|
||||
$optionsFrame->add($checkBox);
|
||||
} else {
|
||||
// Other
|
||||
$entry = new Entry();
|
||||
$optionsFrame->add($entry);
|
||||
$entry->setStyle(Label_Text::STYLE_TextValueSmall)->setX($width * 0.23)->setTextSize(1)->setSize($width * 0.48, $optionHeight * 0.9)->setName(self::ACTION_PREFIX_OPTION . $name)->setDefault($value);
|
||||
|
||||
if ($name === 'Comment') {
|
||||
$entry->setSize($width * 0.48, $optionHeight * 3. + $optionHeight * 0.9)->setAutoNewLine(true);
|
||||
$optionsFrame->setY($posY - $optionHeight * 1.5);
|
||||
$posY -= $optionHeight * 3.;
|
||||
$index += 3;
|
||||
}
|
||||
}
|
||||
|
||||
$posY -= $optionHeight;
|
||||
$index++;
|
||||
}
|
||||
|
||||
return $frame;
|
||||
}
|
||||
|
||||
/**
|
||||
* @see \ManiaControl\Configurators\ConfiguratorMenu::saveConfigData()
|
||||
*/
|
||||
public function saveConfigData(array $configData, Player $player) {
|
||||
if (!$this->maniaControl->getAuthenticationManager()->checkPermission($player, self::SETTING_PERMISSION_CHANGE_SERVER_OPTIONS)
|
||||
) {
|
||||
$this->maniaControl->getAuthenticationManager()->sendNotAllowed($player);
|
||||
return;
|
||||
}
|
||||
if (!$configData[3] || strpos($configData[3][0]['Name'], self::ACTION_PREFIX_OPTION) !== 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
$prefixLength = strlen(self::ACTION_PREFIX_OPTION);
|
||||
|
||||
$oldServerOptions = $this->maniaControl->getClient()->getServerOptions();
|
||||
$newServerOptions = new ServerOptions();
|
||||
|
||||
foreach ($configData[3] as $option) {
|
||||
$optionName = lcfirst(substr($option['Name'], $prefixLength));
|
||||
$newServerOptions->$optionName = $option['Value'];
|
||||
settype($newServerOptions->$optionName, gettype($oldServerOptions->$optionName));
|
||||
}
|
||||
|
||||
$this->fillUpMandatoryOptions($newServerOptions, $oldServerOptions);
|
||||
|
||||
$success = $this->applyNewServerOptions($newServerOptions, $player);
|
||||
if ($success) {
|
||||
$this->maniaControl->getChat()->sendSuccess('Server Options saved!', $player);
|
||||
} else {
|
||||
$this->maniaControl->getChat()->sendError('Server Options saving failed!', $player);
|
||||
}
|
||||
|
||||
// Reopen the Menu
|
||||
$this->maniaControl->getConfigurator()->showMenu($player, $this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply the array of new Server Options
|
||||
*
|
||||
* @param ServerOptions $newServerOptions
|
||||
* @param Player $player
|
||||
* @return bool
|
||||
*/
|
||||
private function applyNewServerOptions(ServerOptions $newServerOptions, Player $player) {
|
||||
try {
|
||||
$this->maniaControl->getClient()->setServerOptions($newServerOptions);
|
||||
} catch (ServerOptionsException $exception) {
|
||||
$this->maniaControl->getChat()->sendException($exception, $player);
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->saveServerOptions($newServerOptions, true);
|
||||
|
||||
$this->maniaControl->getCallbackManager()->triggerCallback(self::CB_SERVER_OPTIONS_CHANGED, array(self::CB_SERVER_OPTIONS_CHANGED));
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
89
core/Server/UsageReporter.php
Normal file
89
core/Server/UsageReporter.php
Normal file
@ -0,0 +1,89 @@
|
||||
<?php
|
||||
|
||||
namespace ManiaControl\Server;
|
||||
|
||||
use ManiaControl\Callbacks\TimerListener;
|
||||
use ManiaControl\Logger;
|
||||
use ManiaControl\ManiaControl;
|
||||
use ManiaControl\Utils\Formatter;
|
||||
use Maniaplanet\DedicatedServer\Xmlrpc\GameModeException;
|
||||
|
||||
/**
|
||||
* Class reporting ManiaControl Usage for the Server
|
||||
*
|
||||
* @author ManiaControl Team <mail@maniacontrol.com>
|
||||
* @copyright 2014 ManiaControl Team
|
||||
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
|
||||
*/
|
||||
class UsageReporter implements TimerListener {
|
||||
/*
|
||||
* Constants
|
||||
*/
|
||||
const UPDATE_MINUTE_COUNT = 10;
|
||||
const SETTING_REPORT_USAGE = 'Report Usage to $lManiaControl.com$l';
|
||||
|
||||
/*
|
||||
* Private properties
|
||||
*/
|
||||
/** @var ManiaControl $maniaControl */
|
||||
private $maniaControl = null;
|
||||
|
||||
/**
|
||||
* Create a new Usage Reporter Instance
|
||||
*
|
||||
* @param ManiaControl $maniaControl
|
||||
*/
|
||||
public function __construct(ManiaControl $maniaControl) {
|
||||
$this->maniaControl = $maniaControl;
|
||||
|
||||
$this->maniaControl->getSettingManager()->initSetting($this, self::SETTING_REPORT_USAGE, true);
|
||||
|
||||
$this->maniaControl->getTimerManager()->registerTimerListening($this, 'reportUsage', 1000 * 60 * self::UPDATE_MINUTE_COUNT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Report Usage of ManiaControl on the current Server
|
||||
*/
|
||||
public function reportUsage() {
|
||||
if (DEV_MODE
|
||||
|| !$this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_REPORT_USAGE)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
$properties = array();
|
||||
$properties['ManiaControlVersion'] = ManiaControl::VERSION;
|
||||
$properties['OperatingSystem'] = php_uname();
|
||||
$properties['PHPVersion'] = phpversion();
|
||||
$properties['ServerLogin'] = $this->maniaControl->getServer()->login;
|
||||
$properties['TitleId'] = $this->maniaControl->getServer()->titleId;
|
||||
$properties['ServerName'] = Formatter::stripDirtyCodes($this->maniaControl->getClient()->getServerName());
|
||||
$properties['UpdateChannel'] = $this->maniaControl->getUpdateManager()->getCurrentUpdateChannelSetting();
|
||||
|
||||
$properties['PlayerCount'] = $this->maniaControl->getPlayerManager()->getPlayerCount();
|
||||
$properties['MemoryUsage'] = memory_get_usage();
|
||||
$properties['MemoryPeakUsage'] = memory_get_peak_usage();
|
||||
|
||||
$maxPlayers = $this->maniaControl->getClient()->getMaxPlayers();
|
||||
$properties['MaxPlayers'] = $maxPlayers['CurrentValue'];
|
||||
|
||||
try {
|
||||
$scriptName = $this->maniaControl->getClient()->getScriptName();
|
||||
$properties['ScriptName'] = $scriptName['CurrentValue'];
|
||||
} catch (GameModeException $e) {
|
||||
$properties['ScriptName'] = '';
|
||||
}
|
||||
|
||||
$properties['ActivePlugins'] = $this->maniaControl->getPluginManager()->getActivePluginsIds();
|
||||
|
||||
$usageReport = json_encode($properties);
|
||||
|
||||
$url = ManiaControl::URL_WEBSERVICE . 'usagereport';
|
||||
$this->maniaControl->getFileReader()->postData($url, function ($response, $error) {
|
||||
$response = json_decode($response);
|
||||
if ($error || !$response) {
|
||||
Logger::logError('Error while Sending data: ' . print_r($error, true));
|
||||
}
|
||||
}, $usageReport);
|
||||
}
|
||||
}
|
177
core/Server/VoteRatiosMenu.php
Normal file
177
core/Server/VoteRatiosMenu.php
Normal file
@ -0,0 +1,177 @@
|
||||
<?php
|
||||
|
||||
namespace ManiaControl\Server;
|
||||
|
||||
use FML\Controls\Entry;
|
||||
use FML\Controls\Frame;
|
||||
use FML\Controls\Labels\Label_Text;
|
||||
use FML\Script\Script;
|
||||
use ManiaControl\Admin\AuthenticationManager;
|
||||
use ManiaControl\Callbacks\CallbackListener;
|
||||
use ManiaControl\Callbacks\TimerListener;
|
||||
use ManiaControl\Configurator\ConfiguratorMenu;
|
||||
use ManiaControl\ManiaControl;
|
||||
use ManiaControl\Players\Player;
|
||||
use Maniaplanet\DedicatedServer\Structures\VoteRatio;
|
||||
|
||||
/**
|
||||
* Class offering a Configurator Menu for Vote Ratios
|
||||
*
|
||||
* @author ManiaControl Team <mail@maniacontrol.com>
|
||||
* @copyright 2014 ManiaControl Team
|
||||
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
|
||||
*/
|
||||
class VoteRatiosMenu implements CallbackListener, ConfiguratorMenu, TimerListener {
|
||||
/*
|
||||
* Constants
|
||||
*/
|
||||
const SETTING_PERMISSION_CHANGE_VOTE_RATIOS = 'Change Vote Ratios';
|
||||
const ACTION_PREFIX_VOTE_RATIO = 'VoteRatiosMenu.VoteRatio.';
|
||||
|
||||
/*
|
||||
* Private properties
|
||||
*/
|
||||
/** @var ManiaControl $maniaControl */
|
||||
private $maniaControl = null;
|
||||
|
||||
/**
|
||||
* Construct a new vote ratios menu instance
|
||||
*
|
||||
* @param ManiaControl $maniaControl
|
||||
*/
|
||||
public function __construct(ManiaControl $maniaControl) {
|
||||
$this->maniaControl = $maniaControl;
|
||||
|
||||
// Permissions
|
||||
$this->maniaControl->getAuthenticationManager()->definePermissionLevel(self::SETTING_PERMISSION_CHANGE_VOTE_RATIOS, AuthenticationManager::AUTH_LEVEL_ADMIN);
|
||||
}
|
||||
|
||||
/**
|
||||
* @see \ManiaControl\Configurators\ConfiguratorMenu::getTitle()
|
||||
*/
|
||||
public static function getTitle() {
|
||||
return 'Vote Ratios';
|
||||
}
|
||||
|
||||
/**
|
||||
* @see \ManiaControl\Configurators\ConfiguratorMenu::getMenu()
|
||||
*/
|
||||
public function getMenu($width, $height, Script $script, Player $player) {
|
||||
$frame = new Frame();
|
||||
$posY = $height * 0.41;
|
||||
$lineHeight = 5.;
|
||||
$index = 0;
|
||||
|
||||
$voteRatioCommands = $this->getVoteCommands();
|
||||
$voteRatios = $this->maniaControl->getClient()->getCallVoteRatios();
|
||||
foreach ($voteRatioCommands as $voteRatioCommand => $voteRatioDescription) {
|
||||
$voteRatioFrame = new Frame();
|
||||
$frame->add($voteRatioFrame);
|
||||
$voteRatioFrame->setY($posY);
|
||||
|
||||
$nameLabel = new Label_Text();
|
||||
$voteRatioFrame->add($nameLabel);
|
||||
$nameLabel->setHAlign($nameLabel::LEFT)->setX($width * -0.46)->setSize($width * 0.7, $lineHeight)->setTextSize(2)->setTranslate(true)->setText($voteRatioDescription);
|
||||
|
||||
$entry = new Entry();
|
||||
$voteRatioFrame->add($entry);
|
||||
$entry->setX($width * 0.35)->setSize($width * 0.14, $lineHeight * 0.9)->setStyle(Label_Text::STYLE_TextValueSmall)->setTextSize($index === 0 ? 2 : 1)->setName(self::ACTION_PREFIX_VOTE_RATIO . $voteRatioCommand);
|
||||
|
||||
$voteRatio = $this->getVoteRatioForCommand($voteRatios, $voteRatioCommand);
|
||||
if ($voteRatio) {
|
||||
$entry->setDefault($voteRatio->ratio);
|
||||
}
|
||||
|
||||
$posY -= $lineHeight;
|
||||
if ($index === 0) {
|
||||
$posY -= $lineHeight;
|
||||
}
|
||||
$index++;
|
||||
}
|
||||
|
||||
return $frame;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the list of available vote commands
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
private function getVoteCommands() {
|
||||
return array(VoteRatio::COMMAND_DEFAULT => 'Default', VoteRatio::COMMAND_RESTART_MAP => 'Restart Map', VoteRatio::COMMAND_NEXT_MAP => 'Skip Map', VoteRatio::COMMAND_SET_NEXT_MAP => 'Set next Map', VoteRatio::COMMAND_JUMP_MAP => 'Jump to Map', VoteRatio::COMMAND_TEAM_BALANCE => 'Balance Teams', VoteRatio::COMMAND_SCRIPT_SETTINGS => 'Change Script Settings and Commands', VoteRatio::COMMAND_KICK => 'Kick Players', VoteRatio::COMMAND_BAN => 'Ban Players');
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the vote ratio for the given command
|
||||
*
|
||||
* @param VoteRatio[] $voteRatios
|
||||
* @param string $command
|
||||
* @return VoteRatio
|
||||
*/
|
||||
private function getVoteRatioForCommand(array $voteRatios, $command) {
|
||||
foreach ($voteRatios as $voteRatio) {
|
||||
if ($voteRatio->command === $command) {
|
||||
return $voteRatio;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @see \ManiaControl\Configurators\ConfiguratorMenu::saveConfigData()
|
||||
*/
|
||||
public function saveConfigData(array $configData, Player $player) {
|
||||
if (!$this->maniaControl->getAuthenticationManager()->checkPermission($player, self::SETTING_PERMISSION_CHANGE_VOTE_RATIOS)
|
||||
) {
|
||||
$this->maniaControl->getAuthenticationManager()->sendNotAllowed($player);
|
||||
return;
|
||||
}
|
||||
if (!$configData[3] || strpos($configData[3][0]['Name'], self::ACTION_PREFIX_VOTE_RATIO) !== 0) {
|
||||
return;
|
||||
}
|
||||
$prefixLength = strlen(self::ACTION_PREFIX_VOTE_RATIO);
|
||||
|
||||
$newVoteRatios = array();
|
||||
foreach ($configData[3] as $voteRatioEntry) {
|
||||
$voteRatioName = substr($voteRatioEntry['Name'], $prefixLength);
|
||||
$voteRatioValue = $voteRatioEntry['Value'];
|
||||
if ($voteRatioValue === '') {
|
||||
continue;
|
||||
}
|
||||
if (!is_numeric($voteRatioValue)) {
|
||||
$this->sendInvalidValueError($player, $voteRatioName);
|
||||
continue;
|
||||
}
|
||||
|
||||
$voteRatio = new VoteRatio();
|
||||
$voteRatio->command = $voteRatioName;
|
||||
$voteRatio->ratio = (float)$voteRatioValue;
|
||||
|
||||
if (!$voteRatio->isValid()) {
|
||||
$this->sendInvalidValueError($player, $voteRatioName);
|
||||
continue;
|
||||
}
|
||||
array_push($newVoteRatios, $voteRatio);
|
||||
}
|
||||
|
||||
$success = $this->maniaControl->getClient()->setCallVoteRatios($newVoteRatios);
|
||||
if ($success) {
|
||||
$this->maniaControl->getChat()->sendSuccess('Vote Ratios saved!', $player);
|
||||
} else {
|
||||
$this->maniaControl->getChat()->sendError('Vote Ratios saving failed!', $player);
|
||||
}
|
||||
|
||||
// Reopen the Menu
|
||||
$this->maniaControl->getConfigurator()->showMenu($player, $this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Inform the player that his entered value is invalid
|
||||
*
|
||||
* @param Player $player
|
||||
* @param string $commandName
|
||||
*/
|
||||
private function sendInvalidValueError(Player $player, $commandName) {
|
||||
$this->maniaControl->getChat()->sendError("Invalid Value given for '{$commandName}'!", $player);
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user