applied common formatting

This commit is contained in:
Steffen Schröder 2014-05-02 17:50:30 +02:00
parent ba720f46bf
commit a0f5421bea
48 changed files with 3539 additions and 3595 deletions

View File

@ -51,8 +51,7 @@ logMessage('Starting ManiaControl ...');
logMessage('Checking for installed MySQLi ... ', false); logMessage('Checking for installed MySQLi ... ', false);
if (extension_loaded('mysqli')) { if (extension_loaded('mysqli')) {
logMessage('FOUND!'); logMessage('FOUND!');
} } else {
else {
logMessage('NOT FOUND!'); logMessage('NOT FOUND!');
logMessage(' -- You don\'t have MySQLi installed, make sure to check: http://www.php.net/manual/en/mysqli.installation.php'); logMessage(' -- You don\'t have MySQLi installed, make sure to check: http://www.php.net/manual/en/mysqli.installation.php');
exit(); exit();
@ -61,8 +60,7 @@ else {
logMessage('Checking for installed cURL ... ', false); logMessage('Checking for installed cURL ... ', false);
if (extension_loaded('curl')) { if (extension_loaded('curl')) {
logMessage('FOUND!'); logMessage('FOUND!');
} } else {
else {
logMessage('NOT FOUND!'); logMessage('NOT FOUND!');
logMessage('You don\'t have cURL installed, make sure to check: http://www.php.net/manual/en/curl.installation.php'); logMessage('You don\'t have cURL installed, make sure to check: http://www.php.net/manual/en/curl.installation.php');
exit(); exit();

View File

@ -5,8 +5,8 @@ namespace ManiaControl\Callbacks;
/** /**
* Interface for Callback Listener * Interface for Callback Listener
* *
* @author steeffeen & kremsy * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
interface CallbackListener { interface CallbackListener {

View File

@ -7,8 +7,8 @@ use ManiaControl\ManiaControl;
/** /**
* Class for managing Server and ManiaControl Callbacks * Class for managing Server and ManiaControl Callbacks
* *
* @author steeffeen & kremsy * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class CallbackManager { class CallbackManager {
@ -150,38 +150,6 @@ class CallbackManager {
return $removed; return $removed;
} }
/**
* Trigger a specific Callback
*
* @param string $callbackName
*/
public function triggerCallback($callbackName) {
if (!array_key_exists($callbackName, $this->callbackListeners)) {
return;
}
$params = func_get_args();
$params = array_slice($params, 1, count($params), true);
foreach($this->callbackListeners[$callbackName] as $listener) {
call_user_func_array(array($listener[0], $listener[1]), $params);
}
}
/**
* Trigger a specific Script Callback
*
* @param string $callbackName
*/
public function triggerScriptCallback($callbackName) {
if (!array_key_exists($callbackName, $this->scriptCallbackListener)) {
return;
}
$params = func_get_args();
$params = array_slice($params, 1, count($params), true);
foreach($this->scriptCallbackListener[$callbackName] as $listener) {
call_user_func_array(array($listener[0], $listener[1]), $params);
}
}
/** /**
* Trigger internal Callbacks and manage Server Callbacks * Trigger internal Callbacks and manage Server Callbacks
*/ */
@ -242,6 +210,22 @@ class CallbackManager {
} }
} }
/**
* Trigger a specific Callback
*
* @param string $callbackName
*/
public function triggerCallback($callbackName) {
if (!array_key_exists($callbackName, $this->callbackListeners)) {
return;
}
$params = func_get_args();
$params = array_slice($params, 1, count($params), true);
foreach ($this->callbackListeners[$callbackName] as $listener) {
call_user_func_array(array($listener[0], $listener[1]), $params);
}
}
/** /**
* Handle the given Script Callback * Handle the given Script Callback
* *
@ -253,4 +237,20 @@ class CallbackManager {
$this->triggerScriptCallback($scriptCallbackName, $scriptCallbackData); $this->triggerScriptCallback($scriptCallbackName, $scriptCallbackData);
$this->triggerCallback(Callbacks::SCRIPTCALLBACK, $scriptCallbackName, $scriptCallbackData[1]); $this->triggerCallback(Callbacks::SCRIPTCALLBACK, $scriptCallbackName, $scriptCallbackData[1]);
} }
/**
* Trigger a specific Script Callback
*
* @param string $callbackName
*/
public function triggerScriptCallback($callbackName) {
if (!array_key_exists($callbackName, $this->scriptCallbackListener)) {
return;
}
$params = func_get_args();
$params = array_slice($params, 1, count($params), true);
foreach ($this->scriptCallbackListener[$callbackName] as $listener) {
call_user_func_array(array($listener[0], $listener[1]), $params);
}
}
} }

View File

@ -1,11 +1,12 @@
<?php <?php
namespace ManiaControl\Callbacks; namespace ManiaControl\Callbacks;
//TODO method class for all the libxmlrpc get Methods, to fetch the callback asnyc //TODO method class for all the libxmlrpc get Methods, to fetch the callback asnyc
/** /**
* Callbacks Interface * Callbacks Interface
* *
* @author steeffeen & kremsy * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
interface Callbacks { interface Callbacks {

View File

@ -8,8 +8,8 @@ use ManiaControl\ManiaControl;
/** /**
* Class managing & converting LibXmlRpc Callbacks * Class managing & converting LibXmlRpc Callbacks
* *
* @author ManiaControl Team * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class LibXmlRpcCallbackManager implements CallbackListener { class LibXmlRpcCallbackManager implements CallbackListener {

View File

@ -7,8 +7,8 @@ use ManiaControl\ManiaControl;
/** /**
* Class handling and parsing ShootMania Callbacks * Class handling and parsing ShootMania Callbacks
* *
* @author steeffeen * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class ShootManiaCallbacks implements CallbackListener { class ShootManiaCallbacks implements CallbackListener {
@ -43,8 +43,8 @@ class ShootManiaCallbacks implements CallbackListener {
/** /**
* Handle Script Callbacks * Handle Script Callbacks
* *
* @param $name * @param string $name
* @param $data * @param array $data
*/ */
public function handleScriptCallbacks($name, $data) { public function handleScriptCallbacks($name, $data) {
switch ($name) { switch ($name) {
@ -63,7 +63,7 @@ class ShootManiaCallbacks implements CallbackListener {
/** /**
* Triggers the AFK Status of an Player * Triggers the AFK Status of an Player
* *
* @param $login * @param string $login
*/ */
private function triggerAfkStatus($login) { private function triggerAfkStatus($login) {
$player = $this->maniaControl->playerManager->getPlayer($login); $player = $this->maniaControl->playerManager->getPlayer($login);

View File

@ -5,8 +5,8 @@ namespace ManiaControl\Callbacks;
/** /**
* Interface for TimerListener * Interface for TimerListener
* *
* @author kremsy * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
interface TimerListener { interface TimerListener {

View File

@ -7,8 +7,8 @@ use ManiaControl\ManiaControl;
/** /**
* Class for managing Timers * Class for managing Timers
* *
* @author kremsy * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class TimerManager { class TimerManager {
@ -38,22 +38,6 @@ class TimerManager {
$this->registerTimerListening($listener, $method, $time, true); $this->registerTimerListening($listener, $method, $time, true);
} }
/**
* Unregister a Timer Listening
* @param TimerListener $listener
* @param $method
* @return bool
*/
public function unregisterTimerListening(TimerListener $listener, $method){
foreach($this->timerListenings as $key => $listening){
if($listening->listener == $listener && $listening->method == $method){
unset($this->timerListenings[$key]);
return true;
}
}
return false;
}
/** /**
* Register a Timer Listening, note < 10ms it can get inaccurate * Register a Timer Listening, note < 10ms it can get inaccurate
* *
@ -86,6 +70,23 @@ class TimerManager {
return true; return true;
} }
/**
* Unregister a Timer Listening
*
* @param TimerListener $listener
* @param $method
* @return bool
*/
public function unregisterTimerListening(TimerListener $listener, $method) {
foreach ($this->timerListenings as $key => $listening) {
if ($listening->listener == $listener && $listening->method == $method) {
unset($this->timerListenings[$key]);
return true;
}
}
return false;
}
/** /**
* Remove a Timer Listener * Remove a Timer Listener
* *

View File

@ -5,8 +5,8 @@ namespace ManiaControl\Commands;
/** /**
* Interface for Command Listeners * Interface for Command Listeners
* *
* @author steeffeen & kremsy * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
interface CommandListener { interface CommandListener {

View File

@ -9,8 +9,8 @@ use ManiaControl\ManiaControl;
/** /**
* Class for handling Chat Commands * Class for handling Chat Commands
* *
* @author steeffeen & kremsy * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class CommandManager implements CallbackListener { class CommandManager implements CallbackListener {

View File

@ -7,18 +7,17 @@ use FML\Controls\Label;
use FML\Controls\Quads\Quad_BgsPlayerCard; use FML\Controls\Quads\Quad_BgsPlayerCard;
use FML\ManiaLink; use FML\ManiaLink;
use FML\Script\Features\Paging; use FML\Script\Features\Paging;
use ManiaControl\Callbacks\CallbackListener; use ManiaControl\Callbacks\CallbackListener;
use ManiaControl\Callbacks\CallbackManager; use ManiaControl\Callbacks\CallbackManager;
use ManiaControl\Manialinks\ManialinkManager;
use ManiaControl\ManiaControl; use ManiaControl\ManiaControl;
use ManiaControl\Manialinks\ManialinkManager;
use ManiaControl\Players\Player; use ManiaControl\Players\Player;
/** /**
* Help Manager * Help Manager
* *
* @author kremsy * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class HelpManager implements CommandListener, CallbackListener { class HelpManager implements CommandListener, CallbackListener {
@ -124,16 +123,6 @@ class HelpManager implements CommandListener, CallbackListener {
$this->prepareHelpAll($this->playerCommands, $player); $this->prepareHelpAll($this->playerCommands, $player);
} }
/**
* Shows a ManiaLink list of Admin Commands
*
* @param array $chat
* @param Player $player
*/
public function command_adminHelpAll(array $chat, Player $player) {
$this->prepareHelpAll($this->adminCommands, $player);
}
/** /**
* Prepares the commands for the HelpAll ManiaLink. * Prepares the commands for the HelpAll ManiaLink.
* *
@ -245,6 +234,16 @@ class HelpManager implements CommandListener, CallbackListener {
$this->maniaControl->manialinkManager->displayWidget($maniaLink, $player, 'HelpAllList'); $this->maniaControl->manialinkManager->displayWidget($maniaLink, $player, 'HelpAllList');
} }
/**
* Shows a ManiaLink list of Admin Commands
*
* @param array $chat
* @param Player $player
*/
public function command_adminHelpAll(array $chat, Player $player) {
$this->prepareHelpAll($this->adminCommands, $player);
}
/** /**
* Registers a new Command * Registers a new Command
* *

View File

@ -23,8 +23,8 @@ use ManiaControl\Players\Player;
/** /**
* Class managing ingame ManiaControl Configuration * Class managing ingame ManiaControl Configuration
* *
* @author steeffeen & kremsy * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class Configurator implements CallbackListener, CommandListener, ManialinkPageAnswerListener { class Configurator implements CallbackListener, CommandListener, ManialinkPageAnswerListener {
@ -99,6 +99,25 @@ class Configurator implements CallbackListener, CommandListener, ManialinkPageAn
$this->maniaControl->commandManager->registerCommandListener('config', $this, 'handleConfigCommand', true, 'Loads Config panel.'); $this->maniaControl->commandManager->registerCommandListener('config', $this, 'handleConfigCommand', true, 'Loads Config panel.');
} }
/**
* Add Menu Item to the Actions Menu
*/
private function addActionsMenuItem() {
$itemQuad = new Quad_UIConstruction_Buttons();
$itemQuad->setSubStyle($itemQuad::SUBSTYLE_Tools);
$itemQuad->setAction(self::ACTION_TOGGLEMENU);
$this->maniaControl->actionsMenu->addAdminMenuItem($itemQuad, 100, 'Settings');
}
/**
* Add a configurator menu
*
* @param ConfiguratorMenu $menu
*/
public function addMenu(ConfiguratorMenu $menu) {
array_push($this->menus, $menu);
}
/** /**
* Handle Config Admin Command * Handle Config Admin Command
* *
@ -114,58 +133,6 @@ class Configurator implements CallbackListener, CommandListener, ManialinkPageAn
$this->showMenu($player); $this->showMenu($player);
} }
/**
* Add a configurator menu
*
* @param ConfiguratorMenu $menu
*/
public function addMenu(ConfiguratorMenu $menu) {
array_push($this->menus, $menu);
}
/**
* Reopen the Menu
*
* @param Player $player
* @param int $menuId
*/
public function reopenMenu(Player $player, $menuId = 0) {
$this->showMenu($player, $menuId);
}
/**
* Handle toggle menu action
*
* @param array $callback
* @param Player $player
*/
public function handleToggleMenuAction(array $callback, Player $player) {
$this->toggleMenu($player);
}
/**
* Save the config data received from the manialink
*
* @param array $callback
* @param Player $player
*/
public function handleSaveConfigAction(array $callback, Player $player) {
foreach($this->menus as $menu) {
/** @var ConfiguratorMenu $menu */
$menu->saveConfigData($callback[1], $player);
}
}
/**
* Handle PlayerDisconnect callback
*
* @param array $callback
*/
public function handlePlayerDisconnect(array $callback) {
$login = $callback[1][0];
unset($this->playersMenuShown[$login]);
}
/** /**
* Show the Menu to the Player * Show the Menu to the Player
* *
@ -178,69 +145,6 @@ class Configurator implements CallbackListener, CommandListener, ManialinkPageAn
$this->playersMenuShown[$player->login] = true; $this->playersMenuShown[$player->login] = true;
} }
/**
* Unset the player if he opened another Main Widget
*
* @param Player $player
* @param $openedWidget
*/
public function handleWidgetOpened(Player $player, $openedWidget) {
//unset when another main widget got opened
if ($openedWidget != 'Configurator') {
unset($this->playersMenuShown[$player->login]);
}
}
/**
* Widget get closed -> unset player
*
* @param \ManiaControl\Players\Player $player
*/
public function closeWidget(Player $player) {
unset($this->playersMenuShown[$player->login]);
}
/**
* Hide the Menu for the Player
*
* @param Player $player
*/
public function hideMenu(Player $player) {
unset($this->playersMenuShown[$player->login]);
$this->maniaControl->manialinkManager->closeWidget($player);
}
/**
* Toggle the Menu for the Player
*
* @param Player $player
*/
public function toggleMenu(Player $player) {
if (isset($this->playersMenuShown[$player->login])) {
$this->hideMenu($player);
} else {
$this->showMenu($player);
}
}
/**
* Gets the Menu Id
*
* @param $name
* @return int
*/
public function getMenuId($name) {
$i = 0;
foreach($this->menus as $menu) {
/** @var ConfiguratorMenu $menu */
if ($menu == $name || $menu->getTitle() == $name) {
return $i;
}
$i++;
}
return 0;
}
/** /**
* Build Menu ManiaLink if necessary * Build Menu ManiaLink if necessary
* *
@ -349,6 +253,112 @@ class Configurator implements CallbackListener, CommandListener, ManialinkPageAn
return $manialink; return $manialink;
} }
/**
* Reopen the Menu
*
* @param Player $player
* @param int $menuId
*/
public function reopenMenu(Player $player, $menuId = 0) {
$this->showMenu($player, $menuId);
}
/**
* Handle toggle menu action
*
* @param array $callback
* @param Player $player
*/
public function handleToggleMenuAction(array $callback, Player $player) {
$this->toggleMenu($player);
}
/**
* Toggle the Menu for the Player
*
* @param Player $player
*/
public function toggleMenu(Player $player) {
if (isset($this->playersMenuShown[$player->login])) {
$this->hideMenu($player);
} else {
$this->showMenu($player);
}
}
/**
* Hide the Menu for the Player
*
* @param Player $player
*/
public function hideMenu(Player $player) {
unset($this->playersMenuShown[$player->login]);
$this->maniaControl->manialinkManager->closeWidget($player);
}
/**
* Save the config data received from the manialink
*
* @param array $callback
* @param Player $player
*/
public function handleSaveConfigAction(array $callback, Player $player) {
foreach ($this->menus as $menu) {
/** @var ConfiguratorMenu $menu */
$menu->saveConfigData($callback[1], $player);
}
}
/**
* Handle PlayerDisconnect callback
*
* @param array $callback
*/
public function handlePlayerDisconnect(array $callback) {
$login = $callback[1][0];
unset($this->playersMenuShown[$login]);
}
/**
* Unset the player if he opened another Main Widget
*
* @param Player $player
* @param $openedWidget
*/
public function handleWidgetOpened(Player $player, $openedWidget) {
//unset when another main widget got opened
if ($openedWidget != 'Configurator') {
unset($this->playersMenuShown[$player->login]);
}
}
/**
* Widget get closed -> unset player
*
* @param \ManiaControl\Players\Player $player
*/
public function closeWidget(Player $player) {
unset($this->playersMenuShown[$player->login]);
}
/**
* Gets the Menu Id
*
* @param $name
* @return int
*/
public function getMenuId($name) {
$i = 0;
foreach ($this->menus as $menu) {
/** @var ConfiguratorMenu $menu */
if ($menu == $name || $menu->getTitle() == $name) {
return $i;
}
$i++;
}
return 0;
}
/** /**
* Handle ManialinkPageAnswer Callback * Handle ManialinkPageAnswer Callback
* *
@ -367,14 +377,4 @@ class Configurator implements CallbackListener, CommandListener, ManialinkPageAn
$player = $this->maniaControl->playerManager->getPlayer($login); $player = $this->maniaControl->playerManager->getPlayer($login);
$this->showMenu($player, intval($actionArray[2])); $this->showMenu($player, intval($actionArray[2]));
} }
/**
* Add Menu Item to the Actions Menu
*/
private function addActionsMenuItem() {
$itemQuad = new Quad_UIConstruction_Buttons();
$itemQuad->setSubStyle($itemQuad::SUBSTYLE_Tools);
$itemQuad->setAction(self::ACTION_TOGGLEMENU);
$this->maniaControl->actionsMenu->addAdminMenuItem($itemQuad, 100, 'Settings');
}
} }

View File

@ -5,6 +5,7 @@ namespace ManiaControl\Configurators;
use FML\Controls\Control; use FML\Controls\Control;
use FML\Controls\Entry; use FML\Controls\Entry;
use FML\Controls\Frame; use FML\Controls\Frame;
use FML\Controls\Labels\Label_Button;
use FML\Controls\Labels\Label_Text; use FML\Controls\Labels\Label_Text;
use FML\Controls\Quads\Quad_Icons64x64_1; use FML\Controls\Quads\Quad_Icons64x64_1;
use FML\Script\Features\Paging; use FML\Script\Features\Paging;
@ -15,14 +16,13 @@ use ManiaControl\Callbacks\CallbackManager;
use ManiaControl\ManiaControl; use ManiaControl\ManiaControl;
use ManiaControl\Players\Player; use ManiaControl\Players\Player;
use ManiaControl\Players\PlayerManager; use ManiaControl\Players\PlayerManager;
use FML\Controls\Labels\Label_Button;
use ManiaControl\Settings\SettingManager; use ManiaControl\Settings\SettingManager;
/** /**
* Class offering a Configurator for ManiaControl Settings * Class offering a Configurator for ManiaControl Settings
* *
* @author steeffeen & kremsy * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class ManiaControlSettings implements ConfiguratorMenu, CallbackListener { class ManiaControlSettings implements ConfiguratorMenu, CallbackListener {
@ -67,115 +67,16 @@ class ManiaControlSettings implements ConfiguratorMenu, CallbackListener {
} }
/** /**
* Get the Menu Title
*
* @return string
*/
public function getTitle() {
return self::TITLE;
}
/**
*
* @see \ManiaControl\Configurators\ConfiguratorMenu::getMenu() * @see \ManiaControl\Configurators\ConfiguratorMenu::getMenu()
*/ */
public function getMenu($width, $height, Script $script, Player $player) { public function getMenu($width, $height, Script $script, Player $player) {
if (isset($this->playersSettingCategoryOpened[$player->login]) && strlen($this->playersSettingCategoryOpened[$player->login]) > 0) { if (isset($this->playersSettingCategoryOpened[$player->login]) && strlen($this->playersSettingCategoryOpened[$player->login]) > 0) {
return $this->getMenuSettingsForClass($this->playersSettingCategoryOpened[$player->login], $width, $height, $script, $player); return $this->getMenuSettingsForClass($this->playersSettingCategoryOpened[$player->login], $width, $height, $script, $player);
} } else {
else {
return $this->getMenuSettingClasses($width, $height, $script, $player); return $this->getMenuSettingClasses($width, $height, $script, $player);
} }
} }
/**
* Get the Menu showing all possible Classes
*
* @param float $width
* @param float $height
* @param Script $script
* @param Player $player
* @return \FML\Controls\Frame
*/
private function getMenuSettingClasses($width, $height, Script $script, Player $player) {
$settingClasses = $this->maniaControl->settingManager->getSettingClasses(true);
$paging = new Paging();
$script->addFeature($paging);
$frame = new Frame();
// Config
$pagerSize = 9.;
$settingHeight = 5.;
$pageMaxCount = 13;
$y = 0;
// Pagers
$pagerPrev = new Quad_Icons64x64_1();
$frame->add($pagerPrev);
$pagerPrev->setPosition($width * 0.39, $height * -0.44, 2);
$pagerPrev->setSize($pagerSize, $pagerSize);
$pagerPrev->setSubStyle($pagerPrev::SUBSTYLE_ArrowPrev);
$pagerNext = new Quad_Icons64x64_1();
$frame->add($pagerNext);
$pagerNext->setPosition($width * 0.45, $height * -0.44, 2);
$pagerNext->setSize($pagerSize, $pagerSize);
$pagerNext->setSubStyle($pagerNext::SUBSTYLE_ArrowNext);
$paging->addButton($pagerNext);
$paging->addButton($pagerPrev);
$pageCountLabel = new Label_Text();
$frame->add($pageCountLabel);
$pageCountLabel->setHAlign($pageCountLabel::RIGHT);
$pageCountLabel->setPosition($width * 0.35, $height * -0.44, 1);
$pageCountLabel->setStyle($pageCountLabel::STYLE_TextTitle1);
$pageCountLabel->setTextSize(2);
$paging->setLabel($pageCountLabel);
$pageFrame = null;
$index = 0;
foreach ($settingClasses as $settingClass) {
if (!$pageFrame) {
$pageFrame = new Frame();
$frame->add($pageFrame);
$y = $height * 0.41;
$paging->addPage($pageFrame);
}
$classLabel = new Label_Text();
$settingClassArray = explode('\\', $settingClass);
$className = "";
for($i = 1; $i < count($settingClassArray); $i++){
$className .= $settingClassArray[$i] . " - ";
}
$className = substr($className, 0, -3);
$pageFrame->add($classLabel);
$classLabel->setHAlign($classLabel::LEFT);
$classLabel->setPosition($width * -0.45, $y);
$classLabel->setSize($width * 0.9, $settingHeight * 0.9);
$classLabel->setStyle($classLabel::STYLE_TextCardSmall);
$classLabel->setTextSize(2);
$classLabel->setText($className);
$classLabel->setTextColor('fff');
$classLabel->setAction(self::ACTION_PREFIX_SETTINGCLASS . $settingClass);
$y -= $settingHeight;
if ($index % $pageMaxCount == $pageMaxCount - 1) {
$pageFrame = null;
}
$index++;
}
return $frame;
}
/** /**
* Get the Menu showing the Settings for the given Class * Get the Menu showing the Settings for the given Class
* *
@ -280,8 +181,7 @@ class ManiaControlSettings implements ConfiguratorMenu, CallbackListener {
$quad->setSubStyle(($setting->value ? $quad::SUBSTYLE_LvlGreen : $quad::SUBSTYLE_LvlRed)); $quad->setSubStyle(($setting->value ? $quad::SUBSTYLE_LvlGreen : $quad::SUBSTYLE_LvlRed));
$quad->setSize(4, 4); $quad->setSize(4, 4);
$quad->setAction(self::ACTION_SETTING_BOOL . $setting->index); $quad->setAction(self::ACTION_SETTING_BOOL . $setting->index);
} } else {
else {
$entry = new Entry(); $entry = new Entry();
$settingFrame->add($entry); $settingFrame->add($entry);
$entry->setStyle(Label_Text::STYLE_TextValueSmall); $entry->setStyle(Label_Text::STYLE_TextValueSmall);
@ -303,6 +203,163 @@ class ManiaControlSettings implements ConfiguratorMenu, CallbackListener {
return $frame; return $frame;
} }
/**
* Get the Menu showing all possible Classes
*
* @param float $width
* @param float $height
* @param Script $script
* @param Player $player
* @return \FML\Controls\Frame
*/
private function getMenuSettingClasses($width, $height, Script $script, Player $player) {
$settingClasses = $this->maniaControl->settingManager->getSettingClasses(true);
$paging = new Paging();
$script->addFeature($paging);
$frame = new Frame();
// Config
$pagerSize = 9.;
$settingHeight = 5.;
$pageMaxCount = 13;
$y = 0;
// Pagers
$pagerPrev = new Quad_Icons64x64_1();
$frame->add($pagerPrev);
$pagerPrev->setPosition($width * 0.39, $height * -0.44, 2);
$pagerPrev->setSize($pagerSize, $pagerSize);
$pagerPrev->setSubStyle($pagerPrev::SUBSTYLE_ArrowPrev);
$pagerNext = new Quad_Icons64x64_1();
$frame->add($pagerNext);
$pagerNext->setPosition($width * 0.45, $height * -0.44, 2);
$pagerNext->setSize($pagerSize, $pagerSize);
$pagerNext->setSubStyle($pagerNext::SUBSTYLE_ArrowNext);
$paging->addButton($pagerNext);
$paging->addButton($pagerPrev);
$pageCountLabel = new Label_Text();
$frame->add($pageCountLabel);
$pageCountLabel->setHAlign($pageCountLabel::RIGHT);
$pageCountLabel->setPosition($width * 0.35, $height * -0.44, 1);
$pageCountLabel->setStyle($pageCountLabel::STYLE_TextTitle1);
$pageCountLabel->setTextSize(2);
$paging->setLabel($pageCountLabel);
$pageFrame = null;
$index = 0;
foreach ($settingClasses as $settingClass) {
if (!$pageFrame) {
$pageFrame = new Frame();
$frame->add($pageFrame);
$y = $height * 0.41;
$paging->addPage($pageFrame);
}
$classLabel = new Label_Text();
$settingClassArray = explode('\\', $settingClass);
$className = "";
for ($i = 1; $i < count($settingClassArray); $i++) {
$className .= $settingClassArray[$i] . " - ";
}
$className = substr($className, 0, -3);
$pageFrame->add($classLabel);
$classLabel->setHAlign($classLabel::LEFT);
$classLabel->setPosition($width * -0.45, $y);
$classLabel->setSize($width * 0.9, $settingHeight * 0.9);
$classLabel->setStyle($classLabel::STYLE_TextCardSmall);
$classLabel->setTextSize(2);
$classLabel->setText($className);
$classLabel->setTextColor('fff');
$classLabel->setAction(self::ACTION_PREFIX_SETTINGCLASS . $settingClass);
$y -= $settingHeight;
if ($index % $pageMaxCount == $pageMaxCount - 1) {
$pageFrame = null;
}
$index++;
}
return $frame;
}
/**
* Handle ManialinkPageAnswer Callback
*
* @param array $callback
*/
public function handleManialinkPageAnswer(array $callback) {
$actionId = $callback[1][2];
if ($actionId === self::ACTION_SETTINGCLASS_BACK) {
// Back to classes list
$login = $callback[1][1];
$player = $this->maniaControl->playerManager->getPlayer($login);
unset($this->playersSettingCategoryOpened[$player->login]);
$menuId = $this->maniaControl->configurator->getMenuId($this);
$this->maniaControl->configurator->showMenu($player, $menuId);
} else if (strpos($actionId, self::ACTION_SETTING_BOOL) === 0) {
// Bool setting change
$settingIndex = (int)substr($actionId, strlen(self::ACTION_SETTING_BOOL));
$login = $callback[1][1];
$player = $this->maniaControl->playerManager->getPlayer($login);
// Toggle the Boolean Setting
$this->toggleBooleanSetting($settingIndex, $player);
if ($callback[1][3]) {
// Save all Changes
$this->saveConfigData($callback[1], $player);
} else {
// Reopen menu directly
$menuId = $this->maniaControl->configurator->getMenuId($this);
$this->maniaControl->configurator->reopenMenu($player, $menuId);
}
} else if (strpos($actionId, self::ACTION_PREFIX_SETTINGCLASS) === 0) {
// Setting class selected
$settingClass = substr($actionId, strlen(self::ACTION_PREFIX_SETTINGCLASS));
$login = $callback[1][1];
$player = $this->maniaControl->playerManager->getPlayer($login);
$this->playersSettingCategoryOpened[$player->login] = $settingClass;
$menuId = $this->maniaControl->configurator->getMenuId($this);
$this->maniaControl->configurator->showMenu($player, $menuId);
}
}
/**
* Toggles a Boolean Value
*
* @param int $settingIndex
* @param Player $player
*/
public function toggleBooleanSetting($settingIndex, Player $player) {
if (!$this->maniaControl->authenticationManager->checkPermission($player, self::SETTING_PERMISSION_CHANGE_MC_SETTINGS)) {
$this->maniaControl->authenticationManager->sendNotAllowed($player);
return;
}
$oldSetting = $this->maniaControl->settingManager->getSettingByIndex($settingIndex);
if (!isset($oldSetting)) {
var_dump('no setting ' . $settingIndex);
return;
}
// Toggle value
$this->maniaControl->settingManager->setSetting($oldSetting->class, $oldSetting->setting, !$oldSetting->value);
}
/** /**
* Save the Config Data * Save the Config Data
* *
@ -340,74 +397,11 @@ class ManiaControlSettings implements ConfiguratorMenu, CallbackListener {
} }
/** /**
* Handle ManialinkPageAnswer Callback * Get the Menu Title
* *
* @param array $callback * @return string
*/ */
public function handleManialinkPageAnswer(array $callback) { public function getTitle() {
$actionId = $callback[1][2]; return self::TITLE;
if ($actionId === self::ACTION_SETTINGCLASS_BACK) {
// Back to classes list
$login = $callback[1][1];
$player = $this->maniaControl->playerManager->getPlayer($login);
unset($this->playersSettingCategoryOpened[$player->login]);
$menuId = $this->maniaControl->configurator->getMenuId($this);
$this->maniaControl->configurator->showMenu($player, $menuId);
}
else if (strpos($actionId, self::ACTION_SETTING_BOOL) === 0) {
// Bool setting change
$settingIndex = (int) substr($actionId, strlen(self::ACTION_SETTING_BOOL));
$login = $callback[1][1];
$player = $this->maniaControl->playerManager->getPlayer($login);
// Toggle the Boolean Setting
$this->toggleBooleanSetting($settingIndex, $player);
if ($callback[1][3]) {
// Save all Changes
$this->saveConfigData($callback[1], $player);
}
else {
// Reopen menu directly
$menuId = $this->maniaControl->configurator->getMenuId($this);
$this->maniaControl->configurator->reopenMenu($player, $menuId);
}
}
else if (strpos($actionId, self::ACTION_PREFIX_SETTINGCLASS) === 0) {
// Setting class selected
$settingClass = substr($actionId, strlen(self::ACTION_PREFIX_SETTINGCLASS));
$login = $callback[1][1];
$player = $this->maniaControl->playerManager->getPlayer($login);
$this->playersSettingCategoryOpened[$player->login] = $settingClass;
$menuId = $this->maniaControl->configurator->getMenuId($this);
$this->maniaControl->configurator->showMenu($player, $menuId);
}
}
/**
* Toggles a Boolean Value
*
* @param int $settingIndex
* @param Player $player
*/
public function toggleBooleanSetting($settingIndex, Player $player) {
if (!$this->maniaControl->authenticationManager->checkPermission($player, self::SETTING_PERMISSION_CHANGE_MC_SETTINGS)) {
$this->maniaControl->authenticationManager->sendNotAllowed($player);
return;
}
$oldSetting = $this->maniaControl->settingManager->getSettingByIndex($settingIndex);
if (!isset($oldSetting)) {
var_dump('no setting ' . $settingIndex);
return;
}
// Toggle value
$this->maniaControl->settingManager->setSetting($oldSetting->class, $oldSetting->setting, !$oldSetting->value);
} }
} }

View File

@ -23,8 +23,8 @@ use Maniaplanet\DedicatedServer\Xmlrpc\NotInScriptModeException;
/** /**
* Class offering a Configurator for Script Settings * Class offering a Configurator for Script Settings
* *
* @author steeffeen & kremsy * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class ScriptSettings implements ConfiguratorMenu, CallbackListener { class ScriptSettings implements ConfiguratorMenu, CallbackListener {
@ -100,17 +100,6 @@ class ScriptSettings implements ConfiguratorMenu, CallbackListener {
$this->loadSettingsFromDatabase(); $this->loadSettingsFromDatabase();
} }
/**
* Handle OnBegin Map Callback
*
* @param Map $map
*/
public function onBeginMap(Map $map) {
if ($this->maniaControl->settingManager->getSetting($this, self::SETTING_LOAD_DEFAULT_SETTINGS_MAP_BEGIN)) {
$this->loadSettingsFromDatabase();
}
}
/** /**
* Load Settings from Database * Load Settings from Database
* *
@ -155,10 +144,14 @@ class ScriptSettings implements ConfiguratorMenu, CallbackListener {
} }
/** /**
* @see \ManiaControl\Configurators\ConfiguratorMenu::getTitle() * Handle OnBegin Map Callback
*
* @param Map $map
*/ */
public function getTitle() { public function onBeginMap(Map $map) {
return 'Script Settings'; if ($this->maniaControl->settingManager->getSetting($this, self::SETTING_LOAD_DEFAULT_SETTINGS_MAP_BEGIN)) {
$this->loadSettingsFromDatabase();
}
} }
/** /**
@ -301,50 +294,6 @@ class ScriptSettings implements ConfiguratorMenu, CallbackListener {
return $frame; return $frame;
} }
/**
* @see \ManiaControl\Configurators\ConfiguratorMenu::saveConfigData()
*/
public function saveConfigData(array $configData, Player $player) {
if (!$this->maniaControl->authenticationManager->checkPermission($player, self::SETTING_PERMISSION_CHANGE_SCRIPT_SETTINGS)) {
$this->maniaControl->authenticationManager->sendNotAllowed($player);
return;
}
if (!$configData[3] || strpos($configData[3][0]['Name'], self::ACTION_PREFIX_SETTING) !== 0) {
return;
}
try {
$scriptSettings = $this->maniaControl->client->getModeScriptSettings();
} catch(NotInScriptModeException $e) {
return;
}
$prefixLength = strlen(self::ACTION_PREFIX_SETTING);
$newSettings = array();
foreach($configData[3] as $setting) {
$settingName = substr($setting['Name'], $prefixLength + 1);
if (!isset($scriptSettings[$settingName])) {
var_dump('no setting ' . $settingName);
continue;
}
if ($setting['Value'] == $scriptSettings[$settingName]) {
// Not changed
continue;
}
$newSettings[$settingName] = $setting['Value'];
settype($newSettings[$settingName], gettype($scriptSettings[$settingName]));
}
$this->applyNewScriptSettings($newSettings, $player);
//Reopen the Menu
$menuId = $this->maniaControl->configurator->getMenuId($this->getTitle());
$this->maniaControl->configurator->reopenMenu($player, $menuId);
}
/** /**
* Handle ManialinkPageAnswer Callback * Handle ManialinkPageAnswer Callback
* *
@ -478,4 +427,55 @@ class ScriptSettings implements ConfiguratorMenu, CallbackListener {
} }
return (string)$value; return (string)$value;
} }
/**
* @see \ManiaControl\Configurators\ConfiguratorMenu::saveConfigData()
*/
public function saveConfigData(array $configData, Player $player) {
if (!$this->maniaControl->authenticationManager->checkPermission($player, self::SETTING_PERMISSION_CHANGE_SCRIPT_SETTINGS)) {
$this->maniaControl->authenticationManager->sendNotAllowed($player);
return;
}
if (!$configData[3] || strpos($configData[3][0]['Name'], self::ACTION_PREFIX_SETTING) !== 0) {
return;
}
try {
$scriptSettings = $this->maniaControl->client->getModeScriptSettings();
} catch (NotInScriptModeException $e) {
return;
}
$prefixLength = strlen(self::ACTION_PREFIX_SETTING);
$newSettings = array();
foreach ($configData[3] as $setting) {
$settingName = substr($setting['Name'], $prefixLength + 1);
if (!isset($scriptSettings[$settingName])) {
var_dump('no setting ' . $settingName);
continue;
}
if ($setting['Value'] == $scriptSettings[$settingName]) {
// Not changed
continue;
}
$newSettings[$settingName] = $setting['Value'];
settype($newSettings[$settingName], gettype($scriptSettings[$settingName]));
}
$this->applyNewScriptSettings($newSettings, $player);
//Reopen the Menu
$menuId = $this->maniaControl->configurator->getMenuId($this->getTitle());
$this->maniaControl->configurator->reopenMenu($player, $menuId);
}
/**
* @see \ManiaControl\Configurators\ConfiguratorMenu::getTitle()
*/
public function getTitle() {
return 'Script Settings';
}
} }

View File

@ -20,8 +20,8 @@ use Maniaplanet\DedicatedServer\Xmlrpc\LadderModeUnknownException;
/** /**
* Class offering a Configurator for Server Settings * Class offering a Configurator for Server Settings
* *
* @author steeffeen & kremsy * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class ServerSettings implements ConfiguratorMenu, CallbackListener { class ServerSettings implements ConfiguratorMenu, CallbackListener {
@ -127,13 +127,6 @@ class ServerSettings implements ConfiguratorMenu, CallbackListener {
return true; return true;
} }
/**
* @see \ManiaControl\Configurators\ConfiguratorMenu::getTitle()
*/
public function getTitle() {
return 'Server Settings';
}
/** /**
* @see \ManiaControl\Configurators\ConfiguratorMenu::getMenu() * @see \ManiaControl\Configurators\ConfiguratorMenu::getMenu()
*/ */
@ -261,6 +254,25 @@ class ServerSettings implements ConfiguratorMenu, CallbackListener {
return $frame; return $frame;
} }
/**
* Handle ManialinkPageAnswer Callback
*
* @param array $callback
*/
public function handleManialinkPageAnswer(array $callback) {
$actionId = $callback[1][2];
$boolSetting = (strpos($actionId, self::ACTION_SETTING_BOOL) === 0);
if (!$boolSetting) {
return;
}
$login = $callback[1][1];
$player = $this->maniaControl->playerManager->getPlayer($login);
// Save all Changes
$this->saveConfigData($callback[1], $player);
}
/** /**
* @see \ManiaControl\Configurators\ConfiguratorMenu::saveConfigData() * @see \ManiaControl\Configurators\ConfiguratorMenu::saveConfigData()
*/ */
@ -304,25 +316,6 @@ class ServerSettings implements ConfiguratorMenu, CallbackListener {
$this->maniaControl->configurator->reopenMenu($player, $menuId); $this->maniaControl->configurator->reopenMenu($player, $menuId);
} }
/**
* Handle ManialinkPageAnswer Callback
*
* @param array $callback
*/
public function handleManialinkPageAnswer(array $callback) {
$actionId = $callback[1][2];
$boolSetting = (strpos($actionId, self::ACTION_SETTING_BOOL) === 0);
if (!$boolSetting) {
return;
}
$login = $callback[1][1];
$player = $this->maniaControl->playerManager->getPlayer($login);
// Save all Changes
$this->saveConfigData($callback[1], $player);
}
/** /**
* Apply the Array of new Server Settings * Apply the Array of new Server Settings
* *
@ -382,4 +375,11 @@ class ServerSettings implements ConfiguratorMenu, CallbackListener {
return true; return true;
} }
/**
* @see \ManiaControl\Configurators\ConfiguratorMenu::getTitle()
*/
public function getTitle() {
return 'Server Settings';
}
} }

