karma plugin settings migration

This commit is contained in:
Steffen Schröder 2014-04-27 21:31:55 +02:00
parent e07ac29d13
commit 8bf32d7157
4 changed files with 317 additions and 203 deletions

View File

@ -1,8 +1,9 @@
<?php <?php
namespace ManiaControl; namespace ManiaControl\Database;
use ManiaControl\Callbacks\TimerListener; use ManiaControl\Callbacks\TimerListener;
use ManiaControl\ManiaControl;
/** /**
* Database Connection Class * Database Connection Class
@ -16,6 +17,7 @@ class Database implements TimerListener {
* Public Properties * Public Properties
*/ */
public $mysqli = null; public $mysqli = null;
public $migrationHelper = null;
/* /*
* Private Properties * Private Properties
@ -59,6 +61,9 @@ class Database implements TimerListener {
// Register Method which checks the Database Connection every 5 seconds // Register Method which checks the Database Connection every 5 seconds
$this->maniaControl->timerManager->registerTimerListening($this, 'checkConnection', 5000); $this->maniaControl->timerManager->registerTimerListening($this, 'checkConnection', 5000);
// Create migration helper
$this->migrationHelper = new MigrationHelper($maniaControl);
} }
/** /**

View File

@ -0,0 +1,75 @@
<?php
namespace ManiaControl\Database;
use ManiaControl\Settings\SettingManager;
use ManiaControl\ManiaControl;
/**
* Database Migration Assistant
*
* @author steeffeen
* @copyright ManiaControl Copyright © 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/
class MigrationHelper {
/*
* Private Properties
*/
private $maniaControl = null;
/**
* Construct Migration Helper
*
* @param ManiaControl $maniaControl
*/
public function __construct(ManiaControl $maniaControl) {
$this->maniaControl = $maniaControl;
}
/**
* Transfer the Settings of the given Class to a new One
*
* @param mixed $sourceClass
* @param mixed $targetClass
* @return bool
*/
public function transferSettings($sourceClass, $targetClass) {
$sourceClass = $this->getClass($sourceClass);
$targetClass = $this->getClass($targetClass);
var_dump($sourceClass, $targetClass);
$mysqli = $this->maniaControl->database->mysqli;
$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) {
trigger_error($mysqli->error);
return false;
}
$statement->bind_param('ss', $targetClass, $sourceClass);
if ($statement->error) {
trigger_error($statement->error);
$statement->close();
return false;
}
$success = $statement->execute();
$statement->close();
return $success;
}
/**
* Get the Class of the given Object
*
* @param mixed $class
* @return string
*/
private function getClass($class) {
if (is_object($class)) {
return get_class($class);
}
return (string) $class;
}
}

View File

@ -26,6 +26,7 @@ use Maniaplanet\DedicatedServer\Connection;
use Maniaplanet\DedicatedServer\Xmlrpc\Exception; use Maniaplanet\DedicatedServer\Xmlrpc\Exception;
use Maniaplanet\DedicatedServer\Xmlrpc\NotInScriptModeException; use Maniaplanet\DedicatedServer\Xmlrpc\NotInScriptModeException;
use Maniaplanet\DedicatedServer\Xmlrpc\TransportException; use Maniaplanet\DedicatedServer\Xmlrpc\TransportException;
use ManiaControl\Database\Database;
require_once __DIR__ . '/Libs/Maniaplanet/DedicatedServer/Connection.php'; require_once __DIR__ . '/Libs/Maniaplanet/DedicatedServer/Connection.php';
require_once __DIR__ . '/Libs/GbxDataFetcher/gbxdatafetcher.inc.php'; require_once __DIR__ . '/Libs/GbxDataFetcher/gbxdatafetcher.inc.php';

View File

