moved some plugins out of the repo

Conflicts:
	application/plugins/CustomVotes.php
This commit is contained in:
Steffen Schröder 2014-05-01 17:36:24 +02:00
parent 92232a6bed
commit 12ff7173fb
15 changed files with 6 additions and 4246 deletions

9
.gitignore vendored
View File

@ -1,5 +1,4 @@
/.idea/ .settings
/application/.idea/ .buildpath
/.settings/ .project
/.buildpath .idea
/.project

View File

@ -1,4 +1,5 @@
<?php <?php
namespace MCTeam; namespace MCTeam;
use ManiaControl\Commands\CommandListener; use ManiaControl\Commands\CommandListener;

View File

@ -1,160 +0,0 @@
<?php
namespace MCTeam;
use ManiaControl\Callbacks\CallbackListener;
use ManiaControl\Callbacks\CallbackManager;
use ManiaControl\Files\FileUtil;
use ManiaControl\ManiaControl;
use ManiaControl\Plugins\Plugin;
/**
* ManiaControl Chatlog Plugin
*
* @author steeffeen
* @copyright ManiaControl Copyright © 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/
class ChatlogPlugin implements CallbackListener, Plugin {
/**
* Constants
*/
const ID = 26;
const VERSION = 0.1;
const DATE = 'd-m-y h:i:sa T';
const SETTING_FOLDERNAME = 'Log-Folder Name';
const SETTING_FILENAME = 'Log-File Name';
const SETTING_USEPID = 'Use Process-Id for File Name';
const SETTING_LOGSERVERMESSAGES = 'Log Server Messages';
/**
* Private properties
*/
/** @var maniaControl $maniaControl */
private $maniaControl = null;
private $fileName = null;
private $logServerMessages = true;
/**
* Prepares the Plugin
*
* @param ManiaControl $maniaControl
* @return mixed
*/
public static function prepare(ManiaControl $maniaControl) {
}
/**
* @see \ManiaControl\Plugins\Plugin::load()
*/
public function load(ManiaControl $maniaControl) {
$this->maniaControl = $maniaControl;
// Init settings
$this->maniaControl->settingManager->initSetting($this, self::SETTING_FOLDERNAME, 'logs');
$this->maniaControl->settingManager->initSetting($this, self::SETTING_FILENAME, 'ChatLog.log');
$this->maniaControl->settingManager->initSetting($this, self::SETTING_USEPID, false);
$this->maniaControl->settingManager->initSetting($this, self::SETTING_LOGSERVERMESSAGES, true);
// Get settings
$folderName = $this->maniaControl->settingManager->getSetting($this, self::SETTING_FOLDERNAME);
$folderName = FileUtil::getClearedFileName($folderName);
$folderDir = ManiaControlDir . '/' . $folderName;
if (!is_dir($folderDir)) {
$success = mkdir($folderDir);
if (!$success) {
trigger_error("Couldn't create chat log folder '{$folderName}'.");
}
}
$fileName = $this->maniaControl->settingManager->getSetting($this, self::SETTING_FILENAME);
$fileName = FileUtil::getClearedFileName($fileName);
$usePId = $this->maniaControl->settingManager->getSetting($this, self::SETTING_USEPID);
if ($usePId) {
$dotIndex = strripos($fileName, '.');
$pIdPart = '_' . getmypid();
if ($dotIndex !== false && $dotIndex >= 0) {
$fileName = substr($fileName, 0, $dotIndex) . $pIdPart . substr($fileName, $dotIndex);
} else {
$fileName .= $pIdPart;
}
}
$this->fileName = $folderDir . '/' . $fileName;
$this->logServerMessages = $this->maniaControl->settingManager->getSetting($this, self::SETTING_LOGSERVERMESSAGES);
// Register for callbacks
$this->maniaControl->callbackManager->registerCallbackListener(CallbackManager::CB_MP_PLAYERCHAT, $this, 'handlePlayerChatCallback');
return true;
}
/**
* @see \ManiaControl\Plugins\Plugin::unload()
*/
public function unload() {
$this->maniaControl->callbackManager->unregisterCallbackListener($this);
unset($this->maniaControl);
}
/**
* @see \ManiaControl\Plugins\Plugin::getId()
*/
public static function getId() {
return self::ID;
}
/**
* @see \ManiaControl\Plugins\Plugin::getName()
*/
public static function getName() {
return 'Chatlog Plugin';
}
/**
* @see \ManiaControl\Plugins\Plugin::getVersion()
*/
public static function getVersion() {
return self::VERSION;
}
/**
* @see \ManiaControl\Plugins\Plugin::getAuthor()
*/
public static function getAuthor() {
return 'steeffeen';
}
/**
* @see \ManiaControl\Plugins\Plugin::getDescription()
*/
public static function getDescription() {
return 'Plugin logging the Chat Messages of the Server for later Checks and Controlling.';
}
/**
* Handle PlayerChat callback
*
* @param array $chatCallback
*/
public function handlePlayerChatCallback(array $chatCallback) {
$data = $chatCallback[1];
if ($data[0] <= 0 && !$this->logServerMessages) {
// Skip server message
return;
}
$this->logText($data[2], $data[1]);
}
/**
* Log the given message
*
* @param string $text
* @param string $login
*/
private function logText($text, $login = null) {
if (!$login) {
$login = '';
}
$message = date(self::DATE) . " >> {$login}: {$text}" . PHP_EOL;
file_put_contents($this->fileName, $message, FILE_APPEND);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,95 +0,0 @@
<?php
namespace Dedimania;
use ManiaControl\ManiaControl;
use Maniaplanet\DedicatedServer\Structures\Version;
/**
* ManiaControl Dedimania Plugin DataStructure
*
* @author kremsy and steeffeen
* @copyright ManiaControl Copyright © 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/
class DedimaniaData {
public $game;
public $path;
public $packmask;
public $serverVersion;
public $serverBuild;
public $tool;
public $version;
public $login;
public $code;
public $sessionId = '';
public $records = array();
public $players = array();
public $directoryAccessChecked = false;
public $serverMaxRank = 30;
public function __construct($serverLogin, $dedimaniaCode, $path, $packmask, Version $serverVersion) {
$this->game = "TM2";
$this->login = $serverLogin;
$this->code = $dedimaniaCode;
$this->version = ManiaControl::VERSION;
$this->tool = "ManiaControl";
$this->path = $path;
$this->packmask = $packmask;
$this->serverVersion = $serverVersion->version;
$this->serverBuild = $serverVersion->build;
}
public function toArray() {
$array = array();
foreach(get_object_vars($this) as $key => $value) {
if ($key == 'records' || $key == 'sessionId' || $key == 'directoryAccessChecked' || $key == 'serverMaxRank' || $key == 'players') {
continue;
}
$array[ucfirst($key)] = $value;
}
return $array;
}
public function getRecordCount() {
return count($this->records);
}
/**
* Get Max Rank for a certain Player
*
* @param $login
* @return int
*/
public function getPlayerMaxRank($login) {
$maxRank = $this->serverMaxRank;
foreach($this->players as $player) {
/** @var DedimaniaPlayer $player */
if ($player->login === $login) {
if ($player->maxRank > $maxRank) {
$maxRank = $player->maxRank;
}
break;
}
}
return $maxRank;
}
/**
* Adds a Player to the Players array
*
* @param DedimaniaPlayer $player
*/
public function addPlayer(DedimaniaPlayer $player) {
/** @var DedimaniaPlayer $player */
$this->players[$player->login] = $player;
}
/**
* Removes a Dedimania Player by its login
*
* @param string $player
*/
public function removePlayer($login) {
unset($this->players[$login]);
}
}

View File

@ -1,38 +0,0 @@
<?php
namespace Dedimania;
/**
* ManiaControl Dedimania-Plugin Player DataStructure
*
* @author kremsy and steeffeen
* @copyright ManiaControl Copyright © 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/
class DedimaniaPlayer {
public $login = '';
public $maxRank = -1;
public $banned = false;
public $optionsEnabled = false;
public $options = '';
public function __construct($player) {
if (!$player) return;
$this->login = $player['Login'];
$this->maxRank = $player['MaxRank'];
$this->banned = $player['Banned'];
$this->optionsEnabled = $player['OptionsEnabled'];
$this->options = $player['Options'];
}
/**
* Construct a new Player by its login and maxRank
*
* @param $login
* @param $maxRank
*/
public function constructNewPlayer($login, $maxRank) {
$this->login = $login;
$this->maxRank = $maxRank;
}
}

View File

@ -1,61 +0,0 @@
<?php
namespace Dedimania;
/**
* ManiaControl Dedimania-Plugin Record DataStructure
*
* @author kremsy and steeffeen
* @copyright ManiaControl Copyright © 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/
use ManiaControl\Formatter;
class RecordData {
public $nullRecord = false;
public $login = '';
public $nickName = '';
public $best = -1;
public $rank = -1;
public $maxRank = -1;
public $checkpoints = '';
public $newRecord = false;
public $vReplay = '';
public $top1GReplay = '';
/**
* Construct a Record by a given Record Array
*
* @param $record
*/
public function __construct($record) {
if (!$record) {
$this->nullRecord = true;
return;
}
$this->login = $record['Login'];
$this->nickName = Formatter::stripDirtyCodes($record['NickName']);
$this->best = $record['Best'];
$this->rank = $record['Rank'];
$this->maxRank = $record['MaxRank'];
$this->checkpoints = $record['Checks'];
}
/**
* Constructs a new Record via it's properties
*
* @param $login
* @param $nickName
* @param $best
* @param $checkpoints
* @param bool $newRecord
*/
public function constructNewRecord($login, $nickName, $best, $checkpoints, $newRecord = false) {
$this->nullRecord = false;
$this->login = $login;
$this->nickName = $nickName;
$this->best = $best;
$this->checkpoints = $checkpoints;
$this->newRecord = $newRecord;
}
}

View File

@ -1,4 +1,5 @@
<?php <?php
namespace MCTeam; namespace MCTeam;
use FML\Controls\Control; use FML\Controls\Control;

View File

@ -1,153 +0,0 @@
<?php
use ManiaControl\Callbacks\CallbackListener;
use ManiaControl\Commands\CommandListener;
use ManiaControl\ManiaControl;
use ManiaControl\Players\Player;
use ManiaControl\Players\PlayerManager;
use ManiaControl\Plugins\Plugin;
/**
* Dynamic Pointlimit plugin
* Based on the Linearmode plugin for MPAseco by kremsy
*
* @author TheM
*/
class DynamicPointlimitPlugin implements CallbackListener, CommandListener, Plugin {
/**
* Constants
*/
const ID = 21;
const VERSION = 0.1;
const DYNPNT_MULTIPLIER = 'Pointlimit multiplier';
const DYNPNT_OFFSET = 'Pointlimit offset';
const DYNPNT_MIN = 'Minimum pointlimit';
const DYNPNT_MAX = 'Maximum pointlimit';
const ACCEPT_OTHER_MODES = 'Activate in Other mode as Royal';
/**
* Prepares the Plugin
*
* @param ManiaControl $maniaControl
* @return mixed
*/
public static function prepare(ManiaControl $maniaControl) {
$maniaControl->settingManager->initSetting(get_class(), self::ACCEPT_OTHER_MODES, false);
$maniaControl->settingManager->initSetting(get_class(), self::DYNPNT_MULTIPLIER, 10);
$maniaControl->settingManager->initSetting(get_class(), self::DYNPNT_OFFSET, 0);
$maniaControl->settingManager->initSetting(get_class(), self::DYNPNT_MIN, 30);
$maniaControl->settingManager->initSetting(get_class(), self::DYNPNT_MAX, 200);
}
/**
* Private properties
*/
/** @var ManiaControl $maniaControl */
private $maniaControl = null;
/**
* Load the plugin
*
* @param \ManiaControl\ManiaControl $maniaControl
* @throws Exception
* @return bool
*/
public function load(ManiaControl $maniaControl) {
$this->maniaControl = $maniaControl;
$this->maniaControl->callbackManager->registerCallbackListener(PlayerManager::CB_PLAYERCONNECT, $this, 'changePointlimit');
$this->maniaControl->callbackManager->registerCallbackListener(PlayerManager::CB_PLAYERDISCONNECT, $this, 'changePointlimit');
$allowOthers = $this->maniaControl->settingManager->getSetting($this, self::ACCEPT_OTHER_MODES);
if (!$allowOthers && $this->maniaControl->server->titleId != 'SMStormRoyal@nadeolabs') {
$error = 'This plugin only supports Royal (check Settings)!';
throw new Exception($error);
}
}
/**
* Unload the plugin and its resources
*/
public function unload() {
$this->maniaControl->callbackManager->unregisterCallbackListener($this);
unset($this->maniaControl);
}
/**
* Get plugin id
*
* @return int
*/
public static function getId() {
return self::ID;
}
/**
* Get Plugin Name
*
* @return string
*/
public static function getName() {
return 'Dynamic Pointlimit Plugin';
}
/**
* Get Plugin Version
*
* @return float
*/
public static function getVersion() {
return self::VERSION;
}
/**
* Get Plugin Author
*
* @return string
*/
public static function getAuthor() {
return 'TheM';
}
/**
* Get Plugin Description
*
* @return string
*/
public static function getDescription() {
return 'Plugin offers a dynamic pointlimit according to the amount of players on the server.';
}
/**
* Function called on player connect and disconnect, changing the pointlimit.
*
* @param Player $player
*/
public function changePointlimit(Player $player) {
$numberOfPlayers = 0;
$numberOfSpectators = 0;
/** @var Player $player */
foreach($this->maniaControl->playerManager->getPlayers() as $player) {
if ($player->isSpectator) {
$numberOfSpectators++;
} else {
$numberOfPlayers++;
}
}
$pointlimit = ($numberOfPlayers * $this->maniaControl->settingManager->getSetting($this, self::DYNPNT_MULTIPLIER)) + $this->maniaControl->settingManager->getSetting($this, self::DYNPNT_OFFSET);
$min_value = $this->maniaControl->settingManager->getSetting($this, self::DYNPNT_MIN);
$max_value = $this->maniaControl->settingManager->getSetting($this, self::DYNPNT_MAX);
if ($pointlimit < $min_value) {
$pointlimit = $min_value;
}
if ($pointlimit > $max_value) {
$pointlimit = $max_value;
}
$this->maniaControl->client->setModeScriptSettings(array('S_MapPointsLimit' => $pointlimit));
}
}