View File

@ -8,8 +8,8 @@ use ManiaControl\Formatter;
* Mania Exchange Map Info Object * Mania Exchange Map Info Object
* *
* @author Xymph * @author Xymph
* @updated kremsy * @updated kremsy <kremsy@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class MXMapInfo { class MXMapInfo {
@ -19,6 +19,7 @@ class MXMapInfo {
public $replaytyp, $replayid, $replaycnt, $acomment, $awards, $comments; public $replaytyp, $replayid, $replaycnt, $acomment, $awards, $comments;
public $pageurl, $replayurl, $imageurl, $thumburl, $downloadurl, $dir; public $pageurl, $replayurl, $imageurl, $thumburl, $downloadurl, $dir;
public $ratingVoteCount, $ratingVoteAverage; public $ratingVoteCount, $ratingVoteAverage;
/** /**
* Returns map object with all available data from MX map data * Returns map object with all available data from MX map data
* *

View File

@ -29,8 +29,8 @@ use ManiaControl\Players\Player;
/** /**
* ManiaExchange List Widget Class * ManiaExchange List Widget Class
* *
* @author steeffeen & kremsy * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class ManiaExchangeList implements CallbackListener, ManialinkPageAnswerListener { class ManiaExchangeList implements CallbackListener, ManialinkPageAnswerListener {
@ -66,6 +66,33 @@ class ManiaExchangeList implements CallbackListener, ManialinkPageAnswerListener
$this->maniaControl->manialinkManager->registerManialinkPageAnswerListener(self::ACTION_SEARCH_AUTHOR, $this, 'showList'); $this->maniaControl->manialinkManager->registerManialinkPageAnswerListener(self::ACTION_SEARCH_AUTHOR, $this, 'showList');
} }
/**
* Handle ManialinkPageAnswer Callback
*
* @param array $callback
*/
public function handleManialinkPageAnswer(array $callback) {
$actionId = $callback[1][2];
$actionArray = explode('.', $actionId);
if (count($actionArray) <= 2) {
return;
}
$action = $actionArray[0] . '.' . $actionArray[1];
$login = $callback[1][1];
$player = $this->maniaControl->playerManager->getPlayer($login);
$mapId = (int)$actionArray[2];
switch ($action) {
case self::ACTION_GET_MAPS_FROM_AUTHOR:
$callback[1][2] = 'auth:' . $actionArray[2];
$this->showList($callback, $player);
break;
case self::ACTION_ADD_MAP:
$this->maniaControl->mapManager->addMapFromMx($mapId, $player->login);
break;
}
}
/** /**
* Shows the List * Shows the List
@ -312,35 +339,6 @@ class ManiaExchangeList implements CallbackListener, ManialinkPageAnswerListener
$this->maniaControl->manialinkManager->displayWidget($maniaLink, $player, 'ManiaExchangeList'); $this->maniaControl->manialinkManager->displayWidget($maniaLink, $player, 'ManiaExchangeList');
} }
/**
* Handle ManialinkPageAnswer Callback
*
* @param array $callback
*/
public function handleManialinkPageAnswer(array $callback) {
$actionId = $callback[1][2];
$actionArray = explode('.', $actionId);
if (count($actionArray) <= 2) {
return;
}
$action = $actionArray[0] . '.' . $actionArray[1];
$login = $callback[1][1];
$player = $this->maniaControl->playerManager->getPlayer($login);
$mapId = (int)$actionArray[2];
switch($action) {
case self::ACTION_GET_MAPS_FROM_AUTHOR:
$callback[1][2] = 'auth:' . $actionArray[2];
$this->showList($callback, $player);
break;
case self::ACTION_ADD_MAP:
$this->maniaControl->mapManager->addMapFromMx($mapId, $player->login);
break;
}
}
/** /**
* Unset the player if he opened another Main Widget * Unset the player if he opened another Main Widget
* *
@ -364,5 +362,4 @@ class ManiaExchangeList implements CallbackListener, ManialinkPageAnswerListener
unset($this->mapListShown[$player->login]); unset($this->mapListShown[$player->login]);
} }
} }

View File

@ -10,8 +10,8 @@ use Maniaplanet\DedicatedServer\Xmlrpc\NotInScriptModeException;
/** /**
* Mania Exchange Info Searcher Class * Mania Exchange Info Searcher Class
* *
* @author steeffeen & kremsy * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class ManiaExchangeManager { class ManiaExchangeManager {
@ -57,49 +57,6 @@ class ManiaExchangeManager {
$this->maniaControl = $maniaControl; $this->maniaControl = $maniaControl;
} }
/**
* Store Map Info from MX and store the mxid in the database and the mx info in the map object
*
* @param $mxMapInfos
*/
public function updateMapObjectsWithManiaExchangeIds($mxMapInfos) {
$mysqli = $this->maniaControl->database->mysqli;
// Save map data
$saveMapQuery = "UPDATE `" . MapManager::TABLE_MAPS . "`
SET `mxid` = ?
WHERE `uid` = ?;";
$saveMapStatement = $mysqli->prepare($saveMapQuery);
if ($mysqli->error) {
trigger_error($mysqli->error);
return;
}
$saveMapStatement->bind_param('is', $mapMxId, $mapUId);
foreach($mxMapInfos as $mxMapInfo) {
/** @var MXMapInfo $mxMapInfo */
$mapMxId = $mxMapInfo->id;
$mapUId = $mxMapInfo->uid;
$saveMapStatement->execute();
if ($saveMapStatement->error) {
trigger_error($saveMapStatement->error);
}
//Take the uid out of the vector
if (isset($this->mxIdUidVector[$mxMapInfo->id])) {
$uid = $this->mxIdUidVector[$mxMapInfo->id];
} else {
$uid = $mxMapInfo->uid;
}
$map = $this->maniaControl->mapManager->getMapByUid($uid);
if ($map) {
// TODO: how does it come that $map can be empty here? we got an error report for that
/** @var Map $map */
$map->mx = $mxMapInfo;
}
}
$saveMapStatement->close();
}
/** /**
* Unset Map by Mx Id * Unset Map by Mx Id
* *
@ -182,37 +139,6 @@ class ManiaExchangeManager {
$fetchMapStatement->close(); $fetchMapStatement->close();
} }
/**
* Get Map Info Asynchronously
*
* @param $id
* @param $function
* @return bool
*/
public function getMapInfo($id, $function) {
// Get Title Prefix
$titlePrefix = $this->maniaControl->mapManager->getCurrentMap()->getGame();
// compile search URL
$url = 'http://api.mania-exchange.com/' . $titlePrefix . '/maps/?ids=' . $id;
return $this->maniaControl->fileReader->loadFile($url, function ($mapInfo, $error) use (&$function, $titlePrefix, $url) {
$mxMapInfo = null;
if ($error) {
trigger_error($error);
} else {
$mxMapList = json_decode($mapInfo);
if ($mxMapList === null) {
trigger_error('Cannot decode searched JSON data from ' . $url);
} else {
$mxMapInfo = new MXMapInfo($titlePrefix, $mxMapList[0]);
}
}
call_user_func($function, $mxMapInfo);
}, "application/json");
}
/** /**
* Get the Whole MapList from MX by Mixed Uid and Id String fetch * Get the Whole MapList from MX by Mixed Uid and Id String fetch
* *
@ -260,6 +186,78 @@ class ManiaExchangeManager {
return $success; return $success;
} }
/**
* Store Map Info from MX and store the mxid in the database and the mx info in the map object
*
* @param $mxMapInfos
*/
public function updateMapObjectsWithManiaExchangeIds($mxMapInfos) {
$mysqli = $this->maniaControl->database->mysqli;
// Save map data
$saveMapQuery = "UPDATE `" . MapManager::TABLE_MAPS . "`
SET `mxid` = ?
WHERE `uid` = ?;";
$saveMapStatement = $mysqli->prepare($saveMapQuery);
if ($mysqli->error) {
trigger_error($mysqli->error);
return;
}
$saveMapStatement->bind_param('is', $mapMxId, $mapUId);
foreach ($mxMapInfos as $mxMapInfo) {
/** @var MXMapInfo $mxMapInfo */
$mapMxId = $mxMapInfo->id;
$mapUId = $mxMapInfo->uid;
$saveMapStatement->execute();
if ($saveMapStatement->error) {
trigger_error($saveMapStatement->error);
}
//Take the uid out of the vector
if (isset($this->mxIdUidVector[$mxMapInfo->id])) {
$uid = $this->mxIdUidVector[$mxMapInfo->id];
} else {
$uid = $mxMapInfo->uid;
}
$map = $this->maniaControl->mapManager->getMapByUid($uid);
if ($map) {
// TODO: how does it come that $map can be empty here? we got an error report for that
/** @var Map $map */
$map->mx = $mxMapInfo;
}
}
$saveMapStatement->close();
}
/**
* Get Map Info Asynchronously
*
* @param $id
* @param $function
* @return bool
*/
public function getMapInfo($id, $function) {
// Get Title Prefix
$titlePrefix = $this->maniaControl->mapManager->getCurrentMap()->getGame();
// compile search URL
$url = 'http://api.mania-exchange.com/' . $titlePrefix . '/maps/?ids=' . $id;
return $this->maniaControl->fileReader->loadFile($url, function ($mapInfo, $error) use (&$function, $titlePrefix, $url) {
$mxMapInfo = null;
if ($error) {
trigger_error($error);
} else {
$mxMapList = json_decode($mapInfo);
if ($mxMapList === null) {
trigger_error('Cannot decode searched JSON data from ' . $url);
} else {
$mxMapInfo = new MXMapInfo($titlePrefix, $mxMapList[0]);
}
}
call_user_func($function, $mxMapInfo);
}, "application/json");
}
/** /**
* Fetch a MapList Asynchronously * Fetch a MapList Asynchronously
* *

View File

@ -12,8 +12,8 @@ use ManiaControl\Players\PlayerManager;
/** /**
* Class managing the Custom UI Settings * Class managing the Custom UI Settings
* *
* @author steeffeen & kremsy * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class CustomUIManager implements CallbackListener, TimerListener { class CustomUIManager implements CallbackListener, TimerListener {
@ -51,19 +51,6 @@ class CustomUIManager implements CallbackListener, TimerListener {
$this->customUI = new CustomUI(); $this->customUI = new CustomUI();
} }
/**
* Update the CustomUI Manialink
*
* @param Player $player
*/
private function updateManialink(Player $player = null) {
if ($player) {
$this->maniaControl->manialinkManager->sendManialink($this->customUI, $player->login);
return;
}
$this->maniaControl->manialinkManager->sendManialink($this->customUI);
}
/** /**
* Handle 1Second * Handle 1Second
* *
@ -77,6 +64,19 @@ class CustomUIManager implements CallbackListener, TimerListener {
$this->updateManialink(); $this->updateManialink();
} }
/**
* Update the CustomUI Manialink
*
* @param Player $player
*/
private function updateManialink(Player $player = null) {
if ($player) {
$this->maniaControl->manialinkManager->sendManialink($this->customUI, $player->login);
return;
}
$this->maniaControl->manialinkManager->sendManialink($this->customUI);
}
/** /**
* Handle PlayerJoined Callback * Handle PlayerJoined Callback
* *

View File

@ -8,14 +8,14 @@ use FML\ManiaLink;
use ManiaControl\Callbacks\CallbackListener; use ManiaControl\Callbacks\CallbackListener;
use ManiaControl\Callbacks\CallbackManager; use ManiaControl\Callbacks\CallbackManager;
use ManiaControl\ManiaControl; use ManiaControl\ManiaControl;
use ManiaControl\Players\PlayerManager;
use ManiaControl\Players\Player; use ManiaControl\Players\Player;
use ManiaControl\Players\PlayerManager;
/** /**
* Class managing Icons * Class managing Icons
* *
* @author steeffeen & kremsy * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class IconManager implements CallbackListener { class IconManager implements CallbackListener {
@ -95,15 +95,6 @@ class IconManager implements CallbackListener {
$this->preloadIcons(); $this->preloadIcons();
} }
/**
* Handle PlayerConnect Callback
*
* @param Player $player
*/
public function handlePlayerConnect(Player $player) {
$this->preloadIcons($player);
}
/** /**
* Preload Icons * Preload Icons
* *
@ -125,4 +116,13 @@ class IconManager implements CallbackListener {
// Send manialink // Send manialink
$this->maniaControl->manialinkManager->sendManialink($maniaLink, $player); $this->maniaControl->manialinkManager->sendManialink($maniaLink, $player);
} }
/**
* Handle PlayerConnect Callback
*
* @param Player $player
*/
public function handlePlayerConnect(Player $player) {
$this->preloadIcons($player);
}
} }

View File

@ -16,8 +16,8 @@ use Maniaplanet\DedicatedServer\Xmlrpc\NotInScriptModeException;
/** /**
* Manialink Manager Class * Manialink Manager Class
* *
* @author steeffeen & kremsy * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class ManialinkManager implements ManialinkPageAnswerListener, CallbackListener { class ManialinkManager implements ManialinkPageAnswerListener, CallbackListener {
@ -214,46 +214,13 @@ class ManialinkManager implements ManialinkPageAnswerListener, CallbackListener
return $success; return $success;
} }
} } catch (LoginUnknownException $e) {
catch (LoginUnknownException $e) {
return false; return false;
} }
return true; return true;
} }
/**
* Enable the alt menu for the player
*
* @param Player $player
* @return bool
*/
public function enableAltMenu(Player $player) {
try {
$success = $this->maniaControl->client->triggerModeScriptEvent('LibXmlRpc_EnableAltMenu', $player->login);
}
catch (NotInScriptModeException $e) {
return false;
}
return $success;
}
/**
* Disable the alt menu for the player
*
* @param Player $player
* @return bool
*/
public function disableAltMenu(Player $player) {
try {
$success = $this->maniaControl->client->triggerModeScriptEvent('LibXmlRpc_DisableAltMenu', $player->login);
}
catch (NotInScriptModeException $e) {
return false;
}
return $success;
}
/** /**
* Displays a ManiaLink Widget to a certain Player (Should only be used on Main Widgets) * Displays a ManiaLink Widget to a certain Player (Should only be used on Main Widgets)
* *
@ -273,6 +240,21 @@ class ManialinkManager implements ManialinkPageAnswerListener, CallbackListener
} }
} }
/**
* Disable the alt menu for the player
*
* @param Player $player
* @return bool
*/
public function disableAltMenu(Player $player) {
try {
$success = $this->maniaControl->client->triggerModeScriptEvent('LibXmlRpc_DisableAltMenu', $player->login);
} catch (NotInScriptModeException $e) {
return false;
}
return $success;
}
/** /**
* Closes a widget via the callback * Closes a widget via the callback
* *
@ -297,13 +279,27 @@ class ManialinkManager implements ManialinkPageAnswerListener, CallbackListener
// Trigger callback // Trigger callback
$this->maniaControl->callbackManager->triggerCallback(self::CB_MAIN_WINDOW_CLOSED, $player); $this->maniaControl->callbackManager->triggerCallback(self::CB_MAIN_WINDOW_CLOSED, $player);
} } else {
else {
$emptyManialink = new ManiaLink($widgetId); $emptyManialink = new ManiaLink($widgetId);
$this->sendManialink($emptyManialink, $player->login); $this->sendManialink($emptyManialink, $player->login);
} }
} }
/**
* Enable the alt menu for the player
*
* @param Player $player
* @return bool
*/
public function enableAltMenu(Player $player) {
try {
$success = $this->maniaControl->client->triggerModeScriptEvent('LibXmlRpc_EnableAltMenu', $player->login);
} catch (NotInScriptModeException $e) {
return false;
}
return $success;
}
/** /**
* Adds a line of labels * Adds a line of labels
* *

View File

@ -5,8 +5,8 @@ namespace ManiaControl\Manialinks;
/** /**
* Interface for Manialink Page Answer Listeners * Interface for Manialink Page Answer Listeners
* *
* @author steeffeen & kremsy * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
interface ManialinkPageAnswerListener { interface ManialinkPageAnswerListener {

View File

@ -16,8 +16,8 @@ use ManiaControl\ManiaControl;
/** /**
* Class managing default Control Styles * Class managing default Control Styles
* *
* @author steeffeen & kremsy * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class StyleManager { class StyleManager {
@ -98,21 +98,23 @@ class StyleManager {
} }
/** /**
* Get the default main window style * Gets the Default Description Label
* *
* @return string * @return Label
*/ */
public function getDefaultMainWindowStyle() { public function getDefaultDescriptionLabel() {
return $this->maniaControl->settingManager->getSetting($this, self::SETTING_MAIN_WIDGET_DEFAULT_STYLE); $width = $this->getListWidgetsWidth();
} $height = $this->getListWidgetsHeight();
/** // Predefine Description Label
* Get the default main window substyle $descriptionLabel = new Label();
* $descriptionLabel->setAlign(Control::LEFT, Control::TOP);
* @return string $descriptionLabel->setPosition(-$width / 2 + 10, -$height / 2 + 5);
*/ $descriptionLabel->setSize($width * 0.7, 4);
public function getDefaultMainWindowSubStyle() { $descriptionLabel->setTextSize(2);
return $this->maniaControl->settingManager->getSetting($this, self::SETTING_MAIN_WIDGET_DEFAULT_SUBSTYLE); $descriptionLabel->setVisible(false);
return $descriptionLabel;
} }
/** /**
@ -133,27 +135,6 @@ class StyleManager {
return $this->maniaControl->settingManager->getSetting($this, self::SETTING_LIST_WIDGETS_HEIGHT); return $this->maniaControl->settingManager->getSetting($this, self::SETTING_LIST_WIDGETS_HEIGHT);
} }
/**
* Gets the Default Description Label
*
* @return Label
*/
public function getDefaultDescriptionLabel() {
$width = $this->getListWidgetsWidth();
$height = $this->getListWidgetsHeight();
// Predefine Description Label
$descriptionLabel = new Label();
$descriptionLabel->setAlign(Control::LEFT, Control::TOP);
$descriptionLabel->setPosition(-$width / 2 + 10, -$height / 2 + 5);
$descriptionLabel->setSize($width * 0.7, 4);
$descriptionLabel->setTextSize(2);
$descriptionLabel->setVisible(false);
return $descriptionLabel;
}
/** /**
* Builds the Default List Frame * Builds the Default List Frame
* *
@ -228,4 +209,22 @@ class StyleManager {
return $frame; return $frame;
} }
/**
* Get the default main window style
*
* @return string
*/
public function getDefaultMainWindowStyle() {
return $this->maniaControl->settingManager->getSetting($this, self::SETTING_MAIN_WIDGET_DEFAULT_STYLE);
}
/**
* Get the default main window substyle
*
* @return string
*/
public function getDefaultMainWindowSubStyle() {
return $this->maniaControl->settingManager->getSetting($this, self::SETTING_MAIN_WIDGET_DEFAULT_SUBSTYLE);
}
} }