@ -22,54 +22,55 @@ use ManiaControl\Settings\SettingManager;
/** /**
* ManiaControl Karma Plugin * ManiaControl Karma Plugin
* *
* @author kremsy and steeffeen * @author kremsy and steeffeen
* @copyright ManiaControl Copyright © 2014 ManiaControl Team * @copyright ManiaControl Copyright © 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class KarmaPlugin implements CallbackListener, TimerListener, Plugin { class KarmaPlugin implements CallbackListener, TimerListener, Plugin {
/** /**
* Constants * Constants
*/ */
const ID = 2; const ID = 2;
const VERSION = 0.1; const VERSION = 0.1;
const MLID_KARMA = 'KarmaPlugin.MLID'; const MLID_KARMA = 'KarmaPlugin.MLID';
const TABLE_KARMA = 'mc_karma'; const TABLE_KARMA = 'mc_karma';
const CB_KARMA_CHANGED = 'KarmaPlugin.Changed'; const CB_KARMA_CHANGED = 'KarmaPlugin.Changed';
const CB_KARMA_MXUPDATED = 'KarmaPlugin.MXUpdated'; const CB_KARMA_MXUPDATED = 'KarmaPlugin.MXUpdated';
const SETTING_AVAILABLE_VOTES = 'Available Votes (X-Y: Comma separated)'; const SETTING_AVAILABLE_VOTES = 'Available Votes (X-Y: Comma separated)';
const SETTING_WIDGET_ENABLE = 'Enable Karma Widget'; const SETTING_WIDGET_ENABLE = 'Enable Karma Widget';
const SETTING_WIDGET_TITLE = 'Widget-Title'; const SETTING_WIDGET_TITLE = 'Widget-Title';
const SETTING_WIDGET_POSX = 'Widget-Position: X'; const SETTING_WIDGET_POSX = 'Widget-Position: X';
const SETTING_WIDGET_POSY = 'Widget-Position: Y'; const SETTING_WIDGET_POSY = 'Widget-Position: Y';
const SETTING_WIDGET_WIDTH = 'Widget-Size: Width'; const SETTING_WIDGET_WIDTH = 'Widget-Size: Width';
const SETTING_WIDGET_HEIGHT = 'Widget-Size: Height'; const SETTING_WIDGET_HEIGHT = 'Widget-Size: Height';
const STAT_PLAYER_MAPVOTES = 'Voted Maps'; const STAT_PLAYER_MAPVOTES = 'Voted Maps';
/** /**
* Constants MX Karma * Constants MX Karma
*/ */
const SETTING_WIDGET_DISPLAY_MX = 'Display MX-Karma in Widget'; const SETTING_WIDGET_DISPLAY_MX = 'Display MX-Karma in Widget';
const SETTING_MX_KARMA_ACTIVATED = 'Activate MX-Karma'; const SETTING_MX_KARMA_ACTIVATED = 'Activate MX-Karma';
const SETTING_MX_KARMA_IMPORTING = 'Import old MX-Karmas'; const SETTING_MX_KARMA_IMPORTING = 'Import old MX-Karmas';
const MX_IMPORT_TABLE = 'mc_karma_mximport'; const MX_IMPORT_TABLE = 'mc_karma_mximport';
const MX_KARMA_URL = 'http://karma.mania-exchange.com/api2/'; const MX_KARMA_URL = 'http://karma.mania-exchange.com/api2/';
const MX_KARMA_STARTSESSION = 'startSession'; const MX_KARMA_STARTSESSION = 'startSession';
const MX_KARMA_ACTIVATESESSION = 'activateSession'; const MX_KARMA_ACTIVATESESSION = 'activateSession';
const MX_KARMA_SAVEVOTES = 'saveVotes'; const MX_KARMA_SAVEVOTES = 'saveVotes';
const MX_KARMA_GETMAPRATING = 'getMapRating'; const MX_KARMA_GETMAPRATING = 'getMapRating';
/** /**
* Private properties * Private properties
*/ */
/** /**
*
* @var maniaControl $maniaControl * @var maniaControl $maniaControl
*/ */
private $maniaControl = null; private $maniaControl = null;
private $updateManialink = false; private $updateManialink = false;
/** @var ManiaLink $manialink */ /**
* @var ManiaLink $manialink
*/
private $manialink = null; private $manialink = null;
private $mxKarma = array(); private $mxKarma = array();
/** /**
@ -83,20 +84,21 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin {
$maniaControl->settingManager->initSetting(get_class(), self::SETTING_MX_KARMA_IMPORTING, true); $maniaControl->settingManager->initSetting(get_class(), self::SETTING_MX_KARMA_IMPORTING, true);
$maniaControl->settingManager->initSetting(get_class(), self::SETTING_WIDGET_DISPLAY_MX, true); $maniaControl->settingManager->initSetting(get_class(), self::SETTING_WIDGET_DISPLAY_MX, true);
$servers = $maniaControl->server->getAllServers(); $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', ''); $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::load() * @see \ManiaControl\Plugins\Plugin::load()
*/ */
public function load(ManiaControl $maniaControl) { public function load(ManiaControl $maniaControl) {
$this->maniaControl = $maniaControl; $this->maniaControl = $maniaControl;
// Init database // Init database
$this->initTables(); $this->initTables();
// Init settings // Init settings
$this->maniaControl->settingManager->initSetting($this, self::SETTING_AVAILABLE_VOTES, '-2,2'); $this->maniaControl->settingManager->initSetting($this, self::SETTING_AVAILABLE_VOTES, '-2,2');
$this->maniaControl->settingManager->initSetting($this, self::SETTING_WIDGET_ENABLE, true); $this->maniaControl->settingManager->initSetting($this, self::SETTING_WIDGET_ENABLE, true);
@ -105,7 +107,7 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin {
$this->maniaControl->settingManager->initSetting($this, self::SETTING_WIDGET_POSY, 90 - 10 - 6); $this->maniaControl->settingManager->initSetting($this, self::SETTING_WIDGET_POSY, 90 - 10 - 6);
$this->maniaControl->settingManager->initSetting($this, self::SETTING_WIDGET_WIDTH, 25.); $this->maniaControl->settingManager->initSetting($this, self::SETTING_WIDGET_WIDTH, 25.);
$this->maniaControl->settingManager->initSetting($this, self::SETTING_WIDGET_HEIGHT, 12.); $this->maniaControl->settingManager->initSetting($this, self::SETTING_WIDGET_HEIGHT, 12.);
// Register for callbacks // Register for callbacks
$this->maniaControl->timerManager->registerTimerListening($this, 'handle1Second', 1000); $this->maniaControl->timerManager->registerTimerListening($this, 'handle1Second', 1000);
$this->maniaControl->callbackManager->registerCallbackListener(MapManager::CB_BEGINMAP, $this, 'handleBeginMap'); $this->maniaControl->callbackManager->registerCallbackListener(MapManager::CB_BEGINMAP, $this, 'handleBeginMap');
@ -114,22 +116,23 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin {
$this->maniaControl->callbackManager->registerCallbackListener(PlayerManager::CB_PLAYERCONNECT, $this, 'handlePlayerConnect'); $this->maniaControl->callbackManager->registerCallbackListener(PlayerManager::CB_PLAYERCONNECT, $this, 'handlePlayerConnect');
$this->maniaControl->callbackManager->registerCallbackListener(CallbackManager::CB_MP_PLAYERCHAT, $this, 'handlePlayerChat'); $this->maniaControl->callbackManager->registerCallbackListener(CallbackManager::CB_MP_PLAYERCHAT, $this, 'handlePlayerChat');
$this->maniaControl->callbackManager->registerCallbackListener(SettingManager::CB_SETTINGS_CHANGED, $this, 'updateSettings'); $this->maniaControl->callbackManager->registerCallbackListener(SettingManager::CB_SETTINGS_CHANGED, $this, 'updateSettings');
// Define player stats // Define player stats
$this->maniaControl->statisticManager->defineStatMetaData(self::STAT_PLAYER_MAPVOTES); $this->maniaControl->statisticManager->defineStatMetaData(self::STAT_PLAYER_MAPVOTES);
// Register Stat in Simple StatsList // Register Stat in Simple StatsList
$this->maniaControl->statisticManager->simpleStatsList->registerStat(self::STAT_PLAYER_MAPVOTES, 100, "VM"); $this->maniaControl->statisticManager->simpleStatsList->registerStat(self::STAT_PLAYER_MAPVOTES, 100, "VM");
$this->updateManialink = true; $this->updateManialink = true;
//Open MX-Karma Session // Open MX-Karma Session
$this->mxKarmaOpenSession(); $this->mxKarmaOpenSession();
$this->mxKarma['startTime'] = time(); $this->mxKarma['startTime'] = time();
return true; return true;
} }
/** /**
*
* @see \ManiaControl\Plugins\Plugin::unload() * @see \ManiaControl\Plugins\Plugin::unload()
*/ */
public function unload() { public function unload() {
@ -141,6 +144,7 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin {
} }
/** /**
*
* @see \ManiaControl\Plugins\Plugin::getId() * @see \ManiaControl\Plugins\Plugin::getId()
*/ */
public static function getId() { public static function getId() {
@ -148,6 +152,7 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin {
} }
/** /**
*
* @see \ManiaControl\Plugins\Plugin::getName() * @see \ManiaControl\Plugins\Plugin::getName()
*/ */
public static function getName() { public static function getName() {
@ -155,6 +160,7 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin {
} }
/** /**
*
* @see \ManiaControl\Plugins\Plugin::getVersion() * @see \ManiaControl\Plugins\Plugin::getVersion()
*/ */
public static function getVersion() { public static function getVersion() {
@ -162,6 +168,7 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin {
} }
/** /**
*
* @see \ManiaControl\Plugins\Plugin::getAuthor() * @see \ManiaControl\Plugins\Plugin::getAuthor()
*/ */
public static function getAuthor() { public static function getAuthor() {
@ -169,6 +176,7 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin {
} }
/** /**
*
* @see \ManiaControl\Plugins\Plugin::getDescription() * @see \ManiaControl\Plugins\Plugin::getDescription()
*/ */
public static function getDescription() { public static function getDescription() {
@ -184,37 +192,42 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin {
if (!$this->updateManialink) { if (!$this->updateManialink) {
return; return;
} }
$displayMxKarma = $this->maniaControl->settingManager->getSetting($this, self::SETTING_WIDGET_DISPLAY_MX); $displayMxKarma = $this->maniaControl->settingManager->getSetting($this, self::SETTING_WIDGET_DISPLAY_MX);
// Get players // Get players
$players = $this->updateManialink; $players = $this->updateManialink;
if ($players === true) { if ($players === true) {
$players = $this->maniaControl->playerManager->getPlayers(); $players = $this->maniaControl->playerManager->getPlayers();
} }
$this->updateManialink = false; $this->updateManialink = false;
// Get map karma // Get map karma
$map = $this->maniaControl->mapManager->getCurrentMap(); $map = $this->maniaControl->mapManager->getCurrentMap();
//Display the mx Karma if the setting is choosen and the MX session is available // 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'])) { if ($displayMxKarma && isset($this->mxKarma['session']) && isset($this->mxKarma['voteCount'])) {
$karma = $this->mxKarma['modeVoteAverage'] / 100; $karma = $this->mxKarma['modeVoteAverage'] / 100;
$voteCount = $this->mxKarma['modeVoteCount']; $voteCount = $this->mxKarma['modeVoteCount'];
} else { }
$karma = $this->getMapKarma($map); else {
$votes = $this->getMapVotes($map); $karma = $this->getMapKarma($map);
$votes = $this->getMapVotes($map);
$voteCount = $votes['count']; $voteCount = $votes['count'];
} }
if($this->maniaControl->settingManager->getSetting($this, self::SETTING_WIDGET_ENABLE)) { if ($this->maniaControl->settingManager->getSetting($this, self::SETTING_WIDGET_ENABLE)) {
// Build karma manialink // Build karma manialink
$this->buildManialink(); $this->buildManialink();
// Update karma gauge & label // Update karma gauge & label
/** @var Gauge $karmaGauge */ /**
* @var Gauge $karmaGauge
*/
$karmaGauge = $this->manialink->karmaGauge; $karmaGauge = $this->manialink->karmaGauge;
/** @var Label $karmaLabel */ /**
* @var Label $karmaLabel
*/
$karmaLabel = $this->manialink->karmaLabel; $karmaLabel = $this->manialink->karmaLabel;
if (is_numeric($karma) && $voteCount > 0) { if (is_numeric($karma) && $voteCount > 0) {
$karma = floatval($karma); $karma = floatval($karma);
@ -222,20 +235,21 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin {
$karmaColor = ColorUtil::floatToStatusColor($karma); $karmaColor = ColorUtil::floatToStatusColor($karma);
$karmaGauge->setColor($karmaColor . '7'); $karmaGauge->setColor($karmaColor . '7');
$karmaLabel->setText(' ' . round($karma * 100.) . '% (' . $voteCount . ')'); $karmaLabel->setText(' ' . round($karma * 100.) . '% (' . $voteCount . ')');
} else { }
else {
$karmaGauge->setRatio(0.); $karmaGauge->setRatio(0.);
$karmaGauge->setColor('00fb'); $karmaGauge->setColor('00fb');
$karmaLabel->setText('-'); $karmaLabel->setText('-');
} }
// Loop players // Loop players
foreach($players as $login => $player) { foreach ($players as $login => $player) {
// Get player vote // Get player vote
// TODO: show the player his own vote in some way // TODO: show the player his own vote in some way
//$vote = $this->getPlayerVote($player, $map); // $vote = $this->getPlayerVote($player, $map);
//$votesFrame = $this->manialink->votesFrame; // $votesFrame = $this->manialink->votesFrame;
//$votesFrame->removeChildren(); // $votesFrame->removeChildren();
// Send manialink // Send manialink
$this->maniaControl->manialinkManager->sendManialink($this->manialink, $login); $this->maniaControl->manialinkManager->sendManialink($this->manialink, $login);
} }
@ -248,22 +262,22 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin {
* @param Map $map * @param Map $map
*/ */
public function handleBeginMap(Map $map) { public function handleBeginMap(Map $map) {
//send Map Karma to MX from previous Map // send Map Karma to MX from previous Map
if (isset($this->mxKarma['map'])) { if (isset($this->mxKarma['map'])) {
$votes = array(); $votes = array();
foreach($this->mxKarma['votes'] as $login => $value) { foreach ($this->mxKarma['votes'] as $login => $value) {
$player = $this->maniaControl->playerManager->getPlayer($login); $player = $this->maniaControl->playerManager->getPlayer($login);
array_push($votes, array("login" => $login, "nickname" => $player->rawNickname, "vote" => $value)); array_push($votes, array("login" => $login, "nickname" => $player->rawNickname, "vote" => $value));
} }
$this->postKarmaVotes($this->mxKarma['map'], $votes); $this->postKarmaVotes($this->mxKarma['map'], $votes);
unset($this->mxKarma['map']); unset($this->mxKarma['map']);
} }
unset($this->mxKarma['votes']); unset($this->mxKarma['votes']);
$this->mxKarma['startTime'] = time(); $this->mxKarma['startTime'] = time();
$this->updateManialink = true; $this->updateManialink = true;
//Get Karma votes at begin of map // Get Karma votes at begin of map
$this->getMxKarmaVotes(); $this->getMxKarmaVotes();
} }
@ -277,8 +291,8 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin {
return; return;
} }
$this->queryManialinkUpdateFor($player); $this->queryManialinkUpdateFor($player);
//Get Mx Karma Vote for Player // Get Mx Karma Vote for Player
$this->getMxKarmaVotes($player); $this->getMxKarmaVotes($player);
} }
@ -288,7 +302,7 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin {
* @param array $chatCallback * @param array $chatCallback
*/ */
public function handlePlayerChat(array $chatCallback) { public function handlePlayerChat(array $chatCallback) {
$login = $chatCallback[1][1]; $login = $chatCallback[1][1];
$player = $this->maniaControl->playerManager->getPlayer($login); $player = $this->maniaControl->playerManager->getPlayer($login);
if (!$player) { if (!$player) {
return; return;
@ -305,7 +319,7 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin {
if ($countPositive <= 0 && $countNegative <= 0) { if ($countPositive <= 0 && $countNegative <= 0) {
return; return;
} }
$vote = $countPositive - $countNegative; $vote = $countPositive - $countNegative;
$success = $this->handleVote($player, $vote); $success = $this->handleVote($player, $vote);
if (!$success) { if (!$success) {
$this->maniaControl->chat->sendError('Error occurred.', $player->login); $this->maniaControl->chat->sendError('Error occurred.', $player->login);
@ -318,55 +332,55 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin {
* Handle a vote done by a player * Handle a vote done by a player
* *
* @param Player $player * @param Player $player
* @param int $vote * @param int $vote
* @return bool * @return bool
*/ */
private function handleVote(Player $player, $vote) { private function handleVote(Player $player, $vote) {
// Check vote // Check vote
$votesSetting = $this->maniaControl->settingManager->getSetting($this, self::SETTING_AVAILABLE_VOTES); $votesSetting = $this->maniaControl->settingManager->getSetting($this, self::SETTING_AVAILABLE_VOTES);
$votes = explode(',', $votesSetting); $votes = explode(',', $votesSetting);
$voteLow = intval($votes[0]); $voteLow = intval($votes[0]);
$voteHigh = $voteLow + 2; $voteHigh = $voteLow + 2;
if (isset($votes[1])) { if (isset($votes[1])) {
$voteHigh = intval($votes[1]); $voteHigh = intval($votes[1]);
} }
if ($vote < $voteLow || $vote > $voteHigh) { if ($vote < $voteLow || $vote > $voteHigh) {
return false; return false;
} }
// Calculate actual voting // Calculate actual voting
$vote -= $voteLow; $vote -= $voteLow;
$voteHigh -= $voteLow; $voteHigh -= $voteLow;
$vote /= $voteHigh; $vote /= $voteHigh;
// Save vote // Save vote
$map = $this->maniaControl->mapManager->getCurrentMap(); $map = $this->maniaControl->mapManager->getCurrentMap();
//Update vote in MX karma array // Update vote in MX karma array
if ($this->maniaControl->settingManager->getSetting($this, self::SETTING_MX_KARMA_ACTIVATED) && isset($this->mxKarma["session"])) { if ($this->maniaControl->settingManager->getSetting($this, self::SETTING_MX_KARMA_ACTIVATED) && isset($this->mxKarma["session"])) {
if (!isset($this->mxKarma["votes"][$player->login])) { if (!isset($this->mxKarma["votes"][$player->login])) {
$sum = $this->mxKarma["voteCount"] * $this->mxKarma["voteAverage"] + $vote * 100; $sum = $this->mxKarma["voteCount"] * $this->mxKarma["voteAverage"] + $vote * 100;
$this->mxKarma["voteCount"]++; $this->mxKarma["voteCount"]++;
$modeSum = $this->mxKarma["modeVoteCount"] * $this->mxKarma["modeVoteAverage"] + $vote * 100; $modeSum = $this->mxKarma["modeVoteCount"] * $this->mxKarma["modeVoteAverage"] + $vote * 100;
$this->mxKarma["modeVoteCount"]++; $this->mxKarma["modeVoteCount"]++;
} else { }
else {
$oldVote = $this->mxKarma["votes"][$player->login]; $oldVote = $this->mxKarma["votes"][$player->login];
$sum = $this->mxKarma["voteCount"] * $this->mxKarma["voteAverage"] - $oldVote + $vote * 100; $sum = $this->mxKarma["voteCount"] * $this->mxKarma["voteAverage"] - $oldVote + $vote * 100;
$modeSum = $this->mxKarma["modeVoteCount"] * $this->mxKarma["modeVoteAverage"] - $oldVote + $vote * 100; $modeSum = $this->mxKarma["modeVoteCount"] * $this->mxKarma["modeVoteAverage"] - $oldVote + $vote * 100;
} }
$this->mxKarma["voteAverage"] = $sum / $this->mxKarma["voteCount"]; $this->mxKarma["voteAverage"] = $sum / $this->mxKarma["voteCount"];
$this->mxKarma["modeVoteAverage"] = $modeSum / $this->mxKarma["modeVoteCount"]; $this->mxKarma["modeVoteAverage"] = $modeSum / $this->mxKarma["modeVoteCount"];
$this->mxKarma["votes"][$player->login] = $vote * 100; $this->mxKarma["votes"][$player->login] = $vote * 100;
} }
$voted = $this->getPlayerVote($player, $map); $voted = $this->getPlayerVote($player, $map);
if (!$voted) { if (!$voted) {
$this->maniaControl->statisticManager->incrementStat(self::STAT_PLAYER_MAPVOTES, $player, $this->maniaControl->server->index); $this->maniaControl->statisticManager->incrementStat(self::STAT_PLAYER_MAPVOTES, $player, $this->maniaControl->server->index);
} }
$success = $this->savePlayerVote($player, $map, $vote); $success = $this->savePlayerVote($player, $map, $vote);
if (!$success) { if (!$success) {
return false; return false;
@ -396,7 +410,9 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin {
*/ */
private function initTables() { private function initTables() {
$mysqli = $this->maniaControl->database->mysqli; $mysqli = $this->maniaControl->database->mysqli;
$query = "CREATE TABLE IF NOT EXISTS `" . self::TABLE_KARMA . "` (
// Create local table
$query = "CREATE TABLE IF NOT EXISTS `" . self::TABLE_KARMA . "` (
`index` int(11) NOT NULL AUTO_INCREMENT, `index` int(11) NOT NULL AUTO_INCREMENT,
`mapIndex` int(11) NOT NULL, `mapIndex` int(11) NOT NULL,
`playerIndex` int(11) NOT NULL, `playerIndex` int(11) NOT NULL,
@ -409,11 +425,15 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin {
if ($mysqli->error) { if ($mysqli->error) {
trigger_error($mysqli->error, E_USER_ERROR); trigger_error($mysqli->error, E_USER_ERROR);
} }
// Migrate settings
$this->maniaControl->database->migrationHelper->transferSettings('ManiaControl\Chat', $this);
if (!$this->maniaControl->settingManager->getSetting($this, self::SETTING_MX_KARMA_ACTIVATED)) { if (!$this->maniaControl->settingManager->getSetting($this, self::SETTING_MX_KARMA_ACTIVATED)) {
return; return;
} }
// Create mx table
$query = "CREATE TABLE IF NOT EXISTS `" . self::MX_IMPORT_TABLE . "` ( $query = "CREATE TABLE IF NOT EXISTS `" . self::MX_IMPORT_TABLE . "` (
`index` int(11) NOT NULL AUTO_INCREMENT, `index` int(11) NOT NULL AUTO_INCREMENT,
`mapIndex` int(11) NOT NULL, `mapIndex` int(11) NOT NULL,
@ -432,13 +452,13 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin {
* Save the vote of the player for the map * Save the vote of the player for the map
* *
* @param Player $player * @param Player $player
* @param Map $map * @param Map $map
* @param float $vote * @param float $vote
* @return bool * @return bool
*/ */
private function savePlayerVote(Player $player, Map $map, $vote) { private function savePlayerVote(Player $player, Map $map, $vote) {
$mysqli = $this->maniaControl->database->mysqli; $mysqli = $this->maniaControl->database->mysqli;
$query = "INSERT INTO `" . self::TABLE_KARMA . "` ( $query = "INSERT INTO `" . self::TABLE_KARMA . "` (
`mapIndex`, `mapIndex`,
`playerIndex`, `playerIndex`,
`vote` `vote`
@ -453,7 +473,7 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin {
trigger_error($mysqli->error); trigger_error($mysqli->error);
return false; return false;
} }
return $result; return $result;
} }
@ -461,12 +481,12 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin {
* Get the current vote of the player for the map * Get the current vote of the player for the map
* *
* @param Player $player * @param Player $player
* @param Map $map * @param Map $map
* @return int * @return int
*/ */
public function getPlayerVote(Player $player, Map $map) { public function getPlayerVote(Player $player, Map $map) {
$mysqli = $this->maniaControl->database->mysqli; $mysqli = $this->maniaControl->database->mysqli;
$query = "SELECT * FROM `" . self::TABLE_KARMA . "` $query = "SELECT * FROM `" . self::TABLE_KARMA . "`
WHERE `playerIndex` = {$player->index} WHERE `playerIndex` = {$player->index}
AND `mapIndex` = {$map->index} AND `mapIndex` = {$map->index}
AND `vote` >= 0;"; AND `vote` >= 0;";
@ -493,7 +513,7 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin {
*/ */
public function getMapKarma(Map $map) { public function getMapKarma(Map $map) {
$mysqli = $this->maniaControl->database->mysqli; $mysqli = $this->maniaControl->database->mysqli;
$query = "SELECT AVG(`vote`) AS `karma` FROM `" . self::TABLE_KARMA . "` $query = "SELECT AVG(`vote`) AS `karma` FROM `" . self::TABLE_KARMA . "`
WHERE `mapIndex` = {$map->index} WHERE `mapIndex` = {$map->index}
AND `vote` >= 0;"; AND `vote` >= 0;";
$result = $mysqli->query($query); $result = $mysqli->query($query);
@ -522,7 +542,7 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin {
*/ */
public function getMapVotes(Map $map) { public function getMapVotes(Map $map) {
$mysqli = $this->maniaControl->database->mysqli; $mysqli = $this->maniaControl->database->mysqli;
$query = "SELECT `vote`, COUNT(`vote`) AS `count` FROM `" . self::TABLE_KARMA . "` $query = "SELECT `vote`, COUNT(`vote`) AS `count` FROM `" . self::TABLE_KARMA . "`
WHERE `mapIndex` = {$map->index} WHERE `mapIndex` = {$map->index}
AND `vote` >= 0 AND `vote` >= 0
GROUP BY `vote`;"; GROUP BY `vote`;";
@ -533,7 +553,7 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin {
} }
$votes = array(); $votes = array();
$count = 0; $count = 0;
while($vote = $result->fetch_object()) { while ($vote = $result->fetch_object()) {
$votes[$vote->vote] = $vote; $votes[$vote->vote] = $vote;
$count += $vote->count; $count += $vote->count;
} }
@ -551,28 +571,28 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin {
if (is_object($this->manialink) && !$forceBuild) { if (is_object($this->manialink) && !$forceBuild) {
return; return;
} }
$title = $this->maniaControl->settingManager->getSetting($this, self::SETTING_WIDGET_TITLE); $title = $this->maniaControl->settingManager->getSetting($this, self::SETTING_WIDGET_TITLE);
$pos_x = $this->maniaControl->settingManager->getSetting($this, self::SETTING_WIDGET_POSX); $pos_x = $this->maniaControl->settingManager->getSetting($this, self::SETTING_WIDGET_POSX);
$pos_y = $this->maniaControl->settingManager->getSetting($this, self::SETTING_WIDGET_POSY); $pos_y = $this->maniaControl->settingManager->getSetting($this, self::SETTING_WIDGET_POSY);
$width = $this->maniaControl->settingManager->getSetting($this, self::SETTING_WIDGET_WIDTH); $width = $this->maniaControl->settingManager->getSetting($this, self::SETTING_WIDGET_WIDTH);
$height = $this->maniaControl->settingManager->getSetting($this, self::SETTING_WIDGET_HEIGHT); $height = $this->maniaControl->settingManager->getSetting($this, self::SETTING_WIDGET_HEIGHT);
$labelStyle = $this->maniaControl->manialinkManager->styleManager->getDefaultLabelStyle(); $labelStyle = $this->maniaControl->manialinkManager->styleManager->getDefaultLabelStyle();
$quadStyle = $this->maniaControl->manialinkManager->styleManager->getDefaultQuadStyle(); $quadStyle = $this->maniaControl->manialinkManager->styleManager->getDefaultQuadStyle();
$quadSubstyle = $this->maniaControl->manialinkManager->styleManager->getDefaultQuadSubstyle(); $quadSubstyle = $this->maniaControl->manialinkManager->styleManager->getDefaultQuadSubstyle();
$manialink = new ManiaLink(self::MLID_KARMA); $manialink = new ManiaLink(self::MLID_KARMA);
$frame = new Frame(); $frame = new Frame();
$manialink->add($frame); $manialink->add($frame);
$frame->setPosition($pos_x, $pos_y); $frame->setPosition($pos_x, $pos_y);
$backgroundQuad = new Quad(); $backgroundQuad = new Quad();
$frame->add($backgroundQuad); $frame->add($backgroundQuad);
$backgroundQuad->setY($height * 0.15); $backgroundQuad->setY($height * 0.15);
$backgroundQuad->setSize($width, $height); $backgroundQuad->setSize($width, $height);
$backgroundQuad->setStyles($quadStyle, $quadSubstyle); $backgroundQuad->setStyles($quadStyle, $quadSubstyle);
$titleLabel = new Label(); $titleLabel = new Label();
$frame->add($titleLabel); $frame->add($titleLabel);
$titleLabel->setY($height * 0.36); $titleLabel->setY($height * 0.36);
@ -582,13 +602,13 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin {
$titleLabel->setTextSize(1); $titleLabel->setTextSize(1);
$titleLabel->setScale(0.90); $titleLabel->setScale(0.90);
$titleLabel->setText($title); $titleLabel->setText($title);
$karmaGauge = new Gauge(); $karmaGauge = new Gauge();
$frame->add($karmaGauge); $frame->add($karmaGauge);
$karmaGauge->setSize($width * 0.95, $height * 0.92); $karmaGauge->setSize($width * 0.95, $height * 0.92);
$karmaGauge->setDrawBg(false); $karmaGauge->setDrawBg(false);
$manialink->karmaGauge = $karmaGauge; $manialink->karmaGauge = $karmaGauge;
$karmaLabel = new Label(); $karmaLabel = new Label();
$frame->add($karmaLabel); $frame->add($karmaLabel);
$karmaLabel->setPosition(0, -0.4, 1); $karmaLabel->setPosition(0, -0.4, 1);
@ -596,15 +616,14 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin {
$karmaLabel->setStyle($labelStyle); $karmaLabel->setStyle($labelStyle);
$karmaLabel->setTextSize(1); $karmaLabel->setTextSize(1);
$manialink->karmaLabel = $karmaLabel; $manialink->karmaLabel = $karmaLabel;
$votesFrame = new Frame(); $votesFrame = new Frame();
$frame->add($votesFrame); $frame->add($votesFrame);
$manialink->votesFrame = $votesFrame; $manialink->votesFrame = $votesFrame;
$this->manialink = $manialink; $this->manialink = $manialink;
} }
/** /**
* Update Settings * Update Settings
* *
@ -616,16 +635,17 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin {
if (!$class = get_class()) { if (!$class = get_class()) {
return; return;
} }
$serverLogin = $this->maniaControl->server->login; $serverLogin = $this->maniaControl->server->login;
if ($settingName == '$l[http://karma.mania-exchange.com/auth/getapikey?server=' . $serverLogin . ']MX Karma Code for ' . $serverLogin . '$l') { if ($settingName == '$l[http://karma.mania-exchange.com/auth/getapikey?server=' . $serverLogin . ']MX Karma Code for ' . $serverLogin . '$l') {
$this->mxKarmaOpenSession(); $this->mxKarmaOpenSession();
} }
if ($settingName == 'Enable Karma Widget' && $value == true) { if ($settingName == 'Enable Karma Widget' && $value == true) {
$this->updateManialink = true; $this->updateManialink = true;
$this->handle1Second(time()); $this->handle1Second(time());
} elseif ($settingName == 'Enable Karma Widget' && $value == false) { }
elseif ($settingName == 'Enable Karma Widget' && $value == false) {
$this->updateManialink = false; $this->updateManialink = false;
$ml = new ManiaLink(self::MLID_KARMA); $ml = new ManiaLink(self::MLID_KARMA);
$mltext = $ml->render()->saveXML(); $mltext = $ml->render()->saveXML();
@ -634,46 +654,48 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin {
} }
/** /**
* Open a Mx Karma Session * Open a Mx Karma Session
*/ */
private function mxKarmaOpenSession() { private function mxKarmaOpenSession() {
if (!$this->maniaControl->settingManager->getSetting($this, self::SETTING_MX_KARMA_ACTIVATED)) { if (!$this->maniaControl->settingManager->getSetting($this, self::SETTING_MX_KARMA_ACTIVATED)) {
return; return;
} }
$serverLogin = $this->maniaControl->server->login; $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'); $mxKarmaCode = $this->maniaControl->settingManager->getSetting($this, '$l[http://karma.mania-exchange.com/auth/getapikey?server=' . $serverLogin . ']MX Karma Code for ' . $serverLogin . '$l');
if ($mxKarmaCode == '') { if ($mxKarmaCode == '') {
return; return;
} }
$applicationIdentifier = 'ManiaControl v' . ManiaControl::VERSION; $applicationIdentifier = 'ManiaControl v' . ManiaControl::VERSION;
$testMode = 'true'; $testMode = 'true';
$query = self::MX_KARMA_URL . self::MX_KARMA_STARTSESSION; $query = self::MX_KARMA_URL . self::MX_KARMA_STARTSESSION;
$query .= '?serverLogin=' . $serverLogin; $query .= '?serverLogin=' . $serverLogin;
$query .= '&applicationIdentifier=' . urlencode($applicationIdentifier); $query .= '&applicationIdentifier=' . urlencode($applicationIdentifier);
$query .= '&testMode=' . $testMode; $query .= '&testMode=' . $testMode;
$this->mxKarma['connectionInProgress'] = true; $this->mxKarma['connectionInProgress'] = true;
$self = $this; $self = $this;
$this->maniaControl->fileReader->loadFile($query, function ($data, $error) use (&$self, $mxKarmaCode) { $this->maniaControl->fileReader->loadFile($query, function ($data, $error) use(&$self, $mxKarmaCode) {
if (!$error) { if (!$error) {
$data = json_decode($data); $data = json_decode($data);
if ($data->success) { if ($data->success) {
$self->mxKarma['session'] = $data->data; $self->mxKarma['session'] = $data->data;
$self->activateSession($mxKarmaCode); $self->activateSession($mxKarmaCode);
} else { }
else {
$self->maniaControl->log("Error while authenticating on Mania-Exchange Karma"); $self->maniaControl->log("Error while authenticating on Mania-Exchange Karma");
//TODO remove temp trigger // TODO remove temp trigger
$self->maniaControl->errorHandler->triggerDebugNotice("Error while authenticating on Mania-Exchange Karma " . $data->data->message); $self->maniaControl->errorHandler->triggerDebugNotice("Error while authenticating on Mania-Exchange Karma " . $data->data->message);
$self->mxKarma['connectionInProgress'] = false; $self->mxKarma['connectionInProgress'] = false;
} }
} else { }
else {
$self->maniaControl->log($error); $self->maniaControl->log($error);
//TODO remove temp trigger // TODO remove temp trigger
$self->maniaControl->errorHandler->triggerDebugNotice("Error while authenticating on Mania-Exchange Karma " . $error); $self->maniaControl->errorHandler->triggerDebugNotice("Error while authenticating on Mania-Exchange Karma " . $error);
$self->mxKarma['connectionInProgress'] = false; $self->mxKarma['connectionInProgress'] = false;
} }
@ -687,29 +709,31 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin {
*/ */
private function activateSession($mxKarmaCode) { private function activateSession($mxKarmaCode) {
$hash = $this->buildActivationHash($this->mxKarma['session']->sessionSeed, $mxKarmaCode); $hash = $this->buildActivationHash($this->mxKarma['session']->sessionSeed, $mxKarmaCode);
$query = self::MX_KARMA_URL . self::MX_KARMA_ACTIVATESESSION; $query = self::MX_KARMA_URL . self::MX_KARMA_ACTIVATESESSION;
$query .= '?sessionKey=' . urlencode($this->mxKarma['session']->sessionKey); $query .= '?sessionKey=' . urlencode($this->mxKarma['session']->sessionKey);
$query .= '&activationHash=' . urlencode($hash); $query .= '&activationHash=' . urlencode($hash);
$self = $this; $self = $this;
$this->maniaControl->fileReader->loadFile($query, function ($data, $error) use (&$self, $query) { $this->maniaControl->fileReader->loadFile($query, function ($data, $error) use(&$self, $query) {
if (!$error) { if (!$error) {
$data = json_decode($data); $data = json_decode($data);
if ($data->success && $data->data->activated) { if ($data->success && $data->data->activated) {
$self->maniaControl->log("Successfully authenticated on Mania-Exchange Karma"); $self->maniaControl->log("Successfully authenticated on Mania-Exchange Karma");
$self->mxKarma['connectionInProgress'] = false; $self->mxKarma['connectionInProgress'] = false;
//Fetch the Mx Karma Votes // Fetch the Mx Karma Votes
$self->getMxKarmaVotes(); $self->getMxKarmaVotes();
} else { }
else {
$self->maniaControl->log("Error while authenticating on Mania-Exchange Karma " . $data->data->message); $self->maniaControl->log("Error while authenticating on Mania-Exchange Karma " . $data->data->message);
//TODO remove temp trigger // TODO remove temp trigger
$self->maniaControl->errorHandler->triggerDebugNotice("Error while authenticating on Mania-Exchange Karma " . $data->data->message . " url Query " . $query); $self->maniaControl->errorHandler->triggerDebugNotice("Error while authenticating on Mania-Exchange Karma " . $data->data->message . " url Query " . $query);
$self->mxKarma['connectionInProgress'] = false; $self->mxKarma['connectionInProgress'] = false;
} }
} else { }
//TODO remove temp trigger else {
// TODO remove temp trigger
$self->maniaControl->errorHandler->triggerDebugNotice("Error while authenticating on Mania-Exchange Karma " . $error); $self->maniaControl->errorHandler->triggerDebugNotice("Error while authenticating on Mania-Exchange Karma " . $error);
$self->maniaControl->log($error); $self->maniaControl->log($error);
$self->mxKarma['connectionInProgress'] = false; $self->mxKarma['connectionInProgress'] = false;
@ -717,7 +741,6 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin {
}, "application/json", 1000); }, "application/json", 1000);
} }
/** /**
* Fetch the mxKarmaVotes for the current map * Fetch the mxKarmaVotes for the current map
*/ */
@ -725,69 +748,75 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin {
if (!$this->maniaControl->settingManager->getSetting($this, self::SETTING_MX_KARMA_ACTIVATED)) { if (!$this->maniaControl->settingManager->getSetting($this, self::SETTING_MX_KARMA_ACTIVATED)) {
return; return;
} }
if (!isset($this->mxKarma['session'])) { if (!isset($this->mxKarma['session'])) {
if (!isset($this->mxKarma['connectionInProgress']) || !$this->mxKarma['connectionInProgress']) { if (!isset($this->mxKarma['connectionInProgress']) || !$this->mxKarma['connectionInProgress']) {
$this->mxKarmaOpenSession(); $this->mxKarmaOpenSession();
} }
return; return;
} }
$map = $this->maniaControl->mapManager->getCurrentMap(); $map = $this->maniaControl->mapManager->getCurrentMap();
$properties = array(); $properties = array();
$gameMode = $this->maniaControl->server->getGameMode(true); $gameMode = $this->maniaControl->server->getGameMode(true);
if ($gameMode == 'Script') { if ($gameMode == 'Script') {
$scriptName = $this->maniaControl->client->getScriptName(); $scriptName = $this->maniaControl->client->getScriptName();
$properties['gamemode'] = $scriptName["CurrentValue"]; $properties['gamemode'] = $scriptName["CurrentValue"];
} else { }
else {
$properties['gamemode'] = $gameMode; $properties['gamemode'] = $gameMode;
} }
$properties['titleid'] = $this->maniaControl->server->titleId; $properties['titleid'] = $this->maniaControl->server->titleId;
$properties['mapuid'] = $map->uid; $properties['mapuid'] = $map->uid;
if (!$player) { if (!$player) {
$properties['getvotesonly'] = false; $properties['getvotesonly'] = false;
$properties['playerlogins'] = array(); $properties['playerlogins'] = array();
foreach($this->maniaControl->playerManager->getPlayers() as $plyr) { foreach ($this->maniaControl->playerManager->getPlayers() as $plyr) {
/** @var Player $player */ /**
* @var Player $player
*/
$properties['playerlogins'][] = $plyr->login; $properties['playerlogins'][] = $plyr->login;
} }
} else { }
else {
$properties['getvotesonly'] = true; $properties['getvotesonly'] = true;
$properties['playerlogins'] = array($player->login); $properties['playerlogins'] = array($player->login);
} }
$content = json_encode($properties); $content = json_encode($properties);
$self = $this; $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) { $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) { if (!$error) {
$data = json_decode($data); $data = json_decode($data);
if ($data->success) { if ($data->success) {
//Fetch averages if its for the whole server // Fetch averages if its for the whole server
if (!$player) { if (!$player) {
$self->mxKarma["voteCount"] = $data->data->votecount; $self->mxKarma["voteCount"] = $data->data->votecount;
$self->mxKarma["voteAverage"] = $data->data->voteaverage; $self->mxKarma["voteAverage"] = $data->data->voteaverage;
$self->mxKarma["modeVoteCount"] = $data->data->modevotecount; $self->mxKarma["modeVoteCount"] = $data->data->modevotecount;
$self->mxKarma["modeVoteAverage"] = $data->data->modevoteaverage; $self->mxKarma["modeVoteAverage"] = $data->data->modevoteaverage;
} }
foreach($data->data->votes as $votes) { foreach ($data->data->votes as $votes) {
$self->mxKarma["votes"][$votes->login] = $votes->vote; $self->mxKarma["votes"][$votes->login] = $votes->vote;
} }
$self->updateManialink = true; $self->updateManialink = true;
$self->maniaControl->callbackManager->triggerCallback($self::CB_KARMA_MXUPDATED, $self->mxKarma); $self->maniaControl->callbackManager->triggerCallback($self::CB_KARMA_MXUPDATED, $self->mxKarma);
$self->maniaControl->log("MX-Karma Votes successfully fetched"); $self->maniaControl->log("MX-Karma Votes successfully fetched");
} else { }
else {
$self->maniaControl->log("Error while fetching votes: " . $data->data->message); $self->maniaControl->log("Error while fetching votes: " . $data->data->message);
//TODO remove temp trigger // 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)); $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 { }
else {
$self->maniaControl->log($error); $self->maniaControl->log($error);
} }
}, $content, false, 'application/json'); }, $content, false, 'application/json');
@ -802,84 +831,84 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin {
if (!$this->maniaControl->settingManager->getSetting($this, self::SETTING_MX_KARMA_ACTIVATED)) { if (!$this->maniaControl->settingManager->getSetting($this, self::SETTING_MX_KARMA_ACTIVATED)) {
return; return;
} }
if (!$this->maniaControl->settingManager->getSetting($this, self::SETTING_MX_KARMA_IMPORTING)) { if (!$this->maniaControl->settingManager->getSetting($this, self::SETTING_MX_KARMA_IMPORTING)) {
return; return;
} }
if (!isset($this->mxKarma['session'])) { if (!isset($this->mxKarma['session'])) {
if (!isset($this->mxKarma['connectionInProgress']) || !$this->mxKarma['connectionInProgress']) { if (!isset($this->mxKarma['connectionInProgress']) || !$this->mxKarma['connectionInProgress']) {
$this->mxKarmaOpenSession(); $this->mxKarmaOpenSession();
} }
return; return;
} }
$mysqli = $this->maniaControl->database->mysqli; $mysqli = $this->maniaControl->database->mysqli;
$query = "SELECT mapImported FROM `" . self::MX_IMPORT_TABLE . "` WHERE `mapIndex` = {$map->index};"; $query = "SELECT mapImported FROM `" . self::MX_IMPORT_TABLE . "` WHERE `mapIndex` = {$map->index};";
$result = $mysqli->query($query); $result = $mysqli->query($query);
if ($mysqli->error) { if ($mysqli->error) {
trigger_error($mysqli->error); trigger_error($mysqli->error);
return; return;
} }
$vote = $result->fetch_object(); $vote = $result->fetch_object();
if ($result->field_count == 0 || !$vote) { if ($result->field_count == 0 || !$vote) {
$query = "SELECT vote, login, nickname FROM `" . self::TABLE_KARMA . "` k LEFT JOIN `" . PlayerManager::TABLE_PLAYERS . "` p ON (k.playerIndex=p.index) WHERE mapIndex = {$map->index}"; $query = "SELECT vote, login, nickname FROM `" . self::TABLE_KARMA . "` k LEFT JOIN `" . PlayerManager::TABLE_PLAYERS . "` p ON (k.playerIndex=p.index) WHERE mapIndex = {$map->index}";
$result2 = $mysqli->query($query); $result2 = $mysqli->query($query);
if ($mysqli->error) { if ($mysqli->error) {
trigger_error($mysqli->error); trigger_error($mysqli->error);
return; return;
} }
$votes = array(); $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)); array_push($votes, array("login" => $row->login, "nickname" => $row->nickname, "vote" => $row->vote * 100));
} }
$this->postKarmaVotes($map, $votes, true); $this->postKarmaVotes($map, $votes, true);
//Flag Map as Imported in database if it is a import // Flag Map as Imported in database if it is a import
$query = "INSERT INTO `" . self::MX_IMPORT_TABLE . "` (`mapIndex`,`mapImported`) VALUES ({$map->index},true) ON DUPLICATE KEY UPDATE `mapImported` = true;"; $query = "INSERT INTO `" . self::MX_IMPORT_TABLE . "` (`mapIndex`,`mapImported`) VALUES ({$map->index},true) ON DUPLICATE KEY UPDATE `mapImported` = true;";
$mysqli->query($query); $mysqli->query($query);
if ($mysqli->error) { if ($mysqli->error) {
trigger_error($mysqli->error); trigger_error($mysqli->error);
} }
$result2->free(); $result2->free();
} }
$result->free_result(); $result->free_result();
return; return;
} }
/** /**
* Save Mx Karma Votes at Mapend * Save Mx Karma Votes at Mapend
*/ */
public function sendMxKarmaVotes(Map $map) { public function sendMxKarmaVotes(Map $map) {
if (!$this->maniaControl->settingManager->getSetting($this, self::SETTING_MX_KARMA_ACTIVATED)) { if (!$this->maniaControl->settingManager->getSetting($this, self::SETTING_MX_KARMA_ACTIVATED)) {
return; return;
} }
if (!isset($this->mxKarma['session'])) { if (!isset($this->mxKarma['session'])) {
if (!isset($this->mxKarma['connectionInProgress']) || !$this->mxKarma['connectionInProgress']) { if (!isset($this->mxKarma['connectionInProgress']) || !$this->mxKarma['connectionInProgress']) {
$this->mxKarmaOpenSession(); $this->mxKarmaOpenSession();
} }
return; return;
} }
if (!isset($this->mxKarma['votes']) || count($this->mxKarma['votes']) == 0) { if (!isset($this->mxKarma['votes']) || count($this->mxKarma['votes']) == 0) {
return; return;
} }
$this->mxKarma['map'] = $map; $this->mxKarma['map'] = $map;
} }
/** /**
* Post the Karma votes to MX-Karma * Post the Karma votes to MX-Karma
* *
* @param Map $map * @param Map $map
* @param array $votes * @param array $votes
* @param bool $import * @param bool $import
*/ */
private function postKarmaVotes(Map $map, array $votes, $import = false) { private function postKarmaVotes(Map $map, array $votes, $import = false) {
if (!isset($this->mxKarma['session'])) { if (!isset($this->mxKarma['session'])) {
@ -888,48 +917,52 @@ class KarmaPlugin implements CallbackListener, TimerListener, Plugin {
} }
return; return;
} }
$gameMode = $this->maniaControl->server->getGameMode(true); $gameMode = $this->maniaControl->server->getGameMode(true);
if (count($votes) == 0) { if (count($votes) == 0) {
return; return;
} }
$properties = array(); $properties = array();
if ($gameMode == 'Script') { if ($gameMode == 'Script') {
$scriptName = $this->maniaControl->client->getScriptName(); $scriptName = $this->maniaControl->client->getScriptName();
$properties['gamemode'] = $scriptName["CurrentValue"]; $properties['gamemode'] = $scriptName["CurrentValue"];
} else { }
else {
$properties['gamemode'] = $gameMode; $properties['gamemode'] = $gameMode;
} }
if ($import) { if ($import) {
$properties['maptime'] = 0; $properties['maptime'] = 0;
} else { }
else {
$properties['maptime'] = time() - $this->mxKarma['startTime']; $properties['maptime'] = time() - $this->mxKarma['startTime'];
} }
$properties['votes'] = $votes; $properties['votes'] = $votes;
$properties['titleid'] = $this->maniaControl->server->titleId; $properties['titleid'] = $this->maniaControl->server->titleId;
$properties['mapname'] = $map->rawName; $properties['mapname'] = $map->rawName;
$properties['mapuid'] = $map->uid; $properties['mapuid'] = $map->uid;
$properties['mapauthor'] = $map->authorLogin; $properties['mapauthor'] = $map->authorLogin;
$properties['isimport'] = $import; $properties['isimport'] = $import;
$content = json_encode($properties); $content = json_encode($properties);
$self = $this; $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){ $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) { if (!$error) {
$data = json_decode($data); $data = json_decode($data);
if ($data->success) { if ($data->success) {
$self->maniaControl->log("Votes successfully permitted"); $self->maniaControl->log("Votes successfully permitted");
} else { }
else {
$self->maniaControl->log("Error while updating votes: " . $data->data->message); $self->maniaControl->log("Error while updating votes: " . $data->data->message);
//TODO remove temp trigger // 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)); $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 { }
else {
$self->maniaControl->log($error); $self->maniaControl->log($error);
} }
}, $content, false, 'application/json'); }, $content, false, 'application/json');