View File

@ -1,157 +0,0 @@
<?php
namespace steeffeen;
use ManiaControl\Callbacks\Callbacks;
use ManiaControl\ManiaControl;
use ManiaControl\Callbacks\CallbackListener;
use ManiaControl\Callbacks\CallbackManager;
use ManiaControl\Maps\Map;
use ManiaControl\Plugins\Plugin;
use ManiaControl\Maps\MapManager;
/**
* Plugin for the TM Game Mode 'Endurance' by TGYoshi
*
* @author steeffeen
*/
class EndurancePlugin implements CallbackListener, Plugin {
/**
* Constants
*/
const ID = 25;
const VERSION = 0.1;
const CB_CHECKPOINT = 'Endurance.Checkpoint';
/**
* Private properties
*/
/** @var maniaControl $maniaControl */
private $maniaControl = null;
/** @var Map $currentMap */
private $currentMap = null;
private $playerLapTimes = array();
/**
* Prepares the Plugin
*
* @param ManiaControl $maniaControl
* @return mixed
*/
public static function prepare(ManiaControl $maniaControl) {
//do nothing
}
/**
*
* @see \ManiaControl\Plugins\Plugin::load()
*/
public function load(ManiaControl $maniaControl) {
$this->maniaControl = $maniaControl;
// Register for callbacks
$this->maniaControl->callbackManager->registerCallbackListener(CallbackManager::CB_ONINIT, $this, 'callback_OnInit');
$this->maniaControl->callbackManager->registerCallbackListener(Callbacks::BEGINMAP, $this, 'callback_BeginMap');
$this->maniaControl->callbackManager->registerScriptCallbackListener(self::CB_CHECKPOINT, $this, 'callback_Checkpoint');
return true;
}
/**
*
* @see \ManiaControl\Plugins\Plugin::unload()
*/
public function unload() {
$this->maniaControl->callbackManager->unregisterCallbackListener($this);
$this->maniaControl->callbackManager->unregisterScriptCallbackListener($this);
unset($this->maniaControl);
}
/**
*
* @see \ManiaControl\Plugins\Plugin::getId()
*/
public static function getId() {
return self::ID;
}
/**
*
* @see \ManiaControl\Plugins\Plugin::getName()
*/
public static function getName() {
return 'Endurance Plugin';
}
/**
*
* @see \ManiaControl\Plugins\Plugin::getVersion()
*/
public static function getVersion() {
return self::VERSION;
}
/**
*
* @see \ManiaControl\Plugins\Plugin::getAuthor()
*/
public static function getAuthor() {
return 'steeffeen';
}
/**
*
* @see \ManiaControl\Plugins\Plugin::getDescription()
*/
public static function getDescription() {
return "Plugin enabling Support for the TM Game Mode 'Endurance' by TGYoshi.";
}
/**
* Handle ManiaControl OnInit callback
*
* @param array $callback
*/
public function callback_OnInit(array $callback) {
$this->currentMap = $this->maniaControl->mapManager->getCurrentMap();
$this->playerLapTimes = array();
}
/**
* Handle BeginMap callback
*
* @param Map $map
*/
public function callback_BeginMap(Map $map) {
$this->currentMap = $map;
$this->playerLapTimes = array();
}
/**
* Handle Endurance Checkpoint callback
*
* @param array $callback
*/
public function callback_Checkpoint(array $callback) {
$callbackData = json_decode($callback[1]);
if (!$this->currentMap->nbCheckpoints || $callbackData->Checkpoint % $this->currentMap->nbCheckpoints != 0) {
return;
}
$player = $this->maniaControl->playerManager->getPlayer($callbackData->Login);
if (!$player) {
return;
}
$time = $callbackData->Time;
if ($time <= 0) {
return;
}
if (isset($this->playerLapTimes[$player->login])) {
$time -= $this->playerLapTimes[$player->login];
}
$this->playerLapTimes[$player->login] = $callbackData->Time;
// Trigger trackmania player finish callback
$finishCallback = array($player->pid, $player->login, $time);
$finishCallback = array(CallbackManager::CB_TM_PLAYERFINISH, $finishCallback);
$this->maniaControl->callbackManager->triggerCallback(CallbackManager::CB_TM_PLAYERFINISH, $finishCallback);
}
}

View File

