From ba720f46bf22aaebce5b17113e70cfc28aca2046 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Steffen=20Schro=CC=88der?= Date: Fri, 2 May 2014 17:40:47 +0200 Subject: [PATCH] applied common formatting --- application/core/Bills/BillData.php | 14 +- application/core/Bills/BillManager.php | 6 +- application/core/Chat.php | 75 +- application/core/ColorUtil.php | 18 +- application/core/CommandLineHelper.php | 12 +- .../core/Configurators/ConfiguratorMenu.php | 6 +- application/core/Database/Database.php | 90 +- application/core/Database/MigrationHelper.php | 20 +- application/core/ErrorHandler.php | 180 ++-- .../core/Files/AsynchronousFileReader.php | 28 +- application/core/Files/BackupUtil.php | 81 +- application/core/Files/FileUtil.php | 66 +- application/core/Formatter.php | 36 +- application/core/ManiaControl.php | 424 ++++---- application/core/Plugins/Plugin.php | 32 +- .../core/Plugins/PluginInstallMenu.php | 44 +- application/core/Plugins/PluginManager.php | 431 ++++---- application/core/Plugins/PluginMenu.php | 125 +-- application/plugins/ChatMessagePlugin.php | 150 +-- application/plugins/Donations.php | 313 +++--- application/plugins/Karma.php | 936 +++++++++--------- application/plugins/WidgetPlugin.php | 138 +-- 22 files changed, 1606 insertions(+), 1619 deletions(-) diff --git a/application/core/Bills/BillData.php b/application/core/Bills/BillData.php index ff5090e5..d228b0a8 100644 --- a/application/core/Bills/BillData.php +++ b/application/core/Bills/BillData.php @@ -1,14 +1,15 @@ + * @copyright 2014 ManiaControl Team + * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 */ class BillData { /* @@ -23,10 +24,11 @@ class BillData { /** * Construct new BillData - * @param mixed $function + * + * @param mixed $function * @param Player $player - * @param int $amount - * @param bool $pay + * @param int $amount + * @param bool $pay * @param string $receiverLogin */ public function __construct($function, Player $player, $amount, $pay = false, $receiverLogin = null) { diff --git a/application/core/Bills/BillManager.php b/application/core/Bills/BillManager.php index 1708447a..532c6fbb 100644 --- a/application/core/Bills/BillManager.php +++ b/application/core/Bills/BillManager.php @@ -11,8 +11,8 @@ use Maniaplanet\DedicatedServer\Structures\Bill; /** * ManiaControl Bill-Manager * - * @author kremsy - * @copyright ManiaControl Copyright © 2014 ManiaControl Team + * @author ManiaControl Team + * @copyright 2014 ManiaControl Team * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 */ class BillManager implements CallbackListener { @@ -103,7 +103,7 @@ class BillManager implements CallbackListener { $billData = $this->openBills[$billId]; /** @var BillData $billData */ - switch($callback[1][1]) { + switch ($callback[1][1]) { case Bill::STATE_PAYED: if ($billData->pay) { call_user_func($billData->function, $billData, self::PAYED_FROM_SERVER); diff --git a/application/core/Chat.php b/application/core/Chat.php index f4303651..a5f5d998 100644 --- a/application/core/Chat.php +++ b/application/core/Chat.php @@ -2,15 +2,14 @@ namespace ManiaControl; -use Maniaplanet\DedicatedServer\Xmlrpc\Exception; use Maniaplanet\DedicatedServer\Xmlrpc\LoginUnknownException; /** * Chat Utility Class * - * @author steeffeen & kremsy - * @copyright ManiaControl Copyright © 2014 ManiaControl Team - * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 + * @author ManiaControl Team + * @copyright 2014 ManiaControl Team + * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 */ class Chat { /* @@ -44,21 +43,18 @@ class Chat { } /** - * Get prefix + * Send an information message to the given login * + * @param string $message + * @param string $login * @param string|bool $prefix - * @return string + * @return bool */ - private function getPrefix($prefix) { - if (is_string($prefix)) { - return $prefix; - } - if ($prefix === true) { - return $this->maniaControl->settingManager->getSetting($this, self::SETTING_PREFIX); - } - return ''; + public function sendInformation($message, $login = null, $prefix = true) { + $format = $this->maniaControl->settingManager->getSetting($this, self::SETTING_FORMAT_INFORMATION); + return $this->sendChat($format . $message, $login); } - + /** * Send a chat message to the given login * @@ -73,7 +69,7 @@ class Chat { } if (!$login) { - $prefix = $this->getPrefix($prefix); + $prefix = $this->getPrefix($prefix); $chatMessage = '$<$z$ff0' . str_replace(' ', '', $prefix) . $prefix . $message . '$>'; $this->maniaControl->client->chatSendServerMessage($chatMessage); } else { @@ -81,25 +77,28 @@ class Chat { if (is_object($login) && property_exists($login, 'login')) { $login = $login->login; } - try{ + try { $this->maniaControl->client->chatSendServerMessage($chatMessage, $login); - } catch(LoginUnknownException $e){ + } catch (LoginUnknownException $e) { } } return true; } /** - * Send an information message to the given login + * Get prefix * - * @param string $message - * @param string $login * @param string|bool $prefix - * @return bool + * @return string */ - public function sendInformation($message, $login = null, $prefix = true) { - $format = $this->maniaControl->settingManager->getSetting($this, self::SETTING_FORMAT_INFORMATION); - return $this->sendChat($format . $message, $login); + private function getPrefix($prefix) { + if (is_string($prefix)) { + return $prefix; + } + if ($prefix === true) { + return $this->maniaControl->settingManager->getSetting($this, self::SETTING_PREFIX); + } + return ''; } /** @@ -115,6 +114,19 @@ class Chat { return $this->sendChat($format . $message, $login); } + /** + * Send the Exception Information to the Chat + * + * @param \Exception $exception + * @param string $login + * @return bool + */ + public function sendException(\Exception $exception, $login = null) { + $message = "Exception occurred: '{$exception->getMessage()}' ({$exception->getCode()})"; + $this->maniaControl->errorHandler->triggerDebugNotice($message); + return $this->sendError($message, $login); + } + /** * Send an Error Message to the Chat * @@ -127,19 +139,6 @@ class Chat { $format = $this->maniaControl->settingManager->getSetting($this, self::SETTING_FORMAT_ERROR); return $this->sendChat($format . $message, $login); } - - /** - * Send the Exception Information to the Chat - * - * @param \Exception $exception - * @param string $login - * @return bool - */ - public function sendException(\Exception $exception, $login = null) { - $message = "Exception occurred: '{$exception->getMessage()}' ({$exception->getCode()})"; - $this->maniaControl->errorHandler->triggerDebugNotice($message); - return $this->sendError($message, $login); - } /** * Send an usage info message to the given login diff --git a/application/core/ColorUtil.php b/application/core/ColorUtil.php index 8e99dfcd..80bd8c1d 100644 --- a/application/core/ColorUtil.php +++ b/application/core/ColorUtil.php @@ -5,21 +5,21 @@ namespace ManiaControl; /** * Utility Class offering Methods to convert and use ManiaPlanet Colors * - * @author steeffeen - * @copyright ManiaControl Copyright © 2014 ManiaControl Team - * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 + * @author ManiaControl Team + * @copyright 2014 ManiaControl Team + * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 */ abstract class ColorUtil { /** * Convert the given float value to a color code from red to green * - * @param float $value + * @param float $value * @return string */ public static function floatToStatusColor($value) { $value = floatval($value); - $red = 1.; + $red = 1.; $green = 1.; if ($value < 0.5) { $green = $value * 2.; @@ -27,7 +27,7 @@ abstract class ColorUtil { if ($value > 0.5) { $red = 2. * (1. - $value); } - $red = ColorUtil::floatToCode($red); + $red = ColorUtil::floatToCode($red); $green = ColorUtil::floatToCode($green); return $red . $green . '0'; } @@ -35,7 +35,7 @@ abstract class ColorUtil { /** * Get hex color representation of the float * - * @param float $value + * @param float $value * @return string */ public static function floatToCode($value) { @@ -47,9 +47,9 @@ abstract class ColorUtil { $value = 1.; } $value *= 15.; - $value = (int) round($value); + $value = (int)round($value); if ($value < 10) { - return (string) $value; + return (string)$value; } $codes = array(10 => 'a', 11 => 'b', 12 => 'c', 13 => 'd', 14 => 'e', 15 => 'f'); return $codes[$value]; diff --git a/application/core/CommandLineHelper.php b/application/core/CommandLineHelper.php index 73c79700..0ad10113 100644 --- a/application/core/CommandLineHelper.php +++ b/application/core/CommandLineHelper.php @@ -4,22 +4,22 @@ namespace ManiaControl; /** * Command Line Helper Class - * - * @author steeffeen & kremsy - * @copyright ManiaControl Copyright © 2014 ManiaControl Team - * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 + * + * @author ManiaControl Team + * @copyright 2014 ManiaControl Team + * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 */ class CommandLineHelper { /** * Get the Command Line Parameter with the given Name - * + * * @param string $paramName * @return mixed */ public static function getParameter($paramName) { global $argv; - $paramName = (string) $paramName; + $paramName = (string)$paramName; foreach ($argv as $arg) { $parts = explode('=', $arg, 2); if (count($parts) < 2) { diff --git a/application/core/Configurators/ConfiguratorMenu.php b/application/core/Configurators/ConfiguratorMenu.php index 10dd093d..d5c9a228 100644 --- a/application/core/Configurators/ConfiguratorMenu.php +++ b/application/core/Configurators/ConfiguratorMenu.php @@ -8,9 +8,9 @@ use ManiaControl\Players\Player; /** * Interface for Configurator Menus * - * @author steeffeen & kremsy - * @copyright ManiaControl Copyright © 2014 ManiaControl Team - * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 + * @author ManiaControl Team + * @copyright 2014 ManiaControl Team + * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 */ interface ConfiguratorMenu { diff --git a/application/core/Database/Database.php b/application/core/Database/Database.php index c1d90b34..b8aafd97 100644 --- a/application/core/Database/Database.php +++ b/application/core/Database/Database.php @@ -8,9 +8,9 @@ use ManiaControl\ManiaControl; /** * Database Connection Class * - * @author steeffeen & kremsy - * @copyright ManiaControl Copyright © 2014 ManiaControl Team - * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 + * @author ManiaControl Team + * @copyright 2014 ManiaControl Team + * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 */ class Database implements TimerListener { /* @@ -18,7 +18,7 @@ class Database implements TimerListener { */ public $mysqli = null; public $migrationHelper = null; - + /* * Private Properties */ @@ -29,13 +29,13 @@ class Database implements TimerListener { */ public function __construct(ManiaControl $maniaControl) { $this->maniaControl = $maniaControl; - + // Get mysql server information $host = $this->maniaControl->config->database->xpath('host'); $port = $this->maniaControl->config->database->xpath('port'); $user = $this->maniaControl->config->database->xpath('user'); $pass = $this->maniaControl->config->database->xpath('pass'); - + if (!$host) { trigger_error("Invalid database configuration (host).", E_USER_ERROR); } @@ -48,52 +48,32 @@ class Database implements TimerListener { if (!$pass) { trigger_error("Invalid database configuration (pass).", E_USER_ERROR); } - - $host = (string) $host[0]; - $port = (int) $port[0]; - $user = (string) $user[0]; - $pass = (string) $pass[0]; - + + $host = (string)$host[0]; + $port = (int)$port[0]; + $user = (string)$user[0]; + $pass = (string)$pass[0]; + // Enable mysqli Reconnect ini_set('mysqli.reconnect', 'on'); - + // Open database connection $this->mysqli = @new \mysqli($host, $user, $pass, null, $port); if ($this->mysqli->connect_error) { trigger_error($this->mysqli->connect_error, E_USER_ERROR); } $this->mysqli->set_charset("utf8"); - + $this->initDatabase(); $this->optimizeTables(); - + // Register Method which checks the Database Connection every 5 seconds $this->maniaControl->timerManager->registerTimerListening($this, 'checkConnection', 5000); - + // Create migration helper $this->migrationHelper = new MigrationHelper($maniaControl); } - /** - * Check if Connection still exists every 5 seconds - * - * @param $time - */ - public function checkConnection($time) { - if (!$this->mysqli->ping()) { - $this->maniaControl->quit("The MySQL server has gone away"); - } - } - - /** - * Destruct database connection - */ - public function __destruct() { - if ($this->mysqli) { - $this->mysqli->close(); - } - } - /** * Connect to the defined database (create it if needed) * @@ -105,14 +85,16 @@ class Database implements TimerListener { trigger_error("Invalid database configuration (database).", E_USER_ERROR); return false; } - $dbName = (string) $dbName[0]; - + $dbName = (string)$dbName[0]; + // Try to connect $result = $this->mysqli->select_db($dbName); - if ($result) return true; - + if ($result) { + return true; + } + // Create database - $databaseQuery = "CREATE DATABASE ?;"; + $databaseQuery = "CREATE DATABASE ?;"; $databaseStatement = $this->mysqli->prepare($databaseQuery); if ($this->mysqli->error) { trigger_error($this->mysqli->error, E_USER_ERROR); @@ -125,7 +107,7 @@ class Database implements TimerListener { return false; } $databaseStatement->close(); - + // Connect to new database $this->mysqli->select_db($dbName); if ($this->mysqli->error) { @@ -142,7 +124,7 @@ class Database implements TimerListener { */ private function optimizeTables() { $showQuery = "SHOW TABLES;"; - $result = $this->mysqli->query($showQuery); + $result = $this->mysqli->query($showQuery); if ($this->mysqli->error) { trigger_error($this->mysqli->error); return false; @@ -153,7 +135,7 @@ class Database implements TimerListener { return true; } $optimizeQuery = "OPTIMIZE TABLE "; - $index = 0; + $index = 0; while ($row = $result->fetch_row()) { $tableName = $row[0]; $optimizeQuery .= "`{$tableName}`"; @@ -171,4 +153,24 @@ class Database implements TimerListener { } return true; } + + /** + * Check if Connection still exists every 5 seconds + * + * @param $time + */ + public function checkConnection($time) { + if (!$this->mysqli->ping()) { + $this->maniaControl->quit("The MySQL server has gone away"); + } + } + + /** + * Destruct database connection + */ + public function __destruct() { + if ($this->mysqli) { + $this->mysqli->close(); + } + } } diff --git a/application/core/Database/MigrationHelper.php b/application/core/Database/MigrationHelper.php index fcc074a9..a6025bdc 100644 --- a/application/core/Database/MigrationHelper.php +++ b/application/core/Database/MigrationHelper.php @@ -1,16 +1,16 @@ + * @copyright 2014 ManiaControl Team + * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 */ class MigrationHelper { /* @@ -20,7 +20,7 @@ class MigrationHelper { /** * Construct Migration Helper - * + * * @param ManiaControl $maniaControl */ public function __construct(ManiaControl $maniaControl) { @@ -37,10 +37,10 @@ class MigrationHelper { public function transferSettings($sourceClass, $targetClass) { $sourceClass = $this->getClass($sourceClass); $targetClass = $this->getClass($targetClass); - + $mysqli = $this->maniaControl->database->mysqli; - - $query = "INSERT INTO `" . SettingManager::TABLE_SETTINGS . "` (`class`, `setting`, `type`, `value`, `default`) + + $query = "INSERT INTO `" . SettingManager::TABLE_SETTINGS . "` (`class`, `setting`, `type`, `value`, `default`) SELECT ?, `setting`, `type`, `value`, `default` FROM `" . SettingManager::TABLE_SETTINGS . "` WHERE `class` = ?;"; $statement = $mysqli->prepare($query); if ($mysqli->error) { @@ -68,6 +68,6 @@ class MigrationHelper { if (is_object($class)) { return get_class($class); } - return (string) $class; + return (string)$class; } } diff --git a/application/core/ErrorHandler.php b/application/core/ErrorHandler.php index 8ddcd4ad..317d196b 100644 --- a/application/core/ErrorHandler.php +++ b/application/core/ErrorHandler.php @@ -7,18 +7,18 @@ use ManiaControl\Update\UpdateManager; /** * Error and Exception Manager Class - * - * @author steeffeen & kremsy - * @copyright ManiaControl Copyright © 2014 ManiaControl Team - * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 + * + * @author ManiaControl Team + * @copyright 2014 ManiaControl Team + * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 */ class ErrorHandler { /* * Constants */ - const MC_DEBUG_NOTICE = "ManiaControl.DebugNotice"; + const MC_DEBUG_NOTICE = "ManiaControl.DebugNotice"; const SETTING_RESTART_ON_EXCEPTION = 'Automatically restart on Exceptions'; - + /* * Private Properties */ @@ -43,55 +43,52 @@ class ErrorHandler { /** * ManiaControl ExceptionHandler - * + * * @param \Exception $ex - * @param bool $shutdown + * @param bool $shutdown */ public function exceptionHandler(\Exception $ex, $shutdown = true) { // Log exception - $message = "[ManiaControl EXCEPTION]: {$ex->getMessage()}"; + $message = "[ManiaControl EXCEPTION]: {$ex->getMessage()}"; $traceMessage = 'Class: ' . get_class($ex) . PHP_EOL; $traceMessage .= 'Trace:' . PHP_EOL . $ex->getTraceAsString(); logMessage($message . PHP_EOL . $traceMessage); - + if ($this->reportErrors) { - $error = array(); - $error["Type"] = "Exception"; - $error["Message"] = $message; - $error["Backtrace"] = $traceMessage; + $error = array(); + $error["Type"] = "Exception"; + $error["Message"] = $message; + $error["Backtrace"] = $traceMessage; $error['OperatingSystem'] = php_uname(); - $error['PHPVersion'] = phpversion(); - + $error['PHPVersion'] = phpversion(); + if ($this->maniaControl->server) { $error['ServerLogin'] = $this->maniaControl->server->login; - } - else { + } else { $error['ServerLogin'] = ''; } - + if ($this->maniaControl->settingManager && $this->maniaControl->updateManager) { - $error['UpdateChannel'] = $this->maniaControl->settingManager->getSetting($this->maniaControl->updateManager, UpdateManager::SETTING_UPDATECHECK_CHANNEL); + $error['UpdateChannel'] = $this->maniaControl->settingManager->getSetting($this->maniaControl->updateManager, UpdateManager::SETTING_UPDATECHECK_CHANNEL); $error['ManiaControlVersion'] = $this->maniaControl->updateManager->getNightlyBuildDate(); - } - else { - $error['UpdateChannel'] = ''; + } else { + $error['UpdateChannel'] = ''; $error['ManiaControlVersion'] = ManiaControl::VERSION; } - + $json = json_encode($error); $info = base64_encode($json); - - $url = ManiaControl::URL_WEBSERVICE . "errorreport?error=" . urlencode($info); + + $url = ManiaControl::URL_WEBSERVICE . "errorreport?error=" . urlencode($info); $success = FileUtil::loadFile($url); - + if (!json_decode($success)) { logMessage("Exception-Report failed!"); - } - else { + } else { logMessage("Exception successfully reported!"); } } - + if ($shutdown) { if ($this->shouldRestart()) { $this->maniaControl->restart(); @@ -100,9 +97,31 @@ class ErrorHandler { } } + /** + * Test if ManiaControl should restart automatically + * + * @return bool + */ + private function shouldRestart() { + if (!$this->maniaControl || !$this->maniaControl->settingManager) { + return false; + } + $setting = $this->maniaControl->settingManager->getSetting($this, self::SETTING_RESTART_ON_EXCEPTION, true); + return $setting; + } + + /** + * Triggers a Debug Notice to the ManiaControl Website + * + * @param $message + */ + public function triggerDebugNotice($message) { + $this->errorHandler(self::MC_DEBUG_NOTICE, $message); + } + /** * Error Handler - * + * * @param $errorNumber * @param $errorString * @param $errorFile @@ -114,52 +133,49 @@ class ErrorHandler { // Error suppressed return false; } - + $userError = $this->isUserErrorNumber($errorNumber); - + // Log error - $errorTag = $this->getErrorTag($errorNumber); - $message = $errorTag . ': ' . $errorString; - $fileLine = $errorFile . ': ' . $errorLine; + $errorTag = $this->getErrorTag($errorNumber); + $message = $errorTag . ': ' . $errorString; + $fileLine = $errorFile . ': ' . $errorLine; $traceMessage = $this->parseBackTrace(debug_backtrace()); - $logMessage = $message . PHP_EOL . ($userError ? $fileLine : $traceMessage); + $logMessage = $message . PHP_EOL . ($userError ? $fileLine : $traceMessage); logMessage($logMessage); - + if ($this->reportErrors && !$userError) { - $error = array(); - $error["Type"] = "Error"; - $error["Message"] = $message; - $error["FileLine"] = $fileLine; - $error["Backtrace"] = $traceMessage; + $error = array(); + $error["Type"] = "Error"; + $error["Message"] = $message; + $error["FileLine"] = $fileLine; + $error["Backtrace"] = $traceMessage; $error['OperatingSystem'] = php_uname(); - $error['PHPVersion'] = phpversion(); - + $error['PHPVersion'] = phpversion(); + if ($this->maniaControl->server) { $error['ServerLogin'] = $this->maniaControl->server->login; - } - else { + } else { $error['ServerLogin'] = ''; } - + if ($this->maniaControl->settingManager && $this->maniaControl->updateManager) { - $error['UpdateChannel'] = $this->maniaControl->settingManager->getSetting($this->maniaControl->updateManager, UpdateManager::SETTING_UPDATECHECK_CHANNEL); + $error['UpdateChannel'] = $this->maniaControl->settingManager->getSetting($this->maniaControl->updateManager, UpdateManager::SETTING_UPDATECHECK_CHANNEL); $error['ManiaControlVersion'] = ManiaControl::VERSION . '#' . $this->maniaControl->updateManager->getNightlyBuildDate(); - } - else { - $error['UpdateChannel'] = ''; + } else { + $error['UpdateChannel'] = ''; $error['ManiaControlVersion'] = ManiaControl::VERSION; } - + $json = json_encode($error); $info = base64_encode($json); - - $url = ManiaControl::URL_WEBSERVICE . "errorreport?error=" . urlencode($info); + + $url = ManiaControl::URL_WEBSERVICE . "errorreport?error=" . urlencode($info); $success = FileUtil::loadFile($url); - + if (!json_decode($success)) { logMessage("Error-Report failed!"); - } - else { + } else { logMessage("Error successfully reported!"); } } @@ -172,7 +188,7 @@ class ErrorHandler { /** * Check if the given Error Number is a User Error - * + * * @param int $errorNumber * @return bool */ @@ -180,18 +196,9 @@ class ErrorHandler { return ($errorNumber === E_USER_ERROR || $errorNumber === E_USER_WARNING || $errorNumber === E_USER_NOTICE || $errorNumber === E_USER_DEPRECATED); } - /** - * Triggers a Debug Notice to the ManiaControl Website - * - * @param $message - */ - public function triggerDebugNotice($message) { - $this->errorHandler(self::MC_DEBUG_NOTICE, $message); - } - /** * Get the Prefix for the given Error Level - * + * * @param int $errorLevel * @return string */ @@ -229,36 +236,13 @@ class ErrorHandler { return "[PHP {$errorLevel}]"; } - /** - * Test if ManiaControl should stop its Execution - * - * @param int $errorNumber - * @return bool - */ - private function shouldStopExecution($errorNumber) { - return ($errorNumber === E_ERROR || $errorNumber === E_USER_ERROR || $errorNumber === E_FATAL); - } - - /** - * Test if ManiaControl should restart automatically - * - * @return bool - */ - private function shouldRestart() { - if (!$this->maniaControl || !$this->maniaControl->settingManager) { - return false; - } - $setting = $this->maniaControl->settingManager->getSetting($this, self::SETTING_RESTART_ON_EXCEPTION, true); - return $setting; - } - /** * Parse the Debug Backtrace into a String for the Error Report * return string */ private function parseBackTrace(array $backtrace) { $traceString = 'Trace:'; - $stepCount = 0; + $stepCount = 0; foreach ($backtrace as $traceStep) { $traceString .= PHP_EOL . '#' . $stepCount . ': '; if (isset($traceStep['class'])) { @@ -282,4 +266,14 @@ class ErrorHandler { } return $traceString; } + + /** + * Test if ManiaControl should stop its Execution + * + * @param int $errorNumber + * @return bool + */ + private function shouldStopExecution($errorNumber) { + return ($errorNumber === E_ERROR || $errorNumber === E_USER_ERROR || $errorNumber === E_FATAL); + } } \ No newline at end of file diff --git a/application/core/Files/AsynchronousFileReader.php b/application/core/Files/AsynchronousFileReader.php index bc3c73f4..422832da 100644 --- a/application/core/Files/AsynchronousFileReader.php +++ b/application/core/Files/AsynchronousFileReader.php @@ -11,9 +11,9 @@ use ManiaControl\ManiaControl; /** * Asynchronous File Reader * - * @author kremsy - * @copyright ManiaControl Copyright © 2014 ManiaControl Team - * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 + * @author ManiaControl Team + * @copyright 2014 ManiaControl Team + * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 */ class AsynchronousFileReader { /* @@ -35,13 +35,13 @@ class AsynchronousFileReader { * Appends the Data */ public function appendData() { - foreach($this->requests as $key => $request) { + foreach ($this->requests as $key => $request) { /** @var Request $request */ try { if ($request->socketPerform()) { $request->socketSelect(); } - } catch(Exception $e) { + } catch (Exception $e) { if ($e->getMessage() == "Cannot perform if there are no requests in queue.") { unset($this->requests[$key]); } else { @@ -54,10 +54,10 @@ class AsynchronousFileReader { /** * Load a remote file * - * @param string $url - * @param callable $function - * @param string $contentType - * @param int $keepAlive + * @param string $url + * @param callable $function + * @param string $contentType + * @param int $keepAlive * @return bool */ public function loadFile($url, $function, $contentType = 'UTF-8', $keepAlive = 0) { @@ -119,11 +119,11 @@ class AsynchronousFileReader { /** * Send Data via POST Method * - * @param string $url - * @param callable $function - * @param string $content - * @param bool $compression - * @param string $contentType + * @param string $url + * @param callable $function + * @param string $content + * @param bool $compression + * @param string $contentType * @return bool */ public function postData($url, $function, $content, $compression = false, $contentType = 'text/xml; charset=UTF-8') { diff --git a/application/core/Files/BackupUtil.php b/application/core/Files/BackupUtil.php index f4f2ec4a..04e9d2be 100644 --- a/application/core/Files/BackupUtil.php +++ b/application/core/Files/BackupUtil.php @@ -1,14 +1,15 @@ + * @copyright 2014 ManiaControl Team + * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 */ abstract class BackupUtil { /* @@ -18,53 +19,30 @@ abstract class BackupUtil { /** * Perform a Full Backup of ManiaControl - * + * * @return bool */ public static function performFullBackup() { - $backupFolder = self::getBackupFolder(); + $backupFolder = self::getBackupFolder(); $backupFileName = $backupFolder . 'backup_' . ManiaControl::VERSION . '_' . date('y-m-d') . '_' . time() . '.zip'; - $backupZip = new \ZipArchive(); - if ($backupZip->open($backupFileName, \ZipArchive::CREATE) !== TRUE) { + $backupZip = new \ZipArchive(); + if ($backupZip->open($backupFileName, \ZipArchive::CREATE) !== true) { trigger_error("Couldn't create Backup Zip!"); return false; } - $excludes = array('.', '..', 'backup', 'logs', 'ManiaControl.log'); - $pathInfo = pathInfo(ManiaControlDir); + $excludes = array('.', '..', 'backup', 'logs', 'ManiaControl.log'); + $pathInfo = pathInfo(ManiaControlDir); $parentPath = $pathInfo['dirname'] . '/'; - $dirName = $pathInfo['basename']; + $dirName = $pathInfo['basename']; $backupZip->addEmptyDir($dirName); self::zipDirectory($backupZip, ManiaControlDir, strlen($parentPath), $excludes); $backupZip->close(); return true; } - /** - * Perform a Backup of the Plugins - * - * @return bool - */ - public static function performPluginsBackup() { - $backupFolder = self::getBackupFolder(); - $backupFileName = $backupFolder . 'backup_plugins_' . date('y-m-d') . '_' . time() . '.zip'; - $backupZip = new \ZipArchive(); - if ($backupZip->open($backupFileName, \ZipArchive::CREATE) !== TRUE) { - trigger_error("Couldn't create Backup Zip!"); - return false; - } - $excludes = array('.', '..'); - $pathInfo = pathInfo(ManiaControlDir . '/plugins'); - $parentPath = $pathInfo['dirname'] . '/'; - $dirName = $pathInfo['basename']; - $backupZip->addEmptyDir($dirName); - self::zipDirectory($backupZip, ManiaControlDir . '/plugins', strlen($parentPath), $excludes); - $backupZip->close(); - return true; - } - /** * Get the Backup Folder Path and create it if necessary - * + * * @return string */ private static function getBackupFolder() { @@ -77,11 +55,11 @@ abstract class BackupUtil { /** * Add a complete Directory to the ZipArchive - * + * * @param \ZipArchive $zipArchive - * @param string $folderName - * @param int $prefixLength - * @param array $excludes + * @param string $folderName + * @param int $prefixLength + * @param array $excludes * @return bool */ private static function zipDirectory(\ZipArchive &$zipArchive, $folderName, $prefixLength, array $excludes = array()) { @@ -94,7 +72,7 @@ abstract class BackupUtil { if (in_array($file, $excludes)) { continue; } - $filePath = $folderName . '/' . $file; + $filePath = $folderName . '/' . $file; $localPath = substr($filePath, $prefixLength); if (is_file($filePath)) { $zipArchive->addFile($filePath, $localPath); @@ -109,4 +87,27 @@ abstract class BackupUtil { closedir($folderHandle); return true; } + + /** + * Perform a Backup of the Plugins + * + * @return bool + */ + public static function performPluginsBackup() { + $backupFolder = self::getBackupFolder(); + $backupFileName = $backupFolder . 'backup_plugins_' . date('y-m-d') . '_' . time() . '.zip'; + $backupZip = new \ZipArchive(); + if ($backupZip->open($backupFileName, \ZipArchive::CREATE) !== true) { + trigger_error("Couldn't create Backup Zip!"); + return false; + } + $excludes = array('.', '..'); + $pathInfo = pathInfo(ManiaControlDir . '/plugins'); + $parentPath = $pathInfo['dirname'] . '/'; + $dirName = $pathInfo['basename']; + $backupZip->addEmptyDir($dirName); + self::zipDirectory($backupZip, ManiaControlDir . '/plugins', strlen($parentPath), $excludes); + $backupZip->close(); + return true; + } } diff --git a/application/core/Files/FileUtil.php b/application/core/Files/FileUtil.php index 2b98458d..9e898841 100644 --- a/application/core/Files/FileUtil.php +++ b/application/core/Files/FileUtil.php @@ -2,15 +2,15 @@ namespace ManiaControl\Files; -use ManiaControl\ManiaControl; use ManiaControl\Formatter; +use ManiaControl\ManiaControl; /** * Files Utility Class - * - * @author steeffeen & kremsy - * @copyright ManiaControl Copyright © 2014 ManiaControl Team - * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 + * + * @author ManiaControl Team + * @copyright 2014 ManiaControl Team + * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 */ abstract class FileUtil { /* @@ -20,7 +20,7 @@ abstract class FileUtil { /** * Load a remote file - * + * * @param string $url * @param string $contentType * @return string || null @@ -29,48 +29,48 @@ abstract class FileUtil { if (!$url) { return null; } - $urlData = parse_url($url); - $port = (isset($urlData['port']) ? $urlData['port'] : 80); + $urlData = parse_url($url); + $port = (isset($urlData['port']) ? $urlData['port'] : 80); $urlQuery = isset($urlData['query']) ? "?" . $urlData['query'] : ""; - + $fsock = fsockopen($urlData['host'], $port); stream_set_timeout($fsock, 3); - + $query = 'GET ' . $urlData['path'] . $urlQuery . ' HTTP/1.0' . PHP_EOL; $query .= 'Host: ' . $urlData['host'] . PHP_EOL; $query .= 'Content-Type: ' . $contentType . PHP_EOL; $query .= 'User-Agent: ManiaControl v' . ManiaControl::VERSION . PHP_EOL; $query .= PHP_EOL; - + fwrite($fsock, $query); - + $buffer = ''; - $info = array('timed_out' => false); + $info = array('timed_out' => false); while (!feof($fsock) && !$info['timed_out']) { $buffer .= fread($fsock, 1024); $info = stream_get_meta_data($fsock); } fclose($fsock); - + if ($info['timed_out'] || !$buffer) { return null; } if (substr($buffer, 9, 3) != "200") { return null; } - + $result = explode("\r\n\r\n", $buffer, 2); - + if (count($result) < 2) { return null; } - + return $result[1]; } /** * Load config xml-file - * + * * @param string $fileName * @return \SimpleXMLElement */ @@ -89,7 +89,7 @@ abstract class FileUtil { /** * Return file name cleared from special characters - * + * * @param string $fileName * @return string */ @@ -100,9 +100,19 @@ abstract class FileUtil { return $fileName; } + /** + * Delete the Temporary Folder if it's empty + * + * @return bool + */ + public static function removeTempFolder() { + $tempFolder = self::getTempFolder(false); + return @rmdir($tempFolder); + } + /** * Get the Temporary Folder and create it if necessary - * + * * @param bool $createIfNecessary * @return string */ @@ -114,19 +124,9 @@ abstract class FileUtil { return $tempFolder; } - /** - * Delete the Temporary Folder if it's empty - * - * @return bool - */ - public static function removeTempFolder() { - $tempFolder = self::getTempFolder(false); - return @rmdir($tempFolder); - } - /** * Check if ManiaControl has sufficient Access to write to Files in the given Directories - * + * * @param mixed $directories * @return bool */ @@ -134,7 +134,7 @@ abstract class FileUtil { if (!is_array($directories)) { $directories = array($directories); } - + foreach ($directories as $directory) { $dir = new \RecursiveDirectoryIterator(ManiaControlDir . $directory); foreach (new \RecursiveIteratorIterator($dir) as $fileName => $file) { @@ -148,7 +148,7 @@ abstract class FileUtil { } } } - + return true; } } diff --git a/application/core/Formatter.php b/application/core/Formatter.php index 7c0d1818..9dfde90a 100644 --- a/application/core/Formatter.php +++ b/application/core/Formatter.php @@ -5,9 +5,9 @@ namespace ManiaControl; /** * Class offering Methods to format Texts and Values * - * @author steeffeen & kremsy - * @copyright ManiaControl Copyright © 2014 ManiaControl Team - * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 + * @author ManiaControl Team + * @copyright 2014 ManiaControl Team + * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 */ abstract class Formatter { @@ -68,7 +68,7 @@ abstract class Formatter { $a = array(12 * 30 * 24 * 60 * 60 => 'year', 30 * 24 * 60 * 60 => 'month', 24 * 60 * 60 => 'day', 60 * 60 => 'hour', 60 => 'minute', 1 => 'second'); - foreach($a as $secs => $str) { + foreach ($a as $secs => $str) { $d = $etime / $secs; if ($d >= 1) { $r = round($d); @@ -111,6 +111,16 @@ abstract class Formatter { return $string; } + /** + * Remove Links from the String + * + * @param string $string + * @return string + */ + public static function stripLinks($string) { + return preg_replace('/(? 'AFG', 'Albania' => 'ALB', 'Algeria' => 'ALG', 'Andorra' => 'AND', 'Angola' => 'ANG', 'Argentina' => 'ARG', 'Armenia' => 'ARM', 'Aruba' => 'ARU', 'Australia' => 'AUS', 'Austria' => 'AUT', 'Azerbaijan' => 'AZE', 'Bahamas' => 'BAH', 'Bahrain' => 'BRN', 'Bangladesh' => 'BAN', 'Barbados' => 'BAR', 'Belarus' => 'BLR', 'Belgium' => 'BEL', 'Belize' => 'BIZ', 'Benin' => 'BEN', 'Bermuda' => 'BER', 'Bhutan' => 'BHU', 'Bolivia' => 'BOL', 'Bosnia&Herzegovina' => 'BIH', 'Botswana' => 'BOT', 'Brazil' => 'BRA', 'Brunei' => 'BRU', 'Bulgaria' => 'BUL', 'Burkina Faso' => 'BUR', 'Burundi' => 'BDI', 'Cambodia' => 'CAM', 'Cameroon' => 'CAR', // actually CMR - 'Canada' => 'CAN', 'Cape Verde' => 'CPV', 'Central African Republic' => 'CAF', 'Chad' => 'CHA', 'Chile' => 'CHI', 'China' => 'CHN', 'Chinese Taipei' => 'TPE', 'Colombia' => 'COL', 'Congo' => 'CGO', 'Costa Rica' => 'CRC', 'Croatia' => 'CRO', 'Cuba' => 'CUB', 'Cyprus' => 'CYP', 'Czech Republic' => 'CZE', 'Czech republic' => 'CZE', 'DR Congo' => 'COD', 'Denmark' => 'DEN', 'Djibouti' => 'DJI', 'Dominica' => 'DMA', 'Dominican Republic' => 'DOM', 'Ecuador' => 'ECU', 'Egypt' => 'EGY', 'El Salvador' => 'ESA', 'Eritrea' => 'ERI', 'Estonia' => 'EST', 'Ethiopia' => 'ETH', 'Fiji' => 'FIJ', 'Finland' => 'FIN', 'France' => 'FRA', 'Gabon' => 'GAB', 'Gambia' => 'GAM', 'Georgia' => 'GEO', 'Germany' => 'GER', 'Ghana' => 'GHA', 'Greece' => 'GRE', 'Grenada' => 'GRN', 'Guam' => 'GUM', 'Guatemala' => 'GUA', 'Guinea' => 'GUI', 'Guinea-Bissau' => 'GBS', 'Guyana' => 'GUY', 'Haiti' => 'HAI', 'Honduras' => 'HON', 'Hong Kong' => 'HKG', 'Hungary' => 'HUN', 'Iceland' => 'ISL', 'India' => 'IND', 'Indonesia' => 'INA', 'Iran' => 'IRI', 'Iraq' => 'IRQ', 'Ireland' => 'IRL', 'Israel' => 'ISR', 'Italy' => 'ITA', 'Ivory Coast' => 'CIV', 'Jamaica' => 'JAM', 'Japan' => 'JPN', 'Jordan' => 'JOR', 'Kazakhstan' => 'KAZ', 'Kenya' => 'KEN', 'Kiribati' => 'KIR', 'Korea' => 'KOR', 'Kuwait' => 'KUW', 'Kyrgyzstan' => 'KGZ', 'Laos' => 'LAO', 'Latvia' => 'LAT', 'Lebanon' => 'LIB', 'Lesotho' => 'LES', 'Liberia' => 'LBR', 'Libya' => 'LBA', 'Liechtenstein' => 'LIE', 'Lithuania' => 'LTU', 'Luxembourg' => 'LUX', 'Macedonia' => 'MKD', 'Malawi' => 'MAW', 'Malaysia' => 'MAS', 'Mali' => 'MLI', 'Malta' => 'MLT', 'Mauritania' => 'MTN', 'Mauritius' => 'MRI', 'Mexico' => 'MEX', 'Moldova' => 'MDA', 'Monaco' => 'MON', 'Mongolia' => 'MGL', 'Montenegro' => 'MNE', 'Morocco' => 'MAR', 'Mozambique' => 'MOZ', 'Myanmar' => 'MYA', 'Namibia' => 'NAM', 'Nauru' => 'NRU', 'Nepal' => 'NEP', 'Netherlands' => 'NED', 'New Zealand' => 'NZL', 'Nicaragua' => 'NCA', 'Niger' => 'NIG', 'Nigeria' => 'NGR', 'Norway' => 'NOR', 'Oman' => 'OMA', 'Other Countries' => 'OTH', 'Pakistan' => 'PAK', 'Palau' => 'PLW', 'Palestine' => 'PLE', 'Panama' => 'PAN', 'Paraguay' => 'PAR', 'Peru' => 'PER', 'Philippines' => 'PHI', 'Poland' => 'POL', 'Portugal' => 'POR', 'Puerto Rico' => 'PUR', 'Qatar' => 'QAT', 'Romania' => 'ROM', // actually ROU - 'Russia' => 'RUS', 'Rwanda' => 'RWA', 'Samoa' => 'SAM', 'San Marino' => 'SMR', 'Saudi Arabia' => 'KSA', 'Senegal' => 'SEN', 'Serbia' => 'SCG', // actually SRB - 'Sierra Leone' => 'SLE', 'Singapore' => 'SIN', 'Slovakia' => 'SVK', 'Slovenia' => 'SLO', 'Somalia' => 'SOM', 'South Africa' => 'RSA', 'Spain' => 'ESP', 'Sri Lanka' => 'SRI', 'Sudan' => 'SUD', 'Suriname' => 'SUR', 'Swaziland' => 'SWZ', 'Sweden' => 'SWE', 'Switzerland' => 'SUI', 'Syria' => 'SYR', 'Taiwan' => 'TWN', 'Tajikistan' => 'TJK', 'Tanzania' => 'TAN', 'Thailand' => 'THA', 'Togo' => 'TOG', 'Tonga' => 'TGA', 'Trinidad and Tobago' => 'TRI', 'Tunisia' => 'TUN', 'Turkey' => 'TUR', 'Turkmenistan' => 'TKM', 'Tuvalu' => 'TUV', 'Uganda' => 'UGA', 'Ukraine' => 'UKR', 'United Arab Emirates' => 'UAE', 'United Kingdom' => 'GBR', 'United States of America' => 'USA', 'Uruguay' => 'URU', 'Uzbekistan' => 'UZB', 'Vanuatu' => 'VAN', 'Venezuela' => 'VEN', 'Vietnam' => 'VIE', 'Yemen' => 'YEM', 'Zambia' => 'ZAM', 'Zimbabwe' => 'ZIM'); + $nations = array('Afghanistan' => 'AFG', 'Albania' => 'ALB', 'Algeria' => 'ALG', 'Andorra' => 'AND', 'Angola' => 'ANG', 'Argentina' => 'ARG', 'Armenia' => 'ARM', 'Aruba' => 'ARU', 'Australia' => 'AUS', 'Austria' => 'AUT', 'Azerbaijan' => 'AZE', 'Bahamas' => 'BAH', 'Bahrain' => 'BRN', 'Bangladesh' => 'BAN', 'Barbados' => 'BAR', 'Belarus' => 'BLR', 'Belgium' => 'BEL', 'Belize' => 'BIZ', 'Benin' => 'BEN', 'Bermuda' => 'BER', 'Bhutan' => 'BHU', 'Bolivia' => 'BOL', 'Bosnia&Herzegovina' => 'BIH', 'Botswana' => 'BOT', 'Brazil' => 'BRA', 'Brunei' => 'BRU', 'Bulgaria' => 'BUL', 'Burkina Faso' => 'BUR', 'Burundi' => 'BDI', 'Cambodia' => 'CAM', 'Cameroon' => 'CAR', // actually CMR + 'Canada' => 'CAN', 'Cape Verde' => 'CPV', 'Central African Republic' => 'CAF', 'Chad' => 'CHA', 'Chile' => 'CHI', 'China' => 'CHN', 'Chinese Taipei' => 'TPE', 'Colombia' => 'COL', 'Congo' => 'CGO', 'Costa Rica' => 'CRC', 'Croatia' => 'CRO', 'Cuba' => 'CUB', 'Cyprus' => 'CYP', 'Czech Republic' => 'CZE', 'Czech republic' => 'CZE', 'DR Congo' => 'COD', 'Denmark' => 'DEN', 'Djibouti' => 'DJI', 'Dominica' => 'DMA', 'Dominican Republic' => 'DOM', 'Ecuador' => 'ECU', 'Egypt' => 'EGY', 'El Salvador' => 'ESA', 'Eritrea' => 'ERI', 'Estonia' => 'EST', 'Ethiopia' => 'ETH', 'Fiji' => 'FIJ', 'Finland' => 'FIN', 'France' => 'FRA', 'Gabon' => 'GAB', 'Gambia' => 'GAM', 'Georgia' => 'GEO', 'Germany' => 'GER', 'Ghana' => 'GHA', 'Greece' => 'GRE', 'Grenada' => 'GRN', 'Guam' => 'GUM', 'Guatemala' => 'GUA', 'Guinea' => 'GUI', 'Guinea-Bissau' => 'GBS', 'Guyana' => 'GUY', 'Haiti' => 'HAI', 'Honduras' => 'HON', 'Hong Kong' => 'HKG', 'Hungary' => 'HUN', 'Iceland' => 'ISL', 'India' => 'IND', 'Indonesia' => 'INA', 'Iran' => 'IRI', 'Iraq' => 'IRQ', 'Ireland' => 'IRL', 'Israel' => 'ISR', 'Italy' => 'ITA', 'Ivory Coast' => 'CIV', 'Jamaica' => 'JAM', 'Japan' => 'JPN', 'Jordan' => 'JOR', 'Kazakhstan' => 'KAZ', 'Kenya' => 'KEN', 'Kiribati' => 'KIR', 'Korea' => 'KOR', 'Kuwait' => 'KUW', 'Kyrgyzstan' => 'KGZ', 'Laos' => 'LAO', 'Latvia' => 'LAT', 'Lebanon' => 'LIB', 'Lesotho' => 'LES', 'Liberia' => 'LBR', 'Libya' => 'LBA', 'Liechtenstein' => 'LIE', 'Lithuania' => 'LTU', 'Luxembourg' => 'LUX', 'Macedonia' => 'MKD', 'Malawi' => 'MAW', 'Malaysia' => 'MAS', 'Mali' => 'MLI', 'Malta' => 'MLT', 'Mauritania' => 'MTN', 'Mauritius' => 'MRI', 'Mexico' => 'MEX', 'Moldova' => 'MDA', 'Monaco' => 'MON', 'Mongolia' => 'MGL', 'Montenegro' => 'MNE', 'Morocco' => 'MAR', 'Mozambique' => 'MOZ', 'Myanmar' => 'MYA', 'Namibia' => 'NAM', 'Nauru' => 'NRU', 'Nepal' => 'NEP', 'Netherlands' => 'NED', 'New Zealand' => 'NZL', 'Nicaragua' => 'NCA', 'Niger' => 'NIG', 'Nigeria' => 'NGR', 'Norway' => 'NOR', 'Oman' => 'OMA', 'Other Countries' => 'OTH', 'Pakistan' => 'PAK', 'Palau' => 'PLW', 'Palestine' => 'PLE', 'Panama' => 'PAN', 'Paraguay' => 'PAR', 'Peru' => 'PER', 'Philippines' => 'PHI', 'Poland' => 'POL', 'Portugal' => 'POR', 'Puerto Rico' => 'PUR', 'Qatar' => 'QAT', 'Romania' => 'ROM', // actually ROU + 'Russia' => 'RUS', 'Rwanda' => 'RWA', 'Samoa' => 'SAM', 'San Marino' => 'SMR', 'Saudi Arabia' => 'KSA', 'Senegal' => 'SEN', 'Serbia' => 'SCG', // actually SRB + 'Sierra Leone' => 'SLE', 'Singapore' => 'SIN', 'Slovakia' => 'SVK', 'Slovenia' => 'SLO', 'Somalia' => 'SOM', 'South Africa' => 'RSA', 'Spain' => 'ESP', 'Sri Lanka' => 'SRI', 'Sudan' => 'SUD', 'Suriname' => 'SUR', 'Swaziland' => 'SWZ', 'Sweden' => 'SWE', 'Switzerland' => 'SUI', 'Syria' => 'SYR', 'Taiwan' => 'TWN', 'Tajikistan' => 'TJK', 'Tanzania' => 'TAN', 'Thailand' => 'THA', 'Togo' => 'TOG', 'Tonga' => 'TGA', 'Trinidad and Tobago' => 'TRI', 'Tunisia' => 'TUN', 'Turkey' => 'TUR', 'Turkmenistan' => 'TKM', 'Tuvalu' => 'TUV', 'Uganda' => 'UGA', 'Ukraine' => 'UKR', 'United Arab Emirates' => 'UAE', 'United Kingdom' => 'GBR', 'United States of America' => 'USA', 'Uruguay' => 'URU', 'Uzbekistan' => 'UZB', 'Vanuatu' => 'VAN', 'Venezuela' => 'VEN', 'Vietnam' => 'VIE', 'Yemen' => 'YEM', 'Zambia' => 'ZAM', 'Zimbabwe' => 'ZIM'); if (array_key_exists($country, $nations)) { return $nations[$country]; } diff --git a/application/core/ManiaControl.php b/application/core/ManiaControl.php index 937aee91..7234fea0 100644 --- a/application/core/ManiaControl.php +++ b/application/core/ManiaControl.php @@ -11,6 +11,7 @@ use ManiaControl\Callbacks\TimerManager; use ManiaControl\Commands\CommandListener; use ManiaControl\Commands\CommandManager; use ManiaControl\Configurators\Configurator; +use ManiaControl\Database\Database; use ManiaControl\Files\AsynchronousFileReader; use ManiaControl\Files\FileUtil; use ManiaControl\Manialinks\ManialinkManager; @@ -26,7 +27,6 @@ use Maniaplanet\DedicatedServer\Connection; use Maniaplanet\DedicatedServer\Xmlrpc\Exception; use Maniaplanet\DedicatedServer\Xmlrpc\NotInScriptModeException; use Maniaplanet\DedicatedServer\Xmlrpc\TransportException; -use ManiaControl\Database\Database; require_once __DIR__ . '/Libs/Maniaplanet/DedicatedServer/Connection.php'; require_once __DIR__ . '/Libs/GbxDataFetcher/gbxdatafetcher.inc.php'; @@ -36,26 +36,26 @@ require_once __DIR__ . '/Libs/curl-easy/autoload.php'; /** * ManiaControl Server Controller for ManiaPlanet Server - * - * @author ManiaControl Team - * @copyright ManiaControl Copyright © 2014 ManiaControl Team - * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 + * + * @author ManiaControl Team + * @copyright 2014 ManiaControl Team + * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 */ class ManiaControl implements CommandListener, TimerListener { /* * Constants */ - const VERSION = '0.12'; - const API_VERSION = '2013-04-16'; - const MIN_DEDIVERSION = '2014-04-02_18_00'; - const OS_UNIX = 'Unix'; - const OS_WIN = 'Windows'; - const CONNECT_TIMEOUT = 50; - const SCRIPT_TIMEOUT = 20; - const URL_WEBSERVICE = 'http://ws.maniacontrol.com/'; + const VERSION = '0.12'; + const API_VERSION = '2013-04-16'; + const MIN_DEDIVERSION = '2014-04-02_18_00'; + const OS_UNIX = 'Unix'; + const OS_WIN = 'Windows'; + const CONNECT_TIMEOUT = 50; + const SCRIPT_TIMEOUT = 20; + const URL_WEBSERVICE = 'http://ws.maniacontrol.com/'; const SETTING_PERMISSION_SHUTDOWN = 'Shutdown ManiaControl'; - const SETTING_PERMISSION_RESTART = 'Restart ManiaControl'; - + const SETTING_PERMISSION_RESTART = 'Restart ManiaControl'; + /* * Public Properties */ @@ -66,7 +66,6 @@ class ManiaControl implements CommandListener, TimerListener { public $config = null; public $configurator = null; /** - * * @var Connection $client */ public $client = null; @@ -85,7 +84,7 @@ class ManiaControl implements CommandListener, TimerListener { public $timerManager = null; public $fileReader = null; public $billManager = null; - + /* * Private Properties */ @@ -97,53 +96,66 @@ class ManiaControl implements CommandListener, TimerListener { public function __construct() { // Construct Error Handler $this->errorHandler = new ErrorHandler($this); - + $this->log('Loading ManiaControl v' . self::VERSION . '...'); - + $this->loadConfig(); - + // Load ManiaControl Modules - $this->callbackManager = new CallbackManager($this); - $this->timerManager = new TimerManager($this); - $this->database = new Database($this); - $this->fileReader = new AsynchronousFileReader($this); - $this->billManager = new BillManager($this); - $this->settingManager = new SettingManager($this); - $this->statisticManager = new StatisticManager($this); - $this->manialinkManager = new ManialinkManager($this); - $this->actionsMenu = new ActionsMenu($this); - $this->chat = new Chat($this); - $this->commandManager = new CommandManager($this); - $this->server = new Server($this); + $this->callbackManager = new CallbackManager($this); + $this->timerManager = new TimerManager($this); + $this->database = new Database($this); + $this->fileReader = new AsynchronousFileReader($this); + $this->billManager = new BillManager($this); + $this->settingManager = new SettingManager($this); + $this->statisticManager = new StatisticManager($this); + $this->manialinkManager = new ManialinkManager($this); + $this->actionsMenu = new ActionsMenu($this); + $this->chat = new Chat($this); + $this->commandManager = new CommandManager($this); + $this->server = new Server($this); $this->authenticationManager = new AuthenticationManager($this); - $this->playerManager = new PlayerManager($this); - $this->mapManager = new MapManager($this); - $this->configurator = new Configurator($this); - $this->pluginManager = new PluginManager($this); - $this->updateManager = new UpdateManager($this); - + $this->playerManager = new PlayerManager($this); + $this->mapManager = new MapManager($this); + $this->configurator = new Configurator($this); + $this->pluginManager = new PluginManager($this); + $this->updateManager = new UpdateManager($this); + // Define Permission Levels $this->authenticationManager->definePermissionLevel(self::SETTING_PERMISSION_SHUTDOWN, AuthenticationManager::AUTH_LEVEL_SUPERADMIN); $this->authenticationManager->definePermissionLevel(self::SETTING_PERMISSION_RESTART, AuthenticationManager::AUTH_LEVEL_SUPERADMIN); - + // Register for commands $this->commandManager->registerCommandListener('version', $this, 'command_Version', false, 'Shows ManiaControl version.'); $this->commandManager->registerCommandListener('restart', $this, 'command_Restart', true, 'Restarts ManiaControl.'); $this->commandManager->registerCommandListener('shutdown', $this, 'command_Shutdown', true, 'Shuts ManiaControl down.'); - + // Check connection every 30 seconds $this->timerManager->registerTimerListening($this, 'checkConnection', 1000 * 30); - + $this->errorHandler->init(); } + /** + * Print a message to console and log + * + * @param string $message + * @param bool $stripCodes + */ + public function log($message, $stripCodes = false) { + if ($stripCodes) { + $message = Formatter::stripCodes($message); + } + logMessage($message); + } + /** * Load the Config XML-File */ private function loadConfig() { - $configId = CommandLineHelper::getParameter('-config'); + $configId = CommandLineHelper::getParameter('-config'); $configFileName = ($configId ? $configId : 'server.xml'); - $this->config = FileUtil::loadConfig($configFileName); + $this->config = FileUtil::loadConfig($configFileName); if (!$this->config) { trigger_error("Error loading Configuration XML-File! ('{$configFileName}')", E_USER_ERROR); } @@ -154,7 +166,7 @@ class ManiaControl implements CommandListener, TimerListener { /** * Checks connection every xxx Minutes - * + * * @param $time */ public function checkConnection($time) { @@ -164,21 +176,65 @@ class ManiaControl implements CommandListener, TimerListener { } /** - * Print a message to console and log - * - * @param string $message - * @param bool $stripCodes + * Handle Version Command + * + * @param array $chatCallback + * @param Player $player */ - public function log($message, $stripCodes = false) { - if ($stripCodes) { - $message = Formatter::stripCodes($message); + public function command_Version(array $chatCallback, Player $player) { + $message = 'This server is using ManiaControl v' . ManiaControl::VERSION . '!'; + $this->chat->sendInformation($message, $player->login); + } + + /** + * Handle Restart AdminCommand + * + * @param array $chatCallback + * @param Player $player + */ + public function command_Restart(array $chatCallback, Player $player) { + if (!$this->authenticationManager->checkPermission($player, self::SETTING_PERMISSION_RESTART)) { + $this->authenticationManager->sendNotAllowed($player); + return; } - logMessage($message); + $this->restart("ManiaControl Restart requested by '{$player->login}'!"); + } + + /** + * Restart ManiaControl + * + * @param string $message + */ + public function restart($message = null) { + // Shutdown callback + $this->callbackManager->triggerCallback(CallbackManager::CB_ONSHUTDOWN); + + // Announce restart + $this->chat->sendInformation('Restarting ManiaControl...'); + if ($message) { + $this->log($message); + } + + // Hide widgets + $this->client->sendHideManialinkPage(); + + $this->log('Restarting ManiaControl!'); + + // Execute start script in background + // TODO: restart the .php script itself ($_SERVER['scriptname'] or something + $argv) + if ($this->getOS(self::OS_UNIX)) { + $command = 'sh ' . escapeshellarg(ManiaControlDir . '/ManiaControl.sh') . ' > /dev/null &'; + exec($command); + } else { + $command = escapeshellarg(ManiaControlDir . "\ManiaControl.bat"); + system($command); // TODO, windows stucks here as long controller is running + } + exit(); } /** * Get the Operating System on which ManiaControl is running - * + * * @param string $compareOS * @return string */ @@ -198,35 +254,10 @@ class ManiaControl implements CommandListener, TimerListener { return self::OS_UNIX; } - /** - * Handle Version Command - * - * @param array $chatCallback - * @param Player $player - */ - public function command_Version(array $chatCallback, Player $player) { - $message = 'This server is using ManiaControl v' . ManiaControl::VERSION . '!'; - $this->chat->sendInformation($message, $player->login); - } - - /** - * Handle Restart AdminCommand - * - * @param array $chatCallback - * @param Player $player - */ - public function command_Restart(array $chatCallback, Player $player) { - if (!$this->authenticationManager->checkPermission($player, self::SETTING_PERMISSION_RESTART)) { - $this->authenticationManager->sendNotAllowed($player); - return; - } - $this->restart("ManiaControl Restart requested by '{$player->login}'!"); - } - /** * Handle //shutdown command - * - * @param array $chat + * + * @param array $chat * @param Player $player */ public function command_Shutdown(array $chat, Player $player) { @@ -239,14 +270,14 @@ class ManiaControl implements CommandListener, TimerListener { /** * Quit ManiaControl and log the given message - * + * * @param string $message */ public function quit($message = null) { if ($message) { $this->log($message); } - + exit(); } @@ -256,144 +287,35 @@ class ManiaControl implements CommandListener, TimerListener { public function handleShutdown() { // OnShutdown callback $this->callbackManager->triggerCallback(CallbackManager::CB_ONSHUTDOWN); - + // Announce quit $this->chat->sendInformation('ManiaControl shutting down.'); - + if ($this->client) { try { // Hide manialinks $this->client->sendHideManialinkPage(); // Close the client connection $this->client->delete($this->server->ip, $this->server->port); - } - catch (TransportException $e) { + } catch (TransportException $e) { $this->errorHandler->triggerDebugNotice($e->getMessage() . " File: " . $e->getFile() . " Line: " . $e->getLine()); } } - + // Check and Trigger Fatal Errors $error = error_get_last(); if ($error && ($error['type'] & E_FATAL)) { $this->errorHandler->errorHandler($error['type'], $error['message'], $error['file'], $error['line']); } - + // Disable Garbage Collector $this->collectGarbage(); gc_disable(); - + $this->log('Quitting ManiaControl!'); exit(); } - /** - * Restart ManiaControl - * - * @param string $message - */ - public function restart($message = null) { - // Shutdown callback - $this->callbackManager->triggerCallback(CallbackManager::CB_ONSHUTDOWN); - - // Announce restart - $this->chat->sendInformation('Restarting ManiaControl...'); - if ($message) { - $this->log($message); - } - - // Hide widgets - $this->client->sendHideManialinkPage(); - - $this->log('Restarting ManiaControl!'); - - // Execute start script in background - // TODO: restart the .php script itself ($_SERVER['scriptname'] or something + $argv) - if ($this->getOS(self::OS_UNIX)) { - $command = 'sh ' . escapeshellarg(ManiaControlDir . '/ManiaControl.sh') . ' > /dev/null &'; - exec($command); - } - else { - $command = escapeshellarg(ManiaControlDir . "\ManiaControl.bat"); - system($command); // TODO, windows stucks here as long controller is running - } - exit(); - } - - /** - * Run ManiaControl - */ - public function run() { - $this->log('Starting ManiaControl v' . self::VERSION . '!'); - - // Register shutdown handler - register_shutdown_function(array($this, 'handleShutdown')); - - // Connect to server - $this->connect(); - - // Check if the version of the server is high enough - $version = $this->client->getVersion(); - if ($version->build < self::MIN_DEDIVERSION) { - trigger_error("The Server has Version '{$version->build}', while at least '" . self::MIN_DEDIVERSION . "' is required!", E_USER_ERROR); - } - - // OnInit callback - $this->callbackManager->triggerCallback(CallbackManager::CB_ONINIT); - - // Load plugins - $this->pluginManager->loadPlugins(); - $this->updateManager->pluginUpdateManager->checkPluginsUpdate(); - - // AfterInit callback - $this->callbackManager->triggerCallback(CallbackManager::CB_AFTERINIT); - - // Enable Garbage Collecting - gc_enable(); - $this->timerManager->registerTimerListening($this, 'collectGarbage', 1000 * 60); - - // Announce ManiaControl - $this->chat->sendInformation('ManiaControl v' . self::VERSION . ' successfully started!'); - - // Loading finished - $this->log('Loading completed!'); - $this->log('Link: maniaplanet://#join=' . $this->server->login . '@' . $this->server->titleId); - - // Main loop - while (!$this->shutdownRequested) { - $loopStart = microtime(true); - - // Disable script timeout - set_time_limit(self::SCRIPT_TIMEOUT); - - try { - // Manager callbacks - $this->callbackManager->manageCallbacks(); - } - catch (TransportException $e) { - $this->log("Connection interrupted!"); - // TODO remove - if ($this->errorHandler) { - $this->errorHandler->exceptionHandler($e, false); - } - $this->quit($e->getMessage()); - } - - // Manage FileReader - $this->fileReader->appendData(); - - // Yield for next tick - $loopEnd = microtime(true); - - $sleepTime = (int) (2000 - ($loopEnd - $loopStart) * 1000000); - if ($sleepTime > 0) { - usleep($sleepTime); - } - } - - // Shutdown - $this->quit(); - } - /** * Collect Garbage */ @@ -401,69 +323,139 @@ class ManiaControl implements CommandListener, TimerListener { gc_collect_cycles(); } + /** + * Run ManiaControl + */ + public function run() { + $this->log('Starting ManiaControl v' . self::VERSION . '!'); + + // Register shutdown handler + register_shutdown_function(array($this, 'handleShutdown')); + + // Connect to server + $this->connect(); + + // Check if the version of the server is high enough + $version = $this->client->getVersion(); + if ($version->build < self::MIN_DEDIVERSION) { + trigger_error("The Server has Version '{$version->build}', while at least '" . self::MIN_DEDIVERSION . "' is required!", E_USER_ERROR); + } + + // OnInit callback + $this->callbackManager->triggerCallback(CallbackManager::CB_ONINIT); + + // Load plugins + $this->pluginManager->loadPlugins(); + $this->updateManager->pluginUpdateManager->checkPluginsUpdate(); + + // AfterInit callback + $this->callbackManager->triggerCallback(CallbackManager::CB_AFTERINIT); + + // Enable Garbage Collecting + gc_enable(); + $this->timerManager->registerTimerListening($this, 'collectGarbage', 1000 * 60); + + // Announce ManiaControl + $this->chat->sendInformation('ManiaControl v' . self::VERSION . ' successfully started!'); + + // Loading finished + $this->log('Loading completed!'); + $this->log('Link: maniaplanet://#join=' . $this->server->login . '@' . $this->server->titleId); + + // Main loop + while (!$this->shutdownRequested) { + $loopStart = microtime(true); + + // Disable script timeout + set_time_limit(self::SCRIPT_TIMEOUT); + + try { + // Manager callbacks + $this->callbackManager->manageCallbacks(); + } catch (TransportException $e) { + $this->log("Connection interrupted!"); + // TODO remove + if ($this->errorHandler) { + $this->errorHandler->exceptionHandler($e, false); + } + $this->quit($e->getMessage()); + } + + // Manage FileReader + $this->fileReader->appendData(); + + // Yield for next tick + $loopEnd = microtime(true); + + $sleepTime = (int)(2000 - ($loopEnd - $loopStart) * 1000000); + if ($sleepTime > 0) { + usleep($sleepTime); + } + } + + // Shutdown + $this->quit(); + } + /** * Connect to ManiaPlanet server */ private function connect() { // Load remote client $this->server->loadConfig(); - + $this->log("Connecting to server at {$this->server->config->host}:{$this->server->config->port}..."); - + try { $this->client = Connection::factory($this->server->config->host, $this->server->config->port, self::CONNECT_TIMEOUT, $this->server->config->login, $this->server->config->pass); - } - catch (Exception $e) { + } catch (Exception $e) { trigger_error("Couldn't authenticate on server with user '{$this->server->config->login}'! " . $e->getMessage(), E_USER_ERROR); } - + // Enable callback system $this->client->enableCallbacks(true); - + // Wait for server to be ready try { if (!$this->server->waitForStatus(4)) { trigger_error("Server couldn't get ready!", E_USER_ERROR); } - } - catch (Exception $e) { + } catch (Exception $e) { // TODO remove if ($this->errorHandler) { $this->errorHandler->triggerDebugNotice("Fatal Exception: " . $e->getMessage() . " Trace: " . $e->getTraceAsString()); } $this->quit($e->getMessage()); } - + // Connect finished $this->log("Server Connection successfully established!"); - + // Hide old widgets $this->client->sendHideManialinkPage(); - + // Enable script callbacks if needed if ($this->server->getGameMode() != 0) { return; } - + try { $scriptSettings = $this->client->getModeScriptSettings(); - } - catch (NotInScriptModeException $e) { + } catch (NotInScriptModeException $e) { return; } - + if (!array_key_exists('S_UseScriptCallbacks', $scriptSettings)) { return; } - + $scriptSettings['S_UseScriptCallbacks'] = true; try { $this->client->setModeScriptSettings($scriptSettings); - } - catch (Exception $e) { + } catch (Exception $e) { // TODO temp added 19.04.2014 $this->errorHandler->triggerDebugNotice("Exception line 437 ManiaControl.php " . $e->getMessage()); - + trigger_error("Couldn't set mode script settings to enable script callbacks. " . $e->getMessage()); return; } diff --git a/application/core/Plugins/Plugin.php b/application/core/Plugins/Plugin.php index 960424ca..7157d3f1 100644 --- a/application/core/Plugins/Plugin.php +++ b/application/core/Plugins/Plugin.php @@ -7,9 +7,9 @@ use ManiaControl\ManiaControl; /** * Interface for ManiaControl Plugins * - * @author steeffeen & kremsy - * @copyright ManiaControl Copyright © 2014 ManiaControl Team - * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 + * @author ManiaControl Team + * @copyright 2014 ManiaControl Team + * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 */ interface Plugin { /* @@ -24,19 +24,6 @@ interface Plugin { */ public static function prepare(ManiaControl $maniaControl); - /** - * Load the plugin - * - * @param \ManiaControl\ManiaControl $maniaControl - * @return bool - */ - public function load(ManiaControl $maniaControl); - - /** - * Unload the plugin and its Resources - */ - public function unload(); - /** * Get plugin id * @@ -71,4 +58,17 @@ interface Plugin { * @return string */ public static function getDescription(); + + /** + * Load the plugin + * + * @param \ManiaControl\ManiaControl $maniaControl + * @return bool + */ + public function load(ManiaControl $maniaControl); + + /** + * Unload the plugin and its Resources + */ + public function unload(); } diff --git a/application/core/Plugins/PluginInstallMenu.php b/application/core/Plugins/PluginInstallMenu.php index 650f07da..4a9c1bff 100644 --- a/application/core/Plugins/PluginInstallMenu.php +++ b/application/core/Plugins/PluginInstallMenu.php @@ -21,16 +21,16 @@ use ManiaControl\Players\Player; /** * Configurator for enabling and disabling Plugins * - * @author steeffeen - * @copyright ManiaControl Copyright © 2014 ManiaControl Team - * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 + * @author ManiaControl Team + * @copyright 2014 ManiaControl Team + * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 */ class PluginInstallMenu implements CallbackListener, ConfiguratorMenu, ManialinkPageAnswerListener { /* * Constants */ - const SETTING_PERMISSION_INSTALL_PLUGINS = 'Install plugins'; - const ACTION_PREFIX_INSTALLPLUGIN = 'PluginInstallMenu.Install.'; + const SETTING_PERMISSION_INSTALL_PLUGINS = 'Install plugins'; + const ACTION_PREFIX_INSTALLPLUGIN = 'PluginInstallMenu.Install.'; /** * Create a new plugin menu instance @@ -62,9 +62,9 @@ class PluginInstallMenu implements CallbackListener, ConfiguratorMenu, Manialink * @return \FML\Controls\Frame */ public function getMenu($width, $height, Script $script, Player $player) { - $paging = new Paging(); - $script->addFeature($paging); - $frame = new Frame(); + $paging = new Paging(); + $script->addFeature($paging); + $frame = new Frame(); // Config $pagerSize = 9.; @@ -87,8 +87,8 @@ class PluginInstallMenu implements CallbackListener, ConfiguratorMenu, Manialink $pagerNext->setSize($pagerSize, $pagerSize); $pagerNext->setSubStyle(Quad_Icons64x64_1::SUBSTYLE_ArrowNext); - $paging->addButton($pagerNext); - $paging->addButton($pagerPrev); + $paging->addButton($pagerNext); + $paging->addButton($pagerPrev); $pageCountLabel = new Label_Text(); $frame->add($pageCountLabel); @@ -97,22 +97,22 @@ class PluginInstallMenu implements CallbackListener, ConfiguratorMenu, Manialink $pageCountLabel->setStyle($pageCountLabel::STYLE_TextTitle1); $pageCountLabel->setTextSize(2); - $paging->setLabel($pageCountLabel); + $paging->setLabel($pageCountLabel); - $url = ManiaControl::URL_WEBSERVICE . 'plugins'; - $dataJson = FileUtil::loadFile($url); - $pluginList = json_decode($dataJson); - $index = 0; + $url = ManiaControl::URL_WEBSERVICE . 'plugins'; + $dataJson = FileUtil::loadFile($url); + $pluginList = json_decode($dataJson); + $index = 0; if ($pluginList && isset($pluginList[0])) { - $pluginClasses = $this->maniaControl->pluginManager->getPluginClasses(); - $pluginIds = array(); + $pluginClasses = $this->maniaControl->pluginManager->getPluginClasses(); + $pluginIds = array(); /** @var Plugin $class */ - foreach($pluginClasses as $class) { + foreach ($pluginClasses as $class) { $pluginIds[] = $class::getId(); } - foreach($pluginList as $plugin) { - if(!in_array($plugin->id, $pluginIds)) { + foreach ($pluginList as $plugin) { + if (!in_array($plugin->id, $pluginIds)) { if (!isset($pageFrame)) { $pageFrame = new Frame(); $frame->add($pageFrame); @@ -121,7 +121,7 @@ class PluginInstallMenu implements CallbackListener, ConfiguratorMenu, Manialink } array_push($pageFrames, $pageFrame); - $paging->addPage($pageFrame); + $paging->addPage($pageFrame); $y = $height * 0.41; } @@ -150,7 +150,7 @@ class PluginInstallMenu implements CallbackListener, ConfiguratorMenu, Manialink $descriptionLabel->setMaxLines(5); $description = "Author: {$plugin->author}\nVersion: {$plugin->currentVersion->version}\nDesc: {$plugin->description}"; $descriptionLabel->setText($description); - $nameLabel->addTooltipFeature($descriptionLabel); + $nameLabel->addTooltipFeature($descriptionLabel); $installButton = new Label_Button(); $pluginFrame->add($installButton); diff --git a/application/core/Plugins/PluginManager.php b/application/core/Plugins/PluginManager.php index 1378aed8..1a71c8e5 100644 --- a/application/core/Plugins/PluginManager.php +++ b/application/core/Plugins/PluginManager.php @@ -3,24 +3,24 @@ namespace ManiaControl\Plugins; use ManiaControl\Callbacks\CallbackListener; -use ManiaControl\ManiaControl; -use ManiaControl\Manialinks\ManialinkPageAnswerListener; use ManiaControl\Callbacks\TimerListener; use ManiaControl\Commands\CommandListener; +use ManiaControl\ManiaControl; +use ManiaControl\Manialinks\ManialinkPageAnswerListener; /** * Class managing Plugins - * - * @author steeffeen & kremsy - * @copyright ManiaControl Copyright © 2014 ManiaControl Team - * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 + * + * @author ManiaControl Team + * @copyright 2014 ManiaControl Team + * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 */ class PluginManager { /* * Constants */ const TABLE_PLUGINS = 'mc_plugins'; - + /* * Private Properties */ @@ -32,27 +32,27 @@ class PluginManager { /** * Construct plugin manager - * + * * @param \ManiaControl\ManiaControl $maniaControl */ public function __construct(ManiaControl $maniaControl) { $this->maniaControl = $maniaControl; $this->initTables(); - + $this->pluginMenu = new PluginMenu($maniaControl); $this->maniaControl->configurator->addMenu($this->pluginMenu); - + $this->pluginInstallMenu = new PluginInstallMenu($maniaControl); $this->maniaControl->configurator->addMenu($this->pluginInstallMenu); } /** * Initialize necessary database tables - * + * * @return bool */ private function initTables() { - $mysqli = $this->maniaControl->database->mysqli; + $mysqli = $this->maniaControl->database->mysqli; $pluginsTableQuery = "CREATE TABLE IF NOT EXISTS `" . self::TABLE_PLUGINS . "` ( `index` int(11) NOT NULL AUTO_INCREMENT, `className` varchar(100) NOT NULL, @@ -61,7 +61,7 @@ class PluginManager { PRIMARY KEY (`index`), UNIQUE KEY `className` (`className`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='ManiaControl plugin status' AUTO_INCREMENT=1;"; - $tableStatement = $mysqli->prepare($pluginsTableQuery); + $tableStatement = $mysqli->prepare($pluginsTableQuery); if ($mysqli->error) { trigger_error($mysqli->error, E_USER_ERROR); return false; @@ -75,95 +75,9 @@ class PluginManager { return true; } - /** - * Check if the plugin is running - * - * @param string $pluginClass - * @return bool - */ - public function isPluginActive($pluginClass) { - $pluginClass = $this->getPluginClass($pluginClass); - return isset($this->activePlugins[$pluginClass]); - } - - /** - * Check if the given class implements the plugin interface - * - * @param string $pluginClass - * @return bool - */ - public static function isPluginClass($pluginClass) { - $pluginClass = self::getClass($pluginClass); - if (!class_exists($pluginClass, false)) { - return false; - } - if (!in_array(Plugin::PLUGIN_INTERFACE, class_implements($pluginClass, false))) { - return false; - } - return true; - } - - /** - * Add the class to array of loaded plugin classes - * - * @param string $pluginClass - * @return bool - */ - public function addPluginClass($pluginClass) { - $pluginClass = $this->getPluginClass($pluginClass); - if (in_array($pluginClass, $this->pluginClasses)) { - return false; - } - if (!$this->isPluginClass($pluginClass)) { - return false; - } - array_push($this->pluginClasses, $pluginClass); - sort($this->pluginClasses); - return true; - } - - /** - * Activate and start the plugin with the given name - * - * @param string $pluginClass - * @param string $adminLogin - * @return bool - */ - public function activatePlugin($pluginClass, $adminLogin = null) { - if (!is_string($pluginClass)) { - return false; - } - if (!$this->isPluginClass($pluginClass)) { - return false; - } - if ($this->isPluginActive($pluginClass)) { - return false; - } - $plugin = new $pluginClass(); - /** - * - * @var Plugin $plugin - */ - $this->activePlugins[$pluginClass] = $plugin; - $this->savePluginStatus($pluginClass, true); - try { - $plugin->load($this->maniaControl); - } - catch (\Exception $e) { - $this->maniaControl->chat->sendError('Error while plugin activating ' . $pluginClass . ': ' . $e->getMessage(), $adminLogin); - $this->maniaControl->log('Error while plugin activation: ' . $pluginClass . ': ' . $e->getMessage()); - unset($this->activePlugins[$pluginClass]); - $this->savePluginStatus($pluginClass, false); - return false; - } - - $this->savePluginStatus($pluginClass, true); - return true; - } - /** * Deactivate the plugin with the given class - * + * * @param string $pluginClass * @return bool */ @@ -174,7 +88,6 @@ class PluginManager { } $plugin = $this->activePlugins[$pluginClass]; /** - * * @var Plugin $plugin */ $plugin->unload(); @@ -197,113 +110,69 @@ class PluginManager { } /** - * Load complete Plugins Directory and start all configured Plugins - * - * @return array + * Get the Class of the Plugin + * + * @param mixed $pluginClass + * @return string */ - public function loadPlugins() { - $pluginsDirectory = ManiaControlDir . '/plugins/'; - - $classesBefore = get_declared_classes(); - $this->loadPluginFiles($pluginsDirectory); - $classesAfter = get_declared_classes(); - - $newPluginClasses = array(); - - $newClasses = array_diff($classesAfter, $classesBefore); - foreach ($newClasses as $className) { - if (!$this->isPluginClass($className)) { - continue; - } - - if (!$this->addPluginClass($className)) { - continue; - } - array_push($newPluginClasses, $className); - - /** @var Plugin $className */ - $className::prepare($this->maniaControl); - - if ($this->getSavedPluginStatus($className)) { - $this->activatePlugin($className); - } + public static function getPluginClass($pluginClass) { + $pluginClass = self::getClass($pluginClass); + if (!self::isPluginClass($pluginClass)) { + return false; } - - return $newPluginClasses; + return $pluginClass; } /** - * Load all Plugin Files from the Directory - * - * @param string $directory + * Get the Class of the Object + * + * @param mixed $object + * @return string */ - public function loadPluginFiles($directory = '') { - $pluginFiles = scandir($directory); - foreach ($pluginFiles as $pluginFile) { - if (stripos($pluginFile, '.') === 0) { - continue; - } - - $filePath = $directory . $pluginFile; - if (is_file($filePath)) { - if (!stripos($pluginFile, '.php')) { - continue; - } - $success = include_once $filePath; - if (!$success) { - trigger_error("Error loading File '{$filePath}'!"); - } - continue; - } - - $dirPath = $directory . $pluginFile; - if (is_dir($dirPath)) { - $this->loadPluginFiles($dirPath . '/'); - continue; - } + private static function getClass($object) { + if (is_object($object)) { + return get_class($object); } + return (string)$object; } /** - * Returns a Plugin if it is activated - * + * Check if the given class implements the plugin interface + * * @param string $pluginClass - * @return Plugin + * @return bool */ - public function getPlugin($pluginClass) { - if ($this->isPluginActive($pluginClass)) { - return $this->activePlugins[$pluginClass]; + public static function isPluginClass($pluginClass) { + $pluginClass = self::getClass($pluginClass); + if (!class_exists($pluginClass, false)) { + return false; } - return null; + if (!in_array(Plugin::PLUGIN_INTERFACE, class_implements($pluginClass, false))) { + return false; + } + return true; } /** - * Get all declared plugin class names - * - * @return array + * Check if the plugin is running + * + * @param string $pluginClass + * @return bool */ - public function getPluginClasses() { - return $this->pluginClasses; - } - - /** - * Get all active plugins - * - * @return array - */ - public function getActivePlugins() { - return $this->activePlugins; + public function isPluginActive($pluginClass) { + $pluginClass = $this->getPluginClass($pluginClass); + return isset($this->activePlugins[$pluginClass]); } /** * Save plugin status in database - * + * * @param string $className - * @param bool $active + * @param bool $active * @return bool */ private function savePluginStatus($className, $active) { - $mysqli = $this->maniaControl->database->mysqli; + $mysqli = $this->maniaControl->database->mysqli; $pluginStatusQuery = "INSERT INTO `" . self::TABLE_PLUGINS . "` ( `className`, `active` @@ -311,7 +180,7 @@ class PluginManager { ?, ? ) ON DUPLICATE KEY UPDATE `active` = VALUES(`active`);"; - $pluginStatement = $mysqli->prepare($pluginStatusQuery); + $pluginStatement = $mysqli->prepare($pluginStatusQuery); if ($mysqli->error) { trigger_error($mysqli->error); return false; @@ -328,17 +197,104 @@ class PluginManager { return true; } + /** + * Load complete Plugins Directory and start all configured Plugins + * + * @return array + */ + public function loadPlugins() { + $pluginsDirectory = ManiaControlDir . '/plugins/'; + + $classesBefore = get_declared_classes(); + $this->loadPluginFiles($pluginsDirectory); + $classesAfter = get_declared_classes(); + + $newPluginClasses = array(); + + $newClasses = array_diff($classesAfter, $classesBefore); + foreach ($newClasses as $className) { + if (!$this->isPluginClass($className)) { + continue; + } + + if (!$this->addPluginClass($className)) { + continue; + } + array_push($newPluginClasses, $className); + + /** @var Plugin $className */ + $className::prepare($this->maniaControl); + + if ($this->getSavedPluginStatus($className)) { + $this->activatePlugin($className); + } + } + + return $newPluginClasses; + } + + /** + * Load all Plugin Files from the Directory + * + * @param string $directory + */ + public function loadPluginFiles($directory = '') { + $pluginFiles = scandir($directory); + foreach ($pluginFiles as $pluginFile) { + if (stripos($pluginFile, '.') === 0) { + continue; + } + + $filePath = $directory . $pluginFile; + if (is_file($filePath)) { + if (!stripos($pluginFile, '.php')) { + continue; + } + $success = include_once $filePath; + if (!$success) { + trigger_error("Error loading File '{$filePath}'!"); + } + continue; + } + + $dirPath = $directory . $pluginFile; + if (is_dir($dirPath)) { + $this->loadPluginFiles($dirPath . '/'); + continue; + } + } + } + + /** + * Add the class to array of loaded plugin classes + * + * @param string $pluginClass + * @return bool + */ + public function addPluginClass($pluginClass) { + $pluginClass = $this->getPluginClass($pluginClass); + if (in_array($pluginClass, $this->pluginClasses)) { + return false; + } + if (!$this->isPluginClass($pluginClass)) { + return false; + } + array_push($this->pluginClasses, $pluginClass); + sort($this->pluginClasses); + return true; + } + /** * Get plugin status from database - * + * * @param string $className * @return bool */ public function getSavedPluginStatus($className) { - $mysqli = $this->maniaControl->database->mysqli; + $mysqli = $this->maniaControl->database->mysqli; $pluginStatusQuery = "SELECT `active` FROM `" . self::TABLE_PLUGINS . "` WHERE `className` = ?;"; - $pluginStatement = $mysqli->prepare($pluginStatusQuery); + $pluginStatement = $mysqli->prepare($pluginStatusQuery); if ($mysqli->error) { trigger_error($mysqli->error); return false; @@ -365,44 +321,85 @@ class PluginManager { return $active; } + /** + * Activate and start the plugin with the given name + * + * @param string $pluginClass + * @param string $adminLogin + * @return bool + */ + public function activatePlugin($pluginClass, $adminLogin = null) { + if (!is_string($pluginClass)) { + return false; + } + if (!$this->isPluginClass($pluginClass)) { + return false; + } + if ($this->isPluginActive($pluginClass)) { + return false; + } + $plugin = new $pluginClass(); + /** + * @var Plugin $plugin + */ + $this->activePlugins[$pluginClass] = $plugin; + $this->savePluginStatus($pluginClass, true); + try { + $plugin->load($this->maniaControl); + } catch (\Exception $e) { + $this->maniaControl->chat->sendError('Error while plugin activating ' . $pluginClass . ': ' . $e->getMessage(), $adminLogin); + $this->maniaControl->log('Error while plugin activation: ' . $pluginClass . ': ' . $e->getMessage()); + unset($this->activePlugins[$pluginClass]); + $this->savePluginStatus($pluginClass, false); + return false; + } + + $this->savePluginStatus($pluginClass, true); + return true; + } + + /** + * Returns a Plugin if it is activated + * + * @param string $pluginClass + * @return Plugin + */ + public function getPlugin($pluginClass) { + if ($this->isPluginActive($pluginClass)) { + return $this->activePlugins[$pluginClass]; + } + return null; + } + + /** + * Get all declared plugin class names + * + * @return array + */ + public function getPluginClasses() { + return $this->pluginClasses; + } + + /** + * Get all active plugins + * + * @return array + */ + public function getActivePlugins() { + return $this->activePlugins; + } + /** * Fetch the Plugins List from the ManiaControl Website - * + * * @param $function */ public function fetchPluginList($function) { $url = ManiaControl::URL_WEBSERVICE . 'plugins'; - - $this->maniaControl->fileReader->loadFile($url, function ($dataJson, $error) use(&$function) { + + $this->maniaControl->fileReader->loadFile($url, function ($dataJson, $error) use (&$function) { $data = json_decode($dataJson); call_user_func($function, $data, $error); }); } - - /** - * Get the Class of the Plugin - * - * @param mixed $pluginClass - * @return string - */ - public static function getPluginClass($pluginClass) { - $pluginClass = self::getClass($pluginClass); - if (!self::isPluginClass($pluginClass)) { - return false; - } - return $pluginClass; - } - - /** - * Get the Class of the Object - * - * @param mixed $object - * @return string - */ - private static function getClass($object) { - if (is_object($object)) { - return get_class($object); - } - return (string) $object; - } } diff --git a/application/core/Plugins/PluginMenu.php b/application/core/Plugins/PluginMenu.php index 5c172cfa..5b5d51f0 100644 --- a/application/core/Plugins/PluginMenu.php +++ b/application/core/Plugins/PluginMenu.php @@ -8,8 +8,8 @@ use FML\Controls\Frame; use FML\Controls\Label; use FML\Controls\Labels\Label_Button; use FML\Controls\Labels\Label_Text; -use FML\Controls\Quads\Quad_Icons128x32_1; use FML\Controls\Quads\Quad_Icons128x128_1; +use FML\Controls\Quads\Quad_Icons128x32_1; use FML\Controls\Quads\Quad_Icons64x64_1; use FML\Script\Features\Paging; use FML\Script\Script; @@ -25,9 +25,9 @@ use ManiaControl\Players\Player; /** * Configurator for enabling and disabling Plugins * - * @author ManiaControl Team - * @copyright ManiaControl Copyright © 2014 ManiaControl Team - * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 + * @author ManiaControl Team + * @copyright 2014 ManiaControl Team + * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 */ class PluginMenu implements CallbackListener, ConfiguratorMenu, ManialinkPageAnswerListener { /* @@ -62,13 +62,6 @@ class PluginMenu implements CallbackListener, ConfiguratorMenu, ManialinkPageAns $this->maniaControl->authenticationManager->definePermissionLevel(self::SETTING_PERMISSION_CHANGE_PLUGIN_SETTINGS, AuthenticationManager::AUTH_LEVEL_SUPERADMIN); } - /** - * @see \ManiaControl\Configurators\ConfiguratorMenu::getTitle() - */ - public function getTitle() { - return 'Plugins'; - } - /** * Returns Back to the Plugins */ @@ -78,13 +71,20 @@ class PluginMenu implements CallbackListener, ConfiguratorMenu, ManialinkPageAns $this->maniaControl->configurator->reopenMenu($player, $menuId); } + /** + * @see \ManiaControl\Configurators\ConfiguratorMenu::getTitle() + */ + public function getTitle() { + return 'Plugins'; + } + /** * @see \ManiaControl\Configurators\ConfiguratorMenu::getMenu() */ public function getMenu($width, $height, Script $script, Player $player) { - $paging = new Paging(); - $script->addFeature($paging); - $frame = new Frame(); + $paging = new Paging(); + $script->addFeature($paging); + $frame = new Frame(); $pluginClasses = $this->maniaControl->pluginManager->getPluginClasses(); @@ -107,8 +107,8 @@ class PluginMenu implements CallbackListener, ConfiguratorMenu, ManialinkPageAns $pagerNext->setSize($pagerSize, $pagerSize); $pagerNext->setSubStyle(Quad_Icons64x64_1::SUBSTYLE_ArrowNext); - $paging->addButton($pagerNext); - $paging->addButton($pagerPrev); + $paging->addButton($pagerNext); + $paging->addButton($pagerPrev); $pageCountLabel = new Label_Text(); $frame->add($pageCountLabel); @@ -117,7 +117,7 @@ class PluginMenu implements CallbackListener, ConfiguratorMenu, ManialinkPageAns $pageCountLabel->setStyle($pageCountLabel::STYLE_TextTitle1); $pageCountLabel->setTextSize(2); - $paging->setLabel($pageCountLabel); + $paging->setLabel($pageCountLabel); //Show Settings Menu if ($this->settingsClass != '') { //TODO improve @@ -128,7 +128,7 @@ class PluginMenu implements CallbackListener, ConfiguratorMenu, ManialinkPageAns $y = 0; $index = 1; $settingHeight = 5.; - foreach($settings as $setting) { + foreach ($settings as $setting) { if (!isset($pageFrame)) { $pageFrame = new Frame(); $frame->add($pageFrame); @@ -137,7 +137,7 @@ class PluginMenu implements CallbackListener, ConfiguratorMenu, ManialinkPageAns } array_push($pageFrames, $pageFrame); $y = $height * 0.41; - $paging->addPage($pageFrame); + $paging->addPage($pageFrame); } $settingFrame = new Frame(); @@ -166,7 +166,7 @@ class PluginMenu implements CallbackListener, ConfiguratorMenu, ManialinkPageAns } array_push($pageFrames, $pageFrame); $y = $height * 0.41; - $paging->addPage($pageFrame); + $paging->addPage($pageFrame); } } @@ -244,11 +244,11 @@ class PluginMenu implements CallbackListener, ConfiguratorMenu, ManialinkPageAns $y = 0.; $pluginUpdates = $this->maniaControl->updateManager->pluginUpdateManager->getPluginsUpdates(); - usort($pluginClasses, function($a, $b) { + usort($pluginClasses, function ($a, $b) { return strcmp($a::getName(), $b::getName()); }); - foreach($pluginClasses as $index => $pluginClass) { + foreach ($pluginClasses as $index => $pluginClass) { /** @var Plugin $pluginClass */ if (!isset($pageFrame)) { $pageFrame = new Frame(); @@ -258,7 +258,7 @@ class PluginMenu implements CallbackListener, ConfiguratorMenu, ManialinkPageAns } array_push($pageFrames, $pageFrame); - $paging->addPage($pageFrame); + $paging->addPage($pageFrame); $y = $height * 0.41; } @@ -299,7 +299,7 @@ class PluginMenu implements CallbackListener, ConfiguratorMenu, ManialinkPageAns $descriptionLabel->setMaxLines(5); $description = "Author: {$pluginClass::getAuthor()}\nVersion: {$pluginClass::getVersion()}\nDesc: {$pluginClass::getDescription()}"; $descriptionLabel->setText($description); - $nameLabel->addTooltipFeature($descriptionLabel); + $nameLabel->addTooltipFeature($descriptionLabel); $quad = new Quad_Icons128x32_1(); $pluginFrame->add($quad); @@ -340,7 +340,7 @@ class PluginMenu implements CallbackListener, ConfiguratorMenu, ManialinkPageAns } } - if($pluginUpdates != false) { + if ($pluginUpdates != false) { $updatePluginsButton = new Label_Button(); $frame->add($updatePluginsButton); $updatePluginsButton->setHAlign(Control::RIGHT); @@ -349,48 +349,13 @@ class PluginMenu implements CallbackListener, ConfiguratorMenu, ManialinkPageAns $updatePluginsButton->setZ(2); $updatePluginsButton->setWidth(10); $updatePluginsButton->setStyle($updatePluginsButton::STYLE_CardButtonSmallS); - $updatePluginsButton->setText(count($pluginUpdates).' update(s)'); + $updatePluginsButton->setText(count($pluginUpdates) . ' update(s)'); $updatePluginsButton->setAction(self::ACTION_UPDATEPLUGINS); } return $frame; } - /** - * @see \ManiaControl\Configurators\ConfiguratorMenu::saveConfigData() - */ - public function saveConfigData(array $configData, Player $player) { - if (!$this->maniaControl->authenticationManager->checkPermission($player, self::SETTING_PERMISSION_CHANGE_PLUGIN_SETTINGS)) { - $this->maniaControl->authenticationManager->sendNotAllowed($player); - return; - } - if (!$configData[3] || strpos($configData[3][0]['Name'], self::ACTION_PREFIX_SETTING) !== 0) { - return; - } - - $maniaControlSettings = $this->maniaControl->settingManager->getSettings(); - - $prefixLength = strlen(self::ACTION_PREFIX_SETTING); - - foreach($configData[3] as $setting) { - $settingName = substr($setting['Name'], $prefixLength + 1); - - if(!isset($maniaControlSettings[$settingName])) - continue; - - $oldSetting = $maniaControlSettings[$settingName]; - if ($setting['Value'] == $oldSetting->value || $oldSetting->type == 'bool') { - continue; - } - - $this->maniaControl->settingManager->setSetting($oldSetting->class, $oldSetting->setting, $setting['Value']); - } - - //Reopen the Menu - $menuId = $this->maniaControl->configurator->getMenuId($this->getTitle()); - $this->maniaControl->configurator->reopenMenu($player, $menuId); - } - /** * Handle PlayerManialinkPageAnswer callback * @@ -456,7 +421,7 @@ class PluginMenu implements CallbackListener, ConfiguratorMenu, ManialinkPageAns } /** - * Toggles a Boolean Value + * Toggle a Boolean Value * * @param $setting * @param Player $player @@ -481,4 +446,40 @@ class PluginMenu implements CallbackListener, ConfiguratorMenu, ManialinkPageAns $this->maniaControl->settingManager->setSetting($oldSetting->class, $oldSetting->setting, "1"); } } + + /** + * @see \ManiaControl\Configurators\ConfiguratorMenu::saveConfigData() + */ + public function saveConfigData(array $configData, Player $player) { + if (!$this->maniaControl->authenticationManager->checkPermission($player, self::SETTING_PERMISSION_CHANGE_PLUGIN_SETTINGS)) { + $this->maniaControl->authenticationManager->sendNotAllowed($player); + return; + } + if (!$configData[3] || strpos($configData[3][0]['Name'], self::ACTION_PREFIX_SETTING) !== 0) { + return; + } + + $maniaControlSettings = $this->maniaControl->settingManager->getSettings(); + + $prefixLength = strlen(self::ACTION_PREFIX_SETTING); + + foreach ($configData[3] as $setting) { + $settingName = substr($setting['Name'], $prefixLength + 1); + + if (!isset($maniaControlSettings[$settingName])) { + continue; + } + + $oldSetting = $maniaControlSettings[$settingName]; + if ($setting['Value'] == $oldSetting->value || $oldSetting->type == 'bool') { + continue; + } + + $this->maniaControl->settingManager->setSetting($oldSetting->class, $oldSetting->setting, $setting['Value']); + } + + //Reopen the Menu + $menuId = $this->maniaControl->configurator->getMenuId($this->getTitle()); + $this->maniaControl->configurator->reopenMenu($player, $menuId); + } } diff --git a/application/plugins/ChatMessagePlugin.php b/application/plugins/ChatMessagePlugin.php index 3de12242..99f084f5 100644 --- a/application/plugins/ChatMessagePlugin.php +++ b/application/plugins/ChatMessagePlugin.php @@ -11,8 +11,8 @@ use Maniaplanet\DedicatedServer\Xmlrpc\Exception; /** * ManiaControl Chat-Message Plugin * - * @author kremsy - * @copyright ManiaControl Copyright © 2014 ManiaControl Team + * @author kremsy + * @copyright 2014 ManiaControl Team * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 */ class ChatMessagePlugin implements CommandListener, Plugin { @@ -43,6 +43,51 @@ class ChatMessagePlugin implements CommandListener, Plugin { //do nothing } + /** + * Get plugin id + * + * @return int + */ + public static function getId() { + return self::PLUGIN_ID; + } + + /** + * Get Plugin Name + * + * @return string + */ + public static function getName() { + return self::PLUGIN_NAME; + } + + /** + * Get Plugin Version + * + * @return float,, + */ + public static function getVersion() { + return self::PLUGIN_VERSION; + } + + /** + * Get Plugin Author + * + * @return string + */ + public static function getAuthor() { + return self::PLUGIN_AUTHOR; + } + + /** + * Get Plugin Description + * + * @return string + */ + public static function getDescription() { + return "Plugin offers various Chat-Commands like /gg /hi /afk /rq..."; + } + /** * Load the plugin * @@ -113,6 +158,30 @@ class ChatMessagePlugin implements CommandListener, Plugin { $this->maniaControl->chat->sendChat($msg, null, false); } + /** + * Checks if a Player is in the PlayerList and returns the nickname if he is, can be called per login, pid or nickname or lj for + * (last joined) + * + * @param $login + * @return mixed + */ + private function getTarget($login) { + /** @var Player $player */ + $player = null; + foreach ($this->maniaControl->playerManager->getPlayers() as $player) { + if ($login == $player->login || $login == $player->pid || $login == $player->nickname) { + return $player->nickname; + } + } + + if ($player && $login == 'lj') { + return $player->nickname; + } + + //returns the text given if nothing matches + return $login; + } + /** * Bye Message * @@ -314,7 +383,7 @@ class ChatMessagePlugin implements CommandListener, Plugin { $message = '$39F Thanks for Playing, see you around!$z'; try { $this->maniaControl->client->kick($player->login, $message); - } catch(Exception $e) { + } catch (Exception $e) { $this->maniaControl->errorHandler->triggerDebugNotice("ChatMessagePlugin Debug Line 316: " . $e->getMessage()); // TODO: only possible valid exception should be "wrong login" - throw others (like connection error) $this->maniaControl->chat->sendError('Error occurred: ' . $e->getMessage(), $player->login); @@ -335,7 +404,7 @@ class ChatMessagePlugin implements CommandListener, Plugin { $message = '$39F Thanks for Playing, please come back soon!$z '; try { $this->maniaControl->client->kick($player->login, $message); - } catch(Exception $e) { + } catch (Exception $e) { $this->maniaControl->errorHandler->triggerDebugNotice("ChatMessagePlugin Debug Line " . $e->getLine() . ": " . $e->getMessage()); // TODO: only possible valid exception should be "wrong login" - throw others (like connection error) $this->maniaControl->chat->sendError('Error occurred: ' . $e->getMessage(), $player->login); @@ -361,7 +430,7 @@ class ChatMessagePlugin implements CommandListener, Plugin { // force into spec try { $this->maniaControl->client->forceSpectator($player->login, 3); - } catch(Exception $e) { + } catch (Exception $e) { $this->maniaControl->errorHandler->triggerDebugNotice("ChatMessagePlugin Debug Line " . $e->getLine() . ": " . $e->getMessage()); // TODO: only possible valid exception should be "wrong login" - throw others (like connection error) $this->maniaControl->chat->sendError('Error occurred: ' . $e->getMessage(), $player->login); @@ -371,7 +440,7 @@ class ChatMessagePlugin implements CommandListener, Plugin { // free player slot try { $this->maniaControl->client->spectatorReleasePlayerSlot($player->login); - } catch(Exception $e) { + } catch (Exception $e) { if ($e->getMessage() != 'The player is not a spectator') { $this->maniaControl->errorHandler->triggerDebugNotice("ChatMessagePlugin Debug Line " . $e->getLine() . ": " . $e->getMessage()); // TODO: only possible valid exception should be "wrong login" - throw others (like connection error) @@ -380,73 +449,4 @@ class ChatMessagePlugin implements CommandListener, Plugin { } } } - - /** - * Checks if a Player is in the PlayerList and returns the nickname if he is, can be called per login, pid or nickname or lj for - * (last joined) - * - * @param $login - * @return mixed - */ - private function getTarget($login) { - /** @var Player $player */ - $player = null; - foreach($this->maniaControl->playerManager->getPlayers() as $player) { - if ($login == $player->login || $login == $player->pid || $login == $player->nickname) { - return $player->nickname; - } - } - - if ($player && $login == 'lj') { - return $player->nickname; - } - - //returns the text given if nothing matches - return $login; - } - - /** - * Get plugin id - * - * @return int - */ - public static function getId() { - return self::PLUGIN_ID; - } - - /** - * Get Plugin Name - * - * @return string - */ - public static function getName() { - return self::PLUGIN_NAME; - } - - /** - * Get Plugin Version - * - * @return float,, - */ - public static function getVersion() { - return self::PLUGIN_VERSION; - } - - /** - * Get Plugin Author - * - * @return string - */ - public static function getAuthor() { - return self::PLUGIN_AUTHOR; - } - - /** - * Get Plugin Description - * - * @return string - */ - public static function getDescription() { - return "Plugin offers various Chat-Commands like /gg /hi /afk /rq..."; - } } \ No newline at end of file diff --git a/application/plugins/Donations.php b/application/plugins/Donations.php index 1aacd965..1e2f0c8f 100644 --- a/application/plugins/Donations.php +++ b/application/plugins/Donations.php @@ -12,7 +12,6 @@ use FML\Controls\Quads\Quad_BgsPlayerCard; use FML\Controls\Quads\Quad_Icons128x128_1; use FML\ManiaLink; use FML\Script\Features\Paging; - use ManiaControl\Admin\AuthenticationManager; use ManiaControl\Bills\BillManager; use ManiaControl\Callbacks\CallbackListener; @@ -28,9 +27,9 @@ use ManiaControl\Statistics\StatisticManager; /** * ManiaControl Donation Plugin * - * @author kremsy and steeffeen - * @copyright ManiaControl Copyright © 2014 ManiaControl Team - * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 + * @author ManiaControl Team + * @copyright 2014 ManiaControl Team + * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 */ class DonationPlugin implements CallbackListener, CommandListener, Plugin { /** @@ -70,52 +69,6 @@ class DonationPlugin implements CallbackListener, CommandListener, Plugin { //do nothing } - /** - * @see \ManiaControl\Plugins\Plugin::load() - */ - public function load(ManiaControl $maniaControl) { - $this->maniaControl = $maniaControl; - - // Register for commands - $this->maniaControl->commandManager->registerCommandListener('donate', $this, 'command_Donate', false, 'Donate some planets to the server.'); - $this->maniaControl->commandManager->registerCommandListener('pay', $this, 'command_Pay', true, 'Pays planets from the server to a player.'); - $this->maniaControl->commandManager->registerCommandListener('planets', $this, 'command_GetPlanets', true, 'Checks the planets-balance of the server.'); - $this->maniaControl->commandManager->registerCommandListener('topdons', $this, 'command_TopDons', false, 'Provides an overview of who dontated the most planets.'); - - // Register for callbacks - $this->maniaControl->callbackManager->registerCallbackListener(PlayerManager::CB_PLAYERCONNECT, $this, 'handlePlayerConnect'); - $this->maniaControl->callbackManager->registerCallbackListener(CallbackManager::CB_MP_PLAYERMANIALINKPAGEANSWER, $this, 'handleManialinkPageAnswer'); - - // Define player stats - $this->maniaControl->statisticManager->defineStatMetaData(self::STAT_PLAYER_DONATIONS); - - $this->maniaControl->settingManager->initSetting($this, self::SETTING_DONATE_WIDGET_ACTIVATED, true); - $this->maniaControl->settingManager->initSetting($this, self::SETTING_DONATE_WIDGET_POSX, 156.); - $this->maniaControl->settingManager->initSetting($this, self::SETTING_DONATE_WIDGET_POSY, -31.4); - $this->maniaControl->settingManager->initSetting($this, self::SETTING_DONATE_WIDGET_WIDTH, 6); - $this->maniaControl->settingManager->initSetting($this, self::SETTING_DONATE_WIDGET_HEIGHT, 6); - $this->maniaControl->settingManager->initSetting($this, self::SETTING_DONATION_VALUES, "20,50,100,500,1000,2000"); - $this->maniaControl->settingManager->initSetting($this, self::SETTING_MIN_AMOUNT_SHOWN, 100); - - // Register Stat in Simple StatsList - $this->maniaControl->statisticManager->simpleStatsList->registerStat(self::STAT_PLAYER_DONATIONS, 90, "DP", 15); - - $this->displayWidget(); - return true; - } - - /** - * @see \ManiaControl\Plugins\Plugin::unload() - */ - public function unload() { - $emptyManialink = new ManiaLink(self::MLID_DONATE_WIDGET); - $this->maniaControl->manialinkManager->sendManialink($emptyManialink); - - $this->maniaControl->callbackManager->unregisterCallbackListener($this); - $this->maniaControl->commandManager->unregisterCommandListener($this); - unset($this->maniaControl); - } - /** * @see \ManiaControl\Plugins\Plugin::getId() */ @@ -151,6 +104,40 @@ class DonationPlugin implements CallbackListener, CommandListener, Plugin { return 'Plugin offering commands like /donate, /pay and /planets and a donation widget.'; } + /** + * @see \ManiaControl\Plugins\Plugin::load() + */ + public function load(ManiaControl $maniaControl) { + $this->maniaControl = $maniaControl; + + // Register for commands + $this->maniaControl->commandManager->registerCommandListener('donate', $this, 'command_Donate', false, 'Donate some planets to the server.'); + $this->maniaControl->commandManager->registerCommandListener('pay', $this, 'command_Pay', true, 'Pays planets from the server to a player.'); + $this->maniaControl->commandManager->registerCommandListener('planets', $this, 'command_GetPlanets', true, 'Checks the planets-balance of the server.'); + $this->maniaControl->commandManager->registerCommandListener('topdons', $this, 'command_TopDons', false, 'Provides an overview of who dontated the most planets.'); + + // Register for callbacks + $this->maniaControl->callbackManager->registerCallbackListener(PlayerManager::CB_PLAYERCONNECT, $this, 'handlePlayerConnect'); + $this->maniaControl->callbackManager->registerCallbackListener(CallbackManager::CB_MP_PLAYERMANIALINKPAGEANSWER, $this, 'handleManialinkPageAnswer'); + + // Define player stats + $this->maniaControl->statisticManager->defineStatMetaData(self::STAT_PLAYER_DONATIONS); + + $this->maniaControl->settingManager->initSetting($this, self::SETTING_DONATE_WIDGET_ACTIVATED, true); + $this->maniaControl->settingManager->initSetting($this, self::SETTING_DONATE_WIDGET_POSX, 156.); + $this->maniaControl->settingManager->initSetting($this, self::SETTING_DONATE_WIDGET_POSY, -31.4); + $this->maniaControl->settingManager->initSetting($this, self::SETTING_DONATE_WIDGET_WIDTH, 6); + $this->maniaControl->settingManager->initSetting($this, self::SETTING_DONATE_WIDGET_HEIGHT, 6); + $this->maniaControl->settingManager->initSetting($this, self::SETTING_DONATION_VALUES, "20,50,100,500,1000,2000"); + $this->maniaControl->settingManager->initSetting($this, self::SETTING_MIN_AMOUNT_SHOWN, 100); + + // Register Stat in Simple StatsList + $this->maniaControl->statisticManager->simpleStatsList->registerStat(self::STAT_PLAYER_DONATIONS, 90, "DP", 15); + + $this->displayWidget(); + return true; + } + /** * Display the Widget */ @@ -160,35 +147,6 @@ class DonationPlugin implements CallbackListener, CommandListener, Plugin { } } - /** - * Handle ManialinkPageAnswer Callback - * - * @param array $callback - */ - public function handleManialinkPageAnswer(array $callback) { - $actionId = $callback[1][2]; - $boolSetting = (strpos($actionId, self::ACTION_DONATE_VALUE) === 0); - if (!$boolSetting) { - return; - } - $login = $callback[1][1]; - $player = $this->maniaControl->playerManager->getPlayer($login); - $actionArray = explode(".", $callback[1][2]); - $this->handleDonation($player, intval($actionArray[2])); - } - - /** - * Handle PlayerConnect callback - * - * @param Player $player - */ - public function handlePlayerConnect(Player $player) { - // Display Map Widget - if ($this->maniaControl->settingManager->getSetting($this, self::SETTING_DONATE_WIDGET_ACTIVATED)) { - $this->displayDonateWidget($player->login); - } - } - /** * Displays the Donate Widget * @@ -207,7 +165,7 @@ class DonationPlugin implements CallbackListener, CommandListener, Plugin { $itemMarginFactorY = 1.2; //If game is shootmania lower the icons position by 20 - if($this->maniaControl->mapManager->getCurrentMap()->getGame() == 'sm') { + if ($this->maniaControl->mapManager->getCurrentMap()->getGame() == 'sm') { $posY -= $shootManiaOffset; } @@ -251,7 +209,7 @@ class DonationPlugin implements CallbackListener, CommandListener, Plugin { $quad->setSize(strlen($values) * 2 + count($valueArray) * 1, $itemSize * $itemMarginFactorY); $popoutFrame->add($quad); - $itemQuad->addToggleFeature($popoutFrame); + $itemQuad->addToggleFeature($popoutFrame); // Description Label $descriptionFrame = new Frame(); @@ -269,7 +227,7 @@ class DonationPlugin implements CallbackListener, CommandListener, Plugin { // Add items $x = -2; - foreach(array_reverse($valueArray) as $value) { + foreach (array_reverse($valueArray) as $value) { $label = new Label_Button(); $popoutFrame->add($label); $label->setX($x); @@ -278,8 +236,8 @@ class DonationPlugin implements CallbackListener, CommandListener, Plugin { $label->setTextSize(1.2); $label->setAction(self::ACTION_DONATE_VALUE . "." . $value); $label->setStyle(Label_Text::STYLE_TextCardSmall); - $description = "Donate {$value} Planets"; - $label->addTooltipLabelFeature($descriptionLabel, $description); + $description = "Donate {$value} Planets"; + $label->addTooltipLabelFeature($descriptionLabel, $description); $x -= strlen($value) * 2 + 1.7; } @@ -288,6 +246,98 @@ class DonationPlugin implements CallbackListener, CommandListener, Plugin { $this->maniaControl->manialinkManager->sendManialink($maniaLink, $login); } + /** + * @see \ManiaControl\Plugins\Plugin::unload() + */ + public function unload() { + $emptyManialink = new ManiaLink(self::MLID_DONATE_WIDGET); + $this->maniaControl->manialinkManager->sendManialink($emptyManialink); + + $this->maniaControl->callbackManager->unregisterCallbackListener($this); + $this->maniaControl->commandManager->unregisterCommandListener($this); + unset($this->maniaControl); + } + + /** + * Handle ManialinkPageAnswer Callback + * + * @param array $callback + */ + public function handleManialinkPageAnswer(array $callback) { + $actionId = $callback[1][2]; + $boolSetting = (strpos($actionId, self::ACTION_DONATE_VALUE) === 0); + if (!$boolSetting) { + return; + } + $login = $callback[1][1]; + $player = $this->maniaControl->playerManager->getPlayer($login); + $actionArray = explode(".", $callback[1][2]); + $this->handleDonation($player, intval($actionArray[2])); + } + + /** + * Handle a Player Donation + * + * @param Player $player + * @param int $amount + * @param string $receiver + * @param string $receiverName + * @return bool + */ + private function handleDonation(Player $player, $amount, $receiver = '', $receiverName = null) { + + if (!$receiverName) { + $serverName = $this->maniaControl->client->getServerName(); + $message = 'Donate ' . $amount . ' Planets to $<' . $serverName . '$>?'; + } else { + $message = 'Donate ' . $amount . ' Planets to $<' . $receiverName . '$>?'; + } + + //Send and Handle the Bill + $self = $this; + $this->maniaControl->billManager->sendBill(function ($data, $status) use (&$self, &$player, $amount, $receiver) { + switch ($status) { + case BillManager::DONATED_TO_SERVER: + if ($self->maniaControl->settingManager->getSetting($self, DonationPlugin::SETTING_ANNOUNCE_SERVERDONATION, true) && $amount >= $self->maniaControl->settingManager->getSetting($self, DonationPlugin::SETTING_MIN_AMOUNT_SHOWN, true)) { + $login = null; + $message = '$<' . $player->nickname . '$> donated ' . $amount . ' Planets! Thanks.'; + } else { + $login = $player->login; + $message = 'Donation successful! Thanks.'; + } + $self->maniaControl->chat->sendSuccess($message, $login); + $self->maniaControl->statisticManager->insertStat(DonationPlugin::STAT_PLAYER_DONATIONS, $player, $self->maniaControl->server->index, $amount); + break; + case BillManager::DONATED_TO_RECEIVER: + $message = "Successfully donated {$amount} to '{$receiver}'!"; + $self->maniaControl->chat->sendSuccess($message, $player->login); + break; + case BillManager::PLAYER_REFUSED_DONATION: + $message = 'Transaction cancelled.'; + $self->maniaControl->chat->sendError($message, $player->login); + break; + case BillManager::ERROR_WHILE_TRANSACTION: + $message = $data; + $self->maniaControl->chat->sendError($message, $player->login); + break; + } + }, $player, $amount, $message); + + return true; + } + + /** + * Handle PlayerConnect callback + * + * @param Player $player + */ + public function handlePlayerConnect(Player $player) { + // Display Map Widget + if ($this->maniaControl->settingManager->getSetting($this, self::SETTING_DONATE_WIDGET_ACTIVATED)) { + $this->displayDonateWidget($player->login); + } + } + /** * Handle /donate command * @@ -320,54 +370,14 @@ class DonationPlugin implements CallbackListener, CommandListener, Plugin { } /** - * Handle a Player Donation + * Send an usage example for /donate to the player * * @param Player $player - * @param int $amount - * @param string $receiver - * @param string $receiverName - * @return bool + * @return boolean */ - private function handleDonation(Player $player, $amount, $receiver = '', $receiverName = null) { - - if (!$receiverName) { - $serverName = $this->maniaControl->client->getServerName(); - $message = 'Donate ' . $amount . ' Planets to $<' . $serverName . '$>?'; - } else { - $message = 'Donate ' . $amount . ' Planets to $<' . $receiverName . '$>?'; - } - - //Send and Handle the Bill - $self = $this; - $this->maniaControl->billManager->sendBill(function ($data, $status) use (&$self, &$player, $amount, $receiver) { - switch($status) { - case BillManager::DONATED_TO_SERVER: - if ($self->maniaControl->settingManager->getSetting($self, DonationPlugin::SETTING_ANNOUNCE_SERVERDONATION, true) && $amount >= $self->maniaControl->settingManager->getSetting($self, DonationPlugin::SETTING_MIN_AMOUNT_SHOWN, true)) { - $login = null; - $message = '$<' . $player->nickname . '$> donated ' . $amount . ' Planets! Thanks.'; - } else { - $login = $player->login; - $message = 'Donation successful! Thanks.'; - } - $self->maniaControl->chat->sendSuccess($message, $login); - $self->maniaControl->statisticManager->insertStat(DonationPlugin::STAT_PLAYER_DONATIONS, $player, $self->maniaControl->server->index, $amount); - break; - case BillManager::DONATED_TO_RECEIVER: - $message = "Successfully donated {$amount} to '{$receiver}'!"; - $self->maniaControl->chat->sendSuccess($message, $player->login); - break; - case BillManager::PLAYER_REFUSED_DONATION: - $message = 'Transaction cancelled.'; - $self->maniaControl->chat->sendError($message, $player->login); - break; - case BillManager::ERROR_WHILE_TRANSACTION: - $message = $data; - $self->maniaControl->chat->sendError($message, $player->login); - break; - } - }, $player, $amount, $message); - - return true; + private function sendDonateUsageExample(Player $player) { + $message = "Usage Example: '/donate 100'"; + return $this->maniaControl->chat->sendChat($message, $player->login); } /** @@ -402,7 +412,7 @@ class DonationPlugin implements CallbackListener, CommandListener, Plugin { $self = $this; $this->maniaControl->billManager->sendPlanets(function ($data, $status) use (&$self, &$player, $amount, $receiver) { - switch($status) { + switch ($status) { case BillManager::PAYED_FROM_SERVER: $message = "Successfully payed out {$amount} to '{$receiver}'!"; $self->maniaControl->chat->sendSuccess($message, $player->login); @@ -421,6 +431,17 @@ class DonationPlugin implements CallbackListener, CommandListener, Plugin { return true; } + /** + * Send an usage example for /pay to the player + * + * @param Player $player + * @return boolean + */ + private function sendPayUsageExample(Player $player) { + $message = "Usage Example: '/pay 100 login'"; + return $this->maniaControl->chat->sendChat($message, $player->login); + } + /** * Handle //getplanets command * @@ -438,28 +459,6 @@ class DonationPlugin implements CallbackListener, CommandListener, Plugin { return $this->maniaControl->chat->sendInformation($message, $player->login); } - /** - * Send an usage example for /donate to the player - * - * @param Player $player - * @return boolean - */ - private function sendDonateUsageExample(Player $player) { - $message = "Usage Example: '/donate 100'"; - return $this->maniaControl->chat->sendChat($message, $player->login); - } - - /** - * Send an usage example for /pay to the player - * - * @param Player $player - * @return boolean - */ - private function sendPayUsageExample(Player $player) { - $message = "Usage Example: '/pay 100 login'"; - return $this->maniaControl->chat->sendChat($message, $player->login); - } - /** * Handles the /topdons command * @@ -477,7 +476,7 @@ class DonationPlugin implements CallbackListener, CommandListener, Plugin { * @return null */ private function showTopDonsList(Player $player) { - $query = "SELECT * FROM `".StatisticManager::TABLE_STATISTICS."` WHERE `statId` = 3 ORDER BY `value` DESC LIMIT 0, 100"; + $query = "SELECT * FROM `" . StatisticManager::TABLE_STATISTICS . "` WHERE `statId` = 3 ORDER BY `value` DESC LIMIT 0, 100"; $mysqli = $this->maniaControl->database->mysqli; $result = $mysqli->query($query); if ($mysqli->error) { @@ -490,8 +489,8 @@ class DonationPlugin implements CallbackListener, CommandListener, Plugin { // create manialink $maniaLink = new ManiaLink(ManialinkManager::MAIN_MLID); - $script = $maniaLink->getScript(); - $paging = new Paging(); + $script = $maniaLink->getScript(); + $paging = new Paging(); $script->addFeature($paging); // Main frame @@ -516,7 +515,7 @@ class DonationPlugin implements CallbackListener, CommandListener, Plugin { $i = 1; $y = $y - 10; $pageFrames = array(); - while($donator = $result->fetch_object()) { + while ($donator = $result->fetch_object()) { if (!isset($pageFrame)) { $pageFrame = new Frame(); $frame->add($pageFrame); @@ -542,7 +541,7 @@ class DonationPlugin implements CallbackListener, CommandListener, Plugin { } $donatingPlayer = $this->maniaControl->playerManager->getPlayerByIndex($donator->playerId); - $array = array($i => $x + 5, $donatingPlayer->nickname => $x + 18, $donator->value => $x + 70); + $array = array($i => $x + 5, $donatingPlayer->nickname => $x + 18, $donator->value => $x + 70); $this->maniaControl->manialinkManager->labelLine($playerFrame, $array); $y -= 4; diff --git a/application/plugins/Karma.php b/application/plugins/Karma.php index 543bfca4..188e09c6 100644 --- a/application/plugins/Karma.php +++ b/application/plugins/Karma.php @@ -22,8 +22,8 @@ use ManiaControl\Settings\SettingManager; /** * ManiaControl Karma Plugin * - * @author kremsy and steeffeen - * @copyright ManiaControl Copyright © 2014 ManiaControl Team + * @author ManiaControl Team + * @copyright 2014 ManiaControl Team * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 */ class KarmaPlugin implements CallbackListener, TimerListener, Plugin { @@ -81,11 +81,46 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin { $maniaControl->settingManager->initSetting(get_class(), self::SETTING_MX_KARMA_IMPORTING, true); $maniaControl->settingManager->initSetting(get_class(), self::SETTING_WIDGET_DISPLAY_MX, true); $servers = $maniaControl->server->getAllServers(); - foreach($servers as $server) { + foreach ($servers as $server) { $maniaControl->settingManager->initSetting(get_class(), '$l[http://karma.mania-exchange.com/auth/getapikey?server=' . $server->login . ']MX Karma Code for ' . $server->login . '$l', ''); } } + /** + * @see \ManiaControl\Plugins\Plugin::getId() + */ + public static function getId() { + return self::ID; + } + + /** + * @see \ManiaControl\Plugins\Plugin::getName() + */ + public static function getName() { + return 'Karma Plugin'; + } + + /** + * @see \ManiaControl\Plugins\Plugin::getVersion() + */ + public static function getVersion() { + return self::VERSION; + } + + /** + * @see \ManiaControl\Plugins\Plugin::getAuthor() + */ + public static function getAuthor() { + return 'steeffeen and kremsy'; + } + + /** + * @see \ManiaControl\Plugins\Plugin::getDescription() + */ + public static function getDescription() { + return 'Plugin offering Karma Voting for Maps.'; + } + /** * @see \ManiaControl\Plugins\Plugin::load() */ @@ -129,6 +164,221 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin { return true; } + /** + * Create necessary database tables + */ + private function initTables() { + $mysqli = $this->maniaControl->database->mysqli; + + // Create local table + $query = "CREATE TABLE IF NOT EXISTS `" . self::TABLE_KARMA . "` ( + `index` int(11) NOT NULL AUTO_INCREMENT, + `mapIndex` int(11) NOT NULL, + `playerIndex` int(11) NOT NULL, + `vote` float NOT NULL DEFAULT '-1', + `changed` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (`index`), + UNIQUE KEY `player_map_vote` (`mapIndex`, `playerIndex`) + ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='Save players map votes' AUTO_INCREMENT=1;"; + $mysqli->query($query); + if ($mysqli->error) { + trigger_error($mysqli->error, E_USER_ERROR); + } + + // Migrate settings + $this->maniaControl->database->migrationHelper->transferSettings('KarmaPlugin', $this); + + if (!$this->maniaControl->settingManager->getSetting($this, self::SETTING_MX_KARMA_ACTIVATED)) { + return; + } + + // Create mx table + $query = "CREATE TABLE IF NOT EXISTS `" . self::MX_IMPORT_TABLE . "` ( + `index` int(11) NOT NULL AUTO_INCREMENT, + `mapIndex` int(11) NOT NULL, + `mapImported` tinyint(1) NOT NULL, + `time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (`index`), + UNIQUE KEY `mapIndex` (`mapIndex`) + ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='MX Karma Import Table' AUTO_INCREMENT=1;"; + $mysqli->query($query); + if ($mysqli->error) { + trigger_error($mysqli->error, E_USER_ERROR); + } + } + + /** + * Open a Mx Karma Session + */ + private function mxKarmaOpenSession() { + if (!$this->maniaControl->settingManager->getSetting($this, self::SETTING_MX_KARMA_ACTIVATED)) { + return; + } + + $serverLogin = $this->maniaControl->server->login; + $mxKarmaCode = $this->maniaControl->settingManager->getSetting($this, '$l[http://karma.mania-exchange.com/auth/getapikey?server=' . $serverLogin . ']MX Karma Code for ' . $serverLogin . '$l'); + + if ($mxKarmaCode == '') { + return; + } + + $applicationIdentifier = 'ManiaControl v' . ManiaControl::VERSION; + $testMode = 'true'; + + $query = self::MX_KARMA_URL . self::MX_KARMA_STARTSESSION; + $query .= '?serverLogin=' . $serverLogin; + $query .= '&applicationIdentifier=' . urlencode($applicationIdentifier); + $query .= '&testMode=' . $testMode; + + $this->mxKarma['connectionInProgress'] = true; + + $self = $this; + $this->maniaControl->fileReader->loadFile($query, function ($data, $error) use (&$self, $mxKarmaCode) { + if (!$error) { + $data = json_decode($data); + if ($data->success) { + $self->mxKarma['session'] = $data->data; + $self->activateSession($mxKarmaCode); + } else { + $self->maniaControl->log("Error while authenticating on Mania-Exchange Karma"); + // TODO remove temp trigger + $self->maniaControl->errorHandler->triggerDebugNotice("Error while authenticating on Mania-Exchange Karma " . $data->data->message); + $self->mxKarma['connectionInProgress'] = false; + } + } else { + $self->maniaControl->log($error); + // TODO remove temp trigger + $self->maniaControl->errorHandler->triggerDebugNotice("Error while authenticating on Mania-Exchange Karma " . $error); + $self->mxKarma['connectionInProgress'] = false; + } + }, "application/json", 1000); + } + + /** + * Activates the MX-Karma Session + * + * @param $mxKarmaCode + */ + private function activateSession($mxKarmaCode) { + $hash = $this->buildActivationHash($this->mxKarma['session']->sessionSeed, $mxKarmaCode); + + $query = self::MX_KARMA_URL . self::MX_KARMA_ACTIVATESESSION; + $query .= '?sessionKey=' . urlencode($this->mxKarma['session']->sessionKey); + $query .= '&activationHash=' . urlencode($hash); + + $self = $this; + $this->maniaControl->fileReader->loadFile($query, function ($data, $error) use (&$self, $query) { + if (!$error) { + $data = json_decode($data); + if ($data->success && $data->data->activated) { + $self->maniaControl->log("Successfully authenticated on Mania-Exchange Karma"); + $self->mxKarma['connectionInProgress'] = false; + + // Fetch the Mx Karma Votes + $self->getMxKarmaVotes(); + } else { + $self->maniaControl->log("Error while authenticating on Mania-Exchange Karma " . $data->data->message); + // TODO remove temp trigger + $self->maniaControl->errorHandler->triggerDebugNotice("Error while authenticating on Mania-Exchange Karma " . $data->data->message . " url Query " . $query); + $self->mxKarma['connectionInProgress'] = false; + } + } else { + // TODO remove temp trigger + $self->maniaControl->errorHandler->triggerDebugNotice("Error while authenticating on Mania-Exchange Karma " . $error); + $self->maniaControl->log($error); + $self->mxKarma['connectionInProgress'] = false; + } + }, "application/json", 1000); + } + + /** + * Builds a sha512 activation Hash for the MX-Karma + * + * @param $sessionSeed + * @param $mxKey + * @return string + */ + private function buildActivationHash($sessionSeed, $mxKey) { + return hash('sha512', $mxKey . $sessionSeed); + } + + /** + * Fetch the mxKarmaVotes for the current map + */ + public function getMxKarmaVotes(Player $player = null) { + if (!$this->maniaControl->settingManager->getSetting($this, self::SETTING_MX_KARMA_ACTIVATED)) { + return; + } + + if (!isset($this->mxKarma['session'])) { + if (!isset($this->mxKarma['connectionInProgress']) || !$this->mxKarma['connectionInProgress']) { + $this->mxKarmaOpenSession(); + } + return; + } + + $map = $this->maniaControl->mapManager->getCurrentMap(); + + $properties = array(); + + $gameMode = $this->maniaControl->server->getGameMode(true); + if ($gameMode == 'Script') { + $scriptName = $this->maniaControl->client->getScriptName(); + $properties['gamemode'] = $scriptName["CurrentValue"]; + } else { + $properties['gamemode'] = $gameMode; + } + + $properties['titleid'] = $this->maniaControl->server->titleId; + $properties['mapuid'] = $map->uid; + + if (!$player) { + $properties['getvotesonly'] = false; + $properties['playerlogins'] = array(); + foreach ($this->maniaControl->playerManager->getPlayers() as $plyr) { + /** + * @var Player $player + */ + $properties['playerlogins'][] = $plyr->login; + } + } else { + $properties['getvotesonly'] = true; + $properties['playerlogins'] = array($player->login); + } + + $content = json_encode($properties); + $self = $this; + $this->maniaControl->fileReader->postData(self::MX_KARMA_URL . self::MX_KARMA_GETMAPRATING . "?sessionKey=" . urlencode($this->mxKarma['session']->sessionKey), function ($data, $error) use (&$self, &$player) { + if (!$error) { + $data = json_decode($data); + if ($data->success) { + + // Fetch averages if its for the whole server + if (!$player) { + $self->mxKarma["voteCount"] = $data->data->votecount; + $self->mxKarma["voteAverage"] = $data->data->voteaverage; + $self->mxKarma["modeVoteCount"] = $data->data->modevotecount; + $self->mxKarma["modeVoteAverage"] = $data->data->modevoteaverage; + } + + foreach ($data->data->votes as $votes) { + $self->mxKarma["votes"][$votes->login] = $votes->vote; + } + + $self->updateManialink = true; + $self->maniaControl->callbackManager->triggerCallback($self::CB_KARMA_MXUPDATED, $self->mxKarma); + $self->maniaControl->log("MX-Karma Votes successfully fetched"); + } else { + $self->maniaControl->log("Error while fetching votes: " . $data->data->message); + // TODO remove temp trigger + $self->maniaControl->errorHandler->triggerDebugNotice("Error while fetching votes: " . $data->data->message . " " . KarmaPlugin::MX_KARMA_URL . KarmaPlugin::MX_KARMA_SAVEVOTES . "?sessionKey=" . urlencode($self->mxKarma['session']->sessionKey)); + } + } else { + $self->maniaControl->log($error); + } + }, $content, false, 'application/json'); + } + /** * @see \ManiaControl\Plugins\Plugin::unload() */ @@ -139,112 +389,6 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin { unset($this->maniaControl); } - /** - * @see \ManiaControl\Plugins\Plugin::getId() - */ - public static function getId() { - return self::ID; - } - - /** - * @see \ManiaControl\Plugins\Plugin::getName() - */ - public static function getName() { - return 'Karma Plugin'; - } - - /** - * @see \ManiaControl\Plugins\Plugin::getVersion() - */ - public static function getVersion() { - return self::VERSION; - } - - /** - * @see \ManiaControl\Plugins\Plugin::getAuthor() - */ - public static function getAuthor() { - return 'steeffeen and kremsy'; - } - - /** - * @see \ManiaControl\Plugins\Plugin::getDescription() - */ - public static function getDescription() { - return 'Plugin offering Karma Voting for Maps.'; - } - - /** - * Handle ManiaControl 1 Second callback - * - * @param $time - */ - public function handle1Second($time) { - if (!$this->updateManialink) { - return; - } - - $displayMxKarma = $this->maniaControl->settingManager->getSetting($this, self::SETTING_WIDGET_DISPLAY_MX); - - // Get players - $players = $this->updateManialink; - if ($players === true) { - $players = $this->maniaControl->playerManager->getPlayers(); - } - $this->updateManialink = false; - - // Get map karma - $map = $this->maniaControl->mapManager->getCurrentMap(); - - // Display the mx Karma if the setting is choosen and the MX session is available - if ($displayMxKarma && isset($this->mxKarma['session']) && isset($this->mxKarma['voteCount'])) { - $karma = $this->mxKarma['modeVoteAverage'] / 100; - $voteCount = $this->mxKarma['modeVoteCount']; - } else { - $karma = $this->getMapKarma($map); - $votes = $this->getMapVotes($map); - $voteCount = $votes['count']; - } - - if ($this->maniaControl->settingManager->getSetting($this, self::SETTING_WIDGET_ENABLE)) { - // Build karma manialink - $this->buildManialink(); - - // Update karma gauge & label - /** - * @var Gauge $karmaGauge - */ - $karmaGauge = $this->manialink->karmaGauge; - /** - * @var Label $karmaLabel - */ - $karmaLabel = $this->manialink->karmaLabel; - if (is_numeric($karma) && $voteCount > 0) { - $karma = floatval($karma); - $karmaGauge->setRatio($karma + 0.15 - $karma * 0.15); - $karmaColor = ColorUtil::floatToStatusColor($karma); - $karmaGauge->setColor($karmaColor . '7'); - $karmaLabel->setText(' ' . round($karma * 100.) . '% (' . $voteCount . ')'); - } else { - $karmaGauge->setRatio(0.); - $karmaGauge->setColor('00fb'); - $karmaLabel->setText('-'); - } - - // Loop players - foreach($players as $login => $player) { - // Get player vote - // TODO: show the player his own vote in some way - // $vote = $this->getPlayerVote($player, $map); - // $votesFrame = $this->manialink->votesFrame; - // $votesFrame->removeChildren(); - - // Send manialink - $this->maniaControl->manialinkManager->sendManialink($this->manialink, $login); - } - } - } - /** * Handle BeginMap ManiaControl callback * @@ -254,7 +398,7 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin { // send Map Karma to MX from previous Map if (isset($this->mxKarma['map'])) { $votes = array(); - foreach($this->mxKarma['votes'] as $login => $value) { + foreach ($this->mxKarma['votes'] as $login => $value) { $player = $this->maniaControl->playerManager->getPlayer($login); array_push($votes, array("login" => $login, "nickname" => $player->rawNickname, "vote" => $value)); } @@ -270,6 +414,67 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin { $this->getMxKarmaVotes(); } + /** + * Post the Karma votes to MX-Karma + * + * @param Map $map + * @param array $votes + * @param bool $import + */ + private function postKarmaVotes(Map $map, array $votes, $import = false) { + if (!isset($this->mxKarma['session'])) { + if (!isset($this->mxKarma['connectionInProgress']) || !$this->mxKarma['connectionInProgress']) { + $this->mxKarmaOpenSession(); + } + return; + } + + $gameMode = $this->maniaControl->server->getGameMode(true); + + if (count($votes) == 0) { + return; + } + + $properties = array(); + if ($gameMode == 'Script') { + $scriptName = $this->maniaControl->client->getScriptName(); + $properties['gamemode'] = $scriptName["CurrentValue"]; + } else { + $properties['gamemode'] = $gameMode; + } + + if ($import) { + $properties['maptime'] = 0; + } else { + $properties['maptime'] = time() - $this->mxKarma['startTime']; + } + + $properties['votes'] = $votes; + $properties['titleid'] = $this->maniaControl->server->titleId; + $properties['mapname'] = $map->rawName; + $properties['mapuid'] = $map->uid; + $properties['mapauthor'] = $map->authorLogin; + $properties['isimport'] = $import; + + $content = json_encode($properties); + + $self = $this; + $this->maniaControl->fileReader->postData(self::MX_KARMA_URL . self::MX_KARMA_SAVEVOTES . "?sessionKey=" . urlencode($this->mxKarma['session']->sessionKey), function ($data, $error) use (&$self) { + if (!$error) { + $data = json_decode($data); + if ($data->success) { + $self->maniaControl->log("Votes successfully permitted"); + } else { + $self->maniaControl->log("Error while updating votes: " . $data->data->message); + // TODO remove temp trigger + $self->maniaControl->errorHandler->triggerDebugNotice("Error while updating votes: " . $data->data->message . " " . KarmaPlugin::MX_KARMA_URL . $self::MX_KARMA_SAVEVOTES . "?sessionKey=" . urlencode($self->mxKarma['session']->sessionKey)); + } + } else { + $self->maniaControl->log($error); + } + }, $content, false, 'application/json'); + } + /** * Handle PlayerConnect callback * @@ -285,6 +490,21 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin { $this->getMxKarmaVotes($player); } + /** + * Query the player to update the manialink + * + * @param Player $player + */ + private function queryManialinkUpdateFor(Player $player) { + if ($this->updateManialink === true) { + return; + } + if (!is_array($this->updateManialink)) { + $this->updateManialink = array(); + } + $this->updateManialink[$player->login] = $player; + } + /** * Handle PlayerChat callback * @@ -379,61 +599,31 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin { } /** - * Query the player to update the manialink + * Get the current vote of the player for the map * * @param Player $player + * @param Map $map + * @return int */ - private function queryManialinkUpdateFor(Player $player) { - if ($this->updateManialink === true) { - return; - } - if (!is_array($this->updateManialink)) { - $this->updateManialink = array(); - } - $this->updateManialink[$player->login] = $player; - } - - /** - * Create necessary database tables - */ - private function initTables() { + public function getPlayerVote(Player $player, Map $map) { $mysqli = $this->maniaControl->database->mysqli; - - // Create local table - $query = "CREATE TABLE IF NOT EXISTS `" . self::TABLE_KARMA . "` ( - `index` int(11) NOT NULL AUTO_INCREMENT, - `mapIndex` int(11) NOT NULL, - `playerIndex` int(11) NOT NULL, - `vote` float NOT NULL DEFAULT '-1', - `changed` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - PRIMARY KEY (`index`), - UNIQUE KEY `player_map_vote` (`mapIndex`, `playerIndex`) - ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='Save players map votes' AUTO_INCREMENT=1;"; - $mysqli->query($query); + $query = "SELECT * FROM `" . self::TABLE_KARMA . "` + WHERE `playerIndex` = {$player->index} + AND `mapIndex` = {$map->index} + AND `vote` >= 0;"; + $result = $mysqli->query($query); if ($mysqli->error) { - trigger_error($mysqli->error, E_USER_ERROR); + trigger_error($mysqli->error); + return false; } - - // Migrate settings - $this->maniaControl->database->migrationHelper->transferSettings('KarmaPlugin', $this); - - if (!$this->maniaControl->settingManager->getSetting($this, self::SETTING_MX_KARMA_ACTIVATED)) { - return; - } - - // Create mx table - $query = "CREATE TABLE IF NOT EXISTS `" . self::MX_IMPORT_TABLE . "` ( - `index` int(11) NOT NULL AUTO_INCREMENT, - `mapIndex` int(11) NOT NULL, - `mapImported` tinyint(1) NOT NULL, - `time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - PRIMARY KEY (`index`), - UNIQUE KEY `mapIndex` (`mapIndex`) - ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='MX Karma Import Table' AUTO_INCREMENT=1;"; - $mysqli->query($query); - if ($mysqli->error) { - trigger_error($mysqli->error, E_USER_ERROR); + if ($result->num_rows <= 0) { + $result->free(); + return false; } + $item = $result->fetch_object(); + $result->free(); + $vote = $item->vote; + return floatval($vote); } /** @@ -466,31 +656,134 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin { } /** - * Get the current vote of the player for the map + * Get all players votes * - * @param Player $player - * @param Map $map - * @return int + * @param Map $map + * @return array */ - public function getPlayerVote(Player $player, Map $map) { + public function getMapPlayerVotes(Map $map) { $mysqli = $this->maniaControl->database->mysqli; $query = "SELECT * FROM `" . self::TABLE_KARMA . "` - WHERE `playerIndex` = {$player->index} - AND `mapIndex` = {$map->index} - AND `vote` >= 0;"; + WHERE `mapIndex` = {$map->index} + AND `vote` >= 0"; $result = $mysqli->query($query); if ($mysqli->error) { trigger_error($mysqli->error); return false; } - if ($result->num_rows <= 0) { - $result->free(); - return false; + + $votes = array(); + while ($vote = $result->fetch_object()) { + $player = $this->maniaControl->playerManager->getPlayerByIndex($vote->playerIndex); + $karma = $vote->vote; + $votes[] = array('player' => $player, 'karma' => $karma); + } + + usort($votes, function ($a, $b) { + return $a['karma'] - $b['karma']; + }); + $votes = array_reverse($votes); + + return $votes; + } + + /** + * Update Settings + * + * @param $class + * @param $settingName + * @param $value + */ + public function updateSettings($class, $settingName, $value) { + if (!$class = get_class()) { + return; + } + + $serverLogin = $this->maniaControl->server->login; + if ($settingName == '$l[http://karma.mania-exchange.com/auth/getapikey?server=' . $serverLogin . ']MX Karma Code for ' . $serverLogin . '$l') { + $this->mxKarmaOpenSession(); + } + + if ($settingName == 'Enable Karma Widget' && $value == true) { + $this->updateManialink = true; + $this->handle1Second(time()); + } elseif ($settingName == 'Enable Karma Widget' && $value == false) { + $this->updateManialink = false; + $ml = new ManiaLink(self::MLID_KARMA); + $mltext = $ml->render()->saveXML(); + $this->maniaControl->manialinkManager->sendManialink($mltext); + } + } + + /** + * Handle ManiaControl 1 Second callback + * + * @param $time + */ + public function handle1Second($time) { + if (!$this->updateManialink) { + return; + } + + $displayMxKarma = $this->maniaControl->settingManager->getSetting($this, self::SETTING_WIDGET_DISPLAY_MX); + + // Get players + $players = $this->updateManialink; + if ($players === true) { + $players = $this->maniaControl->playerManager->getPlayers(); + } + $this->updateManialink = false; + + // Get map karma + $map = $this->maniaControl->mapManager->getCurrentMap(); + + // Display the mx Karma if the setting is choosen and the MX session is available + if ($displayMxKarma && isset($this->mxKarma['session']) && isset($this->mxKarma['voteCount'])) { + $karma = $this->mxKarma['modeVoteAverage'] / 100; + $voteCount = $this->mxKarma['modeVoteCount']; + } else { + $karma = $this->getMapKarma($map); + $votes = $this->getMapVotes($map); + $voteCount = $votes['count']; + } + + if ($this->maniaControl->settingManager->getSetting($this, self::SETTING_WIDGET_ENABLE)) { + // Build karma manialink + $this->buildManialink(); + + // Update karma gauge & label + /** + * @var Gauge $karmaGauge + */ + $karmaGauge = $this->manialink->karmaGauge; + /** + * @var Label $karmaLabel + */ + $karmaLabel = $this->manialink->karmaLabel; + if (is_numeric($karma) && $voteCount > 0) { + $karma = floatval($karma); + $karmaGauge->setRatio($karma + 0.15 - $karma * 0.15); + $karmaColor = ColorUtil::floatToStatusColor($karma); + $karmaGauge->setColor($karmaColor . '7'); + $karmaLabel->setText(' ' . round($karma * 100.) . '% (' . $voteCount . ')'); + } else { + $karmaGauge->setRatio(0.); + $karmaGauge->setColor('00fb'); + $karmaLabel->setText('-'); + } + + // Loop players + foreach ($players as $login => $player) { + // Get player vote + // TODO: show the player his own vote in some way + // $vote = $this->getPlayerVote($player, $map); + // $votesFrame = $this->manialink->votesFrame; + // $votesFrame->removeChildren(); + + // Send manialink + $this->maniaControl->manialinkManager->sendManialink($this->manialink, $login); + } } - $item = $result->fetch_object(); - $result->free(); - $vote = $item->vote; - return floatval($vote); } /** @@ -541,7 +834,7 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin { } $votes = array(); $count = 0; - while($vote = $result->fetch_object()) { + while ($vote = $result->fetch_object()) { $votes[$vote->vote] = $vote; $count += $vote->count; } @@ -550,38 +843,6 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin { return $votes; } - /** - * Get all players votes - * - * @param Map $map - * @return array - */ - public function getMapPlayerVotes(Map $map) { - $mysqli = $this->maniaControl->database->mysqli; - $query = "SELECT * FROM `" . self::TABLE_KARMA . "` - WHERE `mapIndex` = {$map->index} - AND `vote` >= 0"; - $result = $mysqli->query($query); - if ($mysqli->error) { - trigger_error($mysqli->error); - return false; - } - - $votes = array(); - while($vote = $result->fetch_object()) { - $player = $this->maniaControl->playerManager->getPlayerByIndex($vote->playerIndex); - $karma = $vote->vote; - $votes[] = array('player' => $player, 'karma' => $karma); - } - - usort($votes, function($a, $b) { - return $a['karma'] - $b['karma']; - }); - $votes = array_reverse($votes); - - return $votes; - } - /** * Build karma voting manialink if necessary * @@ -644,195 +905,6 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin { $this->manialink = $manialink; } - /** - * Update Settings - * - * @param $class - * @param $settingName - * @param $value - */ - public function updateSettings($class, $settingName, $value) { - if (!$class = get_class()) { - return; - } - - $serverLogin = $this->maniaControl->server->login; - if ($settingName == '$l[http://karma.mania-exchange.com/auth/getapikey?server=' . $serverLogin . ']MX Karma Code for ' . $serverLogin . '$l') { - $this->mxKarmaOpenSession(); - } - - if ($settingName == 'Enable Karma Widget' && $value == true) { - $this->updateManialink = true; - $this->handle1Second(time()); - } elseif ($settingName == 'Enable Karma Widget' && $value == false) { - $this->updateManialink = false; - $ml = new ManiaLink(self::MLID_KARMA); - $mltext = $ml->render()->saveXML(); - $this->maniaControl->manialinkManager->sendManialink($mltext); - } - } - - /** - * Open a Mx Karma Session - */ - private function mxKarmaOpenSession() { - if (!$this->maniaControl->settingManager->getSetting($this, self::SETTING_MX_KARMA_ACTIVATED)) { - return; - } - - $serverLogin = $this->maniaControl->server->login; - $mxKarmaCode = $this->maniaControl->settingManager->getSetting($this, '$l[http://karma.mania-exchange.com/auth/getapikey?server=' . $serverLogin . ']MX Karma Code for ' . $serverLogin . '$l'); - - if ($mxKarmaCode == '') { - return; - } - - $applicationIdentifier = 'ManiaControl v' . ManiaControl::VERSION; - $testMode = 'true'; - - $query = self::MX_KARMA_URL . self::MX_KARMA_STARTSESSION; - $query .= '?serverLogin=' . $serverLogin; - $query .= '&applicationIdentifier=' . urlencode($applicationIdentifier); - $query .= '&testMode=' . $testMode; - - $this->mxKarma['connectionInProgress'] = true; - - $self = $this; - $this->maniaControl->fileReader->loadFile($query, function ($data, $error) use (&$self, $mxKarmaCode) { - if (!$error) { - $data = json_decode($data); - if ($data->success) { - $self->mxKarma['session'] = $data->data; - $self->activateSession($mxKarmaCode); - } else { - $self->maniaControl->log("Error while authenticating on Mania-Exchange Karma"); - // TODO remove temp trigger - $self->maniaControl->errorHandler->triggerDebugNotice("Error while authenticating on Mania-Exchange Karma " . $data->data->message); - $self->mxKarma['connectionInProgress'] = false; - } - } else { - $self->maniaControl->log($error); - // TODO remove temp trigger - $self->maniaControl->errorHandler->triggerDebugNotice("Error while authenticating on Mania-Exchange Karma " . $error); - $self->mxKarma['connectionInProgress'] = false; - } - }, "application/json", 1000); - } - - /** - * Activates the MX-Karma Session - * - * @param $mxKarmaCode - */ - private function activateSession($mxKarmaCode) { - $hash = $this->buildActivationHash($this->mxKarma['session']->sessionSeed, $mxKarmaCode); - - $query = self::MX_KARMA_URL . self::MX_KARMA_ACTIVATESESSION; - $query .= '?sessionKey=' . urlencode($this->mxKarma['session']->sessionKey); - $query .= '&activationHash=' . urlencode($hash); - - $self = $this; - $this->maniaControl->fileReader->loadFile($query, function ($data, $error) use (&$self, $query) { - if (!$error) { - $data = json_decode($data); - if ($data->success && $data->data->activated) { - $self->maniaControl->log("Successfully authenticated on Mania-Exchange Karma"); - $self->mxKarma['connectionInProgress'] = false; - - // Fetch the Mx Karma Votes - $self->getMxKarmaVotes(); - } else { - $self->maniaControl->log("Error while authenticating on Mania-Exchange Karma " . $data->data->message); - // TODO remove temp trigger - $self->maniaControl->errorHandler->triggerDebugNotice("Error while authenticating on Mania-Exchange Karma " . $data->data->message . " url Query " . $query); - $self->mxKarma['connectionInProgress'] = false; - } - } else { - // TODO remove temp trigger - $self->maniaControl->errorHandler->triggerDebugNotice("Error while authenticating on Mania-Exchange Karma " . $error); - $self->maniaControl->log($error); - $self->mxKarma['connectionInProgress'] = false; - } - }, "application/json", 1000); - } - - /** - * Fetch the mxKarmaVotes for the current map - */ - public function getMxKarmaVotes(Player $player = null) { - if (!$this->maniaControl->settingManager->getSetting($this, self::SETTING_MX_KARMA_ACTIVATED)) { - return; - } - - if (!isset($this->mxKarma['session'])) { - if (!isset($this->mxKarma['connectionInProgress']) || !$this->mxKarma['connectionInProgress']) { - $this->mxKarmaOpenSession(); - } - return; - } - - $map = $this->maniaControl->mapManager->getCurrentMap(); - - $properties = array(); - - $gameMode = $this->maniaControl->server->getGameMode(true); - if ($gameMode == 'Script') { - $scriptName = $this->maniaControl->client->getScriptName(); - $properties['gamemode'] = $scriptName["CurrentValue"]; - } else { - $properties['gamemode'] = $gameMode; - } - - $properties['titleid'] = $this->maniaControl->server->titleId; - $properties['mapuid'] = $map->uid; - - if (!$player) { - $properties['getvotesonly'] = false; - $properties['playerlogins'] = array(); - foreach($this->maniaControl->playerManager->getPlayers() as $plyr) { - /** - * @var Player $player - */ - $properties['playerlogins'][] = $plyr->login; - } - } else { - $properties['getvotesonly'] = true; - $properties['playerlogins'] = array($player->login); - } - - $content = json_encode($properties); - $self = $this; - $this->maniaControl->fileReader->postData(self::MX_KARMA_URL . self::MX_KARMA_GETMAPRATING . "?sessionKey=" . urlencode($this->mxKarma['session']->sessionKey), function ($data, $error) use (&$self, &$player) { - if (!$error) { - $data = json_decode($data); - if ($data->success) { - - // Fetch averages if its for the whole server - if (!$player) { - $self->mxKarma["voteCount"] = $data->data->votecount; - $self->mxKarma["voteAverage"] = $data->data->voteaverage; - $self->mxKarma["modeVoteCount"] = $data->data->modevotecount; - $self->mxKarma["modeVoteAverage"] = $data->data->modevoteaverage; - } - - foreach($data->data->votes as $votes) { - $self->mxKarma["votes"][$votes->login] = $votes->vote; - } - - $self->updateManialink = true; - $self->maniaControl->callbackManager->triggerCallback($self::CB_KARMA_MXUPDATED, $self->mxKarma); - $self->maniaControl->log("MX-Karma Votes successfully fetched"); - } else { - $self->maniaControl->log("Error while fetching votes: " . $data->data->message); - // TODO remove temp trigger - $self->maniaControl->errorHandler->triggerDebugNotice("Error while fetching votes: " . $data->data->message . " " . KarmaPlugin::MX_KARMA_URL . KarmaPlugin::MX_KARMA_SAVEVOTES . "?sessionKey=" . urlencode($self->mxKarma['session']->sessionKey)); - } - } else { - $self->maniaControl->log($error); - } - }, $content, false, 'application/json'); - } - /** * Import old Karma votes to Mania-Exchange Karma * @@ -872,7 +944,7 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin { } $votes = array(); - while($row = $result2->fetch_object()) { + while ($row = $result2->fetch_object()) { array_push($votes, array("login" => $row->login, "nickname" => $row->nickname, "vote" => $row->vote * 100)); } @@ -913,76 +985,4 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin { $this->mxKarma['map'] = $map; } - - /** - * Post the Karma votes to MX-Karma - * - * @param Map $map - * @param array $votes - * @param bool $import - */ - private function postKarmaVotes(Map $map, array $votes, $import = false) { - if (!isset($this->mxKarma['session'])) { - if (!isset($this->mxKarma['connectionInProgress']) || !$this->mxKarma['connectionInProgress']) { - $this->mxKarmaOpenSession(); - } - return; - } - - $gameMode = $this->maniaControl->server->getGameMode(true); - - if (count($votes) == 0) { - return; - } - - $properties = array(); - if ($gameMode == 'Script') { - $scriptName = $this->maniaControl->client->getScriptName(); - $properties['gamemode'] = $scriptName["CurrentValue"]; - } else { - $properties['gamemode'] = $gameMode; - } - - if ($import) { - $properties['maptime'] = 0; - } else { - $properties['maptime'] = time() - $this->mxKarma['startTime']; - } - - $properties['votes'] = $votes; - $properties['titleid'] = $this->maniaControl->server->titleId; - $properties['mapname'] = $map->rawName; - $properties['mapuid'] = $map->uid; - $properties['mapauthor'] = $map->authorLogin; - $properties['isimport'] = $import; - - $content = json_encode($properties); - - $self = $this; - $this->maniaControl->fileReader->postData(self::MX_KARMA_URL . self::MX_KARMA_SAVEVOTES . "?sessionKey=" . urlencode($this->mxKarma['session']->sessionKey), function ($data, $error) use (&$self) { - if (!$error) { - $data = json_decode($data); - if ($data->success) { - $self->maniaControl->log("Votes successfully permitted"); - } else { - $self->maniaControl->log("Error while updating votes: " . $data->data->message); - // TODO remove temp trigger - $self->maniaControl->errorHandler->triggerDebugNotice("Error while updating votes: " . $data->data->message . " " . KarmaPlugin::MX_KARMA_URL . $self::MX_KARMA_SAVEVOTES . "?sessionKey=" . urlencode($self->mxKarma['session']->sessionKey)); - } - } else { - $self->maniaControl->log($error); - } - }, $content, false, 'application/json'); - } - - /** - * Builds a sha512 activation Hash for the MX-Karma - * - * @param $sessionSeed - * @param $mxKey - * @return string - */ - private function buildActivationHash($sessionSeed, $mxKey) { - return hash('sha512', $mxKey . $sessionSeed); - } } diff --git a/application/plugins/WidgetPlugin.php b/application/plugins/WidgetPlugin.php index 54a13438..d1555c99 100644 --- a/application/plugins/WidgetPlugin.php +++ b/application/plugins/WidgetPlugin.php @@ -24,8 +24,8 @@ use ManiaControl\Plugins\Plugin; /** * ManiaControl Widget Plugin * - * @author steeffeen and kremsy - * @copyright ManiaControl Copyright © 2014 ManiaControl Team + * @author ManiaControl Team + * @copyright 2014 ManiaControl Team * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 */ class WidgetPlugin implements CallbackListener, TimerListener, Plugin { @@ -88,6 +88,51 @@ class WidgetPlugin implements CallbackListener, TimerListener, Plugin { //do nothing } + /** + * Get plugin id + * + * @return int + */ + public static function getId() { + return self::PLUGIN_ID; + } + + /** + * Get Plugin Name + * + * @return string + */ + public static function getName() { + return self::PLUGIN_NAME; + } + + /** + * Get Plugin Version + * + * @return float,, + */ + public static function getVersion() { + return self::PLUGIN_VERSION; + } + + /** + * Get Plugin Author + * + * @return string + */ + public static function getAuthor() { + return self::PLUGIN_AUTHOR; + } + + /** + * Get Plugin Description + * + * @return string + */ + public static function getDescription() { + return 'Plugin offers some Widgets'; + } + /** * Load the plugin * @@ -135,19 +180,6 @@ class WidgetPlugin implements CallbackListener, TimerListener, Plugin { return true; } - /** - * Unload the plugin and its resources - */ - public function unload() { - $this->closeWidget(self::MLID_CLOCKWIDGET); - $this->closeWidget(self::MLID_SERVERINFOWIDGET); - $this->closeWidget(self::MLID_MAPWIDGET); - $this->closeWidget(self::MLID_NEXTMAPWIDGET); - $this->maniaControl->callbackManager->unregisterCallbackListener($this); - $this->maniaControl->timerManager->unregisterTimerListenings($this); - unset($this->maniaControl); - } - /** * Display the Widgets */ @@ -316,7 +348,7 @@ class WidgetPlugin implements CallbackListener, TimerListener, Plugin { /** * @var Player $player */ - foreach($players as $player) { + foreach ($players as $player) { if ($player->isSpectator) { $spectatorCount++; } else { @@ -381,16 +413,16 @@ class WidgetPlugin implements CallbackListener, TimerListener, Plugin { } /** - * Handle on Begin Map - * - * @param Map $map + * Unload the plugin and its resources */ - public function handleOnBeginMap(Map $map) { - // Display Map Widget - if ($this->maniaControl->settingManager->getSetting($this, self::SETTING_MAP_WIDGET_ACTIVATED)) { - $this->displayMapWidget(); - } + public function unload() { + $this->closeWidget(self::MLID_CLOCKWIDGET); + $this->closeWidget(self::MLID_SERVERINFOWIDGET); + $this->closeWidget(self::MLID_MAPWIDGET); $this->closeWidget(self::MLID_NEXTMAPWIDGET); + $this->maniaControl->callbackManager->unregisterCallbackListener($this); + $this->maniaControl->timerManager->unregisterTimerListenings($this); + unset($this->maniaControl); } /** @@ -403,6 +435,19 @@ class WidgetPlugin implements CallbackListener, TimerListener, Plugin { $this->maniaControl->manialinkManager->sendManialink($emptyManialink); } + /** + * Handle on Begin Map + * + * @param Map $map + */ + public function handleOnBeginMap(Map $map) { + // Display Map Widget + if ($this->maniaControl->settingManager->getSetting($this, self::SETTING_MAP_WIDGET_ACTIVATED)) { + $this->displayMapWidget(); + } + $this->closeWidget(self::MLID_NEXTMAPWIDGET); + } + /** * Handle on End Map * @@ -541,49 +586,4 @@ class WidgetPlugin implements CallbackListener, TimerListener, Plugin { $this->displayServerInfoWidget(); } } - - /** - * Get plugin id - * - * @return int - */ - public static function getId() { - return self::PLUGIN_ID; - } - - /** - * Get Plugin Name - * - * @return string - */ - public static function getName() { - return self::PLUGIN_NAME; - } - - /** - * Get Plugin Version - * - * @return float,, - */ - public static function getVersion() { - return self::PLUGIN_VERSION; - } - - /** - * Get Plugin Author - * - * @return string - */ - public static function getAuthor() { - return self::PLUGIN_AUTHOR; - } - - /** - * Get Plugin Description - * - * @return string - */ - public static function getDescription() { - return 'Plugin offers some Widgets'; - } } \ No newline at end of file