View File

@ -6,10 +6,10 @@ use ManiaControl\Formatter;
use ManiaControl\ManiaExchange\MXMapInfo; use ManiaControl\ManiaExchange\MXMapInfo;
/** /**
* Map Class * Map Model Class
* *
* @author kremsy & steeffeen * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class Map { class Map {

View File

@ -5,8 +5,8 @@ namespace ManiaControl\Maps;
use FML\Controls\Quad; use FML\Controls\Quad;
use FML\Controls\Quads\Quad_Icons64x64_1; use FML\Controls\Quads\Quad_Icons64x64_1;
use FML\Controls\Quads\Quad_UIConstruction_Buttons; use FML\Controls\Quads\Quad_UIConstruction_Buttons;
use ManiaControl\Callbacks\CallbackManager;
use ManiaControl\Callbacks\CallbackListener; use ManiaControl\Callbacks\CallbackListener;
use ManiaControl\Callbacks\CallbackManager;
use ManiaControl\Commands\CommandListener; use ManiaControl\Commands\CommandListener;
use ManiaControl\ManiaControl; use ManiaControl\ManiaControl;
use ManiaControl\Manialinks\IconManager; use ManiaControl\Manialinks\IconManager;
@ -18,8 +18,8 @@ use Maniaplanet\DedicatedServer\Xmlrpc\FaultException;
/** /**
* Class offering Commands to manage Maps * Class offering Commands to manage Maps
* *
* @author steeffeen & kremsy * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class MapCommands implements CommandListener, ManialinkPageAnswerListener, CallbackListener { class MapCommands implements CommandListener, ManialinkPageAnswerListener, CallbackListener {
@ -330,6 +330,30 @@ class MapCommands implements CommandListener, ManialinkPageAnswerListener, Callb
} }
} }
/**
* Show the Player a List of Maps from the given Author
*
* @param string $author
* @param Player $player
*/
private function showMapListAuthor($author, Player $player) {
$maps = $this->maniaControl->mapManager->getMaps();
$mapList = array();
/** @var Map $map */
foreach ($maps as $map) {
if ($map->authorLogin == $author) {
$mapList[] = $map;
}
}
if (count($mapList) == 0) {
$this->maniaControl->chat->sendError('There are no maps to show!', $player->login);
return;
}
$this->maniaControl->mapManager->mapList->showMapList($player, $mapList);
}
/** /**
* Handle /maps command * Handle /maps command
* *
@ -362,29 +386,6 @@ class MapCommands implements CommandListener, ManialinkPageAnswerListener, Callb
} }
} }
/**
* Show the Player a List of Maps from the given Author
* @param string $author
* @param Player $player
*/
private function showMapListAuthor($author, Player $player) {
$maps = $this->maniaControl->mapManager->getMaps();
$mapList = array();
/** @var Map $map */
foreach($maps as $map) {
if($map->authorLogin == $author) {
$mapList[] = $map;
}
}
if(count($mapList) == 0) {
$this->maniaControl->chat->sendError('There are no maps to show!', $player->login);
return;
}
$this->maniaControl->mapManager->mapList->showMapList($player, $mapList);
}
/** /**
* Show a Karma based MapList * Show a Karma based MapList
* *
@ -434,17 +435,6 @@ class MapCommands implements CommandListener, ManialinkPageAnswerListener, Callb
} }
} }
/**
* Helper Function to sort Maps by Karma
*
* @param Map $a
* @param Map $b
* @return mixed
*/
private function sortByKarma($a, $b) {
return ($a->karma - $b->karma);
}
/** /**
* Show a Date based MapList * Show a Date based MapList
* *
@ -474,4 +464,15 @@ class MapCommands implements CommandListener, ManialinkPageAnswerListener, Callb
public function command_xList(array $chatCallback, Player $player) { public function command_xList(array $chatCallback, Player $player) {
$this->maniaControl->mapManager->mxList->showList($chatCallback, $player); $this->maniaControl->mapManager->mxList->showList($chatCallback, $player);
} }
/**
* Helper Function to sort Maps by Karma
*
* @param Map $a
* @param Map $b
* @return mixed
*/
private function sortByKarma($a, $b) {
return ($a->karma - $b->karma);
}
} }

View File