@ -1,658 +0,0 @@
<?php
namespace MCTeam;
use FML\Controls\Control;
use FML\Controls\Frame;
use FML\Controls\Label;
use FML\Controls\Quad;
use FML\Controls\Quads\Quad_BgsPlayerCard;
use FML\ManiaLink;
use FML\Script\Features\Paging;
use ManiaControl\Admin\AuthenticationManager;
use ManiaControl\Callbacks\CallbackListener;
use ManiaControl\Callbacks\CallbackManager;
use ManiaControl\Callbacks\Callbacks;
use ManiaControl\Callbacks\TimerListener;
use ManiaControl\Commands\CommandListener;
use ManiaControl\Settings\SettingManager;
use ManiaControl\Formatter;
use ManiaControl\ManiaControl;
use ManiaControl\Maps\Map;
use ManiaControl\Maps\MapManager;
use ManiaControl\Manialinks\ManialinkManager;
use ManiaControl\Players\Player;
use ManiaControl\Players\PlayerManager;
use ManiaControl\Plugins\Plugin;
/**
* ManiaControl Local Records Plugin
*
* @author steeffeen
* @copyright ManiaControl Copyright © 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/
class LocalRecordsPlugin implements CallbackListener, CommandListener, TimerListener, Plugin {
/*
* Constants
*/
const ID = 7;
const VERSION = 0.1;
const MLID_RECORDS = 'ml_local_records';
const TABLE_RECORDS = 'mc_localrecords';
const SETTING_WIDGET_TITLE = 'Widget Title';
const SETTING_WIDGET_POSX = 'Widget Position: X';
const SETTING_WIDGET_POSY = 'Widget Position: Y';
const SETTING_WIDGET_WIDTH = 'Widget Width';
const SETTING_WIDGET_LINESCOUNT = 'Widget Displayed Lines Count';
const SETTING_WIDGET_LINEHEIGHT = 'Widget Line Height';
const SETTING_WIDGET_ENABLE = 'Enable Local Records Widget';
const SETTING_NOTIFY_ONLY_DRIVER = 'Notify only the Driver on New Records';
const SETTING_NOTIFY_BEST_RECORDS = 'Notify Publicly only for the X Best Records';
const SETTING_ADJUST_OUTER_BORDER = 'Adjust outer Border to Number of actual Records';
const CB_LOCALRECORDS_CHANGED = 'LocalRecords.Changed';
const ACTION_SHOW_RECORDSLIST = 'LocalRecords.ShowRecordsList';
/*
* Private Properties
*/
/**
*
* @var maniaControl $maniaControl
*/
private $maniaControl = null;
private $updateManialink = false;
private $checkpoints = array();
/**
* Prepares the Plugin
*
* @param ManiaControl $maniaControl
* @return mixed
*/
public static function prepare(ManiaControl $maniaControl) {
// do nothing
}
/**
*
* @see \ManiaControl\Plugins\Plugin::load()
*/
public function load(ManiaControl $maniaControl) {
$this->maniaControl = $maniaControl;
$this->initTables();
// Init settings
$this->maniaControl->settingManager->initSetting($this, self::SETTING_WIDGET_TITLE, 'Local Records');
$this->maniaControl->settingManager->initSetting($this, self::SETTING_WIDGET_POSX, -139.);
$this->maniaControl->settingManager->initSetting($this, self::SETTING_WIDGET_POSY, 75);
$this->maniaControl->settingManager->initSetting($this, self::SETTING_WIDGET_WIDTH, 40.);
$this->maniaControl->settingManager->initSetting($this, self::SETTING_WIDGET_LINESCOUNT, 15);
$this->maniaControl->settingManager->initSetting($this, self::SETTING_WIDGET_LINEHEIGHT, 4.);
$this->maniaControl->settingManager->initSetting($this, self::SETTING_WIDGET_ENABLE, true);
$this->maniaControl->settingManager->initSetting($this, self::SETTING_NOTIFY_ONLY_DRIVER, false);
$this->maniaControl->settingManager->initSetting($this, self::SETTING_NOTIFY_BEST_RECORDS, -1);
$this->maniaControl->settingManager->initSetting($this, self::SETTING_ADJUST_OUTER_BORDER, false);
// Register for callbacks
$this->maniaControl->timerManager->registerTimerListening($this, 'handle1Second', 1000);
$this->maniaControl->callbackManager->registerCallbackListener(CallbackManager::CB_AFTERINIT, $this, 'handleAfterInit');
$this->maniaControl->callbackManager->registerCallbackListener(Callbacks::BEGINMAP, $this, 'handleMapBegin');
$this->maniaControl->callbackManager->registerCallbackListener(CallbackManager::CB_TM_PLAYERFINISH, $this, 'handlePlayerFinish');
$this->maniaControl->callbackManager->registerCallbackListener(PlayerManager::CB_PLAYERCONNECT, $this, 'handlePlayerConnect');
$this->maniaControl->callbackManager->registerCallbackListener(CallbackManager::CB_TM_PLAYERCHECKPOINT, $this, 'handlePlayerCheckpoint');
$this->maniaControl->callbackManager->registerCallbackListener(SettingManager::CB_SETTINGS_CHANGED, $this, 'handleSettingsChanged');
$this->maniaControl->callbackManager->registerCallbackListener(CallbackManager::CB_MP_PLAYERMANIALINKPAGEANSWER, $this, 'handleManialinkPageAnswer');
$this->maniaControl->commandManager->registerCommandListener(array('recs', 'records'), $this, 'showRecordsList', false, 'Shows a list of Local Records on the current map.');
$this->maniaControl->commandManager->registerCommandListener('delrec', $this, 'deleteRecord', true, 'Removes a record from the database.');
return true;
}
/**
*
* @see \ManiaControl\Plugins\Plugin::unload()
*/
public function unload() {
$this->maniaControl->callbackManager->unregisterCallbackListener($this);
$this->maniaControl->timerManager->unregisterTimerListenings($this);
}
/**
* Initialize needed database tables
*/
private function initTables() {
$mysqli = $this->maniaControl->database->mysqli;
$query = "CREATE TABLE IF NOT EXISTS `" . self::TABLE_RECORDS . "` (
`index` int(11) NOT NULL AUTO_INCREMENT,
`mapIndex` int(11) NOT NULL,
`playerIndex` int(11) NOT NULL,
`time` int(11) NOT NULL,
`changed` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`index`),
UNIQUE KEY `player_map_record` (`mapIndex`,`playerIndex`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1;";
$mysqli->query($query);
if ($mysqli->error) {
trigger_error($mysqli->error, E_USER_ERROR);
}
$mysqli->query("ALTER TABLE `" . self::TABLE_RECORDS . "` ADD `checkpoints` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL");
if ($mysqli->error) {
if (!strstr($mysqli->error, 'Duplicate')) {
trigger_error($mysqli->error, E_USER_ERROR);
}
}
}
/**
*
* @see \ManiaControl\Plugins\Plugin::getId()
*/
public static function getId() {
return self::ID;
}
/**
*
* @see \ManiaControl\Plugins\Plugin::getName()
*/
public static function getName() {
return 'Local Records Plugin';
}
/**
*
* @see \ManiaControl\Plugins\Plugin::getVersion()
*/
public static function getVersion() {
return self::VERSION;
}
/**
*
* @see \ManiaControl\Plugins\Plugin::getAuthor()
*/
public static function getAuthor() {
return 'steeffeen';
}
/**
*
* @see \ManiaControl\Plugins\Plugin::getDescription()
*/
public static function getDescription() {
return 'Plugin offering tracking of local records and manialinks to display them.';
}
/**
* Handle ManiaControl After Init
*/
public function handleAfterInit() {
$this->updateManialink = true;
}
/**
* Handle 1Second callback
*
* @param $time
*/
public function handle1Second($time) {
if (!$this->updateManialink) {
return;
}
$this->updateManialink = false;
if ($this->maniaControl->settingManager->getSetting($this, self::SETTING_WIDGET_ENABLE)) {
$manialink = $this->buildManialink();
$this->maniaControl->manialinkManager->sendManialink($manialink);
}
}
public function handleSettingsChanged($class, $settingName, $value) {
if (!$class = get_class()) {
return;
}
if ($settingName == 'Enable Local Records Widget' && $value == true) {
$this->updateManialink = true;
}
elseif ($settingName == 'Enable Local Records Widget' && $value == false) {
$ml = new ManiaLink(self::MLID_RECORDS);
$mltext = $ml->render()->saveXML();
$this->maniaControl->manialinkManager->sendManialink($mltext);
}
}
/**
* Handle PlayerCheckpoint callback
*
* @param $callback
*/
public function handlePlayerCheckpoint($callback) {
$data = $callback[1];
$login = $data[1];
$time = $data[2];
// $lap = $data[3];
$cpIndex = $data[4];
if (!isset($this->checkpoints[$login]) || $cpIndex <= 0) {
$this->checkpoints[$login] = array();
}
$this->checkpoints[$login][$cpIndex] = $time;
}
/**
* Handle PlayerConnect callback
*
* @param Player $player
*/
public function handlePlayerConnect(Player $player) {
$this->updateManialink = true;
}
/**
* Handle BeginMap callback
*
* @param Map $map
*/
public function handleMapBegin(Map $map) {
$this->updateManialink = true;
}
/**
* Handle PlayerFinish callback
*
* @param array $callback
*/
public function handlePlayerFinish(array $callback) {
$data = $callback[1];
if ($data[0] <= 0 || $data[2] <= 0) {
// Invalid player or time
return;
}
$login = $data[1];
$player = $this->maniaControl->playerManager->getPlayer($login);
if (!$player) {
// Invalid player
return;
}
$time = $data[2];
$map = $this->maniaControl->mapManager->getCurrentMap();
// Check old record of the player
$oldRecord = $this->getLocalRecord($map, $player);
$oldRank = -1;
if ($oldRecord) {
$oldRank = $oldRecord->rank;
if ($oldRecord->time < $time) {
// Not improved
return;
}
if ($oldRecord->time == $time) {
// Same time
$message = '$<$fff' . $player->nickname . '$> equalized his/her $<$ff0' . $oldRecord->rank . '.$> Local Record: $<$fff' . Formatter::formatTime($oldRecord->time) . '$>!';
$this->maniaControl->chat->sendInformation('$3c0' . $message);
return;
}
}
// Save time
$mysqli = $this->maniaControl->database->mysqli;
$query = "INSERT INTO `" . self::TABLE_RECORDS . "` (
`mapIndex`,
`playerIndex`,
`time`,
`checkpoints`
) VALUES (
{$map->index},
{$player->index},
{$time},
'{$this->getCheckpoints($player->login)}'
) ON DUPLICATE KEY UPDATE
`time` = VALUES(`time`),
`checkpoints` = VALUES(`checkpoints`);";
$mysqli->query($query);
if ($mysqli->error) {
trigger_error($mysqli->error);
return;
}
$this->updateManialink = true;
// Announce record
$newRecord = $this->getLocalRecord($map, $player);
$this->maniaControl->callbackManager->triggerCallback(self::CB_LOCALRECORDS_CHANGED, $newRecord);
$notifyOnlyDriver = $this->maniaControl->settingManager->getSetting($this, self::SETTING_NOTIFY_ONLY_DRIVER);
$notifyOnlyBestRecords = $this->maniaControl->settingManager->getSetting($this, self::SETTING_NOTIFY_BEST_RECORDS);
if ($notifyOnlyDriver || $notifyOnlyBestRecords > 0 && $newRecord->rank > $notifyOnlyBestRecords) {
$improvement = ((!$oldRecord || $newRecord->rank < $oldRecord->rank) ? 'gained the' : 'improved your');
$message = 'You ' . $improvement . ' $<$ff0' . $newRecord->rank . '.$> Local Record: $<$fff' . Formatter::formatTime($newRecord->time) . '$>';
if ($oldRecord) $oldRank = ($improvement == 'improved your') ? '' : $oldRecord->rank . '. ';
if ($oldRecord) $message .= ' ($<$ff0' . $oldRank . '$>$<$fff-' . Formatter::formatTime(($oldRecord->time - $newRecord->time)) . '$>!';
$this->maniaControl->chat->sendInformation('$3c0' . $message.'!', $player->login);
}
else {
$improvement = ((!$oldRecord || $newRecord->rank < $oldRecord->rank) ? 'gained the' : 'improved the');
$message = '$<$fff' . $player->nickname . '$> ' . $improvement . ' $<$ff0' . $newRecord->rank . '.$> Local Record: $<$fff' . Formatter::formatTime($newRecord->time) . '$>';
if ($oldRecord) $oldRank = ($improvement == 'improved the') ? '' : $oldRecord->rank . '. ';
if ($oldRecord) $message .= ' ($<$ff0' . $oldRank . '$>$<$fff-' . Formatter::formatTime(($oldRecord->time - $newRecord->time)) . '$>)';
$this->maniaControl->chat->sendInformation('$3c0' . $message.'!');
}
}
/**
* Handle PlayerManialinkPageAnswer callback
*
* @param array $callback
*/
public function handleManialinkPageAnswer(array $callback) {
$actionId = $callback[1][2];
$login = $callback[1][1];
$player = $this->maniaControl->playerManager->getPlayer($login);
if ($actionId == self::ACTION_SHOW_RECORDSLIST) {
$this->showRecordsList(array(), $player);
}
}
/**
* Delete a Player's record
*
* @param array $chat
* @param Player $player
*/
public function deleteRecord(array $chat, Player $player) {
if (!$this->maniaControl->authenticationManager->checkRight($player, AuthenticationManager::AUTH_LEVEL_MASTERADMIN)) {
$this->maniaControl->authenticationManager->sendNotAllowed($player);
return;
}
$chatCommand = explode(' ', $chat[1][2]);
$recordId = (int) $chatCommand[1];
if (is_integer($recordId)) {
$currentMap = $this->maniaControl->mapManager->getCurrentMap();
$records = $this->getLocalRecords($currentMap);
if (count($records) < $recordId) {
$this->maniaControl->chat->sendError('Cannot remove record $<$fff' . $recordId . '$>!', $player);
return;
}
$mysqli = $this->maniaControl->database->mysqli;
$query = "DELETE FROM `" . self::TABLE_RECORDS . "` WHERE `mapIndex` = " . $currentMap->index . " AND `playerIndex` = " . $player->index . "";
$mysqli->query($query);
if ($mysqli->error) {
trigger_error($mysqli->error);
return;
}
$this->maniaControl->callbackManager->triggerCallback(self::CB_LOCALRECORDS_CHANGED, null);
$this->maniaControl->chat->sendInformation('Record no. $<$fff' . $recordId . '$> has been removed!');
}
else {
$this->maniaControl->chat->sendError('Cannot remove record $<$fff' . $recordId . '$>, because it\'s not an integer!', $player);
}
}
/**
* Shows a ManiaLink list with the local records.
*
* @param array $chat
* @param Player $player
*/
public function showRecordsList(array $chat, Player $player) {
$width = $this->maniaControl->manialinkManager->styleManager->getListWidgetsWidth();
$height = $this->maniaControl->manialinkManager->styleManager->getListWidgetsHeight();
// get PlayerList
$records = $this->getLocalRecords($this->maniaControl->mapManager->getCurrentMap());
$pagesId = '';
if (count($records) > 15) {
$pagesId = 'RecordsListPages';
}
// create manialink
$maniaLink = new ManiaLink(ManialinkManager::MAIN_MLID);
$script = $maniaLink->getScript();
$paging = new Paging();
$script->addFeature($paging);
// Main frame
$frame = $this->maniaControl->manialinkManager->styleManager->getDefaultListFrame($script, $paging);
$maniaLink->add($frame);
// Start offsets
$x = -$width / 2;
$y = $height / 2;
// Predefine Description Label
$descriptionLabel = $this->maniaControl->manialinkManager->styleManager->getDefaultDescriptionLabel();
$frame->add($descriptionLabel);
// Headline
$headFrame = new Frame();
$frame->add($headFrame);
$headFrame->setY($y - 5);
$array = array("Rank" => $x + 5, "Nickname" => $x + 18, "Login" => $x + 70, "Time" => $x + 101);
$this->maniaControl->manialinkManager->labelLine($headFrame, $array);
$i = 0;
$y = $height / 2 - 10;
$pageFrames = array();
foreach ($records as $listRecord) {
if (!isset($pageFrame)) {
$pageFrame = new Frame();
$frame->add($pageFrame);
if (!empty($pageFrames)) {
$pageFrame->setVisible(false);
}
array_push($pageFrames, $pageFrame);
$y = $height / 2 - 10;
$paging->addPage($pageFrame);
}
$recordFrame = new Frame();
$pageFrame->add($recordFrame);
if ($i % 2 != 0) {
$lineQuad = new Quad_BgsPlayerCard();
$recordFrame->add($lineQuad);
$lineQuad->setSize($width, 4);
$lineQuad->setSubStyle($lineQuad::SUBSTYLE_BgPlayerCardBig);
$lineQuad->setZ(0.001);
}
if (strlen($listRecord->nickname) < 2) $listRecord->nickname = $listRecord->login;
$array = array($listRecord->rank => $x + 5, '$fff' . $listRecord->nickname => $x + 18, $listRecord->login => $x + 70,
Formatter::formatTime($listRecord->time) => $x + 101);
$this->maniaControl->manialinkManager->labelLine($recordFrame, $array);
$recordFrame->setY($y);
$y -= 4;
$i++;
if ($i % 15 == 0) {
unset($pageFrame);
}
}
// Render and display xml
$this->maniaControl->manialinkManager->displayWidget($maniaLink, $player, 'PlayerList');
}
/**
* Get current checkpoint string for dedimania record
*
* @param string $login
* @return string
*/
private function getCheckpoints($login) {
if (!$login || !isset($this->checkpoints[$login])) {
return null;
}
$string = '';
$count = count($this->checkpoints[$login]);
foreach ($this->checkpoints[$login] as $index => $check) {
$string .= $check;
if ($index < $count - 1) {
$string .= ',';
}
}
return $string;
}
/**
* Build the local records manialink
*
* @return string
*/
private function buildManialink() {
$map = $this->maniaControl->mapManager->getCurrentMap();
if (!$map) {
return null;
}
$title = $this->maniaControl->settingManager->getSetting($this, self::SETTING_WIDGET_TITLE);
$pos_x = $this->maniaControl->settingManager->getSetting($this, self::SETTING_WIDGET_POSX);
$pos_y = $this->maniaControl->settingManager->getSetting($this, self::SETTING_WIDGET_POSY);
$width = $this->maniaControl->settingManager->getSetting($this, self::SETTING_WIDGET_WIDTH);
$lines = $this->maniaControl->settingManager->getSetting($this, self::SETTING_WIDGET_LINESCOUNT);
$lineHeight = $this->maniaControl->settingManager->getSetting($this, self::SETTING_WIDGET_LINEHEIGHT);
$labelStyle = $this->maniaControl->manialinkManager->styleManager->getDefaultLabelStyle();
$quadStyle = $this->maniaControl->manialinkManager->styleManager->getDefaultQuadStyle();
$quadSubstyle = $this->maniaControl->manialinkManager->styleManager->getDefaultQuadSubstyle();
$records = $this->getLocalRecords($map);
if (!is_array($records)) {
trigger_error("Couldn't fetch player records.");
return null;
}
$manialink = new ManiaLink(self::MLID_RECORDS);
$frame = new Frame();
$manialink->add($frame);
$frame->setPosition($pos_x, $pos_y);
$backgroundQuad = new Quad();
$frame->add($backgroundQuad);
$backgroundQuad->setVAlign(Control::TOP);
$adjustOuterBorder = $this->maniaControl->settingManager->getSetting($this, self::SETTING_ADJUST_OUTER_BORDER);
$height = 7. + ($adjustOuterBorder ? count($records) : $lines) * $lineHeight;
$backgroundQuad->setSize($width * 1.05, $height);
$backgroundQuad->setStyles($quadStyle, $quadSubstyle);
$backgroundQuad->setAction(self::ACTION_SHOW_RECORDSLIST);
$titleLabel = new Label();
$frame->add($titleLabel);
$titleLabel->setPosition(0, $lineHeight * -0.9);
$titleLabel->setWidth($width);
$titleLabel->setStyle($labelStyle);
$titleLabel->setTextSize(2);
$titleLabel->setText($title);
$titleLabel->setTranslate(true);
// Times
foreach ($records as $index => $record) {
if ($index >= $lines) {
break;
}
$y = -8. - $index * $lineHeight;
$recordFrame = new Frame();
$frame->add($recordFrame);
$recordFrame->setPosition(0, $y);
/*
* $backgroundQuad = new Quad(); $recordFrame->add($backgroundQuad); $backgroundQuad->setSize($width * 1.04, $lineHeight * 1.4); $backgroundQuad->setStyles($quadStyle, $quadSubstyle);
*/
$rankLabel = new Label();
$recordFrame->add($rankLabel);
$rankLabel->setHAlign(Control::LEFT);
$rankLabel->setX($width * -0.47);
$rankLabel->setSize($width * 0.06, $lineHeight);
$rankLabel->setTextSize(1);
$rankLabel->setTextPrefix('$o');
$rankLabel->setText($record->rank);
$rankLabel->setTextEmboss(true);
$nameLabel = new Label();
$recordFrame->add($nameLabel);
$nameLabel->setHAlign(Control::LEFT);
$nameLabel->setX($width * -0.4);
$nameLabel->setSize($width * 0.6, $lineHeight);
$nameLabel->setTextSize(1);
$nameLabel->setText($record->nickname);
$nameLabel->setTextEmboss(true);
$timeLabel = new Label();
$recordFrame->add($timeLabel);
$timeLabel->setHAlign(Control::RIGHT);
$timeLabel->setX($width * 0.47);
$timeLabel->setSize($width * 0.25, $lineHeight);
$timeLabel->setTextSize(1);
$timeLabel->setText(Formatter::formatTime($record->time));
$timeLabel->setTextEmboss(true);
}
return $manialink;
}
/**
* Fetch local records for the given map
*
* @param Map $map
* @param int $limit
* @return array
*/
public function getLocalRecords(Map $map, $limit = -1) {
$mysqli = $this->maniaControl->database->mysqli;
$limit = ($limit > 0 ? "LIMIT " . $limit : "");
$query = "SELECT * FROM (
SELECT recs.*, @rank := @rank + 1 as `rank` FROM `" . self::TABLE_RECORDS . "` recs, (SELECT @rank := 0) ra
WHERE recs.`mapIndex` = {$map->index}
ORDER BY recs.`time` ASC
{$limit}) records
LEFT JOIN `" . PlayerManager::TABLE_PLAYERS . "` players
ON records.`playerIndex` = players.`index`;";
$result = $mysqli->query($query);
if ($mysqli->error) {
trigger_error($mysqli->error);
return null;
}
$records = array();
while ($record = $result->fetch_object()) {
array_push($records, $record);
}
$result->free();
return $records;
}
/**
* Retrieve the local record for the given map and login
*
* @param Map $map
* @param Player $player
* @return mixed
*/
private function getLocalRecord(Map $map, Player $player) {
$mysqli = $this->maniaControl->database->mysqli;
$query = "SELECT records.* FROM (
SELECT recs.*, @rank := @rank + 1 as `rank` FROM `" . self::TABLE_RECORDS . "` recs, (SELECT @rank := 0) ra
WHERE recs.`mapIndex` = {$map->index}
ORDER BY recs.`time` ASC) records
WHERE records.`playerIndex` = {$player->index};";
$result = $mysqli->query($query);
if ($mysqli->error) {
trigger_error("Couldn't retrieve player record for '{$player->login}'." . $mysqli->error);
return null;
}
$record = $result->fetch_object();
$result->free();
return $record;
}
}

View File

@ -1,181 +0,0 @@
<?php
namespace steeffeen;
use ManiaControl\ManiaControl;
use ManiaControl\Admin\AuthenticationManager;
use ManiaControl\Callbacks\CallbackListener;
use ManiaControl\Callbacks\CallbackManager;
use ManiaControl\Commands\CommandListener;
use ManiaControl\Players\Player;
use ManiaControl\Plugins\Plugin;
use Maniaplanet\DedicatedServer\Xmlrpc\Exception;
/**
* ManiaControl Obstacle Plugin
*
* @author steeffeen
*/
class ObstaclePlugin implements CallbackListener, CommandListener, Plugin {
/**
* Constants
*/
const ID = 24;
const VERSION = 0.1;
const CB_JUMPTO = 'Obstacle.JumpTo';
const SCB_ONFINISH = 'OnFinish';
const SCB_ONCHECKPOINT = 'OnCheckpoint';
const SETTING_JUMPTOAUTHLEVEL = 'Authentication level for JumpTo commands';
/**
* Private Properties
*/
/**
* @var maniaControl $maniaControl
*/
private $maniaControl = null;
/**
* Prepares the Plugin
*
* @param ManiaControl $maniaControl
* @return mixed
*/
public static function prepare(ManiaControl $maniaControl) {
// do nothing
}
/**
*
* @see \ManiaControl\Plugins\Plugin::load()
*/
public function load(ManiaControl $maniaControl) {
$this->maniaControl = $maniaControl;
// Init settings
$this->maniaControl->settingManager->initSetting($this, self::SETTING_JUMPTOAUTHLEVEL, AuthenticationManager::AUTH_LEVEL_MODERATOR);
// Register for commands
$this->maniaControl->commandManager->registerCommandListener('jumpto', $this, 'command_JumpTo');
// Register for callbacks
$this->maniaControl->callbackManager->registerScriptCallbackListener(self::SCB_ONFINISH, $this, 'callback_OnFinish');
$this->maniaControl->callbackManager->registerScriptCallbackListener(self::SCB_ONCHECKPOINT, $this, 'callback_OnCheckpoint');
return true;
}
/**
*
* @see \ManiaControl\Plugins\Plugin::unload()
*/
public function unload() {
$this->maniaControl->commandManager->unregisterCommandListener($this);
$this->maniaControl->callbackManager->unregisterScriptCallbackListener($this);
unset($this->maniaControl);
}
/**
*
* @see \ManiaControl\Plugins\Plugin::getId()
*/
public static function getId() {
return self::ID;
}
/**
*
* @see \ManiaControl\Plugins\Plugin::getName()
*/
public static function getName() {
return 'Obstacle Plugin';
}
/**
*
* @see \ManiaControl\Plugins\Plugin::getVersion()
*/
public static function getVersion() {
return self::VERSION;
}
/**
*
* @see \ManiaControl\Plugins\Plugin::getAuthor()
*/
public static function getAuthor() {
return 'steeffeen';
}
/**
*
* @see \ManiaControl\Plugins\Plugin::getDescription()
*/
public static function getDescription() {
return "Plugin offering CP Jumping and Local Records Support for the ShootManie Gamemode 'Obstacle'.";
}
/**
* Handle JumpTo command
*
* @param array $chatCallback
* @param Player $player
* @return bool
*/
public function command_JumpTo(array $chatCallback, Player $player) {
$authLevel = $this->maniaControl->settingManager->getSetting($this, self::SETTING_JUMPTOAUTHLEVEL);
if (!$this->maniaControl->authenticationManager->checkRight($player, $authLevel)) {
$this->maniaControl->authenticationManager->sendNotAllowed($player);
return;
}
// Send jump callback
$params = explode(' ', $chatCallback[1][2], 2);
$param = $player->login . ";" . $params[1] . ";";
try {
$this->maniaControl->client->triggerModeScriptEvent(self::CB_JUMPTO, $param);
}
catch (Exception $e) {
if ($e->getMessage() == 'Not in script mode.') {
trigger_error("Couldn't send jump callback for '{$player->login}'. " . $e->getMessage());
return;
}
throw $e;
}
}
/**
* Handle OnFinish script callback
*
* @param array $callback
*/
public function callback_OnFinish(array $callback) {
$data = json_decode($callback[1]);
$player = $this->maniaControl->playerManager->getPlayer($data->Player->Login);
if (!$player) {
return;
}
$time = $data->Run->Time;
// Trigger trackmania player finish callback
$finishCallback = array($player->pid, $player->login, $time);
$this->maniaControl->callbackManager->triggerCallback(CallbackManager::CB_TM_PLAYERFINISH,
array(CallbackManager::CB_TM_PLAYERFINISH, $finishCallback));
}
/**
* Handle OnCheckpoint script callback
*
* @param array $callback
*/
public function callback_OnCheckpoint(array $callback) {
$data = json_decode($callback[1]);
$player = $this->maniaControl->playerManager->getPlayer($data->Player->Login);
$time = $data->Run->Time;
if (!$player || $time <= 0) {
return;
}
// Trigger Trackmania player checkpoint callback
$checkpointCallback = array($player->pid, $player->login, $time, 0, 0);
$this->maniaControl->callbackManager->triggerCallback(CallbackManager::CB_TM_PLAYERCHECKPOINT,
array(CallbackManager::CB_TM_PLAYERCHECKPOINT, $checkpointCallback));
}
}

View File