@ -2,7 +2,6 @@
namespace ManiaControl\Maps; namespace ManiaControl\Maps;
use MCTeam\CustomVotesPlugin;
use FML\Controls\Control; use FML\Controls\Control;
use FML\Controls\Frame; use FML\Controls\Frame;
use FML\Controls\Gauge; use FML\Controls\Gauge;
@ -25,13 +24,14 @@ use ManiaControl\Manialinks\ManialinkManager;
use ManiaControl\Manialinks\ManialinkPageAnswerListener; use ManiaControl\Manialinks\ManialinkPageAnswerListener;
use ManiaControl\Players\Player; use ManiaControl\Players\Player;
use Maniaplanet\DedicatedServer\Xmlrpc\Exception; use Maniaplanet\DedicatedServer\Xmlrpc\Exception;
use MCTeam\CustomVotesPlugin;
use MCTeam\KarmaPlugin; use MCTeam\KarmaPlugin;
/** /**
* MapList Widget Class * MapList Widget Class
* *
* @author steeffeen & kremsy * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class MapList implements ManialinkPageAnswerListener, CallbackListener { class MapList implements ManialinkPageAnswerListener, CallbackListener {
@ -127,14 +127,12 @@ class MapList implements ManialinkPageAnswerListener, CallbackListener {
$mapList = array_slice($maps, $chunk, self::MAX_PAGES_PER_CHUNK * self::MAX_MAPS_PER_PAGE); $mapList = array_slice($maps, $chunk, self::MAX_PAGES_PER_CHUNK * self::MAX_MAPS_PER_PAGE);
$this->mapsInListShown[$player->login] = $maps; $this->mapsInListShown[$player->login] = $maps;
$pageCount = ceil(count($maps) / self::MAX_MAPS_PER_PAGE); $pageCount = ceil(count($maps) / self::MAX_MAPS_PER_PAGE);
} } else if (array_key_exists($player->login, $this->mapsInListShown)) {
else if (array_key_exists($player->login, $this->mapsInListShown)) {
$completeList = $this->mapsInListShown[$player->login]; $completeList = $this->mapsInListShown[$player->login];
$this->mapsInListShown[$player->login] = $completeList; $this->mapsInListShown[$player->login] = $completeList;
$mapList = array_slice($completeList, $chunk * self::MAX_PAGES_PER_CHUNK * self::MAX_MAPS_PER_PAGE, self::MAX_PAGES_PER_CHUNK * self::MAX_MAPS_PER_PAGE); $mapList = array_slice($completeList, $chunk * self::MAX_PAGES_PER_CHUNK * self::MAX_MAPS_PER_PAGE, self::MAX_PAGES_PER_CHUNK * self::MAX_MAPS_PER_PAGE);
$pageCount = ceil(count($completeList) / self::MAX_MAPS_PER_PAGE); $pageCount = ceil(count($completeList) / self::MAX_MAPS_PER_PAGE);
} } else {
else {
$mapList = $this->maniaControl->mapManager->getMaps($chunk * self::MAX_PAGES_PER_CHUNK * self::MAX_MAPS_PER_PAGE, self::MAX_PAGES_PER_CHUNK * self::MAX_MAPS_PER_PAGE); $mapList = $this->maniaControl->mapManager->getMaps($chunk * self::MAX_PAGES_PER_CHUNK * self::MAX_MAPS_PER_PAGE, self::MAX_PAGES_PER_CHUNK * self::MAX_MAPS_PER_PAGE);
$pageCount = ceil($this->maniaControl->mapManager->getMapsCount() / self::MAX_MAPS_PER_PAGE); $pageCount = ceil($this->maniaControl->mapManager->getMapsCount() / self::MAX_MAPS_PER_PAGE);
$this->mapsInListShown[$player->login] = $this->maniaControl->mapManager->getMaps(); $this->mapsInListShown[$player->login] = $this->maniaControl->mapManager->getMaps();
@ -145,7 +143,9 @@ class MapList implements ManialinkPageAnswerListener, CallbackListener {
$script = $maniaLink->getScript(); $script = $maniaLink->getScript();
$paging = new Paging(); $paging = new Paging();
$script->addFeature($paging); $script->addFeature($paging);
if (!is_null($pageCount)) $paging->setCustomMaxPageNumber($pageCount); if (!is_null($pageCount)) {
$paging->setCustomMaxPageNumber($pageCount);
}
$paging->setChunkActionAppendsPageNumber(true); $paging->setChunkActionAppendsPageNumber(true);
$paging->setChunkActions(self::ACTION_PAGING_CHUNKS); $paging->setChunkActions(self::ACTION_PAGING_CHUNKS);
@ -204,8 +204,7 @@ class MapList implements ManialinkPageAnswerListener, CallbackListener {
$frame->add($headFrame); $frame->add($headFrame);
$headFrame->setY($height / 2 - 5); $headFrame->setY($height / 2 - 5);
$x = -$width / 2; $x = -$width / 2;
$array = array('Id' => $x + 5, 'Mx Id' => $x + 10, 'Map Name' => $x + 20, 'Author' => $x + 68, 'Karma' => $x + 115, $array = array('Id' => $x + 5, 'Mx Id' => $x + 10, 'Map Name' => $x + 20, 'Author' => $x + 68, 'Karma' => $x + 115, 'Actions' => $width / 2 - 15);
'Actions' => $width / 2 - 15);
$this->maniaControl->manialinkManager->labelLine($headFrame, $array); $this->maniaControl->manialinkManager->labelLine($headFrame, $array);
// Predefine description Label // Predefine description Label
@ -214,7 +213,6 @@ class MapList implements ManialinkPageAnswerListener, CallbackListener {
$queuedMaps = $this->maniaControl->mapManager->mapQueue->getQueuedMapsRanking(); $queuedMaps = $this->maniaControl->mapManager->mapQueue->getQueuedMapsRanking();
/** /**
*
* @var KarmaPlugin $karmaPlugin * @var KarmaPlugin $karmaPlugin
*/ */
$karmaPlugin = $this->maniaControl->pluginManager->getPlugin(self::DEFAULT_KARMA_PLUGIN); $karmaPlugin = $this->maniaControl->pluginManager->getPlugin(self::DEFAULT_KARMA_PLUGIN);
@ -227,7 +225,6 @@ class MapList implements ManialinkPageAnswerListener, CallbackListener {
$y = $height / 2 - 10; $y = $height / 2 - 10;
$pageFrames = array(); $pageFrames = array();
/** /**
*
* @var Map $map * @var Map $map
*/ */
$currentMap = $this->maniaControl->mapManager->getCurrentMap(); $currentMap = $this->maniaControl->mapManager->getCurrentMap();
@ -312,7 +309,6 @@ class MapList implements ManialinkPageAnswerListener, CallbackListener {
$labels = $this->maniaControl->manialinkManager->labelLine($mapFrame, $array); $labels = $this->maniaControl->manialinkManager->labelLine($mapFrame, $array);
if (isset($labels[3])) { if (isset($labels[3])) {
/** /**
*
* @var Label $label * @var Label $label
*/ */
$label = $labels[3]; $label = $labels[3];
@ -340,13 +336,11 @@ class MapList implements ManialinkPageAnswerListener, CallbackListener {
$description = 'Remove $<' . $map->name . '$> from the Map Queue'; $description = 'Remove $<' . $map->name . '$> from the Map Queue';
$label->addTooltipLabelFeature($descriptionLabel, $description); $label->addTooltipLabelFeature($descriptionLabel, $description);
$label->setAction(self::ACTION_UNQUEUE_MAP . '.' . $map->uid); $label->setAction(self::ACTION_UNQUEUE_MAP . '.' . $map->uid);
} } else {
else {
$description = '$<' . $map->name . '$> is on Map-Queue Position: ' . $queuedMaps[$map->uid]; $description = '$<' . $map->name . '$> is on Map-Queue Position: ' . $queuedMaps[$map->uid];
$label->addTooltipLabelFeature($descriptionLabel, $description); $label->addTooltipLabelFeature($descriptionLabel, $description);
} }
} } else {
else {
// Map-Queue-Map-Button // Map-Queue-Map-Button
$queueLabel = new Label_Button(); $queueLabel = new Label_Button();
$mapFrame->add($queueLabel); $mapFrame->add($queueLabel);
@ -403,8 +397,7 @@ class MapList implements ManialinkPageAnswerListener, CallbackListener {
$description = 'Switch Directly to Map: $<' . $map->name . '$>'; $description = 'Switch Directly to Map: $<' . $map->name . '$>';
$switchLabel->addTooltipLabelFeature($descriptionLabel, $description); $switchLabel->addTooltipLabelFeature($descriptionLabel, $description);
} } else if ($this->maniaControl->pluginManager->isPluginActive(self::DEFAULT_CUSTOM_VOTE_PLUGIN)) {
else if ($this->maniaControl->pluginManager->isPluginActive(self::DEFAULT_CUSTOM_VOTE_PLUGIN)) {
// Switch Map Voting // Switch Map Voting
$switchLabel = new Label_Button(); $switchLabel = new Label_Button();
$mapFrame->add($switchLabel); $mapFrame->add($switchLabel);
@ -527,8 +520,7 @@ class MapList implements ManialinkPageAnswerListener, CallbackListener {
$buttLabel->setText('»'); $buttLabel->setText('»');
$buttLabel->setTextColor('0f0'); $buttLabel->setTextColor('0f0');
$buttLabel->setTextSize(2); $buttLabel->setTextSize(2);
} } else {
else {
$buttLabel->setTextSize(1); $buttLabel->setTextSize(1);
$buttLabel->setText('x'); $buttLabel->setText('x');
$buttLabel->setTextColor('a00'); $buttLabel->setTextColor('a00');
@ -560,17 +552,6 @@ class MapList implements ManialinkPageAnswerListener, CallbackListener {
unset($this->mapsInListShown[$player->login]); unset($this->mapsInListShown[$player->login]);
} }
/**
* Closes the widget
*
* @param Player $player
*/
public function playerCloseWidget(Player $player) {
unset($this->mapListShown[$player->login]);
unset($this->mapsInListShown[$player->login]);
$this->maniaControl->manialinkManager->closeWidget($player);
}
/** /**
* Handle ManialinkPageAnswer Callback * Handle ManialinkPageAnswer Callback
* *
@ -602,8 +583,7 @@ class MapList implements ManialinkPageAnswerListener, CallbackListener {
case self::ACTION_SWITCH_MAP: case self::ACTION_SWITCH_MAP:
try { try {
$this->maniaControl->client->jumpToMapIndex($mapId); $this->maniaControl->client->jumpToMapIndex($mapId);
} } catch (Exception $e) {
catch (Exception $e) {
// TODO: is it even possible that an exception other than connection errors will be thrown? - remove try-catch? // TODO: is it even possible that an exception other than connection errors will be thrown? - remove try-catch?
$this->maniaControl->chat->sendError("Error while Jumping to Map Index"); $this->maniaControl->chat->sendError("Error while Jumping to Map Index");
break; break;
@ -619,7 +599,6 @@ class MapList implements ManialinkPageAnswerListener, CallbackListener {
break; break;
case self::ACTION_START_SWITCH_VOTE: case self::ACTION_START_SWITCH_VOTE:
/** /**
*
* @var $votesPlugin CustomVotesPlugin * @var $votesPlugin CustomVotesPlugin
*/ */
$votesPlugin = $this->maniaControl->pluginManager->getPlugin(self::DEFAULT_CUSTOM_VOTE_PLUGIN); $votesPlugin = $this->maniaControl->pluginManager->getPlugin(self::DEFAULT_CUSTOM_VOTE_PLUGIN);
@ -629,7 +608,6 @@ class MapList implements ManialinkPageAnswerListener, CallbackListener {
$message = '$<' . $player->nickname . '$>$s started a vote to switch to $<' . $map->name . '$>!'; $message = '$<' . $player->nickname . '$>$s started a vote to switch to $<' . $map->name . '$>!';
/** /**
*
* @var Map $map * @var Map $map
*/ */
$votesPlugin->defineVote('switchmap', "Goto " . $map->name, true, $message); $votesPlugin->defineVote('switchmap', "Goto " . $map->name, true, $message);
@ -642,8 +620,7 @@ class MapList implements ManialinkPageAnswerListener, CallbackListener {
try { try {
$index = $self->maniaControl->mapManager->getMapIndex($map); $index = $self->maniaControl->mapManager->getMapIndex($map);
$self->maniaControl->client->jumpToMapIndex($index); $self->maniaControl->client->jumpToMapIndex($index);
} } catch (Exception $e) {
catch (Exception $e) {
// TODO temp added 19.04.2014 // TODO temp added 19.04.2014
$self->maniaControl->errorHandler->triggerDebugNotice("Exception line 557 MapList.php" . $e->getMessage()); $self->maniaControl->errorHandler->triggerDebugNotice("Exception line 557 MapList.php" . $e->getMessage());
@ -670,6 +647,17 @@ class MapList implements ManialinkPageAnswerListener, CallbackListener {
} }
} }
/**
* Closes the widget
*
* @param Player $player
*/
public function playerCloseWidget(Player $player) {
unset($this->mapListShown[$player->login]);
unset($this->mapsInListShown[$player->login]);
$this->maniaControl->manialinkManager->closeWidget($player);
}
/** /**
* Reopen the widget on Map Begin, MapListChanged, etc. * Reopen the widget on Map Begin, MapListChanged, etc.
*/ */
@ -679,8 +667,7 @@ class MapList implements ManialinkPageAnswerListener, CallbackListener {
$player = $this->maniaControl->playerManager->getPlayer($login); $player = $this->maniaControl->playerManager->getPlayer($login);
if ($player) { if ($player) {
$this->showMapList($player); $this->showMapList($player);
} } else {
else {
unset($this->mapListShown[$login]); unset($this->mapListShown[$login]);
} }
} }
@ -696,8 +683,7 @@ class MapList implements ManialinkPageAnswerListener, CallbackListener {
$player = $this->maniaControl->playerManager->getPlayer($login); $player = $this->maniaControl->playerManager->getPlayer($login);
if ($player) { if ($player) {
$this->showMapList($player); $this->showMapList($player);
} } else {
else {
unset($this->mapListShown[$login]); unset($this->mapListShown[$login]);
} }
} }

View File

@ -22,8 +22,8 @@ use Maniaplanet\DedicatedServer\Xmlrpc\StartIndexOutOfBoundException;
/** /**
* Manager for Maps * Manager for Maps
* *
* @author kremsy & steeffeen * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class MapManager implements CallbackListener { class MapManager implements CallbackListener {
@ -129,44 +129,26 @@ class MapManager implements CallbackListener {
} }
/** /**
* Save a Map in the Database * Update a Map from Mania Exchange
* *
* @param \ManiaControl\Maps\Map $map * @param Player $admin
* @return bool * @param string $uid
*/ */
private function saveMap(Map &$map) { public function updateMap(Player $admin, $uid) {
//TODO saveMaps for whole maplist at once (usage of prepared statements) $this->updateMapTimestamp($uid);
$mysqli = $this->maniaControl->database->mysqli;
$mapQuery = "INSERT INTO `" . self::TABLE_MAPS . "` (
`uid`,
`name`,
`authorLogin`,
`fileName`,
`environment`,
`mapType`
) VALUES (
?, ?, ?, ?, ?, ?
) ON DUPLICATE KEY UPDATE
`index` = LAST_INSERT_ID(`index`),
`fileName` = VALUES(`fileName`),
`environment` = VALUES(`environment`),
`mapType` = VALUES(`mapType`);";
$mapStatement = $mysqli->prepare($mapQuery); if (!isset($uid) || !isset($this->maps[$uid])) {
if ($mysqli->error) { trigger_error("Error while updating Map, unknown UID: " . $uid);
trigger_error($mysqli->error); $this->maniaControl->chat->sendError("Error while updating Map.", $admin->login);
return false; return;
} }
$mapStatement->bind_param('ssssss', $map->uid, $map->rawName, $map->authorLogin, $map->fileName, $map->environment, $map->mapType);
$mapStatement->execute(); /** @var Map $map */
if ($mapStatement->error) { $map = $this->maps[$uid];
trigger_error($mapStatement->error);
$mapStatement->close(); $mxId = $map->mx->id;
return false; $this->removeMap($admin, $uid, true, false);
} $this->addMapFromMx($mxId, $admin->login, true);
$map->index = $mapStatement->insert_id;
$mapStatement->close();
return true;
} }
/** /**
@ -198,29 +180,6 @@ class MapManager implements CallbackListener {
return true; return true;
} }
/**
* Update a Map from Mania Exchange
*
* @param Player $admin
* @param string $uid
*/
public function updateMap(Player $admin, $uid) {
$this->updateMapTimestamp($uid);
if (!isset($uid) || !isset($this->maps[$uid])) {
trigger_error("Error while updating Map, unknown UID: " . $uid);
$this->maniaControl->chat->sendError("Error while updating Map.", $admin->login);
return;
}
/** @var Map $map */
$map = $this->maps[$uid];
$mxId = $map->mx->id;
$this->removeMap($admin, $uid, true, false);
$this->addMapFromMx($mxId, $admin->login, true);
}
/** /**
* Remove a Map * Remove a Map
* *
@ -273,330 +232,6 @@ class MapManager implements CallbackListener {
unset($this->maps[$uid]); unset($this->maps[$uid]);
} }
/**
* Restructures the Maplist
*/
public function restructureMapList() {
$currentIndex = $this->getMapIndex($this->currentMap);
// No RestructureNeeded
if ($currentIndex < Maplist::MAX_MAPS_PER_PAGE - 1) {
return true;
}
$lowerMapArray = array();
$higherMapArray = array();
$i = 0;
foreach($this->maps as $map) {
if ($i < $currentIndex) {
$lowerMapArray[] = $map->fileName;
} else {
$higherMapArray[] = $map->fileName;
}
$i++;
}
$mapArray = array_merge($higherMapArray, $lowerMapArray);
array_shift($mapArray);
try {
$this->maniaControl->client->chooseNextMapList($mapArray);
} catch(Exception $e) {
trigger_error("Error while restructuring the Maplist. " . $e->getMessage());
return false;
}
return true;
}
/**
* Shuffles the MapList
*
* @param Player $admin
* @return bool
*/
public function shuffleMapList($admin = null) {
$shuffledMaps = $this->maps;
shuffle($shuffledMaps);
$mapArray = array();
foreach($shuffledMaps as $map) {
/**
* @var Map $map
*/
$mapArray[] = $map->fileName;
}
try {
$this->maniaControl->client->chooseNextMapList($mapArray);
} catch(Exception $e) {
//TODO temp added 19.04.2014
$this->maniaControl->errorHandler->triggerDebugNotice("Exception line 331 MapManager" . $e->getMessage());
trigger_error("Couldn't shuffle mapList. " . $e->getMessage());
return false;
}
$this->fetchCurrentMap();
if ($admin) {
$message = '$<' . $admin->nickname . '$> shuffled the Maplist!';
$this->maniaControl->chat->sendSuccess($message);
$this->maniaControl->log($message, true);
}
// Restructure if needed
$this->restructureMapList();
return true;
}
/**
* Initializes a Map
*
* @param $rpcMap
* @return Map
*/
public function initializeMap($rpcMap) {
$map = new Map($rpcMap);
$this->saveMap($map);
/*$mapsDirectory = $this->maniaControl->server->getMapsDirectory();
if (is_readable($mapsDirectory . $map->fileName)) {
$mapFetcher = new \GBXChallMapFetcher(true);
$mapFetcher->processFile($mapsDirectory . $map->fileName);
$map->authorNick = FORMATTER::stripDirtyCodes($mapFetcher->authorNick);
$map->authorEInfo = $mapFetcher->authorEInfo;
$map->authorZone = $mapFetcher->authorZone;
$map->comment = $mapFetcher->comment;
}*/
return $map;
}
/**
* Updates the full Map list, needed on Init, addMap and on ShuffleMaps
*/
private function updateFullMapList() {
$tempList = array();
try {
$i = 0;
while(true) {
$maps = $this->maniaControl->client->getMapList(150, $i);
foreach($maps as $rpcMap) {
if (array_key_exists($rpcMap->uId, $this->maps)) {
// Map already exists, only update index
$tempList[$rpcMap->uId] = $this->maps[$rpcMap->uId];
} else { // Insert Map Object
$map = $this->initializeMap($rpcMap);
$tempList[$map->uid] = $map;
}
}
$i += 150;
}
} catch(StartIndexOutOfBoundException $e) {
}
// restore Sorted MapList
$this->maps = $tempList;
// Trigger own callback
$this->maniaControl->callbackManager->triggerCallback(self::CB_MAPS_UPDATED);
// Write MapList
if ($this->maniaControl->settingManager->getSetting($this, self::SETTING_AUTOSAVE_MAPLIST)) {
try {
$this->maniaControl->client->saveMatchSettings($this->maniaControl->settingManager->getSetting($this, self::SETTING_MAPLIST_FILE));
} catch(CouldNotWritePlaylistFileException $e) {
$this->maniaControl->log("Unable to write the playlist file, please checkout your MX-Folders File permissions!");
}
}
}
/**
* Freshly fetch current Map
*
* @return Map
*/
private function fetchCurrentMap() {
$rpcMap = $this->maniaControl->client->getCurrentMapInfo();
if (array_key_exists($rpcMap->uId, $this->maps)) {
$this->currentMap = $this->maps[$rpcMap->uId];
$this->currentMap->nbCheckpoints = $rpcMap->nbCheckpoints;
$this->currentMap->nbLaps = $rpcMap->nbLaps;
return $this->currentMap;
}
$this->currentMap = $this->initializeMap($rpcMap);
$this->maps[$this->currentMap->uid] = $this->currentMap;
return $this->currentMap;
}
/**
* Handle OnInit callback
*/
public function handleOnInit() {
$this->updateFullMapList();
$this->fetchCurrentMap();
// Restructure Maplist
$this->restructureMapList();
}
/**
* Handle AfterInit callback
*/
public function handleAfterInit() {
// Fetch MX infos
$this->mxManager->fetchManiaExchangeMapInformations();
}
/**
* Get Current Map
*
* @return Map currentMap
*/
public function getCurrentMap() {
if (!$this->currentMap) {
return $this->fetchCurrentMap();
}
return $this->currentMap;
}
/**
* Returns map By UID
*
* @param $uid
* @return Map array
*/
public function getMapByUid($uid) {
if (!isset($this->maps[$uid])) {
return null;
}
return $this->maps[$uid];
}
/**
* Handle BeginMap callback
*
* @param array $callback
*/
public function handleBeginMap(array $callback) {
if ($this->mapBegan) {
return;
}
$this->mapBegan = true;
$this->mapEnded = false;
if (!isset($callback[1][0]["UId"])) {
$this->currentMap = $this->fetchCurrentMap();
} else if (array_key_exists($callback[1][0]["UId"], $this->maps)) {
// Map already exists, only update index
$this->currentMap = $this->maps[$callback[1][0]["UId"]];
if (!$this->currentMap->nbCheckpoints || !$this->currentMap->nbLaps) {
$rpcMap = $this->maniaControl->client->getCurrentMapInfo();
$this->currentMap->nbLaps = $rpcMap->nbLaps;
$this->currentMap->nbCheckpoints = $rpcMap->nbCheckpoints;
}
}
// Restructure MapList if id is over 15
$this->restructureMapList();
// Update the mx of the map (for update checks, etc.)
$this->mxManager->fetchManiaExchangeMapInformations($this->currentMap);
// Trigger own BeginMap callback (
//TODO remove deprecated callback later
$this->maniaControl->callbackManager->triggerCallback(self::CB_BEGINMAP, $this->currentMap);
$this->maniaControl->callbackManager->triggerCallback(Callbacks::BEGINMAP, $this->currentMap);
}
/**
* Handle Script BeginMap callback
*
* @param int $mapNumber
*/
public function handleScriptBeginMap($mapNumber) {
$this->handleBeginMap(array());
}
/**
* Handle EndMap Callback
*
* @param array $callback
*/
public function handleEndMap(array $callback) {
if ($this->mapEnded) {
return;
}
$this->mapEnded = true;
$this->mapBegan = false;
// Trigger own EndMap callback
$this->maniaControl->callbackManager->triggerCallback(self::CB_ENDMAP, $this->currentMap);
//TODO remove deprecated callback later
$this->maniaControl->callbackManager->triggerCallback(Callbacks::ENDMAP, $this->currentMap);
}
/**
* Handle Script EndMap Callback
*
* @param int $mapNumber
*/
public function handleScriptEndMap($mapNumber) {
$this->handleEndMap(array());
}
/**
* Handle Maps Modified Callback
*
* @param array $callback
*/
public function mapsModified(array $callback) {
$this->updateFullMapList();
}
/**
* Get all Maps
*
* @param int $offset
* @param int $length
* @return array
*/
public function getMaps($offset = null, $length = null) {
if ($offset === null) {
return array_values($this->maps);
}
if ($length === null) {
return array_slice($this->maps, $offset);
}
return array_slice($this->maps, $offset, $length);
}
/**
* Get the Number of Maps
*
* @return int
*/
public function getMapsCount() {
return count($this->maps);
}
/**
* Returns the MapIndex of a given map
*
* @param Map $map
* @internal param $uid
* @return mixed
*/
public function getMapIndex(Map $map) {
$maps = $this->getMaps();
return array_search($map, $maps);
}
/** /**
* Adds a Map from Mania Exchange * Adds a Map from Mania Exchange
* *
@ -719,5 +354,370 @@ class MapManager implements CallbackListener {
$this->maniaControl->log($message, true); $this->maniaControl->log($message, true);
} }
} }
/**
* Returns map By UID
*
* @param $uid
* @return Map array
*/
public function getMapByUid($uid) {
if (!isset($this->maps[$uid])) {
return null;
}
return $this->maps[$uid];
}
/**
* Updates the full Map list, needed on Init, addMap and on ShuffleMaps
*/
private function updateFullMapList() {
$tempList = array();
try {
$i = 0;
while (true) {
$maps = $this->maniaControl->client->getMapList(150, $i);
foreach ($maps as $rpcMap) {
if (array_key_exists($rpcMap->uId, $this->maps)) {
// Map already exists, only update index
$tempList[$rpcMap->uId] = $this->maps[$rpcMap->uId];
} else { // Insert Map Object
$map = $this->initializeMap($rpcMap);
$tempList[$map->uid] = $map;
}
}
$i += 150;
}
} catch (StartIndexOutOfBoundException $e) {
}
// restore Sorted MapList
$this->maps = $tempList;
// Trigger own callback
$this->maniaControl->callbackManager->triggerCallback(self::CB_MAPS_UPDATED);
// Write MapList
if ($this->maniaControl->settingManager->getSetting($this, self::SETTING_AUTOSAVE_MAPLIST)) {
try {
$this->maniaControl->client->saveMatchSettings($this->maniaControl->settingManager->getSetting($this, self::SETTING_MAPLIST_FILE));
} catch (CouldNotWritePlaylistFileException $e) {
$this->maniaControl->log("Unable to write the playlist file, please checkout your MX-Folders File permissions!");
}
}
}
/**
* Initializes a Map
*
* @param $rpcMap
* @return Map
*/
public function initializeMap($rpcMap) {
$map = new Map($rpcMap);
$this->saveMap($map);
/*$mapsDirectory = $this->maniaControl->server->getMapsDirectory();
if (is_readable($mapsDirectory . $map->fileName)) {
$mapFetcher = new \GBXChallMapFetcher(true);
$mapFetcher->processFile($mapsDirectory . $map->fileName);
$map->authorNick = FORMATTER::stripDirtyCodes($mapFetcher->authorNick);
$map->authorEInfo = $mapFetcher->authorEInfo;
$map->authorZone = $mapFetcher->authorZone;
$map->comment = $mapFetcher->comment;
}*/
return $map;
}
/**
* Save a Map in the Database
*
* @param \ManiaControl\Maps\Map $map
* @return bool
*/
private function saveMap(Map &$map) {
//TODO saveMaps for whole maplist at once (usage of prepared statements)
$mysqli = $this->maniaControl->database->mysqli;
$mapQuery = "INSERT INTO `" . self::TABLE_MAPS . "` (
`uid`,
`name`,
`authorLogin`,
`fileName`,
`environment`,
`mapType`
) VALUES (
?, ?, ?, ?, ?, ?
) ON DUPLICATE KEY UPDATE
`index` = LAST_INSERT_ID(`index`),
`fileName` = VALUES(`fileName`),
`environment` = VALUES(`environment`),
`mapType` = VALUES(`mapType`);";
$mapStatement = $mysqli->prepare($mapQuery);
if ($mysqli->error) {
trigger_error($mysqli->error);
return false;
}
$mapStatement->bind_param('ssssss', $map->uid, $map->rawName, $map->authorLogin, $map->fileName, $map->environment, $map->mapType);
$mapStatement->execute();
if ($mapStatement->error) {
trigger_error($mapStatement->error);
$mapStatement->close();
return false;
}
$map->index = $mapStatement->insert_id;
$mapStatement->close();
return true;
}
/**
* Shuffles the MapList
*
* @param Player $admin
* @return bool
*/
public function shuffleMapList($admin = null) {
$shuffledMaps = $this->maps;
shuffle($shuffledMaps);
$mapArray = array();
foreach ($shuffledMaps as $map) {
/**
* @var Map $map
*/
$mapArray[] = $map->fileName;
}
try {
$this->maniaControl->client->chooseNextMapList($mapArray);
} catch (Exception $e) {
//TODO temp added 19.04.2014
$this->maniaControl->errorHandler->triggerDebugNotice("Exception line 331 MapManager" . $e->getMessage());
trigger_error("Couldn't shuffle mapList. " . $e->getMessage());
return false;
}
$this->fetchCurrentMap();
if ($admin) {
$message = '$<' . $admin->nickname . '$> shuffled the Maplist!';
$this->maniaControl->chat->sendSuccess($message);
$this->maniaControl->log($message, true);
}
// Restructure if needed
$this->restructureMapList();
return true;
}
/**
* Freshly fetch current Map
*
* @return Map
*/
private function fetchCurrentMap() {
$rpcMap = $this->maniaControl->client->getCurrentMapInfo();
if (array_key_exists($rpcMap->uId, $this->maps)) {
$this->currentMap = $this->maps[$rpcMap->uId];
$this->currentMap->nbCheckpoints = $rpcMap->nbCheckpoints;
$this->currentMap->nbLaps = $rpcMap->nbLaps;
return $this->currentMap;
}
$this->currentMap = $this->initializeMap($rpcMap);
$this->maps[$this->currentMap->uid] = $this->currentMap;
return $this->currentMap;
}
/**
* Restructures the Maplist
*/
public function restructureMapList() {
$currentIndex = $this->getMapIndex($this->currentMap);
// No RestructureNeeded
if ($currentIndex < Maplist::MAX_MAPS_PER_PAGE - 1) {
return true;
}
$lowerMapArray = array();
$higherMapArray = array();
$i = 0;
foreach ($this->maps as $map) {
if ($i < $currentIndex) {
$lowerMapArray[] = $map->fileName;
} else {
$higherMapArray[] = $map->fileName;
}
$i++;
}
$mapArray = array_merge($higherMapArray, $lowerMapArray);
array_shift($mapArray);
try {
$this->maniaControl->client->chooseNextMapList($mapArray);
} catch (Exception $e) {
trigger_error("Error while restructuring the Maplist. " . $e->getMessage());
return false;
}
return true;
}
/**
* Returns the MapIndex of a given map
*
* @param Map $map
* @internal param $uid
* @return mixed
*/
public function getMapIndex(Map $map) {
$maps = $this->getMaps();
return array_search($map, $maps);
}
/**
* Get all Maps
*
* @param int $offset
* @param int $length
* @return array
*/
public function getMaps($offset = null, $length = null) {
if ($offset === null) {
return array_values($this->maps);
}
if ($length === null) {
return array_slice($this->maps, $offset);
}
return array_slice($this->maps, $offset, $length);
}
/**
* Handle OnInit callback
*/
public function handleOnInit() {
$this->updateFullMapList();
$this->fetchCurrentMap();
// Restructure Maplist
$this->restructureMapList();
}
/**
* Handle AfterInit callback
*/
public function handleAfterInit() {
// Fetch MX infos
$this->mxManager->fetchManiaExchangeMapInformations();
}
/**
* Get Current Map
*
* @return Map currentMap
*/
public function getCurrentMap() {
if (!$this->currentMap) {
return $this->fetchCurrentMap();
}
return $this->currentMap;
}
/**
* Handle Script BeginMap callback
*
* @param int $mapNumber
*/
public function handleScriptBeginMap($mapNumber) {
$this->handleBeginMap(array());
}
/**
* Handle BeginMap callback
*
* @param array $callback
*/
public function handleBeginMap(array $callback) {
if ($this->mapBegan) {
return;
}
$this->mapBegan = true;
$this->mapEnded = false;
if (!isset($callback[1][0]["UId"])) {
$this->currentMap = $this->fetchCurrentMap();
} else if (array_key_exists($callback[1][0]["UId"], $this->maps)) {
// Map already exists, only update index
$this->currentMap = $this->maps[$callback[1][0]["UId"]];
if (!$this->currentMap->nbCheckpoints || !$this->currentMap->nbLaps) {
$rpcMap = $this->maniaControl->client->getCurrentMapInfo();
$this->currentMap->nbLaps = $rpcMap->nbLaps;
$this->currentMap->nbCheckpoints = $rpcMap->nbCheckpoints;
}
}
// Restructure MapList if id is over 15
$this->restructureMapList();
// Update the mx of the map (for update checks, etc.)
$this->mxManager->fetchManiaExchangeMapInformations($this->currentMap);
// Trigger own BeginMap callback (
//TODO remove deprecated callback later
$this->maniaControl->callbackManager->triggerCallback(self::CB_BEGINMAP, $this->currentMap);
$this->maniaControl->callbackManager->triggerCallback(Callbacks::BEGINMAP, $this->currentMap);
}
/**
* Handle Script EndMap Callback
*
* @param int $mapNumber
*/
public function handleScriptEndMap($mapNumber) {
$this->handleEndMap(array());
}
/**
* Handle EndMap Callback
*
* @param array $callback
*/
public function handleEndMap(array $callback) {
if ($this->mapEnded) {
return;
}
$this->mapEnded = true;
$this->mapBegan = false;
// Trigger own EndMap callback
$this->maniaControl->callbackManager->triggerCallback(self::CB_ENDMAP, $this->currentMap);
//TODO remove deprecated callback later
$this->maniaControl->callbackManager->triggerCallback(Callbacks::ENDMAP, $this->currentMap);
}
/**
* Handle Maps Modified Callback
*
* @param array $callback
*/
public function mapsModified(array $callback) {
$this->updateFullMapList();
}
/**
* Get the Number of Maps
*
* @return int
*/
public function getMapsCount() {
return count($this->maps);
}
// TODO: add local map by filename // TODO: add local map by filename
} }