@ -1,570 +0,0 @@
<?php
use FML\Controls\Frame;
use FML\Controls\Labels\Label_Button;
use FML\Controls\Labels\Label_Text;
use FML\Controls\Quad;
use FML\Controls\Quads\Quad_Icons64x64_1;
use FML\ManiaLink;
use ManiaControl\Callbacks\CallbackListener;
use ManiaControl\Callbacks\CallbackManager;
use ManiaControl\Callbacks\Callbacks;
use ManiaControl\Callbacks\TimerListener;
use ManiaControl\Commands\CommandListener;
use ManiaControl\ManiaControl;
use ManiaControl\Manialinks\ManialinkPageAnswerListener;
use ManiaControl\Players\Player;
use ManiaControl\Players\PlayerManager;
use ManiaControl\Plugins\Plugin;
use Maniaplanet\DedicatedServer\Xmlrpc\Exception;
/**
* Queue plugin
*
* @author TheM
*/
// TODO: worst kick function
// TODO: idlekick function (?)
class QueuePlugin implements CallbackListener, CommandListener, ManialinkPageAnswerListener, TimerListener, Plugin {
/**
* Constants
*/
const ID = 22;
const VERSION = 0.1;
const ML_ID = 'Queue.Widget';
const ML_ADDTOQUEUE = 'Queue.Add';
const ML_REMOVEFROMQUEUE = 'Queue.Remove';
const QUEUE_MAX = 'Maximum number in the queue';
const QUEUE_WIDGET_POS_X = 'X position of the widget';
const QUEUE_WIDGET_POS_Y = 'Y position of the widget';
const QUEUE_ACTIVE_ON_PASS = 'Activate queue when there is a play password';
const QUEUE_CHATMESSAGES = 'Activate chatmessages on queue join/leave/move to play';
/**
* Private properties
*/
/** @var ManiaControl $maniaControl */
private $maniaControl = null;
private $queue = array();
private $spectators = array();
private $showPlay = array();
private $maxPlayers = 0;
/**
* Prepares the Plugin
*
* @param ManiaControl $maniaControl
* @return mixed
*/
public static function prepare(ManiaControl $maniaControl) {
// TODO: Implement prepare() method.
}
/**
* Load the plugin
*
* @param \ManiaControl\ManiaControl $maniaControl
* @return bool
*/
public function load(ManiaControl $maniaControl) {
$this->maniaControl = $maniaControl;
$this->maniaControl->timerManager->registerTimerListening($this, 'handleEverySecond', 1000);
$this->maniaControl->callbackManager->registerCallbackListener(PlayerManager::CB_PLAYERCONNECT, $this, 'handlePlayerConnect');
$this->maniaControl->callbackManager->registerCallbackListener(PlayerManager::CB_PLAYERDISCONNECT, $this, 'handlePlayerDisconnect');
$this->maniaControl->callbackManager->registerCallbackListener(CallbackManager::CB_MP_PLAYERINFOCHANGED, $this, 'handlePlayerInfoChanged');
$this->maniaControl->callbackManager->registerCallbackListener(Callbacks::BEGINMAP, $this, 'handleBeginMap');
$this->maniaControl->manialinkManager->registerManialinkPageAnswerListener(self::ML_ADDTOQUEUE, $this, 'handleManiaLinkAnswerAdd');
$this->maniaControl->manialinkManager->registerManialinkPageAnswerListener(self::ML_REMOVEFROMQUEUE, $this, 'handleManiaLinkAnswerRemove');
$this->maniaControl->settingManager->initSetting($this, self::QUEUE_MAX, 8);
$this->maniaControl->settingManager->initSetting($this, self::QUEUE_WIDGET_POS_X, 0);
$this->maniaControl->settingManager->initSetting($this, self::QUEUE_WIDGET_POS_Y, -46);
$this->maniaControl->settingManager->initSetting($this, self::QUEUE_ACTIVE_ON_PASS, false);
$this->maniaControl->settingManager->initSetting($this, self::QUEUE_CHATMESSAGES, true);
$maxPlayers = $this->maniaControl->client->getMaxPlayers();
$this->maxPlayers = $maxPlayers['CurrentValue'];
foreach($this->maniaControl->playerManager->getPlayers() as $player) {
if ($player->isSpectator) {
$this->spectators[$player->login] = $player->login;
$this->maniaControl->client->forceSpectator($player->login, 1);
$this->showJoinQueueWidget($player);
}
}
}
/**
* Unload the plugin and its resources
*/
public function unload() {
$this->maniaControl->manialinkManager->unregisterManialinkPageAnswerListener($this);
$this->maniaControl->callbackManager->unregisterCallbackListener($this);
$this->maniaControl->timerManager->unregisterTimerListenings($this);
foreach($this->spectators as $spectator) {
$this->maniaControl->client->forceSpectator($spectator, 3);
$this->maniaControl->client->forceSpectator($spectator, 0);
}
foreach($this->maniaControl->playerManager->getPlayers() as $player) {
$this->hideQueueWidget($player);
}
$this->queue = array();
$this->spectators = array();
$this->showPlay = array();
unset($this->maniaControl);
}
/**
* Get plugin id
*
* @return int
*/
public static function getId() {
return self::ID;
}
/**
* Get Plugin Name
*
* @return string
*/
public static function getName() {
return 'Queue Plugin';
}
/**
* Get Plugin Version
*
* @return float
*/
public static function getVersion() {
return self::VERSION;
}
/**
* Get Plugin Author
*
* @return string
*/
public static function getAuthor() {
return 'TheM';
}
/**
* Get Plugin Description
*
* @return string
*/
public static function getDescription() {
return 'Plugin offers the known AutoQueue/SpecJam options.';
}
/**
* Function handling on the connection of a player.
*
* @param Player $player
*/
public function handlePlayerConnect(Player $player) {
$maxPlayers = $this->maniaControl->client->getMaxPlayers();
$this->maxPlayers = $maxPlayers['CurrentValue'];
if ($player->isSpectator) {
$this->spectators[$player->login] = $player->login;
$this->maniaControl->client->forceSpectator($player->login, 1);
$this->showJoinQueueWidget($player);
} else {
if (count($this->queue) != 0) {
$this->maniaControl->client->forceSpectator($player->login, 1);
$this->spectators[$player->login] = $player->login;
$this->showJoinQueueWidget($player);
}
}
}
/**
* Function handling on the disconnection of a player.
*
* @param Player $player
*/
public function handlePlayerDisconnect(Player $player) {
$maxPlayers = $this->maniaControl->client->getMaxPlayers();
$this->maxPlayers = $maxPlayers['CurrentValue'];
if (isset($this->spectators[$player->login])) {
unset($this->spectators[$player->login]);
}
$this->removePlayerFromQueue($player->login);
$this->moveFirstPlayerToPlay();
}
/**
* Function handling the change of player information.
*
* @param array $callback
*/
public function handlePlayerInfoChanged(array $callback) {
$login = $callback[1][0]['Login'];
$player = $this->maniaControl->playerManager->getPlayer($login);
if (!is_null($player)) {
if ($player->isSpectator) {
if (!isset($this->spectators[$player->login])) {
$this->maniaControl->client->forceSpectator($player->login, 1);
$this->spectators[$player->login] = $player->login;
$this->showJoinQueueWidget($player);
$this->showQueueWidgetSpectators();
}
} else {
$this->removePlayerFromQueue($player->login);
if (isset($this->spectators[$player->login])) {
unset($this->spectators[$player->login]);
}
$found = false;
foreach($this->showPlay as $showPlay) {
if ($showPlay['player']->login == $player->login) {
$found = true;
}
}
if (!$found) {
$this->hideQueueWidget($player);
}
}
}
}
public function showQueueWidgetSpectators() {
foreach($this->spectators as $login) {
$player = $this->maniaControl->playerManager->getPlayer($login);
$this->showJoinQueueWidget($player);
}
}
/**
* Function called on every second.
*/
public function handleEverySecond() {
if ($this->maxPlayers > (count($this->maniaControl->playerManager->players) - count($this->spectators))) {
$this->moveFirstPlayerToPlay();
$this->showQueueWidgetSpectators();
}
foreach($this->showPlay as $showPlay) {
if (($showPlay['time'] + 5) < time()) {
$this->hideQueueWidget($showPlay['player']);
unset($this->showPlay[$showPlay['player']->login]);
}
}
}
/**
* Checks for being of new map to retrieve maximum number of players.
*
* @param $currentMap
*/
public function handleBeginMap($currentMap) {
$maxPlayers = $this->maniaControl->client->getMaxPlayers();
$this->maxPlayers = $maxPlayers['CurrentValue'];
}
/**
* Function handling the click of the widget to add them to the queue.
*
* @param array $chatCallback
* @param Player $player
*/
public function handleManiaLinkAnswerAdd(array $chatCallback, Player $player) {
$this->addPlayerToQueue($player);
}
/**
* Function handling the click of the widget to remove them from the queue.
*
* @param array $chatCallback
* @param Player $player
*/
public function handleManiaLinkAnswerRemove(array $chatCallback, Player $player) {
$this->removePlayerFromQueue($player->login);
$this->showJoinQueueWidget($player);
$this->sendChatMessage('$<$fff' . $player->nickname . '$> has left the queue!');
}
/**
* Function used to move the first queued player to the
*/
private function moveFirstPlayerToPlay() {
if (count($this->queue) > 0) {
$firstPlayer = $this->maniaControl->playerManager->getPlayer($this->queue[0]->login);
$this->forcePlayerToPlay($firstPlayer);
$this->showQueueWidgetSpectators();
}
}
/**
* Function to force a player to play status.
*
* @param Player $player
*/
private function forcePlayerToPlay(Player $player) {
if ($this->maniaControl->client->getServerPassword() != false && $this->maniaControl->settingManager->getSetting($this, self::QUEUE_ACTIVE_ON_PASS) == false) {
return;
}
if ($this->maxPlayers > (count($this->maniaControl->playerManager->players) - count($this->spectators))) {
try {
$this->maniaControl->client->forceSpectator($player->login, 2);
} catch(Exception $e) {
// TODO: only possible valid exception should be "wrong login" - throw others (like connection error)
$this->maniaControl->chat->sendError("Error while leaving the Queue", $player->login);
return;
}
try {
$this->maniaControl->client->forceSpectator($player->login, 0);
} catch(Exception $e) {
// TODO: only possible valid exception should be "wrong login" - throw others (like connection error)
}
$teams = array();
/** @var Player $playerObj */
foreach($this->maniaControl->playerManager->players as $playerObj) {
if (!isset($teams[$playerObj->teamId])) {
$teams[$playerObj->teamId] = 1;
} else {
$teams[$playerObj->teamId]++;
}
}
$smallestTeam = null;
$smallestSize = 999;
foreach($teams as $team => $size) {
if ($size < $smallestSize) {
$smallestTeam = $team;
$smallestSize = $size;
}
}
try {
if ($smallestTeam != -1) {
$this->maniaControl->client->forcePlayerTeam($player->login, $smallestTeam);
}
} catch(Exception $e) {
// TODO: only possible valid exceptions should be "wrong login" or "not in team mode" - throw others (like connection error)
}
if (isset($this->spectators[$player->login])) {
unset($this->spectators[$player->login]);
}
$this->removePlayerFromQueue($player->login);
$this->showPlayWidget($player);
$this->sendChatMessage('$<$fff' . $player->nickname . '$> has a free spot and is now playing!');
}
}
/**
* Function adds a player to the queue.
*
* @param Player $player
* @return bool
*/
private function addPlayerToQueue(Player $player) {
if ($this->maniaControl->client->getServerPassword() != false && $this->maniaControl->settingManager->getSetting($this, self::QUEUE_ACTIVE_ON_PASS) == false) {
return false;
}
foreach($this->queue as $queuedPlayer) {
if ($queuedPlayer->login == $player->login) {
$this->maniaControl->chat->sendError('You\'re already in the queue!', $player->login);
return false;
}
}
if ($this->maniaControl->settingManager->getSetting($this, self::QUEUE_MAX) > count($this->queue)) {
$this->queue[count($this->queue)] = $player;
$this->sendChatMessage('$<$fff' . $player->nickname . '$> just joined the queue!');
}
$this->showQueueWidgetSpectators();
return true;
}
/**
* Function removes a player from the queue.
*
* @param $login
*/
private function removePlayerFromQueue($login) {
$count = 0;
$newQueue = array();
foreach($this->queue as $queuePlayer) {
if ($queuePlayer->login != $login) {
$newQueue[$count] = $queuePlayer;
$count++;
}
}
$this->queue = $newQueue;
$this->showQueueWidgetSpectators();
}
/**
* Function sends (or not depending on setting) chatmessages for the queue.
*
* @param $message
*/
private function sendChatMessage($message) {
if ($this->maniaControl->settingManager->getSetting($this, self::QUEUE_CHATMESSAGES)) {
$this->maniaControl->chat->sendChat('$090[Queue] ' . $message);
}
}
/**
* Function shows the join queue widget to a player.
*
* @param Player $player
*/
private function showJoinQueueWidget(Player $player) {
$maniaLink = new ManiaLink(self::ML_ID);
$quadStyle = $this->maniaControl->manialinkManager->styleManager->getDefaultMainWindowStyle();
$quadSubstyle = $this->maniaControl->manialinkManager->styleManager->getDefaultMainWindowSubStyle();
$max_queue = $this->maniaControl->settingManager->getSetting($this, self::QUEUE_MAX);
// Main frame
$frame = new Frame();
$maniaLink->add($frame);
$frame->setSize(60, 6);
$frame->setPosition($this->maniaControl->settingManager->getSetting($this, self::QUEUE_WIDGET_POS_X), $this->maniaControl->settingManager->getSetting($this, self::QUEUE_WIDGET_POS_Y), 0);
// Background
$backgroundQuad = new Quad();
$frame->add($backgroundQuad);
$backgroundQuad->setPosition(0, 0, 0);
$backgroundQuad->setSize(70, 10);
$backgroundQuad->setStyles($quadStyle, $quadSubstyle);
$cameraQuad = new Quad_Icons64x64_1();
$frame->add($cameraQuad);
$cameraQuad->setPosition(-29, 0.4, 2);
$cameraQuad->setSize(9, 9);
$cameraQuad->setSubStyle(Quad_Icons64x64_1::SUBSTYLE_Camera);
$statusLabel = new Label_Text();
$frame->add($statusLabel);
$statusLabel->setPosition(4.5, 2.8, 1);
$statusLabel->setSize(66, 4);
$statusLabel->setAlign('center', 'center');
$statusLabel->setScale(0.8);
$statusLabel->setStyle(Label_Text::STYLE_TextStaticSmall);
$messageLabel = new Label_Button();
$frame->add($messageLabel);
$messageLabel->setPosition(4.5, -1.6, 1);
$messageLabel->setSize(56, 4);
$messageLabel->setAlign('center', 'center');
$messageLabel->setScale(1.0);
$inQueue = false;
foreach($this->queue as $queuedPlayer) {
if ($queuedPlayer->login == $player->login) {
$inQueue = true;
}
}
if ($inQueue) {
$message = '$fff$sYou\'re in the queue (click to unqueue).';
$position = 0;
foreach(array_values($this->queue) as $i => $queuePlayer) {
if ($player->login == $queuePlayer->login) {
$position = ($i + 1);
}
}
$statusLabel->setText('$aaaStatus: In queue (' . $position . '/' . count($this->queue) . ') Waiting: ' . count($this->queue) . '/' . $max_queue . '');
$messageLabel->setAction(self::ML_REMOVEFROMQUEUE);
$backgroundQuad->setAction(self::ML_REMOVEFROMQUEUE);
$statusLabel->setAction(self::ML_REMOVEFROMQUEUE);
$cameraQuad->setAction(self::ML_REMOVEFROMQUEUE);
} else {
if (count($this->queue) < $max_queue) {
$message = '$0ff$sClick to join spectator waiting list.';
$messageLabel->setAction(self::ML_ADDTOQUEUE);
$backgroundQuad->setAction(self::ML_ADDTOQUEUE);
$statusLabel->setAction(self::ML_ADDTOQUEUE);
$cameraQuad->setAction(self::ML_ADDTOQUEUE);
} else {
$message = '$f00The waiting list is full!';
}
$statusLabel->setText('$aaaStatus: Not queued spectator Waiting: ' . count($this->queue) . '/' . $max_queue . '');
}
$messageLabel->setText($message);
$messageLabel->setStyle(Label_Text::STYLE_TextStaticSmall);
$this->maniaControl->manialinkManager->sendManialink($maniaLink, $player->login);
}
/**
* Function shows the "You got a free spot, enjoy playing!" widget.
*
* @param Player $player
*/
private function showPlayWidget(Player $player) {
$maniaLink = new ManiaLink(self::ML_ID);
$quadStyle = $this->maniaControl->manialinkManager->styleManager->getDefaultMainWindowStyle();
$quadSubstyle = $this->maniaControl->manialinkManager->styleManager->getDefaultMainWindowSubStyle();
// Main frame
$frame = new Frame();
$maniaLink->add($frame);
$frame->setSize(60, 6);
$frame->setPosition($this->maniaControl->settingManager->getSetting($this, self::QUEUE_WIDGET_POS_X), $this->maniaControl->settingManager->getSetting($this, self::QUEUE_WIDGET_POS_Y), 0);
// Background
$backgroundQuad = new Quad();
$frame->add($backgroundQuad);
$backgroundQuad->setPosition(0, 0, 0);
$backgroundQuad->setSize(70, 10);
$backgroundQuad->setStyles($quadStyle, $quadSubstyle);
$cameraQuad = new Quad_Icons64x64_1();
$frame->add($cameraQuad);
$cameraQuad->setPosition(-29, 0.4, 2);
$cameraQuad->setSize(9, 9);
$cameraQuad->setSubStyle(Quad_Icons64x64_1::SUBSTYLE_Camera);
$messageLabel = new Label_Button();
$frame->add($messageLabel);
$messageLabel->setPosition(4.5, 0.6, 1);
$messageLabel->setSize(56, 4);
$messageLabel->setAlign('center', 'center');
$messageLabel->setScale(1.0);
$messageLabel->setText('$090You got a free spot, enjoy playing!');
$messageLabel->setStyle(Label_Text::STYLE_TextStaticSmall);
$this->maniaControl->manialinkManager->sendManialink($maniaLink, $player->login);
$this->showPlay[$player->login] = array('time' => time(), 'player' => $player);
}
/**
* Function hides the queue widget from the player.
*
* @param Player $player
*/
private function hideQueueWidget(Player $player) {
$maniaLink = new ManiaLink(self::ML_ID);
$this->maniaControl->manialinkManager->sendManialink($maniaLink, $player->login);
}
}

View File

@ -1,461 +0,0 @@
<?php
namespace MCTeam;
use ManiaControl\Callbacks\CallbackListener;
use ManiaControl\Callbacks\Callbacks;
use ManiaControl\Commands\CommandListener;
use ManiaControl\ManiaControl;
use ManiaControl\Maps\Map;
use ManiaControl\Maps\MapManager;
use ManiaControl\Players\Player;
use ManiaControl\Players\PlayerManager;
use ManiaControl\Plugins\Plugin;
use ManiaControl\Statistics\StatisticCollector;
use ManiaControl\Statistics\StatisticManager;
use Maniaplanet\DedicatedServer\Structures\AbstractStructure;
/**
* ManiaControl ServerRanking Plugin
*
* @author kremsy
* @copyright ManiaControl Copyright © 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/
class ServerRankingPlugin implements Plugin, CallbackListener, CommandListener {
/**
* Constants
*/
const PLUGIN_ID = 6;
const PLUGIN_VERSION = 0.1;
const PLUGIN_NAME = 'ServerRankingPlugin';
const PLUGIN_AUTHOR = 'kremsy';
const TABLE_RANK = 'mc_rank';
const RANKING_TYPE_RECORDS = 'Records';
const RANKING_TYPE_RATIOS = 'Ratios';
const RANKING_TYPE_POINTS = 'Points';
const SETTING_MIN_RANKING_TYPE = 'ServerRankings Type Records/Points/Ratios';
const SETTING_MIN_HITS_RATIO_RANKING = 'Min Hits on Ratio Rankings';
const SETTING_MIN_HITS_POINTS_RANKING = 'Min Hits on Points Rankings';
const SETTING_MIN_REQUIRED_RECORDS = 'Minimum amount of records required on Records Ranking';
const SETTING_MAX_STORED_RECORDS = 'Maximum number of records per map for calculations';
const CB_RANK_BUILT = 'ServerRankingPlugin.RankBuilt';
/**
* Private Properties
*/
/** @var maniaControl $maniaControl * */
private $maniaControl = null;
private $recordCount = 0;
/**
* Prepares the Plugin
*
* @param ManiaControl $maniaControl
* @return mixed
*/
public static function prepare(ManiaControl $maniaControl) {
//Todo
}
/**
* Load the plugin
*
* @param \ManiaControl\ManiaControl $maniaControl
* @return bool
*/
public function load(ManiaControl $maniaControl) {
$this->maniaControl = $maniaControl;
$this->initTables();
$maniaControl->settingManager->initSetting($this, self::SETTING_MIN_HITS_RATIO_RANKING, 100);
$maniaControl->settingManager->initSetting($this, self::SETTING_MIN_HITS_POINTS_RANKING, 15);
$maniaControl->settingManager->initSetting($this, self::SETTING_MIN_REQUIRED_RECORDS, 3);
$maniaControl->settingManager->initSetting($this, self::SETTING_MAX_STORED_RECORDS, 50);
$script = $this->maniaControl->client->getScriptName();
if ($this->maniaControl->mapManager->getCurrentMap()->getGame() == 'tm') {
//TODO also add obstacle here as default
$maniaControl->settingManager->initSetting($this, self::SETTING_MIN_RANKING_TYPE, self::RANKING_TYPE_RECORDS);
} else if ($script["CurrentValue"] == "InstaDM.Script.txt") {
$maniaControl->settingManager->initSetting($this, self::SETTING_MIN_RANKING_TYPE, self::RANKING_TYPE_RATIOS);
} else {
$maniaControl->settingManager->initSetting($this, self::SETTING_MIN_RANKING_TYPE, self::RANKING_TYPE_POINTS);
}
//Check if the type is Correct
$type = $this->maniaControl->settingManager->getSetting($this, self::SETTING_MIN_RANKING_TYPE);
if ($type != self::RANKING_TYPE_RECORDS && $type != self::RANKING_TYPE_POINTS && $type != self::RANKING_TYPE_RATIOS) {
$error = 'Ranking Type is not correct, possible values(' . self::RANKING_TYPE_RATIOS . ', ' . self::RANKING_TYPE_POINTS . ', ' . self::RANKING_TYPE_POINTS . ')';
throw new Exception($error);
}
//Register CallbackListeners
$this->maniaControl->callbackManager->registerCallbackListener(PlayerManager::CB_PLAYERCONNECT, $this, 'handlePlayerConnect');
$this->maniaControl->callbackManager->registerCallbackListener(Callbacks::ENDMAP, $this, 'handleEndMap');
//Register CommandListener
$this->maniaControl->commandManager->registerCommandListener('rank', $this, 'command_showRank', false, 'Shows your current serverrank.');
$this->maniaControl->commandManager->registerCommandListener('nextrank', $this, 'command_nextRank', false, 'Shows the person in front of you in the serverranking.');
$this->resetRanks(); //TODO only update records count
}
/**
* Unload the plugin and its resources
*/
public function unload() {
$this->maniaControl->callbackManager->unregisterCallbackListener($this);
$this->maniaControl->commandManager->unregisterCommandListener($this);
}
/**
* Get plugin id
*
* @return int
*/
public static function getId() {
return self::PLUGIN_ID;
}
/**
* Get Plugin Name
*
* @return string
*/
public static function getName() {
return self::PLUGIN_NAME;
}
/**
* Get Plugin Version
*
* @return float
*/
public static function getVersion() {
return self::PLUGIN_VERSION;
}
/**
* Get Plugin Author
*
* @return string
*/
public static function getAuthor() {
return self::PLUGIN_AUTHOR;
}
/**
* Get Plugin Description
*
* @return string
*/
public static function getDescription() {
return "ServerRanking Plugin, ServerRanking by an avg build from the records, per count of points, or by a multiplication from Kill/Death Ratio and Laser accuracy";
}
/**
* Create necessary database tables
*/
private function initTables() {
$mysqli = $this->maniaControl->database->mysqli;
$query = "CREATE TABLE IF NOT EXISTS `" . self::TABLE_RANK . "` (
`PlayerIndex` mediumint(9) NOT NULL default 0,
`Rank` mediumint(9) NOT NULL default 0,
`Avg` float NOT NULL default 0,
KEY `PlayerIndex` (`PlayerIndex`),
UNIQUE `Rank` (`Rank`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='Mania Control Serverranking';";
$mysqli->query($query);
if ($mysqli->error) {
trigger_error($mysqli->error, E_USER_ERROR);
}
}
/**
* Resets and rebuilds the Ranking
*/
private function resetRanks() {
$mysqli = $this->maniaControl->database->mysqli;
// Erase old Average Data
$mysqli->query('TRUNCATE TABLE ' . self::TABLE_RANK);
$type = $this->maniaControl->settingManager->getSetting($this, self::SETTING_MIN_RANKING_TYPE);
switch($type) {
case self::RANKING_TYPE_RATIOS:
$minHits = $this->maniaControl->settingManager->getSetting($this, self::SETTING_MIN_HITS_RATIO_RANKING);
$hits = $this->maniaControl->statisticManager->getStatsRanking(StatisticCollector::STAT_ON_HIT, -1, $minHits);
$killDeathRatios = $this->maniaControl->statisticManager->getStatsRanking(StatisticManager::SPECIAL_STAT_KD_RATIO);
$accuracies = $this->maniaControl->statisticManager->getStatsRanking(StatisticManager::SPECIAL_STAT_LASER_ACC);
$ranks = array();
foreach($hits as $player => $hitCount) {
if (!isset($killDeathRatios[$player]) || !isset($accuracies[$player])) {
continue;
}
$ranks[$player] = $killDeathRatios[$player] * $accuracies[$player] * 1000;
}
arsort($ranks);
break;
case self::RANKING_TYPE_POINTS:
$minHits = $this->maniaControl->settingManager->getSetting($this, self::SETTING_MIN_HITS_POINTS_RANKING);
$ranks = $this->maniaControl->statisticManager->getStatsRanking(StatisticCollector::STAT_ON_HIT, -1, $minHits);
break;
case self::RANKING_TYPE_RECORDS: //TODO verify workable status
if (!$this->maniaControl->pluginManager->isPluginActive('MCTeam\LocalRecordsPlugin')) {
return;
}
$requiredRecords = $this->maniaControl->settingManager->getSetting($this, self::SETTING_MIN_REQUIRED_RECORDS);
$maxRecords = $this->maniaControl->settingManager->getSetting($this, self::SETTING_MAX_STORED_RECORDS);
$query = 'SELECT playerIndex, COUNT(*) AS Cnt
FROM ' . \MCTeam\LocalRecordsPlugin::TABLE_RECORDS . '
GROUP BY PlayerIndex
HAVING Cnt >=' . $requiredRecords;
$result = $mysqli->query($query);
$players = array();
while($row = $result->fetch_object()) {
$players[$row->playerIndex] = array(0, 0); //sum, count
}
$result->free_result();
/** @var \MCTeam\LocalRecordsPlugin $localRecordsPlugin */
$localRecordsPlugin = $this->maniaControl->pluginManager->getPlugin('MCTeam\LocalRecordsPlugin');
$maps = $this->maniaControl->mapManager->getMaps();
foreach($maps as $map) {
$records = $localRecordsPlugin->getLocalRecords($map, $maxRecords);
$i = 1;
foreach($records as $record) {
if (isset($players[$record->playerIndex])) {
$players[$record->playerIndex][0] += $i;
$players[$record->playerIndex][1]++;
}
$i++;
}
}
$mapCount = count($maps);
//compute each players new average score
$ranks = array();
foreach($players as $player => $val) {
$sum = $val[0];
$cnt = $val[1];
// ranked maps sum + $maxRecs rank for all remaining maps
$ranks[$player] = ($sum + ($mapCount - $cnt) * $maxRecords) / $mapCount;
}
asort($ranks);
break;
}
if (empty($ranks)) {
return;
}
$this->recordCount = count($ranks);
//Compute each player's new average score
$query = "INSERT INTO " . self::TABLE_RANK . " VALUES ";
$i = 1;
foreach($ranks as $player => $rankValue) {
$query .= '(' . $player . ',' . $i . ',' . $rankValue . '),';
$i++;
}
$query = substr($query, 0, strlen($query) - 1); // strip trailing ','
$mysqli->query($query);
}
/**
* Handle PlayerConnect callback
*
* @param Player $player
*/
public function handlePlayerConnect(Player $player) {
$this->showRank($player);
$this->showNextRank($player);
}
/**
* Shows Ranks on endMap
*
* @param Map $map
*/
public function handleEndMap(Map $map) {
$this->resetRanks();
foreach($this->maniaControl->playerManager->getPlayers() as $player) {
/** @var Player $player */
if ($player->isFakePlayer()) {
continue;
}
$this->showRank($player);
$this->showNextRank($player);
}
// Trigger callback
$this->maniaControl->callbackManager->triggerCallback(self::CB_RANK_BUILT);
}
/**
* Shows the serverRank to a certain Player
*
* @param Player $player
*/
public function showRank(Player $player) {
$rankObj = $this->getRank($player);
$type = $this->maniaControl->settingManager->getSetting($this, self::SETTING_MIN_RANKING_TYPE);
$message = '';
if ($rankObj) {
switch($type) {
case self::RANKING_TYPE_RATIOS:
$kd = $this->maniaControl->statisticManager->getStatisticData(StatisticManager::SPECIAL_STAT_KD_RATIO, $player->index);
$acc = $this->maniaControl->statisticManager->getStatisticData(StatisticManager::SPECIAL_STAT_LASER_ACC, $player->index);
$message = '$0f3Your Server rank is $<$ff3' . $rankObj->rank . '$> / $<$fff' . $this->recordCount . '$> (K/D: $<$fff' . round($kd, 2) . '$> Acc: $<$fff' . round($acc * 100) . '%$>)';
break;
case self::RANKING_TYPE_POINTS:
$message = '$0f3Your Server rank is $<$ff3' . $rankObj->rank . '$> / $<$fff' . $this->recordCount . '$> Points: $fff' . $rankObj->avg;
break;
case self::RANKING_TYPE_RECORDS:
$message = '$0f3Your Server rank is $<$ff3' . $rankObj->rank . '$> / $<$fff' . $this->recordCount . '$> Avg: $fff' . round($rankObj->avg, 2);
}
} else {
switch($type) {
case self::RANKING_TYPE_RATIOS:
$minHits = $this->maniaControl->settingManager->getSetting($this, self::SETTING_MIN_HITS_RATIO_RANKING);
$message = '$0f3 You must make $<$fff' . $minHits . '$> Hits on this server before receiving a rank...';
break;
case self::RANKING_TYPE_POINTS:
$minHits = $this->maniaControl->settingManager->getSetting($this, self::SETTING_MIN_HITS_POINTS_RANKING);
$message = '$0f3 You must make $<$fff' . $minHits . '$> Hits on this server before receiving a rank...';
break;
case self::RANKING_TYPE_RECORDS:
$minHits = $this->maniaControl->settingManager->getSetting($this, self::SETTING_MIN_REQUIRED_RECORDS);
$message = '$0f3 You need $<$fff' . $minHits . '$> Records on this server before receiving a rank...';
}
}
$this->maniaControl->chat->sendChat($message, $player->login);
}
/**
* Gets A Rank As Object with properties Avg PlayerIndex and Rank
*
* @param Player $player
* @return Rank $rank
*/
private function getRank(Player $player) {
//TODO setting global from db or local
$mysqli = $this->maniaControl->database->mysqli;
$result = $mysqli->query('SELECT * FROM ' . self::TABLE_RANK . ' WHERE PlayerIndex=' . $player->index);
if ($mysqli->error) {
trigger_error($mysqli->error);
return null;
}
if ($result->num_rows <= 0) {
$result->free_result();
return null;
}
$row = $result->fetch_array();
$result->free_result();
return Rank::fromArray($row);
}
/**
* Get the Next Ranked Player
*
* @param Player $player
* @return Rank
*/
private function getNextRank(Player $player) {
$mysqli = $this->maniaControl->database->mysqli;
$rankObject = $this->getRank($player);
$nextRank = $rankObject->rank - 1;
$result = $mysqli->query('SELECT * FROM ' . self::TABLE_RANK . ' WHERE Rank=' . $nextRank);
if ($result->num_rows > 0) {
$row = $result->fetch_array();
$result->free_result();
return Rank::fromArray($row);
} else {
$result->free_result();
return null;
}
}
/**
* Shows the current Server-Rank
*
* @param array $chatCallback
* @param Player $player
*/
public function command_showRank(array $chatCallback, Player $player) {
$this->showRank($player);
}
/**
* Show the next better ranked player
*
* @param array $chatCallback
* @param Player $player
*/
public function command_nextRank(array $chatCallback, Player $player) {
if (!$this->showNextRank($player)) {
$message = '$0f3You need to have a ServerRank first!';
$this->maniaControl->chat->sendChat($message, $player->login);
}
}
/**
* Shows which Player is next ranked to you
*
* @param Player $player
*/
public function showNextRank(Player $player) {
$rankObject = $this->getRank($player);
if ($rankObject) {
if ($rankObject->rank > 1) {
$nextRank = $this->getNextRank($player);
$nextPlayer = $this->maniaControl->playerManager->getPlayerByIndex($nextRank->playerIndex);
$message = '$0f3The next better ranked player is $fff' . $nextPlayer->nickname;
} else {
$message = '$0f3No better ranked player :-)';
}
$this->maniaControl->chat->sendChat($message, $player->login);
return true;
}
return false;
}
}
/**
* Rank Structure
*/
class Rank extends AbstractStructure {
public $playerIndex;
public $rank;
public $avg;
}