View File

@ -14,8 +14,8 @@ use ManiaControl\Players\Player;
/** /**
* MapQueue Class * MapQueue Class
* *
* @author steeffeen & kremsy * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class MapQueue implements CallbackListener, CommandListener { class MapQueue implements CallbackListener, CommandListener {
@ -90,6 +90,34 @@ class MapQueue implements CallbackListener, CommandListener {
$this->clearMapQueue($admin); $this->clearMapQueue($admin);
} }
/**
* Clears the Map Queue
*
* @param $admin
*/
public function clearMapQueue($admin) {
if (!$this->maniaControl->authenticationManager->checkPermission($admin, self::SETTING_PERMISSION_CLEAR_MAPQUEUE)) {
$this->maniaControl->authenticationManager->sendNotAllowed($admin);
return;
}
if (count($this->queuedMaps) == 0) {
$this->maniaControl->chat->sendError('$fa0There are no maps in the jukebox!', $admin->login);
return;
}
$title = $this->maniaControl->authenticationManager->getAuthLevelName($admin->authLevel);
//Destroy map - queue list
$this->queuedMaps = array();
$this->maniaControl->chat->sendInformation('$fa0' . $title . ' $<$fff' . $admin->nickname . '$> cleared the Queued-Map list!');
$this->maniaControl->log($title . ' ' . Formatter::stripCodes($admin->nickname) . ' cleared the Queued-Map list!');
// Trigger callback
$this->maniaControl->callbackManager->triggerCallback(self::CB_MAPQUEUE_CHANGED, array('clear'));
}
/** /**
* Handles the mapqueue/jukebox command * Handles the mapqueue/jukebox command
* *
@ -161,34 +189,6 @@ class MapQueue implements CallbackListener, CommandListener {
return $this->buffer; return $this->buffer;
} }
/**
* Clears the Map Queue
*
* @param $admin
*/
public function clearMapQueue($admin) {
if (!$this->maniaControl->authenticationManager->checkPermission($admin, self::SETTING_PERMISSION_CLEAR_MAPQUEUE)) {
$this->maniaControl->authenticationManager->sendNotAllowed($admin);
return;
}
if(count($this->queuedMaps) == 0) {
$this->maniaControl->chat->sendError('$fa0There are no maps in the jukebox!', $admin->login);
return;
}
$title = $this->maniaControl->authenticationManager->getAuthLevelName($admin->authLevel);
//Destroy map - queue list
$this->queuedMaps = array();
$this->maniaControl->chat->sendInformation('$fa0'. $title . ' $<$fff' . $admin->nickname . '$> cleared the Queued-Map list!');
$this->maniaControl->log($title . ' ' . Formatter::stripCodes($admin->nickname) . ' cleared the Queued-Map list!');
// Trigger callback
$this->maniaControl->callbackManager->triggerCallback(self::CB_MAPQUEUE_CHANGED, array('clear'));
}
/** /**
* Adds map as first map in queue (for /replay) * Adds map as first map in queue (for /replay)
* *
@ -216,9 +216,7 @@ class MapQueue implements CallbackListener, CommandListener {
//Check if player is allowed to add (another) map //Check if player is allowed to add (another) map
$admin = false; $admin = false;
if($this->maniaControl->authenticationManager->checkRight($player, 2) || if ($this->maniaControl->authenticationManager->checkRight($player, 2) || $this->maniaControl->authenticationManager->checkRight($player, 3) || $this->maniaControl->authenticationManager->checkRight($player, 4)) {
$this->maniaControl->authenticationManager->checkRight($player, 3) ||
$this->maniaControl->authenticationManager->checkRight($player, 4)) {
$admin = true; $admin = true;
} }
@ -297,7 +295,7 @@ class MapQueue implements CallbackListener, CommandListener {
*/ */
public function endMap(Map $map) { public function endMap(Map $map) {
$this->nextMap = null; $this->nextMap = null;
if ($this->maniaControl->settingManager->getSetting($this, self::SETTING_SKIP_MAP_ON_LEAVE) == TRUE) { if ($this->maniaControl->settingManager->getSetting($this, self::SETTING_SKIP_MAP_ON_LEAVE) == true) {
//Skip Map if requester has left //Skip Map if requester has left
foreach ($this->queuedMaps as $queuedMap) { foreach ($this->queuedMaps as $queuedMap) {
@ -308,7 +306,7 @@ class MapQueue implements CallbackListener, CommandListener {
break; break;
} }
if ($this->maniaControl->settingManager->getSetting($this, self::SETTING_SKIP_MAPQUEUE_ADMIN) == FALSE) { if ($this->maniaControl->settingManager->getSetting($this, self::SETTING_SKIP_MAPQUEUE_ADMIN) == false) {
//Check if the queuer is a admin //Check if the queuer is a admin
if ($player->authLevel > 0) { if ($player->authLevel > 0) {
break; break;

View File

@ -7,8 +7,8 @@ use ManiaControl\Formatter;
/** /**
* Player Model Class * Player Model Class
* *
* @author kremsy & steeffeen * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class Player { class Player {

View File

@ -21,8 +21,8 @@ use Maniaplanet\DedicatedServer\Xmlrpc\PlayerNotIgnoredException;
/** /**
* Player Actions Class * Player Actions Class
* *
* @author steeffeen & kremsy * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class PlayerActions { class PlayerActions {
@ -70,6 +70,49 @@ class PlayerActions {
$this->maniaControl->authenticationManager->definePermissionLevel(self::SETTING_PERMISSION_FORCE_PLAYER_SPEC, AuthenticationManager::AUTH_LEVEL_MODERATOR); $this->maniaControl->authenticationManager->definePermissionLevel(self::SETTING_PERMISSION_FORCE_PLAYER_SPEC, AuthenticationManager::AUTH_LEVEL_MODERATOR);
} }
/**
* Force a Player to a certain Team
*
* @param string $adminLogin
* @param string $targetLogin
* @param int $teamId
*/
public function forcePlayerToTeam($adminLogin, $targetLogin, $teamId) {
$admin = $this->maniaControl->playerManager->getPlayer($adminLogin);
if (!$this->maniaControl->authenticationManager->checkPermission($admin, self::SETTING_PERMISSION_FORCE_PLAYER_TEAM)) {
$this->maniaControl->authenticationManager->sendNotAllowed($admin);
return;
}
$target = $this->maniaControl->playerManager->getPlayer($targetLogin);
if (!$target || !$admin) {
return;
}
if ($target->isSpectator) {
$this->forcePlayerToPlay($adminLogin, $targetLogin, true, false);
}
try {
$this->maniaControl->client->forcePlayerTeam($target->login, $teamId);
} catch (NotInTeamModeException $e) {
$this->forcePlayerToPlay($adminLogin, $targetLogin);
return;
}
$chatMessage = false;
$title = $this->maniaControl->authenticationManager->getAuthLevelName($admin->authLevel);
if ($teamId == self::TEAM_BLUE) {
$chatMessage = $title . ' $<' . $admin->nickname . '$> forced $<' . $target->nickname . '$> into the Blue-Team!';
} else if ($teamId == self::TEAM_RED) {
$chatMessage = $title . ' $<' . $admin->nickname . '$> forced $<' . $target->nickname . '$> into the Red-Team!';
}
if (!$chatMessage) {
return;
}
$this->maniaControl->chat->sendInformation($chatMessage);
$this->maniaControl->log($chatMessage, true);
}
/** /**
* Force a Player to Play * Force a Player to Play
* *
@ -114,49 +157,6 @@ class PlayerActions {
} }
} }
/**
* Force a Player to a certain Team
*
* @param string $adminLogin
* @param string $targetLogin
* @param int $teamId
*/
public function forcePlayerToTeam($adminLogin, $targetLogin, $teamId) {
$admin = $this->maniaControl->playerManager->getPlayer($adminLogin);
if (!$this->maniaControl->authenticationManager->checkPermission($admin, self::SETTING_PERMISSION_FORCE_PLAYER_TEAM)) {
$this->maniaControl->authenticationManager->sendNotAllowed($admin);
return;
}
$target = $this->maniaControl->playerManager->getPlayer($targetLogin);
if (!$target || !$admin) {
return;
}
if ($target->isSpectator) {
$this->forcePlayerToPlay($adminLogin, $targetLogin, true, false);
}
try {
$this->maniaControl->client->forcePlayerTeam($target->login, $teamId);
} catch(NotInTeamModeException $e) {
$this->forcePlayerToPlay($adminLogin, $targetLogin);
return;
}
$chatMessage = false;
$title = $this->maniaControl->authenticationManager->getAuthLevelName($admin->authLevel);
if ($teamId == self::TEAM_BLUE) {
$chatMessage = $title . ' $<' . $admin->nickname . '$> forced $<' . $target->nickname . '$> into the Blue-Team!';
} else if ($teamId == self::TEAM_RED) {
$chatMessage = $title . ' $<' . $admin->nickname . '$> forced $<' . $target->nickname . '$> into the Red-Team!';
}
if (!$chatMessage) {
return;
}
$this->maniaControl->chat->sendInformation($chatMessage);
$this->maniaControl->log($chatMessage, true);
}
/** /**
* Force a Player to Spectator * Force a Player to Spectator
* *

View File

@ -15,8 +15,8 @@ use Maniaplanet\DedicatedServer\Xmlrpc\Exception;
/** /**
* Class offering various Admin Commands related to Players * Class offering various Admin Commands related to Players
* *
* @author steeffeen & kremsy * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class PlayerCommands implements CommandListener, ManialinkPageAnswerListener, CallbackListener { class PlayerCommands implements CommandListener, ManialinkPageAnswerListener, CallbackListener {

View File

@ -8,8 +8,8 @@ use ManiaControl\ManiaControl;
/** /**
* Player Data Manager * Player Data Manager
* *
* @author steeffeen & kremsy * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class PlayerDataManager { class PlayerDataManager {
@ -42,6 +42,80 @@ class PlayerDataManager {
$this->storeMetaData(); $this->storeMetaData();
} }
/**
* Initialize necessary database tables
*
* @return bool
*/
private function initTables() {
$mysqli = $this->maniaControl->database->mysqli;
$defaultType = "'" . self::TYPE_STRING . "'";
$typeSet = $defaultType . ",'" . self::TYPE_INT . "','" . self::TYPE_REAL . "','" . self::TYPE_BOOL . "','" . self::TYPE_ARRAY . "'";
$query = "CREATE TABLE IF NOT EXISTS `" . self::TABLE_PLAYERDATAMETADATA . "` (
`dataId` int(11) NOT NULL AUTO_INCREMENT,
`class` varchar(100) NOT NULL,
`dataName` varchar(100) NOT NULL,
`type` set({$typeSet}) NOT NULL DEFAULT {$defaultType},
`defaultValue` varchar(150) NOT NULL,
`description` varchar(150) NOT NULL,
PRIMARY KEY (`dataId`),
UNIQUE KEY `name` (`class`, `dataName`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Player-Data MetaData' 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();
$query = "CREATE TABLE IF NOT EXISTS `" . self::TABLE_PLAYERDATA . "` (
`index` int(11) NOT NULL AUTO_INCREMENT,
`serverIndex` int(11) NOT NULL,
`playerId` int(11) NOT NULL,
`dataId` int(11) NOT NULL,
`value` varchar(150) NOT NULL,
`changed` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`index`),
UNIQUE KEY `unique` (`dataId`,`playerId`,`serverIndex`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Player Data' 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;
}
/**
* Store Meta Data from the Database in the Ram
*/
private function storeMetaData() {
$mysqli = $this->maniaControl->database->mysqli;
$query = "SELECT * FROM `" . self::TABLE_PLAYERDATAMETADATA . "`;";
$result = $mysqli->query($query);
if (!$result) {
trigger_error($mysqli->error);
return;
}
while ($row = $result->fetch_object()) {
$this->metaData[$row->class . $row->dataName] = $row;
}
$result->close();
}
/** /**
* Destroys the stored PlayerData (Method get called by PlayerManager, so don't call it anywhere else) * Destroys the stored PlayerData (Method get called by PlayerManager, so don't call it anywhere else)
* *
@ -95,22 +169,46 @@ class PlayerDataManager {
} }
/** /**
* Store Meta Data from the Database in the Ram * Get Class Name of a Parameter
*
* @param mixed $param
* @return string
*/ */
private function storeMetaData() { private function getClassName($param) {
$mysqli = $this->maniaControl->database->mysqli; if (is_object($param)) {
return get_class($param);
$query = "SELECT * FROM `" . self::TABLE_PLAYERDATAMETADATA . "`;"; }
$result = $mysqli->query($query); if (is_string($param)) {
if (!$result) { return $param;
trigger_error($mysqli->error); }
return; trigger_error('Invalid class param. ' . $param);
return (string)$param;
} }
while($row = $result->fetch_object()) { /**
$this->metaData[$row->class . $row->dataName] = $row; * Get Type of a Parameter
*
* @param mixed $param
* @return string
*/
private function getType($param) {
if (is_int($param)) {
return self::TYPE_INT;
} }
$result->close(); if (is_real($param)) {
return self::TYPE_REAL;
}
if (is_bool($param)) {
return self::TYPE_BOOL;
}
if (is_string($param)) {
return self::TYPE_STRING;
}
if (is_array($param)) {
return self::TYPE_ARRAY;
}
trigger_error('Unsupported setting type. ' . print_r($param, true));
return null;
} }
/** /**
@ -237,87 +335,6 @@ class PlayerDataManager {
return null; return null;
} }
/**
* Initialize necessary database tables
*
* @return bool
*/
private function initTables() {
$mysqli = $this->maniaControl->database->mysqli;
$defaultType = "'" . self::TYPE_STRING . "'";
$typeSet = $defaultType . ",'" . self::TYPE_INT . "','" . self::TYPE_REAL . "','" . self::TYPE_BOOL . "','" . self::TYPE_ARRAY . "'";
$query = "CREATE TABLE IF NOT EXISTS `" . self::TABLE_PLAYERDATAMETADATA . "` (
`dataId` int(11) NOT NULL AUTO_INCREMENT,
`class` varchar(100) NOT NULL,
`dataName` varchar(100) NOT NULL,
`type` set({$typeSet}) NOT NULL DEFAULT {$defaultType},
`defaultValue` varchar(150) NOT NULL,
`description` varchar(150) NOT NULL,
PRIMARY KEY (`dataId`),
UNIQUE KEY `name` (`class`, `dataName`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Player-Data MetaData' 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();
$query = "CREATE TABLE IF NOT EXISTS `" . self::TABLE_PLAYERDATA . "` (
`index` int(11) NOT NULL AUTO_INCREMENT,
`serverIndex` int(11) NOT NULL,
`playerId` int(11) NOT NULL,
`dataId` int(11) NOT NULL,
`value` varchar(150) NOT NULL,
`changed` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`index`),
UNIQUE KEY `unique` (`dataId`,`playerId`,`serverIndex`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Player Data' 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;
}
/**
* Get Type of a Parameter
*
* @param mixed $param
* @return string
*/
private function getType($param) {
if (is_int($param)) {
return self::TYPE_INT;
}
if (is_real($param)) {
return self::TYPE_REAL;
}
if (is_bool($param)) {
return self::TYPE_BOOL;
}
if (is_string($param)) {
return self::TYPE_STRING;
}
if (is_array($param)) {
return self::TYPE_ARRAY;
}
trigger_error('Unsupported setting type. ' . print_r($param, true));
return null;
}
/** /**
* Cast a Setting to the given Type * Cast a Setting to the given Type
* *
@ -344,21 +361,4 @@ class PlayerDataManager {
trigger_error('Unsupported setting type. ' . print_r($type, true)); trigger_error('Unsupported setting type. ' . print_r($type, true));
return $value; return $value;
} }
/**
* Get Class Name of a Parameter
*
* @param mixed $param
* @return string
*/
private function getClassName($param) {
if (is_object($param)) {
return get_class($param);
}
if (is_string($param)) {
return $param;
}
trigger_error('Invalid class param. ' . $param);
return (string)$param;
}
} }

View File

@ -19,8 +19,8 @@ use Maniaplanet\DedicatedServer\Structures\Player;
/** /**
* Player Detailed Page * Player Detailed Page
* *
* @author steeffeen & kremsy * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class PlayerDetailed { class PlayerDetailed {

View File

@ -2,8 +2,6 @@
namespace ManiaControl\Players; namespace ManiaControl\Players;
use Maniaplanet\DedicatedServer\Structures\Player;
use MCTeam\CustomVotesPlugin;
use FML\Controls\Control; use FML\Controls\Control;
use FML\Controls\Frame; use FML\Controls\Frame;
use FML\Controls\Labels\Label_Button; use FML\Controls\Labels\Label_Button;
@ -24,14 +22,16 @@ use ManiaControl\Formatter;
use ManiaControl\ManiaControl; use ManiaControl\ManiaControl;
use ManiaControl\Manialinks\ManialinkManager; use ManiaControl\Manialinks\ManialinkManager;
use ManiaControl\Manialinks\ManialinkPageAnswerListener; use ManiaControl\Manialinks\ManialinkPageAnswerListener;
use Maniaplanet\DedicatedServer\Structures\Player;
use Maniaplanet\DedicatedServer\Xmlrpc\LoginUnknownException; use Maniaplanet\DedicatedServer\Xmlrpc\LoginUnknownException;
use Maniaplanet\DedicatedServer\Xmlrpc\PlayerIsNotSpectatorException; use Maniaplanet\DedicatedServer\Xmlrpc\PlayerIsNotSpectatorException;
use MCTeam\CustomVotesPlugin;
/** /**
* PlayerList Widget Class * PlayerList Widget Class
* *
* @author steeffeen & kremsy * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class PlayerList implements ManialinkPageAnswerListener, CallbackListener, TimerListener { class PlayerList implements ManialinkPageAnswerListener, CallbackListener, TimerListener {
@ -97,6 +97,39 @@ class PlayerList implements ManialinkPageAnswerListener, CallbackListener, Timer
$this->playersListShown[$player->login] = $showStatus; $this->playersListShown[$player->login] = $showStatus;
} }
/**
* Unset the player if he opened another Main Widget
*
* @param Player $player
* @param $openedWidget
*/
public function handleWidgetOpened(Player $player, $openedWidget) {
//unset when another main widget got opened
if ($openedWidget != 'PlayerList') {
unset($this->playersListShown[$player->login]);
}
}
/**
* Closes the widget
*
* @param Player $player
*/
public function closeWidget(Player $player) {
unset($this->playersListShown[$player->login]);
}
/**
* Closes the player advanced widget widget
*
* @param array $callback
* @param Player $player
*/
public function closePlayerAdvancedWidget(array $callback, Player $player) {
$this->playersListShown[$player->login] = self::SHOWN_MAIN_WINDOW;
$this->showPlayerList($player); // overwrite the manialink
}
/** /**
* Show the PlayerList Widget to the Player * Show the PlayerList Widget to the Player
* *
@ -396,20 +429,6 @@ class PlayerList implements ManialinkPageAnswerListener, CallbackListener, Timer
$this->maniaControl->manialinkManager->displayWidget($maniaLink, $player, 'PlayerList'); $this->maniaControl->manialinkManager->displayWidget($maniaLink, $player, 'PlayerList');
} }
/**
* Displays the Advanced Player Window
*
* @param Player $caller
* @param $login
*/
public function advancedPlayerWidget(Player $caller, $login) {
// Set status to target player login
$this->playersListShown[$caller->login] = $login;
// Reopen playerlist
$this->showPlayerList($caller);
}
/** /**
* Extra window with special actions on players like warn,kick, ban, authorization levels... * Extra window with special actions on players like warn,kick, ban, authorization levels...
* *
@ -610,39 +629,6 @@ class PlayerList implements ManialinkPageAnswerListener, CallbackListener, Timer
return $frame; return $frame;
} }
/**
* Unset the player if he opened another Main Widget
*
* @param Player $player
* @param $openedWidget
*/
public function handleWidgetOpened(Player $player, $openedWidget) {
//unset when another main widget got opened
if ($openedWidget != 'PlayerList') {
unset($this->playersListShown[$player->login]);
}
}
/**
* Closes the widget
*
* @param Player $player
*/
public function closeWidget(Player $player) {
unset($this->playersListShown[$player->login]);
}
/**
* Closes the player advanced widget widget
*
* @param array $callback
* @param Player $player
*/
public function closePlayerAdvancedWidget(array $callback, Player $player) {
$this->playersListShown[$player->login] = self::SHOWN_MAIN_WINDOW;
$this->showPlayerList($player); // overwrite the manialink
}
/** /**
* Called on ManialinkPageAnswer * Called on ManialinkPageAnswer
* *
@ -767,6 +753,20 @@ class PlayerList implements ManialinkPageAnswerListener, CallbackListener, Timer
} }
} }
/**
* Displays the Advanced Player Window
*
* @param Player $caller
* @param $login
*/
public function advancedPlayerWidget(Player $caller, $login) {
// Set status to target player login
$this->playersListShown[$caller->login] = $login;
// Reopen playerlist
$this->showPlayerList($caller);
}
/** /**
* Reopen the widget on PlayerInfoChanged / Player Connect and Disconnect * Reopen the widget on PlayerInfoChanged / Player Connect and Disconnect
* *

View File

@ -14,8 +14,8 @@ use Maniaplanet\DedicatedServer\Xmlrpc\LoginUnknownException;
/** /**
* Class managing Players * Class managing Players
* *
* @author kremsy & steeffeen * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class PlayerManager implements CallbackListener, TimerListener { class PlayerManager implements CallbackListener, TimerListener {
@ -141,6 +141,76 @@ class PlayerManager implements CallbackListener, TimerListener {
} }
} }
/**
* Add a player
*
* @param Player $player
* @return bool
*/
private function addPlayer(Player $player) {
$this->savePlayer($player);
$this->players[$player->login] = $player;
return true;
}
/**
* Save player in Database and fill up Object Properties
*
* @param Player $player
* @return bool
*/
private function savePlayer(Player &$player) {
$mysqli = $this->maniaControl->database->mysqli;
// Save player
$playerQuery = "INSERT INTO `" . self::TABLE_PLAYERS . "` (
`login`,
`nickname`,
`path`
) VALUES (
?, ?, ?
) ON DUPLICATE KEY UPDATE
`index` = LAST_INSERT_ID(`index`),
`nickname` = VALUES(`nickname`),
`path` = VALUES(`path`);";
$playerStatement = $mysqli->prepare($playerQuery);
if ($mysqli->error) {
trigger_error($mysqli->error);
return false;
}
$playerStatement->bind_param('sss', $player->login, $player->rawNickname, $player->path);
$playerStatement->execute();
if ($playerStatement->error) {
trigger_error($playerStatement->error);
$playerStatement->close();
return false;
}
$player->index = $playerStatement->insert_id;
$playerStatement->close();
// Get Player Auth Level from DB
$playerQuery = "SELECT `authLevel` FROM `" . self::TABLE_PLAYERS . "` WHERE `index` = ?;";
$playerStatement = $mysqli->prepare($playerQuery);
if ($mysqli->error) {
trigger_error($mysqli->error);
return false;
}
$playerStatement->bind_param('i', $player->index);
$playerStatement->execute();
if ($playerStatement->error) {
trigger_error($playerStatement->error);
$playerStatement->close();
return false;
}
$playerStatement->store_result();
$playerStatement->bind_result($player->authLevel);
$playerStatement->fetch();
$playerStatement->free_result();
$playerStatement->close();
return true;
}
/** /**
* Handle playerConnect callback * Handle playerConnect callback
* *
@ -188,6 +258,40 @@ class PlayerManager implements CallbackListener, TimerListener {
$this->playerDataManager->destroyPlayerData($player); $this->playerDataManager->destroyPlayerData($player);
} }
/**
* Remove a Player
*
* @param string $login
* @param bool $savePlayedTime
* @return Player $player
*/
private function removePlayer($login, $savePlayedTime = true) {
if (!isset($this->players[$login])) {
return null;
}
$player = $this->players[$login];
unset($this->players[$login]);
if ($savePlayedTime) {
$this->updatePlayedTime($player);
}
return $player;
}
/**
* Update total played time of the player
*
* @param Player $player
* @return bool
*/
private function updatePlayedTime(Player $player) {
if (!$player) {
return false;
}
$playedTime = time() - $player->joinTime;
return $this->maniaControl->statisticManager->insertStat(self::STAT_SERVERTIME, $player, $this->maniaControl->server->index, $playedTime);
}
/** /**
* Update PlayerInfo * Update PlayerInfo
* *
@ -237,6 +341,56 @@ class PlayerManager implements CallbackListener, TimerListener {
$this->maniaControl->callbackManager->triggerCallback(self::CB_PLAYERINFOCHANGED, $player); $this->maniaControl->callbackManager->triggerCallback(self::CB_PLAYERINFOCHANGED, $player);
} }
/**
* Get a Player by Login
*
* @param string $login
* @param bool $connectedPlayersOnly
* @return Player
*/
public function getPlayer($login, $connectedPlayersOnly = false) {
if (!isset($this->players[$login])) {
if ($connectedPlayersOnly) {
return null;
}
return $this->getPlayerFromDatabaseByLogin($login);
}
return $this->players[$login];
}
/**
* Get a Player from the Database
*
* @param string $playerLogin
* @return Player
*/
private function getPlayerFromDatabaseByLogin($playerLogin) {
$mysqli = $this->maniaControl->database->mysqli;
$query = "SELECT * FROM `" . self::TABLE_PLAYERS . "` WHERE `login` LIKE '" . $mysqli->escape_string($playerLogin) . "';";
$result = $mysqli->query($query);
if (!$result) {
trigger_error($mysqli->error);
return null;
}
$row = $result->fetch_object();
$result->close();
if (!isset($row)) {
return null;
}
$player = new Player(null);
$player->index = $row->index;
$player->login = $row->login;
$player->rawNickname = $row->nickname;
$player->nickname = Formatter::stripDirtyCodes($player->rawNickname);
$player->path = $row->path;
$player->authLevel = $row->authLevel;
return $player;
}
/** /**
* Get all Players * Get all Players
@ -301,55 +455,6 @@ class PlayerManager implements CallbackListener, TimerListener {
return $this->getPlayerFromDatabaseByIndex($index); return $this->getPlayerFromDatabaseByIndex($index);
} }
/**
* Get a Player by Login
*
* @param string $login
* @param bool $connectedPlayersOnly
* @return Player
*/
public function getPlayer($login, $connectedPlayersOnly = false) {
if (!isset($this->players[$login])) {
if ($connectedPlayersOnly) {
return null;
}
return $this->getPlayerFromDatabaseByLogin($login);
}
return $this->players[$login];
}
/**
* Add a player
*
* @param Player $player
* @return bool
*/
private function addPlayer(Player $player) {
$this->savePlayer($player);
$this->players[$player->login] = $player;
return true;
}
/**
* Remove a Player
*
* @param string $login
* @param bool $savePlayedTime
* @return Player $player
*/
private function removePlayer($login, $savePlayedTime = true) {
if (!isset($this->players[$login])) {
return null;
}
$player = $this->players[$login];
unset($this->players[$login]);
if ($savePlayedTime) {
$this->updatePlayedTime($player);
}
return $player;
}
/** /**
* Get's a Player out of the database * Get's a Player out of the database
* *
@ -387,112 +492,4 @@ class PlayerManager implements CallbackListener, TimerListener {
return $player; return $player;
} }
/**
* Get a Player from the Database
*
* @param string $playerLogin
* @return Player
*/
private function getPlayerFromDatabaseByLogin($playerLogin) {
$mysqli = $this->maniaControl->database->mysqli;
$query = "SELECT * FROM `" . self::TABLE_PLAYERS . "` WHERE `login` LIKE '" . $mysqli->escape_string($playerLogin) . "';";
$result = $mysqli->query($query);
if (!$result) {
trigger_error($mysqli->error);
return null;
}
$row = $result->fetch_object();
$result->close();
if (!isset($row)) {
return null;
}
$player = new Player(null);
$player->index = $row->index;
$player->login = $row->login;
$player->rawNickname = $row->nickname;
$player->nickname = Formatter::stripDirtyCodes($player->rawNickname);
$player->path = $row->path;
$player->authLevel = $row->authLevel;
return $player;
}
/**
* Save player in Database and fill up Object Properties
*
* @param Player $player
* @return bool
*/
private function savePlayer(Player &$player) {
$mysqli = $this->maniaControl->database->mysqli;
// Save player
$playerQuery = "INSERT INTO `" . self::TABLE_PLAYERS . "` (
`login`,
`nickname`,
`path`
) VALUES (
?, ?, ?
) ON DUPLICATE KEY UPDATE
`index` = LAST_INSERT_ID(`index`),
`nickname` = VALUES(`nickname`),
`path` = VALUES(`path`);";
$playerStatement = $mysqli->prepare($playerQuery);
if ($mysqli->error) {
trigger_error($mysqli->error);
return false;
}
$playerStatement->bind_param('sss', $player->login, $player->rawNickname, $player->path);
$playerStatement->execute();
if ($playerStatement->error) {
trigger_error($playerStatement->error);
$playerStatement->close();
return false;
}
$player->index = $playerStatement->insert_id;
$playerStatement->close();
// Get Player Auth Level from DB
$playerQuery = "SELECT `authLevel` FROM `" . self::TABLE_PLAYERS . "` WHERE `index` = ?;";
$playerStatement = $mysqli->prepare($playerQuery);
if ($mysqli->error) {
trigger_error($mysqli->error);
return false;
}
$playerStatement->bind_param('i', $player->index);
$playerStatement->execute();
if ($playerStatement->error) {
trigger_error($playerStatement->error);
$playerStatement->close();
return false;
}
$playerStatement->store_result();
$playerStatement->bind_result($player->authLevel);
$playerStatement->fetch();
$playerStatement->free_result();
$playerStatement->close();
return true;
}
/**
* Update total played time of the player
*
* @param Player $player
* @return bool
*/
private function updatePlayedTime(Player $player) {
if (!$player) {
return false;
}
$playedTime = time() - $player->joinTime;
return $this->maniaControl->statisticManager->insertStat(self::STAT_SERVERTIME, $player, $this->maniaControl->server->index, $playedTime);
}
} }

View File

@ -5,8 +5,8 @@ namespace ManiaControl\Server;
/** /**
* Model Class holding the Server Config * Model Class holding the Server Config
* *
* @author steeffeen * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class Config { class Config {

View File

@ -11,8 +11,8 @@ use Maniaplanet\DedicatedServer\Xmlrpc\NotInScriptModeException;
/** /**
* Class managing Rankings * Class managing Rankings
* *
* @author kremsy * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class RankingManager implements CallbackListener { class RankingManager implements CallbackListener {
@ -46,16 +46,6 @@ class RankingManager implements CallbackListener {
} }
} }
/**
* Get Rankings
*
* @return array
*/
public function getRankings() {
return $this->rankings;
}
/** /**
* Handle stats on callbacks (never call this Method) * Handle stats on callbacks (never call this Method)
* *
@ -101,6 +91,15 @@ class RankingManager implements CallbackListener {
$this->maniaControl->callbackManager->triggerCallback(Callbacks::RANKINGSUPDATED, $this->getRankings()); $this->maniaControl->callbackManager->triggerCallback(Callbacks::RANKINGSUPDATED, $this->getRankings());
} }
/**
* Get Rankings
*
* @return array
*/
public function getRankings() {
return $this->rankings;
}
/** /**
* Get the Current Leading Players (as Login Array) * Get the Current Leading Players (as Login Array)
* *

View File

@ -4,15 +4,15 @@ namespace ManiaControl\Server;
use ManiaControl\Callbacks\CallbackListener; use ManiaControl\Callbacks\CallbackListener;
use ManiaControl\Callbacks\CallbackManager; use ManiaControl\Callbacks\CallbackManager;
use ManiaControl\CommandLineHelper;
use ManiaControl\ManiaControl; use ManiaControl\ManiaControl;
use Maniaplanet\DedicatedServer\Xmlrpc\Exception; use Maniaplanet\DedicatedServer\Xmlrpc\Exception;
use ManiaControl\CommandLineHelper;
/** /**
* Class providing Access to the connected ManiaPlanet Server * Class providing Access to the connected ManiaPlanet Server
* *
* @author steeffeen & kremsy * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class Server implements CallbackListener { class Server implements CallbackListener {
@ -26,7 +26,6 @@ class Server implements CallbackListener {
* Public Properties * Public Properties
*/ */
/** /**
*
* @var Config $config * @var Config $config
*/ */
public $config = null; public $config = null;
@ -64,6 +63,33 @@ class Server implements CallbackListener {
$this->maniaControl->callbackManager->registerCallbackListener(CallbackManager::CB_ONINIT, $this, 'onInit'); $this->maniaControl->callbackManager->registerCallbackListener(CallbackManager::CB_ONINIT, $this, 'onInit');
} }
/**
* Initialize necessary Database Tables
*
* @return bool
*/
private function initTables() {
$mysqli = $this->maniaControl->database->mysqli;
$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;
}
/** /**
* Load the Server Configuration from the Config XML * Load the Server Configuration from the Config XML
*/ */
@ -81,8 +107,7 @@ class Server implements CallbackListener {
if (!$serverTag) { if (!$serverTag) {
trigger_error("No Server configured with the ID '{$serverId}'!", E_USER_ERROR); trigger_error("No Server configured with the ID '{$serverId}'!", E_USER_ERROR);
} }
} } else {
else {
$serverTags = $this->maniaControl->config->xpath('server'); $serverTags = $this->maniaControl->config->xpath('server');
if ($serverTags) { if ($serverTags) {
$serverTag = $serverTags[0]; $serverTag = $serverTags[0];
@ -132,6 +157,36 @@ class Server implements CallbackListener {
$this->config = new Config($serverId, $host, $port, $login, $pass); $this->config = new Config($serverId, $host, $port, $login, $pass);
} }
/**
* Gets all Servers from the Database
*
* @return array
*/
public function getAllServers() {
$mysqli = $this->maniaControl->database->mysqli;
$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->close();
return $servers;
}
/**
* Handle OnInit Callback
*/
public function onInit() {
$this->updateProperties();
}
/** /**
* Refetch the Server Properties * Refetch the Server Properties
*/ */
@ -168,63 +223,6 @@ class Server implements CallbackListener {
$statement->close(); $statement->close();
} }
/**
* Initialize necessary Database Tables
*
* @return bool
*/
private function initTables() {
$mysqli = $this->maniaControl->database->mysqli;
$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;
}
/**
* Gets all Servers from the Database
*
* @return array
*/
public function getAllServers() {
$mysqli = $this->maniaControl->database->mysqli;
$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->close();
return $servers;
}
/**
* Handle OnInit Callback
*/
public function onInit() {
$this->updateProperties();
}
/** /**
* Set if the Server Runs a Team-Mode or not * Set if the Server Runs a Team-Mode or not
* *
@ -249,18 +247,6 @@ class Server implements CallbackListener {
return $this->teamMode; return $this->teamMode;
} }
/**
* Fetch Game Data Directory
*
* @return string
*/
public function getDataDirectory() {
if ($this->dataDirectory == '') {
$this->dataDirectory = $this->maniaControl->client->gameDataDirectory();
}
return $this->dataDirectory;
}
/** /**
* Fetch Maps Directory * Fetch Maps Directory
* *
@ -275,16 +261,15 @@ class Server implements CallbackListener {
} }
/** /**
* Checks if ManiaControl has Access to the given Directory * Fetch Game Data Directory
* *
* @param string $directory * @return string
* @return bool
*/ */
public function checkAccess($directory) { public function getDataDirectory() {
if (!$directory) { if ($this->dataDirectory == '') {
return false; $this->dataDirectory = $this->maniaControl->client->gameDataDirectory();
} }
return (is_dir($directory) && is_writable($directory)); return $this->dataDirectory;
} }
/** /**
@ -296,43 +281,6 @@ class Server implements CallbackListener {
return $this->maniaControl->client->getMainServerPlayerInfo(); return $this->maniaControl->client->getMainServerPlayerInfo();
} }
/**
* Fetch 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->client->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;
}
/** /**
* Retrieve Validation Replay for the given Player * Retrieve Validation Replay for the given Player
* *
@ -342,8 +290,7 @@ class Server implements CallbackListener {
public function getValidationReplay($login) { public function getValidationReplay($login) {
try { try {
$replay = $this->maniaControl->client->getValidationReplay($login); $replay = $this->maniaControl->client->getValidationReplay($login);
} } catch (Exception $e) {
catch (Exception $e) {
// TODO temp added 19.04.2014 // TODO temp added 19.04.2014
$this->maniaControl->errorHandler->triggerDebugNotice("Exception line 330 Server.php" . $e->getMessage()); $this->maniaControl->errorHandler->triggerDebugNotice("Exception line 330 Server.php" . $e->getMessage());
@ -374,8 +321,7 @@ class Server implements CallbackListener {
// Save ghost replay // Save ghost replay
try { try {
$this->maniaControl->client->saveBestGhostsReplay($login, $fileName); $this->maniaControl->client->saveBestGhostsReplay($login, $fileName);
} } catch (Exception $e) {
catch (Exception $e) {
// TODO temp added 19.04.2014 // TODO temp added 19.04.2014
$this->maniaControl->errorHandler->triggerDebugNotice("Exception line 360 Server.php" . $e->getMessage()); $this->maniaControl->errorHandler->triggerDebugNotice("Exception line 360 Server.php" . $e->getMessage());
@ -392,6 +338,55 @@ class Server implements CallbackListener {
return $ghostReplay; return $ghostReplay;
} }
/**
* Checks if ManiaControl has Access to the given Directory
*
* @param string $directory
* @return bool
*/
public function checkAccess($directory) {
if (!$directory) {
return false;
}
return (is_dir($directory) && is_writable($directory));
}
/**
* Fetch 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->client->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 * Wait for the Server to have the given Status
* *

View File

@ -18,8 +18,8 @@ use Maniaplanet\DedicatedServer\Xmlrpc\NotInScriptModeException;
/** /**
* Class offering various Commands related to the Dedicated Server * Class offering various Commands related to the Dedicated Server
* *
* @author steeffeen & kremsy * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class ServerCommands implements CallbackListener, CommandListener, ManialinkPageAnswerListener, TimerListener { class ServerCommands implements CallbackListener, CommandListener, ManialinkPageAnswerListener, TimerListener {
@ -201,7 +201,7 @@ class ServerCommands implements CallbackListener, CommandListener, ManialinkPage
return; return;
} }
try { try {
$this->maniaControl->client->sendModeScriptCommands(array('Command_ForceWarmUp' => True)); $this->maniaControl->client->sendModeScriptCommands(array('Command_ForceWarmUp' => true));
} catch (NotInScriptModeException $e) { } catch (NotInScriptModeException $e) {
return; return;
} }
@ -232,6 +232,16 @@ class ServerCommands implements CallbackListener, CommandListener, ManialinkPage
} }
} }
/**
* Perform server shutdown
*
* @param string $login
*/
private function shutdownServer($login = '#') {
$this->maniaControl->client->stopServer();
$this->maniaControl->quit("Server shutdown requested by '{$login}'");
}
/** /**
* Handle //systeminfo command * Handle //systeminfo command
* *
@ -411,14 +421,4 @@ class ServerCommands implements CallbackListener, CommandListener, ManialinkPage
$this->maniaControl->client->setMaxSpectators($amount); $this->maniaControl->client->setMaxSpectators($amount);
$this->maniaControl->chat->sendSuccess("Changed max spectators to: {$amount}", $player->login); $this->maniaControl->chat->sendSuccess("Changed max spectators to: {$amount}", $player->login);
} }
/**
* Perform server shutdown
*
* @param string $login
*/
private function shutdownServer($login = '#') {
$this->maniaControl->client->stopServer();
$this->maniaControl->quit("Server shutdown requested by '{$login}'");
}
} }

View File

@ -11,8 +11,8 @@ use Maniaplanet\DedicatedServer\Xmlrpc\Exception;
/** /**
* Class reporting ManiaControl Usage for the Server * Class reporting ManiaControl Usage for the Server
* *
* @author steeffeen & kremsy * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class UsageReporter implements TimerListener { class UsageReporter implements TimerListener {

View File

@ -10,8 +10,8 @@ use ManiaControl\Plugins\PluginManager;
/** /**
* Class managing Settings and Configurations * Class managing Settings and Configurations
* *
* @author steeffeen & kremsy * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class SettingManager implements CallbackListener { class SettingManager implements CallbackListener {
@ -45,13 +45,6 @@ class SettingManager implements CallbackListener {
$this->maniaControl->callbackManager->registerCallbackListener(CallbackManager::CB_AFTERINIT, $this, 'handleAfterInit'); $this->maniaControl->callbackManager->registerCallbackListener(CallbackManager::CB_AFTERINIT, $this, 'handleAfterInit');
} }
/**
* Handle After Init Callback
*/
public function handleAfterInit() {
$this->deleteUnusedSettings();
}
/** /**
* Initialize necessary Database Tables * Initialize necessary Database Tables
* *
@ -81,93 +74,35 @@ class SettingManager implements CallbackListener {
} }
/** /**
* Get Class Name of a Parameter * Handle After Init Callback
*
* @param mixed $param
* @return string
*/ */
private function getClassName($param) { public function handleAfterInit() {
if (is_object($param)) { $this->deleteUnusedSettings();
return get_class($param);
}
if (is_string($param)) {
return $param;
}
trigger_error('Invalid class param. ' . $param);
return (string) $param;
} }
/** /**
* Get Type of a Parameter * Delete all unused Settings that haven't been initialized during the current Startup
* *
* @param mixed $param * @return bool
* @return string
*/ */
private function getType($param) { private function deleteUnusedSettings() {
if (is_int($param)) { $mysqli = $this->maniaControl->database->mysqli;
return self::TYPE_INT; $settingQuery = "DELETE FROM `" . self::TABLE_SETTINGS . "`
WHERE `changed` < NOW() - INTERVAL 1 HOUR;";
$settingStatement = $mysqli->prepare($settingQuery);
if ($mysqli->error) {
trigger_error($mysqli->error);
return false;
} }
if (is_real($param)) { $success = $settingStatement->execute();
return self::TYPE_REAL; if ($settingStatement->error) {
trigger_error($settingStatement->error);
$settingStatement->close();
return false;
} }
if (is_bool($param)) { $settingStatement->close();
return self::TYPE_BOOL; $this->storedSettings = array();
} return $success;
if (is_string($param)) {
return self::TYPE_STRING;
}
if (is_array($param)) {
return self::TYPE_ARRAY;
}
trigger_error('Unsupported setting type. ' . print_r($param, true));
return null;
}
/**
* Cast a Setting to the given Type
*
* @param string $type
* @param mixed $value
* @return mixed
*/
private function castSetting($type, $value) {
if ($type === self::TYPE_INT) {
return (int) $value;
}
if ($type === self::TYPE_REAL) {
return (float) $value;
}
if ($type === self::TYPE_BOOL) {
return (bool) $value;
}
if ($type === self::TYPE_STRING) {
return (string) $value;
}
if ($type === self::TYPE_ARRAY) {
return explode($this->arrayDelimiter, $value);
}
trigger_error('Unsupported setting type. ' . print_r($type, true));
return $value;
}
/**
* Format a Setting for saving it to the Database
*
* @param mixed $value
* @param string $type
* @return mixed
*/
private function formatSetting($value, $type = null) {
if ($type === null) {
$type = $this->getType($value);
}
if ($type === self::TYPE_ARRAY) {
return implode($this->arrayDelimiter, $value);
}
if ($type === self::TYPE_BOOL) {
return ($value ? 1 : 0);
}
return $value;
} }
/** /**
@ -217,6 +152,69 @@ class SettingManager implements CallbackListener {
return $success; return $success;
} }
/**
* Get Class Name of a Parameter
*
* @param mixed $param
* @return string
*/
private function getClassName($param) {
if (is_object($param)) {
return get_class($param);
}
if (is_string($param)) {
return $param;
}
trigger_error('Invalid class param. ' . $param);
return (string)$param;
}
/**
* Get Type of a Parameter
*
* @param mixed $param
* @return string
*/
private function getType($param) {
if (is_int($param)) {
return self::TYPE_INT;
}
if (is_real($param)) {
return self::TYPE_REAL;
}
if (is_bool($param)) {
return self::TYPE_BOOL;
}
if (is_string($param)) {
return self::TYPE_STRING;
}
if (is_array($param)) {
return self::TYPE_ARRAY;
}
trigger_error('Unsupported setting type. ' . print_r($param, true));
return null;
}
/**
* Format a Setting for saving it to the Database
*
* @param mixed $value
* @param string $type
* @return mixed
*/
private function formatSetting($value, $type = null) {
if ($type === null) {
$type = $this->getType($value);
}
if ($type === self::TYPE_ARRAY) {
return implode($this->arrayDelimiter, $value);
}
if ($type === self::TYPE_BOOL) {
return ($value ? 1 : 0);
}
return $value;
}
/** /**
* Get a Setting by its Index * Get a Setting by its Index
* *
@ -327,6 +325,33 @@ class SettingManager implements CallbackListener {
return $success; return $success;
} }
/**
* Cast a Setting to the given Type
*
* @param string $type
* @param mixed $value
* @return mixed
*/
private function castSetting($type, $value) {
if ($type === self::TYPE_INT) {
return (int)$value;
}
if ($type === self::TYPE_REAL) {
return (float)$value;
}
if ($type === self::TYPE_BOOL) {
return (bool)$value;
}
if ($type === self::TYPE_STRING) {
return (string)$value;
}
if ($type === self::TYPE_ARRAY) {
return explode($this->arrayDelimiter, $value);
}
trigger_error('Unsupported setting type. ' . print_r($type, true));
return $value;
}
/** /**
* Reset a Setting to its default Value * Reset a Setting to its default Value
* *
@ -462,29 +487,4 @@ class SettingManager implements CallbackListener {
$result->free(); $result->free();
return $settingClasses; return $settingClasses;
} }
/**
* Delete all unused Settings that haven't been initialized during the current Startup
*
* @return bool
*/
private function deleteUnusedSettings() {
$mysqli = $this->maniaControl->database->mysqli;
$settingQuery = "DELETE FROM `" . self::TABLE_SETTINGS . "`
WHERE `changed` < NOW() - INTERVAL 1 HOUR;";
$settingStatement = $mysqli->prepare($settingQuery);
if ($mysqli->error) {
trigger_error($mysqli->error);
return false;
}
$success = $settingStatement->execute();
if ($settingStatement->error) {
trigger_error($settingStatement->error);
$settingStatement->close();
return false;
}
$settingStatement->close();
$this->storedSettings = array();
return $success;
}
} }

View File

@ -24,8 +24,8 @@ use ManiaControl\Players\PlayerManager;
/** /**
* Simple Stats List Class * Simple Stats List Class
* *
* @author kremsy * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class SimpleStatsList implements ManialinkPageAnswerListener, CallbackListener, CommandListener { class SimpleStatsList implements ManialinkPageAnswerListener, CallbackListener, CommandListener {
@ -82,17 +82,6 @@ class SimpleStatsList implements ManialinkPageAnswerListener, CallbackListener,
$this->registerStat(StatisticManager::SPECIAL_STAT_HITS_PH, 85, "H/h", 15, StatisticManager::STAT_TYPE_FLOAT); $this->registerStat(StatisticManager::SPECIAL_STAT_HITS_PH, 85, "H/h", 15, StatisticManager::STAT_TYPE_FLOAT);
} }
/**
* Show the stat List
*
* @param array $callback
* @param Player $player
*/
public function command_ShowStatsList(array $callback, Player $player) {
$this->showStatsList($player);
}
/** /**
* Register a Certain Stat * Register a Certain Stat
* *
@ -111,6 +100,15 @@ class SimpleStatsList implements ManialinkPageAnswerListener, CallbackListener,
$this->statsWidth += $width; $this->statsWidth += $width;
} }
/**
* Show the stat List
*
* @param array $callback
* @param Player $player
*/
public function command_ShowStatsList(array $callback, Player $player) {
$this->showStatsList($player);
}
/** /**
* Show the StatsList Widget to the Player * Show the StatsList Widget to the Player

View File

@ -11,8 +11,8 @@ use ManiaControl\Players\PlayerManager;
/** /**
* Statistic Collector Class * Statistic Collector Class
* *
* @author steeffeen & kremsy * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class StatisticCollector implements CallbackListener { class StatisticCollector implements CallbackListener {
@ -121,87 +121,6 @@ class StatisticCollector implements CallbackListener {
} }
} }
/**
* Handle Player Shots
*
* @param string $login
* @param int $weaponNumber
*/
private function handleOnShoot($login, $weaponNumber) {
if (!isset($this->onShootArray[$login])) {
$this->onShootArray[$login] = array(self::WEAPON_ROCKET => 0, self::WEAPON_ARROW => 0, self::WEAPON_NUCLEUS => 0, self::WEAPON_LASER => 0);
$this->onShootArray[$login][$weaponNumber]++;
} else {
$this->onShootArray[$login][$weaponNumber]++;
}
//Write Shoot Data into database
if (array_sum($this->onShootArray[$login]) > $this->maniaControl->settingManager->getSetting($this, self::SETTING_ON_SHOOT_PRESTORE)) {
$player = $this->maniaControl->playerManager->getPlayer($login);
$rocketShots = $this->onShootArray[$login][self::WEAPON_ROCKET];
$laserShots = $this->onShootArray[$login][self::WEAPON_LASER];
$arrowShots = $this->onShootArray[$login][self::WEAPON_ARROW];
$nucleusShots = $this->onShootArray[$login][self::WEAPON_NUCLEUS];
if ($rocketShots > 0) {
$this->maniaControl->statisticManager->insertStat(self::STAT_ROCKET_SHOT, $player, $this->maniaControl->server->index, $rocketShots);
$this->onShootArray[$login][self::WEAPON_ROCKET] = 0;
}
if ($laserShots > 0) {
$this->maniaControl->statisticManager->insertStat(self::STAT_LASER_SHOT, $player, $this->maniaControl->server->index, $laserShots);
$this->onShootArray[$login][self::WEAPON_LASER] = 0;
}
if ($arrowShots > 0) {
$this->maniaControl->statisticManager->insertStat(self::STAT_ARROW_SHOT, $player, $this->maniaControl->server->index, $arrowShots);
$this->onShootArray[$login][self::WEAPON_ARROW] = 0;
}
if ($nucleusShots > 0) {
$this->maniaControl->statisticManager->insertStat(self::STAT_NUCLEUS_SHOT, $player, $this->maniaControl->server->index, $nucleusShots);
$this->onShootArray[$login][self::WEAPON_NUCLEUS] = 0;
}
$this->maniaControl->statisticManager->insertStat(self::STAT_ON_SHOOT, $player, $this->maniaControl->server->index, $rocketShots + $laserShots + $arrowShots + $nucleusShots);
}
}
/**
* Get the Weapon stat
*
* @param int $weaponNumber
* @param bool $shot
* @return string
*/
private function getWeaponStat($weaponNumber, $shot = true) {
if ($shot) {
switch($weaponNumber) {
case self::WEAPON_ROCKET:
return self::STAT_ROCKET_SHOT;
case self::WEAPON_LASER:
return self::STAT_LASER_SHOT;
case self::WEAPON_ARROW:
return self::STAT_ARROW_SHOT;
case self::WEAPON_NUCLEUS:
return self::STAT_NUCLEUS_SHOT;
default:
return -1;
}
} else {
switch($weaponNumber) {
case self::WEAPON_ROCKET:
return self::STAT_ROCKET_HIT;
case self::WEAPON_LASER:
return self::STAT_LASER_HIT;
case self::WEAPON_ARROW:
return self::STAT_ARROW_HIT;
case self::WEAPON_NUCLEUS:
return self::STAT_NUCLEUS_HIT;
default:
return -1;
}
}
}
/** /**
* Insert OnShoot Statistic when a player leaves * Insert OnShoot Statistic when a player leaves
* *
@ -342,4 +261,85 @@ class StatisticCollector implements CallbackListener {
break; break;
} }
} }
/**
* Handle Player Shots
*
* @param string $login
* @param int $weaponNumber
*/
private function handleOnShoot($login, $weaponNumber) {
if (!isset($this->onShootArray[$login])) {
$this->onShootArray[$login] = array(self::WEAPON_ROCKET => 0, self::WEAPON_ARROW => 0, self::WEAPON_NUCLEUS => 0, self::WEAPON_LASER => 0);
$this->onShootArray[$login][$weaponNumber]++;
} else {
$this->onShootArray[$login][$weaponNumber]++;
}
//Write Shoot Data into database
if (array_sum($this->onShootArray[$login]) > $this->maniaControl->settingManager->getSetting($this, self::SETTING_ON_SHOOT_PRESTORE)) {
$player = $this->maniaControl->playerManager->getPlayer($login);
$rocketShots = $this->onShootArray[$login][self::WEAPON_ROCKET];
$laserShots = $this->onShootArray[$login][self::WEAPON_LASER];
$arrowShots = $this->onShootArray[$login][self::WEAPON_ARROW];
$nucleusShots = $this->onShootArray[$login][self::WEAPON_NUCLEUS];
if ($rocketShots > 0) {
$this->maniaControl->statisticManager->insertStat(self::STAT_ROCKET_SHOT, $player, $this->maniaControl->server->index, $rocketShots);
$this->onShootArray[$login][self::WEAPON_ROCKET] = 0;
}
if ($laserShots > 0) {
$this->maniaControl->statisticManager->insertStat(self::STAT_LASER_SHOT, $player, $this->maniaControl->server->index, $laserShots);
$this->onShootArray[$login][self::WEAPON_LASER] = 0;
}
if ($arrowShots > 0) {
$this->maniaControl->statisticManager->insertStat(self::STAT_ARROW_SHOT, $player, $this->maniaControl->server->index, $arrowShots);
$this->onShootArray[$login][self::WEAPON_ARROW] = 0;
}
if ($nucleusShots > 0) {
$this->maniaControl->statisticManager->insertStat(self::STAT_NUCLEUS_SHOT, $player, $this->maniaControl->server->index, $nucleusShots);
$this->onShootArray[$login][self::WEAPON_NUCLEUS] = 0;
}
$this->maniaControl->statisticManager->insertStat(self::STAT_ON_SHOOT, $player, $this->maniaControl->server->index, $rocketShots + $laserShots + $arrowShots + $nucleusShots);
}
}
/**
* Get the Weapon stat
*
* @param int $weaponNumber
* @param bool $shot
* @return string
*/
private function getWeaponStat($weaponNumber, $shot = true) {
if ($shot) {
switch ($weaponNumber) {
case self::WEAPON_ROCKET:
return self::STAT_ROCKET_SHOT;
case self::WEAPON_LASER:
return self::STAT_LASER_SHOT;
case self::WEAPON_ARROW:
return self::STAT_ARROW_SHOT;
case self::WEAPON_NUCLEUS:
return self::STAT_NUCLEUS_SHOT;
default:
return -1;
}
} else {
switch ($weaponNumber) {
case self::WEAPON_ROCKET:
return self::STAT_ROCKET_HIT;
case self::WEAPON_LASER:
return self::STAT_LASER_HIT;
case self::WEAPON_ARROW:
return self::STAT_ARROW_HIT;
case self::WEAPON_NUCLEUS:
return self::STAT_NUCLEUS_HIT;
default:
return -1;
}
}
}
} }