View File

@ -1,514 +0,0 @@
<?php
use FML\Controls\Frame;
use FML\Controls\Labels\Label_Button;
use FML\Controls\Labels\Label_Text;
use FML\Controls\Quad;
use FML\Controls\Quads\Quad_Icons64x64_1;
use FML\ManiaLink;
use ManiaControl\Callbacks\CallbackListener;
use ManiaControl\Callbacks\TimerListener;
use ManiaControl\Commands\CommandListener;
use ManiaControl\ManiaControl;
use ManiaControl\Manialinks\ManialinkManager;
use ManiaControl\Manialinks\ManialinkPageAnswerListener;
use ManiaControl\Players\Player;
use ManiaControl\Plugins\Plugin;
/**
* TeamSpeak Info plugin
* Based on the TeamSpeak Info plugin created by undef.de:
* http://forum.maniaplanet.com/viewtopic.php?f=450&t=24805
*
* @author TheM
*/
class TeamSpeakPlugin implements CallbackListener, CommandListener, ManialinkPageAnswerListener, TimerListener, Plugin {
/**
* Constants
*/
const ID = 23;
const VERSION = 0.1;
const TEAMSPEAK_SID = 'TS Server ID';
const TEAMSPEAK_SERVERHOST = 'TS Server host';
const TEAMSPEAK_SERVERPORT = 'TS Server port';
const TEAMSPEAK_QUERYHOST = 'TS Server Query host';
const TEAMSPEAK_QUERYPORT = 'TS Server Query port';
const TEAMSPEAK_QUERYUSER = 'TS Server Query user';
const TEAMSPEAK_QUERYPASS = 'TS Server Query password';
const ACTION_OPEN_TSVIEWER = 'TSViewer.OpenWidget';
const TS_ICON = 'Teamspeak.png';
const TS_ICON_MOVER = 'Teamspeak_logo_press.png';
/**
* Private properties
*/
/** @var ManiaControl $maniaControl */
private $maniaControl = null;
private $serverData = array();
private $refreshTime = 0;
private $refreshInterval = 90;
/**
* Prepares the Plugin (Init Settings)
*
* @param ManiaControl $maniaControl
* @return mixed
*/
public static function prepare(ManiaControl $maniaControl) {
$maniaControl->settingManager->initSetting(get_class(), self::TEAMSPEAK_SID, 1);
$maniaControl->settingManager->initSetting(get_class(), self::TEAMSPEAK_SERVERHOST, 'ts3.somehoster.com');
$maniaControl->settingManager->initSetting(get_class(), self::TEAMSPEAK_SERVERPORT, 9987);
$maniaControl->settingManager->initSetting(get_class(), self::TEAMSPEAK_QUERYHOST, '');
$maniaControl->settingManager->initSetting(get_class(), self::TEAMSPEAK_QUERYPORT, 10011);
$maniaControl->settingManager->initSetting(get_class(), self::TEAMSPEAK_QUERYUSER, '');
$maniaControl->settingManager->initSetting(get_class(), self::TEAMSPEAK_QUERYPASS, '');
}
/**
* Load the plugin
*
* @param \ManiaControl\ManiaControl $maniaControl
* @return bool
*/
public function load(ManiaControl $maniaControl) {
$this->maniaControl = $maniaControl;
$this->checkConfig();
$this->refreshTime = time();
$this->maniaControl->manialinkManager->iconManager->addIcon(self::TS_ICON);
$this->maniaControl->manialinkManager->iconManager->addIcon(self::TS_ICON_MOVER);
$this->maniaControl->timerManager->registerTimerListening($this, 'ts3_queryServer', 1000);
$this->addToMenu();
}
/**
* Function used to check certain configuration options to check if they can be used.
*
* @throws Exception
*/
private function checkConfig() {
if ($this->maniaControl->settingManager->getSetting($this, self::TEAMSPEAK_SERVERHOST) == 'ts3.somehoster.com') {
$error = 'Missing the required serverhost, please set it up before enabling the TeamSpeak plugin!';
throw new Exception($error);
}
$this->ts3_queryServer(); // Get latest information from the TeamSpeak server
if (!isset($this->serverData['channels']) || count($this->serverData['channels']) == 0) {
$error = 'Could not make proper connections with the server!';
throw new Exception($error);
}
}
/**
* Function used insert the icon into the menu.
*/
private function addToMenu() {
$this->maniaControl->manialinkManager->registerManialinkPageAnswerListener(self::ACTION_OPEN_TSVIEWER, $this, 'command_tsViewer');
$itemQuad = new Quad();
$itemQuad->setImage($this->maniaControl->manialinkManager->iconManager->getIcon(self::TS_ICON));
$itemQuad->setImageFocus($this->maniaControl->manialinkManager->iconManager->getIcon(self::TS_ICON_MOVER));
$itemQuad->setAction(self::ACTION_OPEN_TSVIEWER);
$this->maniaControl->actionsMenu->addMenuItem($itemQuad, true, 1, 'Open TeamSpeak Viewer');
}
/**
* Unload the plugin and its resources
*/
public function unload() {
$this->serverData = array();
$this->maniaControl->actionsMenu->removeMenuItem(1, true);
$this->maniaControl->manialinkManager->unregisterManialinkPageAnswerListener($this);
$this->maniaControl->callbackManager->unregisterCallbackListener($this);
$this->maniaControl->commandManager->unregisterCommandListener($this);
$this->maniaControl->timerManager->unregisterTimerListenings($this);
unset($this->maniaControl);
}
/**
* Get plugin id
*
* @return int
*/
public static function getId() {
return self::ID;
}
/**
* Get Plugin Name
*
* @return string
*/
public static function getName() {
return 'TeamSpeak Plugin';
}
/**
* Get Plugin Version
*
* @return float
*/
public static function getVersion() {
return self::VERSION;
}
/**
* Get Plugin Author
*
* @return string
*/
public static function getAuthor() {
return 'TheM';
}
/**
* Get Plugin Description
*
* @return string
*/
public static function getDescription() {
return 'Plugin offers a connection with a TeamSpeak server (via widgets).';
}
/**
* Function handling the pressing of the icon.
*
* @param array $chatCallback
* @param Player $player
*/
public function command_tsViewer(array $chatCallback, Player $player) {
$this->showWidget($player);
}
/**
* Function showing the TeamSpeak widget to the player.
*
* @param $player
*/
private function showWidget($player) {
$width = $this->maniaControl->manialinkManager->styleManager->getListWidgetsWidth();
$height = $this->maniaControl->manialinkManager->styleManager->getListWidgetsHeight();
$quadStyle = $this->maniaControl->manialinkManager->styleManager->getDefaultMainWindowStyle();
$quadSubstyle = $this->maniaControl->manialinkManager->styleManager->getDefaultMainWindowSubStyle();
$maniaLink = new ManiaLink(ManialinkManager::MAIN_MLID);
// Main frame
$frame = new Frame();
$maniaLink->add($frame);
$frame->setSize($width, $height);
$frame->setPosition(0, 0, 10);
// Background
$backgroundQuad = new Quad();
$frame->add($backgroundQuad);
$backgroundQuad->setSize($width, $height);
$backgroundQuad->setStyles($quadStyle, $quadSubstyle);
// Close Quad (X)
$closeQuad = new Quad_Icons64x64_1();
$frame->add($closeQuad);
$closeQuad->setPosition($width * 0.483, $height * 0.467, 3);
$closeQuad->setSize(6, 6);
$closeQuad->setSubStyle(Quad_Icons64x64_1::SUBSTYLE_QuitRace);
$closeQuad->setAction(ManialinkManager::ACTION_CLOSEWIDGET);
$servername = new Label_Text();
$frame->add($servername);
$servername->setY($height / 2 - 4);
$servername->setX(-70);
$servername->setStyle($servername::STYLE_TextCardMedium);
$servername->setHAlign('left');
$servername->setTextSize(1);
$servername->setText('$oServername:$o ' . $this->serverData['server']['virtualserver_name']);
$servername->setTextColor('fff');
$serverversion = new Label_Text();
$frame->add($serverversion);
$serverversion->setY($height / 2 - 4);
$serverversion->setX(2);
$serverversion->setStyle($serverversion::STYLE_TextCardMedium);
$serverversion->setHAlign('left');
$serverversion->setTextSize(1);
$serverversion->setText('$oServerversion:$o ' . $this->serverData['server']['virtualserver_version']);
$serverversion->setTextColor('fff');
$clients = new Label_Text();
$frame->add($clients);
$clients->setY($height / 2 - 7);
$clients->setX(-70);
$clients->setStyle($clients::STYLE_TextCardMedium);
$clients->setHAlign('left');
$clients->setTextSize(1);
$clients->setText('$oConnected clients:$o ' . $this->serverData['server']['virtualserver_clientsonline'] . '/' . $this->serverData['server']['virtualserver_maxclients']);
$clients->setTextColor('fff');
$channels = new Label_Text();
$frame->add($channels);
$channels->setY($height / 2 - 7);
$channels->setX(2);
$channels->setStyle($channels::STYLE_TextCardMedium);
$channels->setHAlign('left');
$channels->setTextSize(1);
$nochannels = 0;
foreach($this->serverData['channels'] as $channel) {
if ($channel['channel_maxclients'] == 0 || strpos($channel['channel_name'], 'spacer') > 0) {
continue;
}
$nochannels++;
}
$channels->setText('$oChannels:$o ' . $nochannels);
$channels->setTextColor('fff');
// Join button
$joinbutton = new Label_Button();
$frame->add($joinbutton);
$joinbutton->setWidth(150);
$joinbutton->setY($height / 2 - 11.5);
$joinbutton->setStyle($joinbutton::STYLE_CardButtonSmallWide);
$joinbutton->setText('Join TeamSpeak: ' . $this->maniaControl->settingManager->getSetting($this, self::TEAMSPEAK_SERVERHOST) . ':' . $this->maniaControl->settingManager->getSetting($this, self::TEAMSPEAK_SERVERPORT));
$joinbutton->setTextColor('fff');
$url = 'ts3server://' . $this->maniaControl->settingManager->getSetting($this, self::TEAMSPEAK_SERVERHOST) . '/?port=' . $this->maniaControl->settingManager->getSetting($this, self::TEAMSPEAK_SERVERPORT) . '&nickname=' . rawurlencode(\ManiaControl\Formatter::stripCodes($player->nickname));
$joinbutton->setUrl($url);
$leftlistQuad = new Quad();
$frame->add($leftlistQuad);
$leftlistQuad->setSize((($width / 2) - 5), ($height - 18));
$leftlistQuad->setX(-36);
$leftlistQuad->setY($height / 2 - 46);
$leftlistQuad->setStyles($quadStyle, $quadSubstyle);
$channels = array();
$users = array();
$userid = 0;
$i = 0;
$startx = -69.5;
foreach($this->serverData['channels'] as $channel) {
if ($channel['channel_maxclients'] == 0 || strpos($channel['channel_name'], 'spacer') > 0) {
continue;
}
$channelLabel = new Label_Text();
$frame->add($channelLabel);
$y = 17.5 + ($i * 2.5);
$channelLabel->setY($height / 2 - $y);
$x = $startx;
if ($channel['pid'] != 0) {
$x = $startx + 5;
}
$channelLabel->setX($x);
$channelLabel->setStyle($channelLabel::STYLE_TextCardMedium);
$channelLabel->setHAlign('left');
$channelLabel->setTextSize(1);
$channelLabel->setScale(0.9);
if ($channel['channel_flag_default'] == 1) {
$channel['total_clients'] = ($channel['total_clients'] - 1);
} // remove query client
$channelLabel->setText('$o' . $channel['channel_name'] . '$o (' . $channel['total_clients'] . ')');
$channelLabel->setTextColor('fff');
$channels[$i] = $channelLabel;
$i++;
foreach($this->serverData['users'] as $user) {
if ($user['cid'] == $channel['cid']) {
$userLabel = new Label_Text();
$frame->add($userLabel);
$y = 17.5 + ($i * 2.5);
$userLabel->setY($height / 2 - $y);
if ($channel['pid'] != 0) {
$x = $startx + 7;
} else {
$x = $startx + 2;
}
$userLabel->setX($x);
$userLabel->setStyle($userLabel::STYLE_TextCardMedium);
$userLabel->setHAlign('left');
$userLabel->setTextSize(1);
$userLabel->setScale(0.9);
$userLabel->setText($user['client_nickname']);
$userLabel->setTextColor('fff');
$users[$userid] = $userLabel;
$userid++;
$i++;
if ($i > 22) {
$i = 0;
$startx = 2.5;
}
}
}
if ($i > 22) {
$i = 0;
$startx = 2.5;
}
}
$rightlistQuad = new Quad();
$frame->add($rightlistQuad);
$rightlistQuad->setSize((($width / 2) - 5), ($height - 18));
$rightlistQuad->setX(36);
$rightlistQuad->setY($height / 2 - 46);
$rightlistQuad->setStyles($quadStyle, $quadSubstyle);
$this->maniaControl->manialinkManager->displayWidget($maniaLink, $player, 'TSViewer');
}
/**
* TeamSpeak related functions
* The functions are based upon tsstatus.php from http://tsstatus.sebastien.me/
* and were optimized by SilentStorm.
* Functions originally from the TeamSpeakInfo plugin made by undef.de for XAseco(2) and MPAseco.
*/
public function ts3_queryServer() {
if (time() >= $this->refreshTime) {
$this->refreshTime = (time() + $this->refreshInterval);
$queryhost = $this->maniaControl->settingManager->getSetting($this, self::TEAMSPEAK_QUERYHOST);
$host = $this->maniaControl->settingManager->getSetting($this, self::TEAMSPEAK_SERVERHOST);
$host = ($queryhost != '') ? $queryhost : $host;
$socket = fsockopen(@$host, $this->maniaControl->settingManager->getSetting($this, self::TEAMSPEAK_QUERYPORT), $errno, $errstr, 2);
if ($socket) {
socket_set_timeout($socket, 2);
$is_ts3 = trim(fgets($socket)) == 'TS3';
if (!$is_ts3) {
trigger_error('[TeamSpeakPlugin] Server at "' . $host . '" is not a Teamspeak3-Server or you have setup a bad query-port!', E_USER_WARNING);
}
$queryuser = $this->maniaControl->settingManager->getSetting($this, self::TEAMSPEAK_QUERYUSER);
$querypass = $this->maniaControl->settingManager->getSetting($this, self::TEAMSPEAK_QUERYPASS);
if (($queryuser != '') && !is_numeric($queryuser) && $queryuser != false && ($querypass != '') && !is_numeric($querypass) && $querypass != false) {
$ret = $this->ts3_sendCommand($socket, 'login client_login_name=' . $this->ts3_escape($queryuser) . ' client_login_password=' . $this->ts3_escape($querypass));
if (stripos($ret, "error id=0") === false) {
trigger_error("[TeamSpeakPlugin] Failed to authenticate with TS3 Server! Make sure you put the correct username & password in teamspeak.xml", E_USER_WARNING);
return;
}
}
$response = '';
$response .= $this->ts3_sendCommand($socket, 'use sid=' . $this->maniaControl->settingManager->getSetting($this, self::TEAMSPEAK_SID));
$this->ts3_sendCommand($socket, 'clientupdate client_nickname=' . $this->ts3_escape('ManiaControl Viewer'));
$response .= $this->ts3_sendCommand($socket, 'serverinfo');
$response .= $this->ts3_sendCommand($socket, 'channellist -topic -flags -voice -limits');
$response .= $this->ts3_sendCommand($socket, 'clientlist -uid -away -voice -groups');
fputs($socket, "quit\n");
fclose($socket);
$lines = explode("error id=0 msg=ok\n\r", $response);
if (count($lines) == 5) {
$serverdata = $this->ts3_parseLine($lines[1]);
$this->serverData['server'] = $serverdata[0];
$this->serverData['channels'] = $this->ts3_parseLine($lines[2]);
$users = $this->ts3_parseLine($lines[3]);
$this->serverData['users'] = array(); // reset userslist
foreach($users as $user) {
if ($user['client_nickname'] != 'ManiaControl Viewer') {
$this->serverData['users'][] = $user;
}
}
// Subtract reserved slots
$this->serverData['server']['virtualserver_maxclients'] -= $this->serverData['server']['virtualserver_reserved_slots'];
// Make ping value int
$this->serverData['server']['virtualserver_total_ping'] = intval($this->serverData['server']['virtualserver_total_ping']);
// Format the Date of server startup
$this->serverData['server']['virtualserver_uptime'] = date('Y-m-d H:i:s', (time() - $this->serverData['server']['virtualserver_uptime']));
// Always subtract all Query Clients
$this->serverData['server']['virtualserver_clientsonline'] -= $this->serverData['server']['virtualserver_queryclientsonline'];
}
} else {
trigger_error("[TeamSpeakPlugin] Failed to connect with TS3 server; socket error: " . $errstr . " [" . $errno . "]", E_USER_WARNING);
}
}
}
/**
* TS Function to send a command to the TeamSpeak server.
*
* @param $socket
* @param $cmd
* @return string
*/
private function ts3_sendCommand($socket, $cmd) {
fputs($socket, "$cmd\n");
$response = '';
/*while(strpos($response, 'error id=') === false) {
$response .= fread($socket, 8096);
}*/
/*while (!feof($socket)) {
$response .= fread($socket, 8192);
}*/
$info = array('timed_out' => false);
while(!feof($socket) && !$info['timed_out'] && strpos($response, 'error id=') === false) {
$response .= fread($socket, 1024);
$info = stream_get_meta_data($socket);
}
return $response;
}
/**
* TS Function used to parse lines in the serverresponse.
*
* @param $rawLine
* @return array
*/
private function ts3_parseLine($rawLine) {
$datas = array();
$rawItems = explode('|', $rawLine);
foreach($rawItems as &$rawItem) {
$rawDatas = explode(' ', $rawItem);
$tempDatas = array();
foreach($rawDatas as &$rawData) {
$ar = explode("=", $rawData, 2);
$tempDatas[$ar[0]] = isset($ar[1]) ? $this->ts3_unescape($ar[1]) : '';
}
$datas[] = $tempDatas;
}
unset($rawItem, $rawData);
return $datas;
}
/**
* TS Function used to escape characters in channelnames.
*
* @param $str
* @return mixed
*/
private function ts3_escape($str) {
return str_replace(array(chr(92), chr(47), chr(32), chr(124), chr(7), chr(8), chr(12), chr(10), chr(3), chr(9), chr(11)), array('\\\\', "\/", "\s", "\p", "\a", "\b", "\f", "\n", "\r", "\t", "\v"), $str);
}
/**
* TS Function used to unescape characters in channelnames.
*
* @param $str
* @return mixed
*/
private function ts3_unescape($str) {
return str_replace(array('\\\\', "\/", "\s", "\p", "\a", "\b", "\f", "\n", "\r", "\t", "\v"), array(chr(92), chr(47), chr(32), chr(124), chr(7), chr(8), chr(12), chr(10), chr(3), chr(9), chr(11)), $str);
}
}