View File

@ -8,8 +8,8 @@ use ManiaControl\Players\Player;
/** /**
* Statistic Manager Class * Statistic Manager Class
* *
* @author steeffeen & kremsy * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class StatisticManager { class StatisticManager {
@ -59,81 +59,110 @@ class StatisticManager {
} }
/** /**
* Get the value of an statistic * Initialize necessary database tables
* *
* @param $statName * @return bool
* @param $playerId
* @param int $serverIndex
* @return int
*/ */
public function getStatisticData($statName, $playerId, $serverIndex = -1) { private function initTables() {
//Handle Special Stats
switch($statName) {
case self::SPECIAL_STAT_KD_RATIO:
$kills = $this->getStatisticData(StatisticCollector::STAT_ON_KILL, $playerId, $serverIndex);
$deaths = $this->getStatisticData(StatisticCollector::STAT_ON_DEATH, $playerId, $serverIndex);
if ($deaths == 0) {
return -1;
}
return intval($kills) / intval($deaths);
case self::SPECIAL_STAT_HITS_PH:
$hits = $this->getStatisticData(StatisticCollector::STAT_ON_HIT, $playerId, $serverIndex);
$time = $this->getStatisticData(StatisticCollector::STAT_PLAYTIME, $playerId, $serverIndex);
if ($time == 0) {
return -1;
}
return intval($hits) / (intval($time) / 3600);
case self::SPECIAL_STAT_ARROW_ACC:
$hits = $this->getStatisticData(StatisticCollector::STAT_ARROW_HIT, $playerId, $serverIndex);
$shots = $this->getStatisticData(StatisticCollector::STAT_ARROW_SHOT, $playerId, $serverIndex);
if ($shots == 0) {
return -1;
}
return intval($hits) / intval($shots);
case self::SPECIAL_STAT_LASER_ACC:
$hits = $this->getStatisticData(StatisticCollector::STAT_LASER_HIT, $playerId, $serverIndex);
$shots = $this->getStatisticData(StatisticCollector::STAT_LASER_SHOT, $playerId, $serverIndex);
if ($shots == 0) {
return -1;
}
return intval($hits) / intval($shots);
case self::SPECIAL_STAT_NUCLEUS_ACC:
$hits = $this->getStatisticData(StatisticCollector::STAT_NUCLEUS_HIT, $playerId, $serverIndex);
$shots = $this->getStatisticData(StatisticCollector::STAT_NUCLEUS_SHOT, $playerId, $serverIndex);
if ($shots == 0) {
return -1;
}
return intval($hits) / intval($shots);
case self::SPECIAL_STAT_ROCKET_ACC:
$hits = $this->getStatisticData(StatisticCollector::STAT_ROCKET_HIT, $playerId, $serverIndex);
$shots = $this->getStatisticData(StatisticCollector::STAT_ROCKET_SHOT, $playerId, $serverIndex);
if ($shots == 0) {
return -1;
}
return intval($hits) / intval($shots);
}
$mysqli = $this->maniaControl->database->mysqli; $mysqli = $this->maniaControl->database->mysqli;
$statId = $this->getStatId($statName); $query = "CREATE TABLE IF NOT EXISTS `" . self::TABLE_STATMETADATA . "` (
`index` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`type` int(5) NOT NULL,
`description` varchar(150) NOT NULL,
PRIMARY KEY (`index`),
UNIQUE KEY `name` (`name`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Statistics Meta Data' 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();
if (!$statId) return -1; $query = "CREATE TABLE IF NOT EXISTS `" . self::TABLE_STATISTICS . "` (
`index` int(11) NOT NULL AUTO_INCREMENT,
if ($serverIndex == -1) { `serverIndex` int(11) NOT NULL,
$query = "SELECT SUM(value) as value FROM `" . self::TABLE_STATISTICS . "` WHERE `statId` = " . $statId . " AND `playerId` = " . $playerId . ";"; `playerId` int(11) NOT NULL,
} else { `statId` int(11) NOT NULL,
$query = "SELECT value FROM `" . self::TABLE_STATISTICS . "` WHERE `statId` = " . $statId . " AND `playerId` = " . $playerId . " AND `serverIndex` = '" . $serverIndex . "';"; `value` int(20) NOT NULL DEFAULT '0',
PRIMARY KEY (`index`),
UNIQUE KEY `unique` (`statId`,`playerId`,`serverIndex`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Statistics' 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;
} }
/**
* Store Stats Meta Data from the Database
*/
private function storeStatMetaData() {
$mysqli = $this->maniaControl->database->mysqli;
$query = "SELECT * FROM `" . self::TABLE_STATMETADATA . "`;";
$result = $mysqli->query($query); $result = $mysqli->query($query);
if (!$result) { if (!$result) {
trigger_error($mysqli->error); trigger_error($mysqli->error);
return -1; return;
} }
$row = $result->fetch_object(); while ($row = $result->fetch_object()) {
$this->stats[$row->name] = $row;
}
$result->close(); $result->close();
return $row->value;
// TODO: own model class
//Define Special Stat Kill / Death Ratio
$stat = new \stdClass();
$stat->name = self::SPECIAL_STAT_KD_RATIO;
$stat->type = self::STAT_TYPE_FLOAT;
$this->specialStats[self::SPECIAL_STAT_KD_RATIO] = $stat;
//Hits Per Hour
$stat = new \stdClass();
$stat->name = self::SPECIAL_STAT_HITS_PH;
$stat->type = self::STAT_TYPE_FLOAT;
$this->specialStats[self::SPECIAL_STAT_HITS_PH] = $stat;
//Laser Accuracy
$stat = new \stdClass();
$stat->name = self::SPECIAL_STAT_LASER_ACC;
$stat->type = self::STAT_TYPE_FLOAT;
$this->specialStats[self::SPECIAL_STAT_LASER_ACC] = $stat;
//Nucleus Accuracy
$stat = new \stdClass();
$stat->name = self::SPECIAL_STAT_NUCLEUS_ACC;
$stat->type = self::STAT_TYPE_FLOAT;
$this->specialStats[self::SPECIAL_STAT_NUCLEUS_ACC] = $stat;
//Arrow Accuracy
$stat = new \stdClass();
$stat->name = self::SPECIAL_STAT_ARROW_ACC;
$stat->type = self::STAT_TYPE_FLOAT;
$this->specialStats[self::SPECIAL_STAT_ARROW_ACC] = $stat;
//Rocket Accuracy
$stat = new \stdClass();
$stat->name = self::SPECIAL_STAT_ROCKET_ACC;
$stat->type = self::STAT_TYPE_FLOAT;
$this->specialStats[self::SPECIAL_STAT_ROCKET_ACC] = $stat;
} }
/** /**
@ -281,64 +310,6 @@ class StatisticManager {
return $statsArray; return $statsArray;
} }
/**
* Store Stats Meta Data from the Database
*/
private function storeStatMetaData() {
$mysqli = $this->maniaControl->database->mysqli;
$query = "SELECT * FROM `" . self::TABLE_STATMETADATA . "`;";
$result = $mysqli->query($query);
if (!$result) {
trigger_error($mysqli->error);
return;
}
while($row = $result->fetch_object()) {
$this->stats[$row->name] = $row;
}
$result->close();
// TODO: own model class
//Define Special Stat Kill / Death Ratio
$stat = new \stdClass();
$stat->name = self::SPECIAL_STAT_KD_RATIO;
$stat->type = self::STAT_TYPE_FLOAT;
$this->specialStats[self::SPECIAL_STAT_KD_RATIO] = $stat;
//Hits Per Hour
$stat = new \stdClass();
$stat->name = self::SPECIAL_STAT_HITS_PH;
$stat->type = self::STAT_TYPE_FLOAT;
$this->specialStats[self::SPECIAL_STAT_HITS_PH] = $stat;
//Laser Accuracy
$stat = new \stdClass();
$stat->name = self::SPECIAL_STAT_LASER_ACC;
$stat->type = self::STAT_TYPE_FLOAT;
$this->specialStats[self::SPECIAL_STAT_LASER_ACC] = $stat;
//Nucleus Accuracy
$stat = new \stdClass();
$stat->name = self::SPECIAL_STAT_NUCLEUS_ACC;
$stat->type = self::STAT_TYPE_FLOAT;
$this->specialStats[self::SPECIAL_STAT_NUCLEUS_ACC] = $stat;
//Arrow Accuracy
$stat = new \stdClass();
$stat->name = self::SPECIAL_STAT_ARROW_ACC;
$stat->type = self::STAT_TYPE_FLOAT;
$this->specialStats[self::SPECIAL_STAT_ARROW_ACC] = $stat;
//Rocket Accuracy
$stat = new \stdClass();
$stat->name = self::SPECIAL_STAT_ROCKET_ACC;
$stat->type = self::STAT_TYPE_FLOAT;
$this->specialStats[self::SPECIAL_STAT_ROCKET_ACC] = $stat;
}
/** /**
* Return the Stat Id * Return the Stat Id
* *
@ -441,6 +412,98 @@ class StatisticManager {
return $playerStats; return $playerStats;
} }
/**
* Get the value of an statistic
*
* @param $statName
* @param $playerId
* @param int $serverIndex
* @return int
*/
public function getStatisticData($statName, $playerId, $serverIndex = -1) {
//Handle Special Stats
switch ($statName) {
case self::SPECIAL_STAT_KD_RATIO:
$kills = $this->getStatisticData(StatisticCollector::STAT_ON_KILL, $playerId, $serverIndex);
$deaths = $this->getStatisticData(StatisticCollector::STAT_ON_DEATH, $playerId, $serverIndex);
if ($deaths == 0) {
return -1;
}
return intval($kills) / intval($deaths);
case self::SPECIAL_STAT_HITS_PH:
$hits = $this->getStatisticData(StatisticCollector::STAT_ON_HIT, $playerId, $serverIndex);
$time = $this->getStatisticData(StatisticCollector::STAT_PLAYTIME, $playerId, $serverIndex);
if ($time == 0) {
return -1;
}
return intval($hits) / (intval($time) / 3600);
case self::SPECIAL_STAT_ARROW_ACC:
$hits = $this->getStatisticData(StatisticCollector::STAT_ARROW_HIT, $playerId, $serverIndex);
$shots = $this->getStatisticData(StatisticCollector::STAT_ARROW_SHOT, $playerId, $serverIndex);
if ($shots == 0) {
return -1;
}
return intval($hits) / intval($shots);
case self::SPECIAL_STAT_LASER_ACC:
$hits = $this->getStatisticData(StatisticCollector::STAT_LASER_HIT, $playerId, $serverIndex);
$shots = $this->getStatisticData(StatisticCollector::STAT_LASER_SHOT, $playerId, $serverIndex);
if ($shots == 0) {
return -1;
}
return intval($hits) / intval($shots);
case self::SPECIAL_STAT_NUCLEUS_ACC:
$hits = $this->getStatisticData(StatisticCollector::STAT_NUCLEUS_HIT, $playerId, $serverIndex);
$shots = $this->getStatisticData(StatisticCollector::STAT_NUCLEUS_SHOT, $playerId, $serverIndex);
if ($shots == 0) {
return -1;
}
return intval($hits) / intval($shots);
case self::SPECIAL_STAT_ROCKET_ACC:
$hits = $this->getStatisticData(StatisticCollector::STAT_ROCKET_HIT, $playerId, $serverIndex);
$shots = $this->getStatisticData(StatisticCollector::STAT_ROCKET_SHOT, $playerId, $serverIndex);
if ($shots == 0) {
return -1;
}
return intval($hits) / intval($shots);
}
$mysqli = $this->maniaControl->database->mysqli;
$statId = $this->getStatId($statName);
if (!$statId) {
return -1;
}
if ($serverIndex == -1) {
$query = "SELECT SUM(value) as value FROM `" . self::TABLE_STATISTICS . "` WHERE `statId` = " . $statId . " AND `playerId` = " . $playerId . ";";
} else {
$query = "SELECT value FROM `" . self::TABLE_STATISTICS . "` WHERE `statId` = " . $statId . " AND `playerId` = " . $playerId . " AND `serverIndex` = '" . $serverIndex . "';";
}
$result = $mysqli->query($query);
if (!$result) {
trigger_error($mysqli->error);
return -1;
}
$row = $result->fetch_object();
$result->close();
return $row->value;
}
/**
* Increments a Statistic by one
*
* @param string $statName
* @param Player $player
* @param int $serverIndex
* @return bool
*/
public function incrementStat($statName, Player $player, $serverIndex = -1) {
return $this->insertStat($statName, $player, $serverIndex, 1);
}
/** /**
* Inserts a Stat into the database * Inserts a Stat into the database
* *
@ -496,18 +559,6 @@ class StatisticManager {
return true; return true;
} }
/**
* Increments a Statistic by one
*
* @param string $statName
* @param Player $player
* @param int $serverIndex
* @return bool
*/
public function incrementStat($statName, Player $player, $serverIndex = -1) {
return $this->insertStat($statName, $player, $serverIndex, 1);
}
/** /**
* Defines a Stat * Defines a Stat
* *
@ -542,54 +593,4 @@ class StatisticManager {
$statement->close(); $statement->close();
return true; return true;
} }
/**
* Initialize necessary database tables
*
* @return bool
*/
private function initTables() {
$mysqli = $this->maniaControl->database->mysqli;
$query = "CREATE TABLE IF NOT EXISTS `" . self::TABLE_STATMETADATA . "` (
`index` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`type` int(5) NOT NULL,
`description` varchar(150) NOT NULL,
PRIMARY KEY (`index`),
UNIQUE KEY `name` (`name`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Statistics Meta Data' 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();
$query = "CREATE TABLE IF NOT EXISTS `" . self::TABLE_STATISTICS . "` (
`index` int(11) NOT NULL AUTO_INCREMENT,
`serverIndex` int(11) NOT NULL,
`playerId` int(11) NOT NULL,
`statId` int(11) NOT NULL,
`value` int(20) NOT NULL DEFAULT '0',
PRIMARY KEY (`index`),
UNIQUE KEY `unique` (`statId`,`playerId`,`serverIndex`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Statistics' 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;
}
} }

View File

@ -5,8 +5,8 @@ namespace ManiaControl\Update;
/** /**
* Plugin Update Data Structure * Plugin Update Data Structure
* *
* @author ManiaControl Team * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class PluginUpdateData { class PluginUpdateData {

View File

@ -6,20 +6,20 @@ use ManiaControl\Callbacks\CallbackListener;
use ManiaControl\Callbacks\CallbackManager; use ManiaControl\Callbacks\CallbackManager;
use ManiaControl\Callbacks\TimerListener; use ManiaControl\Callbacks\TimerListener;
use ManiaControl\Commands\CommandListener; use ManiaControl\Commands\CommandListener;
use ManiaControl\Files\BackupUtil;
use ManiaControl\Files\FileUtil; use ManiaControl\Files\FileUtil;
use ManiaControl\ManiaControl; use ManiaControl\ManiaControl;
use ManiaControl\Players\Player; use ManiaControl\Players\Player;
use ManiaControl\Plugins\Plugin; use ManiaControl\Plugins\Plugin;
use ManiaControl\Plugins\PluginInstallMenu; use ManiaControl\Plugins\PluginInstallMenu;
use ManiaControl\Plugins\PluginMenu;
use ManiaControl\Plugins\PluginManager; use ManiaControl\Plugins\PluginManager;
use ManiaControl\Files\BackupUtil; use ManiaControl\Plugins\PluginMenu;
/** /**
* Manager checking for ManiaControl Plugin Updates * Manager checking for ManiaControl Plugin Updates
* *
* @author ManiaControl Team * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class PluginUpdateManager implements CallbackListener, CommandListener, TimerListener { class PluginUpdateManager implements CallbackListener, CommandListener, TimerListener {
@ -59,76 +59,6 @@ class PluginUpdateManager implements CallbackListener, CommandListener, TimerLis
$this->checkPluginsUpdate($player); $this->checkPluginsUpdate($player);
} }
/**
* Handle //pluginsupdate command
*
* @param array $chatCallback
* @param Player $player
*/
public function handle_PluginsUpdate(array $chatCallback, Player $player) {
if (!$this->maniaControl->authenticationManager->checkPermission($player, UpdateManager::SETTING_PERMISSION_UPDATE)) {
$this->maniaControl->authenticationManager->sendNotAllowed($player);
return;
}
$this->performPluginsUpdate($player);
}
/**
* Handle PlayerManialinkPageAnswer callback
*
* @param array $callback
*/
public function handleManialinkPageAnswer(array $callback) {
$actionId = $callback[1][2];
$update = (strpos($actionId, PluginMenu::ACTION_PREFIX_UPDATEPLUGIN) === 0);
$install = (strpos($actionId, PluginInstallMenu::ACTION_PREFIX_INSTALLPLUGIN) === 0);
if (!$update && !$install) {
return;
}
$login = $callback[1][1];
$player = $this->maniaControl->playerManager->getPlayer($login);
if ($update) {
$pluginClass = substr($actionId, strlen(PluginMenu::ACTION_PREFIX_UPDATEPLUGIN));
if ($pluginClass == 'All') {
$this->performPluginsUpdate($player);
}
else {
$pluginUpdateData = $this->getPluginUpdate($pluginClass);
if ($pluginUpdateData) {
$this->installPlugin($pluginUpdateData, $player, true);
}
else {
$message = 'Error loading Plugin Update Data!';
$this->maniaControl->chat->sendError($message, $player);
}
}
}
else {
$pluginId = substr($actionId, strlen(PluginInstallMenu::ACTION_PREFIX_INSTALLPLUGIN));
$url = ManiaControl::URL_WEBSERVICE . 'plugins?id=' . $pluginId;
$self = $this;
$this->maniaControl->fileReader->loadFile($url, function ($data, $error) use(&$self, &$player) {
if ($error || !$data) {
$message = "Error loading Plugin Install Data! {$error}";
$self->maniaControl->chat->sendError($message, $player);
return;
}
$data = json_decode($data);
if (!isset($data[0])) {
$message = "Error loading Plugin Install Data! {$error}";
$self->maniaControl->chat->sendError($message, $player);
return;
}
$pluginUpdateData = new PluginUpdateData($data[0]);
$self->installPlugin($pluginUpdateData, $player);
});
}
}
/** /**
* Check if there are Outdated Plugins installed * Check if there are Outdated Plugins installed
* *
@ -159,7 +89,6 @@ class PluginUpdateManager implements CallbackListener, CommandListener, TimerLis
foreach ($pluginClasses as $pluginClass) { foreach ($pluginClasses as $pluginClass) {
/** /**
*
* @var Plugin $pluginClass * @var Plugin $pluginClass
*/ */
$pluginId = $pluginClass::getId(); $pluginId = $pluginClass::getId();
@ -185,8 +114,7 @@ class PluginUpdateManager implements CallbackListener, CommandListener, TimerLis
$self->maniaControl->chat->sendSuccess($message, $player); $self->maniaControl->chat->sendSuccess($message, $player);
} }
$self->maniaControl->log($message); $self->maniaControl->log($message);
} } else {
else {
$updatesCount = count($pluginUpdates); $updatesCount = count($pluginUpdates);
$message = "Plugins Update Check completed: There are {$updatesCount} Updates available!"; $message = "Plugins Update Check completed: There are {$updatesCount} Updates available!";
if ($player) { if ($player) {
@ -197,6 +125,39 @@ class PluginUpdateManager implements CallbackListener, CommandListener, TimerLis
}); });
} }
/**
* Get an Array of Plugin Update Data from the given Web Service Result
*
* @param mixed $webServiceResult
* @return mixed
*/
public function parsePluginsData($webServiceResult) {
if (!$webServiceResult || !is_array($webServiceResult)) {
return false;
}
$pluginsData = array();
foreach ($webServiceResult as $pluginResult) {
$pluginData = new PluginUpdateData($pluginResult);
$pluginsData[$pluginData->pluginId] = $pluginData;
}
return $pluginsData;
}
/**
* Handle //pluginsupdate command
*
* @param array $chatCallback
* @param Player $player
*/
public function handle_PluginsUpdate(array $chatCallback, Player $player) {
if (!$this->maniaControl->authenticationManager->checkPermission($player, UpdateManager::SETTING_PERMISSION_UPDATE)) {
$this->maniaControl->authenticationManager->sendNotAllowed($player);
return;
}
$this->performPluginsUpdate($player);
}
/** /**
* Perform an Update of all outdated Plugins * Perform an Update of all outdated Plugins
* *
@ -233,51 +194,6 @@ class PluginUpdateManager implements CallbackListener, CommandListener, TimerLis
} }
} }
/**
* Check given Plugin Class for Update
*
* @param string $pluginClass
* @return mixed
*/
public function getPluginUpdate($pluginClass) {
$pluginClass = PluginManager::getPluginClass($pluginClass);
/**
*
* @var Plugin $pluginClass
*/
$pluginId = $pluginClass::getId();
$url = ManiaControl::URL_WEBSERVICE . 'plugins?id=' . $pluginId;
$dataJson = FileUtil::loadFile($url);
$pluginVersions = json_decode($dataJson);
if (!$pluginVersions || !isset($pluginVersions[0])) {
return false;
}
$pluginUpdateData = new PluginUpdateData($pluginVersions[0]);
$pluginVersion = $pluginClass::getVersion();
if ($pluginUpdateData->isNewerThan($pluginVersion)) {
return $pluginUpdateData;
}
return false;
}
/**
* Get an Array of Plugin Update Data from the given Web Service Result
*
* @param mixed $webServiceResult
* @return mixed
*/
public function parsePluginsData($webServiceResult) {
if (!$webServiceResult || !is_array($webServiceResult)) {
return false;
}
$pluginsData = array();
foreach ($webServiceResult as $pluginResult) {
$pluginData = new PluginUpdateData($pluginResult);
$pluginsData[$pluginData->pluginId] = $pluginData;
}
return $pluginsData;
}
/** /**
* Check for Plugin Updates * Check for Plugin Updates
* *
@ -297,7 +213,6 @@ class PluginUpdateManager implements CallbackListener, CommandListener, TimerLis
$pluginClasses = $this->maniaControl->pluginManager->getPluginClasses(); $pluginClasses = $this->maniaControl->pluginManager->getPluginClasses();
foreach ($pluginClasses as $pluginClass) { foreach ($pluginClasses as $pluginClass) {
/** /**
*
* @var Plugin $pluginClass * @var Plugin $pluginClass
*/ */
$pluginId = $pluginClass::getId(); $pluginId = $pluginClass::getId();
@ -384,8 +299,7 @@ class PluginUpdateManager implements CallbackListener, CommandListener, TimerLis
$self->maniaControl->chat->sendError($message, $player); $self->maniaControl->chat->sendError($message, $player);
} }
$self->maniaControl->log($message); $self->maniaControl->log($message);
} } else {
else {
$message = "Successfully loaded fresh installed Plugin '{$pluginUpdateData->pluginName}'!"; $message = "Successfully loaded fresh installed Plugin '{$pluginUpdateData->pluginName}'!";
if ($player) { if ($player) {
$self->maniaControl->chat->sendSuccess($message, $player); $self->maniaControl->chat->sendSuccess($message, $player);
@ -398,4 +312,82 @@ class PluginUpdateManager implements CallbackListener, CommandListener, TimerLis
} }
}); });
} }
/**
* Handle PlayerManialinkPageAnswer callback
*
* @param array $callback
*/
public function handleManialinkPageAnswer(array $callback) {
$actionId = $callback[1][2];
$update = (strpos($actionId, PluginMenu::ACTION_PREFIX_UPDATEPLUGIN) === 0);
$install = (strpos($actionId, PluginInstallMenu::ACTION_PREFIX_INSTALLPLUGIN) === 0);
if (!$update && !$install) {
return;
}
$login = $callback[1][1];
$player = $this->maniaControl->playerManager->getPlayer($login);
if ($update) {
$pluginClass = substr($actionId, strlen(PluginMenu::ACTION_PREFIX_UPDATEPLUGIN));
if ($pluginClass == 'All') {
$this->performPluginsUpdate($player);
} else {
$pluginUpdateData = $this->getPluginUpdate($pluginClass);
if ($pluginUpdateData) {
$this->installPlugin($pluginUpdateData, $player, true);
} else {
$message = 'Error loading Plugin Update Data!';
$this->maniaControl->chat->sendError($message, $player);
}
}
} else {
$pluginId = substr($actionId, strlen(PluginInstallMenu::ACTION_PREFIX_INSTALLPLUGIN));
$url = ManiaControl::URL_WEBSERVICE . 'plugins?id=' . $pluginId;
$self = $this;
$this->maniaControl->fileReader->loadFile($url, function ($data, $error) use (&$self, &$player) {
if ($error || !$data) {
$message = "Error loading Plugin Install Data! {$error}";
$self->maniaControl->chat->sendError($message, $player);
return;
}
$data = json_decode($data);
if (!isset($data[0])) {
$message = "Error loading Plugin Install Data! {$error}";
$self->maniaControl->chat->sendError($message, $player);
return;
}
$pluginUpdateData = new PluginUpdateData($data[0]);
$self->installPlugin($pluginUpdateData, $player);
});
}
}
/**
* Check given Plugin Class for Update
*
* @param string $pluginClass
* @return mixed
*/
public function getPluginUpdate($pluginClass) {
$pluginClass = PluginManager::getPluginClass($pluginClass);
/**
* @var Plugin $pluginClass
*/
$pluginId = $pluginClass::getId();
$url = ManiaControl::URL_WEBSERVICE . 'plugins?id=' . $pluginId;
$dataJson = FileUtil::loadFile($url);
$pluginVersions = json_decode($dataJson);
if (!$pluginVersions || !isset($pluginVersions[0])) {
return false;
}
$pluginUpdateData = new PluginUpdateData($pluginVersions[0]);
$pluginVersion = $pluginClass::getVersion();
if ($pluginUpdateData->isNewerThan($pluginVersion)) {
return $pluginUpdateData;
}
return false;
}
} }

View File

@ -5,8 +5,8 @@ namespace ManiaControl\Update;
/** /**
* Update Data Structure * Update Data Structure
* *
* @author ManiaControl Team * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class UpdateData { class UpdateData {

View File

@ -6,17 +6,17 @@ use ManiaControl\Admin\AuthenticationManager;
use ManiaControl\Callbacks\CallbackListener; use ManiaControl\Callbacks\CallbackListener;
use ManiaControl\Callbacks\TimerListener; use ManiaControl\Callbacks\TimerListener;
use ManiaControl\Commands\CommandListener; use ManiaControl\Commands\CommandListener;
use ManiaControl\Files\BackupUtil;
use ManiaControl\Files\FileUtil; use ManiaControl\Files\FileUtil;
use ManiaControl\ManiaControl; use ManiaControl\ManiaControl;
use ManiaControl\Players\Player; use ManiaControl\Players\Player;
use ManiaControl\Players\PlayerManager; use ManiaControl\Players\PlayerManager;
use ManiaControl\Files\BackupUtil;
/** /**
* Manager checking for ManiaControl Core Updates * Manager checking for ManiaControl Core Updates
* *
* @author ManiaControl Team * @author ManiaControl Team <mail@maniacontrol.com>
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class UpdateManager implements CallbackListener, CommandListener, TimerListener { class UpdateManager implements CallbackListener, CommandListener, TimerListener {
@ -44,7 +44,6 @@ class UpdateManager implements CallbackListener, CommandListener, TimerListener
*/ */
private $maniaControl = null; private $maniaControl = null;
/** /**
*
* @var UpdateData $coreUpdateData * @var UpdateData $coreUpdateData
*/ */
private $coreUpdateData = null; private $coreUpdateData = null;
@ -83,13 +82,6 @@ class UpdateManager implements CallbackListener, CommandListener, TimerListener
$this->pluginUpdateManager = new PluginUpdateManager($maniaControl); $this->pluginUpdateManager = new PluginUpdateManager($maniaControl);
} }
/**
* Start an Update Check
*/
public function checkUpdate() {
$this->checkCoreUpdateAsync(array($this, 'handleUpdateCheck'));
}
/** /**
* Perform Hourly Update Check * Perform Hourly Update Check
* *
@ -104,6 +96,56 @@ class UpdateManager implements CallbackListener, CommandListener, TimerListener
$this->checkUpdate(); $this->checkUpdate();
} }
/**
* Set Core Update Data
*
* @param UpdateData $coreUpdateData
*/
public function setCoreUpdateData(UpdateData $coreUpdateData = null) {
$this->coreUpdateData = $coreUpdateData;
}
/**
* Start an Update Check
*/
public function checkUpdate() {
$this->checkCoreUpdateAsync(array($this, 'handleUpdateCheck'));
}
/**
* Checks a Core Update asynchronously
*
* @param callable $function
*/
private function checkCoreUpdateAsync($function) {
$updateChannel = $this->getCurrentUpdateChannelSetting();
$url = ManiaControl::URL_WEBSERVICE . 'versions?current=1&channel=' . $updateChannel;
$this->maniaControl->fileReader->loadFile($url, function ($dataJson, $error) use (&$function) {
$versions = json_decode($dataJson);
if (!$versions || !isset($versions[0])) {
call_user_func($function, null);
} else {
$updateData = new UpdateData($versions[0]);
call_user_func($function, $updateData);
}
});
}
/**
* Retrieve the Update Channel Setting
*
* @return string
*/
private function getCurrentUpdateChannelSetting() {
$updateChannel = $this->maniaControl->settingManager->getSetting($this, self::SETTING_UPDATECHECK_CHANNEL);
$updateChannel = strtolower($updateChannel);
if (!in_array($updateChannel, array(self::CHANNEL_RELEASE, self::CHANNEL_BETA, self::CHANNEL_NIGHTLY))) {
$updateChannel = self::CHANNEL_RELEASE;
}
return $updateChannel;
}
/** /**
* Handle the fetched Update Data * Handle the fetched Update Data
* *
@ -122,8 +164,7 @@ class UpdateManager implements CallbackListener, CommandListener, TimerListener
if ($this->isNightlyUpdateChannel()) { if ($this->isNightlyUpdateChannel()) {
$this->maniaControl->log("New Nightly Build ({$updateData->releaseDate}) available!"); $this->maniaControl->log("New Nightly Build ({$updateData->releaseDate}) available!");
} } else {
else {
$this->maniaControl->log("New ManiaControl Version {$updateData->version} available!"); $this->maniaControl->log("New ManiaControl Version {$updateData->version} available!");
} }
$this->setCoreUpdateData($updateData); $this->setCoreUpdateData($updateData);
@ -153,6 +194,34 @@ class UpdateManager implements CallbackListener, CommandListener, TimerListener
return ($updateData->version > ManiaControl::VERSION); return ($updateData->version > ManiaControl::VERSION);
} }
/**
* Check if ManiaControl is running the Nightly Update Channel
*
* @param string $updateChannel
* @return bool
*/
public function isNightlyUpdateChannel($updateChannel = null) {
if (!$updateChannel) {
$updateChannel = $this->getCurrentUpdateChannelSetting();
}
return ($updateChannel === self::CHANNEL_NIGHTLY);
}
/**
* Get the Build Date of the local Nightly Build Version
*
* @return string
*/
public function getNightlyBuildDate() {
if (!$this->currentBuildDate) {
$nightlyBuildDateFile = ManiaControlDir . '/core/nightly_build.txt';
if (file_exists($nightlyBuildDateFile)) {
$this->currentBuildDate = file_get_contents($nightlyBuildDateFile);
}
}
return $this->currentBuildDate;
}
/** /**
* Check if the Update Data is compatible with the Server * Check if the Update Data is compatible with the Server
* *
@ -174,46 +243,6 @@ class UpdateManager implements CallbackListener, CommandListener, TimerListener
return true; return true;
} }
/**
* Set Core Update Data
*
* @param UpdateData $coreUpdateData
*/
public function setCoreUpdateData(UpdateData $coreUpdateData = null) {
$this->coreUpdateData = $coreUpdateData;
}
/**
* Handle ManiaControl PlayerJoined callback
*
* @param Player $player
*/
public function handlePlayerJoined(Player $player) {
if (!$this->coreUpdateData) {
return;
}
// Announce available update
if (!$this->maniaControl->authenticationManager->checkPermission($player, self::SETTING_PERMISSION_UPDATE)) {
return;
}
if ($this->isNightlyUpdateChannel()) {
$this->maniaControl->chat->sendSuccess('New Nightly Build (' . $this->coreUpdateData->releaseDate . ') available!', $player->login);
}
else {
$this->maniaControl->chat->sendInformation('New ManiaControl Version ' . $this->coreUpdateData->version . ' available!', $player->login);
}
}
/**
* Handle Player Disconnect Callback
*
* @param Player $player
*/
public function handlePlayerDisconnect(Player $player) {
$this->checkAutoUpdate();
}
/** /**
* Check if an automatic Update should be performed * Check if an automatic Update should be performed
*/ */
@ -235,138 +264,6 @@ class UpdateManager implements CallbackListener, CommandListener, TimerListener
$this->performCoreUpdate(); $this->performCoreUpdate();
} }
/**
* Handle //checkupdate command
*
* @param array $chatCallback
* @param Player $player
*/
public function handle_CheckUpdate(array $chatCallback, Player $player) {
if (!$this->maniaControl->authenticationManager->checkPermission($player, self::SETTING_PERMISSION_UPDATECHECK)) {
$this->maniaControl->authenticationManager->sendNotAllowed($player);
return;
}
$self = $this;
$this->checkCoreUpdateAsync(function (UpdateData $updateData = null) use(&$self, &$player) {
if (!$self->checkUpdateData($updateData)) {
$self->maniaControl->chat->sendInformation('No Update available!', $player->login);
return;
}
if (!$self->checkUpdateDataBuildVersion($updateData)) {
$self->maniaControl->chat->sendError("Please update Your Server to '{$updateData->minDedicatedBuild}' in order to receive further Updates!", $player->login);
return;
}
$isNightly = $self->isNightlyUpdateChannel();
if ($isNightly) {
$buildDate = $self->getNightlyBuildDate();
if ($buildDate) {
if ($updateData->isNewerThan($buildDate)) {
$self->maniaControl->chat->sendInformation("No new Build available! (Current Build: '{$buildDate}')", $player->login);
}
else {
$self->maniaControl->chat->sendSuccess("New Nightly Build ({$updateData->releaseDate}) available! (Current Build: '{$buildDate}')", $player->login);
}
}
else {
$self->maniaControl->chat->sendSuccess("New Nightly Build ('{$updateData->releaseDate}') available!", $player->login);
}
}
else {
$self->maniaControl->chat->sendSuccess('Update for Version ' . $updateData->version . ' available!', $player->login);
}
});
}
/**
* Get the Build Date of the local Nightly Build Version
*
* @return string
*/
public function getNightlyBuildDate() {
if (!$this->currentBuildDate) {
$nightlyBuildDateFile = ManiaControlDir . '/core/nightly_build.txt';
if (file_exists($nightlyBuildDateFile)) {
$this->currentBuildDate = file_get_contents($nightlyBuildDateFile);
}
}
return $this->currentBuildDate;
}
/**
* Set the Build Date of the local Nightly Build Version
*
* @param string $date
* @return bool
*/
private function setNightlyBuildDate($date) {
$nightlyBuildDateFile = ManiaControlDir . '/core/nightly_build.txt';
$success = (bool) file_put_contents($nightlyBuildDateFile, $date);
$this->currentBuildDate = $date;
return $success;
}
/**
* Handle //coreupdate command
*
* @param array $chatCallback
* @param Player $player
*/
public function handle_CoreUpdate(array $chatCallback, Player $player) {
if (!$this->maniaControl->authenticationManager->checkPermission($player, self::SETTING_PERMISSION_UPDATE)) {
$this->maniaControl->authenticationManager->sendNotAllowed($player);
return;
}
$self = $this;
$this->checkCoreUpdateAsync(function (UpdateData $updateData = null) use(&$self, &$player) {
if (!$updateData) {
$self->maniaControl->chat->sendError('Update is currently not possible!', $player->login);
return;
}
if (!$self->checkUpdateDataBuildVersion($updateData)) {
$self->maniaControl->chat->sendError("The Next ManiaControl Update requires a newer Dedicated Server Version!", $player->login);
return;
}
$message = "Starting Update to Version v{$updateData->version}...";
$self->maniaControl->chat->sendInformation($message, $player->login);
$self->maniaControl->log($message);
$performBackup = $self->maniaControl->settingManager->getSetting($self, UpdateManager::SETTING_PERFORM_BACKUPS);
if ($performBackup && !BackupUtil::performFullBackup()) {
$message = 'Creating Backup failed!';
$self->maniaControl->chat->sendError($message, $player->login);
$self->maniaControl->log($message);
}
$self->performCoreUpdate($player);
});
}
/**
* Checks a Core Update asynchronously
*
* @param callable $function
*/
private function checkCoreUpdateAsync($function) {
$updateChannel = $this->getCurrentUpdateChannelSetting();
$url = ManiaControl::URL_WEBSERVICE . 'versions?current=1&channel=' . $updateChannel;
$this->maniaControl->fileReader->loadFile($url, function ($dataJson, $error) use(&$function) {
$versions = json_decode($dataJson);
if (!$versions || !isset($versions[0])) {
call_user_func($function, null);
}
else {
$updateData = new UpdateData($versions[0]);
call_user_func($function, $updateData);
}
});
}
/** /**
* Perform a Core Update * Perform a Core Update
* *
@ -450,29 +347,125 @@ class UpdateManager implements CallbackListener, CommandListener, TimerListener
} }
/** /**
* Check if ManiaControl is running the Nightly Update Channel * Set the Build Date of the local Nightly Build Version
* *
* @param string $updateChannel * @param string $date
* @return bool * @return bool
*/ */
public function isNightlyUpdateChannel($updateChannel = null) { private function setNightlyBuildDate($date) {
if (!$updateChannel) { $nightlyBuildDateFile = ManiaControlDir . '/core/nightly_build.txt';
$updateChannel = $this->getCurrentUpdateChannelSetting(); $success = (bool)file_put_contents($nightlyBuildDateFile, $date);
} $this->currentBuildDate = $date;
return ($updateChannel === self::CHANNEL_NIGHTLY); return $success;
} }
/** /**
* Retrieve the Update Channel Setting * Handle ManiaControl PlayerJoined callback
* *
* @return string * @param Player $player
*/ */
private function getCurrentUpdateChannelSetting() { public function handlePlayerJoined(Player $player) {
$updateChannel = $this->maniaControl->settingManager->getSetting($this, self::SETTING_UPDATECHECK_CHANNEL); if (!$this->coreUpdateData) {
$updateChannel = strtolower($updateChannel); return;
if (!in_array($updateChannel, array(self::CHANNEL_RELEASE, self::CHANNEL_BETA, self::CHANNEL_NIGHTLY))) {
$updateChannel = self::CHANNEL_RELEASE;
} }
return $updateChannel; // Announce available update
if (!$this->maniaControl->authenticationManager->checkPermission($player, self::SETTING_PERMISSION_UPDATE)) {
return;
}
if ($this->isNightlyUpdateChannel()) {
$this->maniaControl->chat->sendSuccess('New Nightly Build (' . $this->coreUpdateData->releaseDate . ') available!', $player->login);
} else {
$this->maniaControl->chat->sendInformation('New ManiaControl Version ' . $this->coreUpdateData->version . ' available!', $player->login);
}
}
/**
* Handle Player Disconnect Callback
*
* @param Player $player
*/
public function handlePlayerDisconnect(Player $player) {
$this->checkAutoUpdate();
}
/**
* Handle //checkupdate command
*
* @param array $chatCallback
* @param Player $player
*/
public function handle_CheckUpdate(array $chatCallback, Player $player) {
if (!$this->maniaControl->authenticationManager->checkPermission($player, self::SETTING_PERMISSION_UPDATECHECK)) {
$this->maniaControl->authenticationManager->sendNotAllowed($player);
return;
}
$self = $this;
$this->checkCoreUpdateAsync(function (UpdateData $updateData = null) use (&$self, &$player) {
if (!$self->checkUpdateData($updateData)) {
$self->maniaControl->chat->sendInformation('No Update available!', $player->login);
return;
}
if (!$self->checkUpdateDataBuildVersion($updateData)) {
$self->maniaControl->chat->sendError("Please update Your Server to '{$updateData->minDedicatedBuild}' in order to receive further Updates!", $player->login);
return;
}
$isNightly = $self->isNightlyUpdateChannel();
if ($isNightly) {
$buildDate = $self->getNightlyBuildDate();
if ($buildDate) {
if ($updateData->isNewerThan($buildDate)) {
$self->maniaControl->chat->sendInformation("No new Build available! (Current Build: '{$buildDate}')", $player->login);
} else {
$self->maniaControl->chat->sendSuccess("New Nightly Build ({$updateData->releaseDate}) available! (Current Build: '{$buildDate}')", $player->login);
}
} else {
$self->maniaControl->chat->sendSuccess("New Nightly Build ('{$updateData->releaseDate}') available!", $player->login);
}
} else {
$self->maniaControl->chat->sendSuccess('Update for Version ' . $updateData->version . ' available!', $player->login);
}
});
}
/**
* Handle //coreupdate command
*
* @param array $chatCallback
* @param Player $player
*/
public function handle_CoreUpdate(array $chatCallback, Player $player) {
if (!$this->maniaControl->authenticationManager->checkPermission($player, self::SETTING_PERMISSION_UPDATE)) {
$this->maniaControl->authenticationManager->sendNotAllowed($player);
return;
}
$self = $this;
$this->checkCoreUpdateAsync(function (UpdateData $updateData = null) use (&$self, &$player) {
if (!$updateData) {
$self->maniaControl->chat->sendError('Update is currently not possible!', $player->login);
return;
}
if (!$self->checkUpdateDataBuildVersion($updateData)) {
$self->maniaControl->chat->sendError("The Next ManiaControl Update requires a newer Dedicated Server Version!", $player->login);
return;
}
$message = "Starting Update to Version v{$updateData->version}...";
$self->maniaControl->chat->sendInformation($message, $player->login);
$self->maniaControl->log($message);
$performBackup = $self->maniaControl->settingManager->getSetting($self, UpdateManager::SETTING_PERFORM_BACKUPS);
if ($performBackup && !BackupUtil::performFullBackup()) {
$message = 'Creating Backup failed!';
$self->maniaControl->chat->sendError($message, $player->login);
$self->maniaControl->log($message);
}
$self->performCoreUpdate($player);
});
} }
} }