fixed + improved map saving/adding

This commit is contained in:
Steffen Schröder 2014-03-31 21:04:15 +02:00
parent b4bbfe6c72
commit 334b3b606c
3 changed files with 195 additions and 168 deletions

View File

@ -3,6 +3,7 @@
namespace ManiaControl\Files; namespace ManiaControl\Files;
use ManiaControl\ManiaControl; use ManiaControl\ManiaControl;
use ManiaControl\Formatter;
/** /**
* File utility class * File utility class
@ -87,6 +88,8 @@ abstract class FileUtil {
* @return string * @return string
*/ */
public static function getClearedFileName($fileName) { public static function getClearedFileName($fileName) {
return str_replace(array('\\', '/', ':', '*', '?', '"', '<', '>', '|'), '_', $fileName); $fileName = Formatter::stripCodes($fileName);
$fileName = str_replace(array('\\', '/', ':', '*', '?', '"', '<', '>', '|'), '_', $fileName);
return $fileName;
} }
} }

View File

@ -136,7 +136,7 @@ class MapCommands implements CommandListener, ManialinkPageAnswerListener, Callb
} }
/** /**
* Handle addmap command * Handle shufflemaps command
* *
* @param array $chatCallback * @param array $chatCallback
* @param \ManiaControl\Players\Player $player * @param \ManiaControl\Players\Player $player

View File

@ -24,20 +24,20 @@ class MapManager implements CallbackListener {
/* /*
* Constants * Constants
*/ */
const TABLE_MAPS = 'mc_maps'; const TABLE_MAPS = 'mc_maps';
const CB_BEGINMAP = 'MapManager.BeginMap'; const CB_BEGINMAP = 'MapManager.BeginMap';
const CB_ENDMAP = 'MapManager.EndMap'; const CB_ENDMAP = 'MapManager.EndMap';
const CB_MAPS_UPDATED = 'MapManager.MapsUpdated'; const CB_MAPS_UPDATED = 'MapManager.MapsUpdated';
const CB_KARMA_UPDATED = 'MapManager.KarmaUpdated'; const CB_KARMA_UPDATED = 'MapManager.KarmaUpdated';
const SETTING_PERMISSION_ADD_MAP = 'Add Maps'; const SETTING_PERMISSION_ADD_MAP = 'Add Maps';
const SETTING_PERMISSION_REMOVE_MAP = 'Remove Maps'; const SETTING_PERMISSION_REMOVE_MAP = 'Remove Maps';
const SETTING_PERMISSION_SHUFFLE_MAPS = 'Shuffle Maps'; const SETTING_PERMISSION_SHUFFLE_MAPS = 'Shuffle Maps';
const SETTING_PERMISSION_CHECK_UPDATE = 'Check Map Update'; const SETTING_PERMISSION_CHECK_UPDATE = 'Check Map Update';
const SETTING_PERMISSION_SKIP_MAP = 'Skip Map'; const SETTING_PERMISSION_SKIP_MAP = 'Skip Map';
const SETTING_PERMISSION_RESTART_MAP = 'Restart Map'; const SETTING_PERMISSION_RESTART_MAP = 'Restart Map';
const SETTING_AUTOSAVE_MAPLIST = 'Autosave Maplist file'; const SETTING_AUTOSAVE_MAPLIST = 'Autosave Maplist file';
const SETTING_MAPLIST_FILE = 'File to write Maplist in'; const SETTING_MAPLIST_FILE = 'File to write Maplist in';
/* /*
* Public Properties * Public Properties
*/ */
@ -46,13 +46,15 @@ class MapManager implements CallbackListener {
public $mapList = null; public $mapList = null;
public $mxList = null; public $mxList = null;
public $mxManager = null; public $mxManager = null;
/* /*
* Private Properties * Private Properties
*/ */
private $maniaControl = null; private $maniaControl = null;
private $maps = array(); private $maps = array();
/** @var Map $currentMap */ /**
* @var Map $currentMap
*/
private $currentMap = null; private $currentMap = null;
private $mapEnded = false; private $mapEnded = false;
private $mapBegan = false; private $mapBegan = false;
@ -65,26 +67,31 @@ class MapManager implements CallbackListener {
public function __construct(ManiaControl $maniaControl) { public function __construct(ManiaControl $maniaControl) {
$this->maniaControl = $maniaControl; $this->maniaControl = $maniaControl;
$this->initTables(); $this->initTables();
// Create map commands instance // Create map commands instance
$this->mxManager = new ManiaExchangeManager($this->maniaControl); $this->mxManager = new ManiaExchangeManager($this->maniaControl);
$this->mapList = new MapList($this->maniaControl); $this->mapList = new MapList($this->maniaControl);
$this->mxList = new ManiaExchangeList($this->maniaControl); $this->mxList = new ManiaExchangeList($this->maniaControl);
$this->mapCommands = new MapCommands($maniaControl); $this->mapCommands = new MapCommands($maniaControl);
$this->mapQueue = new MapQueue($this->maniaControl); $this->mapQueue = new MapQueue($this->maniaControl);
// Register for callbacks // Register for callbacks
$this->maniaControl->callbackManager->registerCallbackListener(CallbackManager::CB_ONINIT, $this, 'handleOnInit'); $this->maniaControl->callbackManager->registerCallbackListener(CallbackManager::CB_ONINIT, $this, 'handleOnInit');
$this->maniaControl->callbackManager->registerCallbackListener(CallbackManager::CB_MP_MAPLISTMODIFIED, $this, 'mapsModified'); $this->maniaControl->callbackManager->registerCallbackListener(CallbackManager::CB_MP_MAPLISTMODIFIED, $this, 'mapsModified');
// Define Rights // Define Rights
$this->maniaControl->authenticationManager->definePermissionLevel(self::SETTING_PERMISSION_ADD_MAP, AuthenticationManager::AUTH_LEVEL_ADMIN); $this->maniaControl->authenticationManager->definePermissionLevel(self::SETTING_PERMISSION_ADD_MAP, AuthenticationManager::AUTH_LEVEL_ADMIN);
$this->maniaControl->authenticationManager->definePermissionLevel(self::SETTING_PERMISSION_REMOVE_MAP, AuthenticationManager::AUTH_LEVEL_ADMIN); $this->maniaControl->authenticationManager->definePermissionLevel(self::SETTING_PERMISSION_REMOVE_MAP,
$this->maniaControl->authenticationManager->definePermissionLevel(self::SETTING_PERMISSION_SHUFFLE_MAPS, AuthenticationManager::AUTH_LEVEL_ADMIN); AuthenticationManager::AUTH_LEVEL_ADMIN);
$this->maniaControl->authenticationManager->definePermissionLevel(self::SETTING_PERMISSION_CHECK_UPDATE, AuthenticationManager::AUTH_LEVEL_MODERATOR); $this->maniaControl->authenticationManager->definePermissionLevel(self::SETTING_PERMISSION_SHUFFLE_MAPS,
$this->maniaControl->authenticationManager->definePermissionLevel(self::SETTING_PERMISSION_SKIP_MAP, AuthenticationManager::AUTH_LEVEL_MODERATOR); AuthenticationManager::AUTH_LEVEL_ADMIN);
$this->maniaControl->authenticationManager->definePermissionLevel(self::SETTING_PERMISSION_RESTART_MAP, AuthenticationManager::AUTH_LEVEL_MODERATOR); $this->maniaControl->authenticationManager->definePermissionLevel(self::SETTING_PERMISSION_CHECK_UPDATE,
AuthenticationManager::AUTH_LEVEL_MODERATOR);
$this->maniaControl->authenticationManager->definePermissionLevel(self::SETTING_PERMISSION_SKIP_MAP,
AuthenticationManager::AUTH_LEVEL_MODERATOR);
$this->maniaControl->authenticationManager->definePermissionLevel(self::SETTING_PERMISSION_RESTART_MAP,
AuthenticationManager::AUTH_LEVEL_MODERATOR);
$this->maniaControl->settingManager->initSetting($this, self::SETTING_AUTOSAVE_MAPLIST, true); $this->maniaControl->settingManager->initSetting($this, self::SETTING_AUTOSAVE_MAPLIST, true);
$this->maniaControl->settingManager->initSetting($this, self::SETTING_MAPLIST_FILE, "MatchSettings/tracklist.txt"); $this->maniaControl->settingManager->initSetting($this, self::SETTING_MAPLIST_FILE, "MatchSettings/tracklist.txt");
} }
@ -96,7 +103,7 @@ class MapManager implements CallbackListener {
*/ */
private function initTables() { private function initTables() {
$mysqli = $this->maniaControl->database->mysqli; $mysqli = $this->maniaControl->database->mysqli;
$query = "CREATE TABLE IF NOT EXISTS `" . self::TABLE_MAPS . "` ( $query = "CREATE TABLE IF NOT EXISTS `" . self::TABLE_MAPS . "` (
`index` int(11) NOT NULL AUTO_INCREMENT, `index` int(11) NOT NULL AUTO_INCREMENT,
`mxid` int(11), `mxid` int(11),
`uid` varchar(50) NOT NULL, `uid` varchar(50) NOT NULL,
@ -124,7 +131,7 @@ class MapManager implements CallbackListener {
* @return bool * @return bool
*/ */
private function saveMap(Map &$map) { private function saveMap(Map &$map) {
$mysqli = $this->maniaControl->database->mysqli; $mysqli = $this->maniaControl->database->mysqli;
$mapQuery = "INSERT INTO `" . self::TABLE_MAPS . "` ( $mapQuery = "INSERT INTO `" . self::TABLE_MAPS . "` (
`uid`, `uid`,
`name`, `name`,
@ -139,7 +146,7 @@ class MapManager implements CallbackListener {
`fileName` = VALUES(`fileName`), `fileName` = VALUES(`fileName`),
`environment` = VALUES(`environment`), `environment` = VALUES(`environment`),
`mapType` = VALUES(`mapType`);"; `mapType` = VALUES(`mapType`);";
$mapStatement = $mysqli->prepare($mapQuery); $mapStatement = $mysqli->prepare($mapQuery);
if ($mysqli->error) { if ($mysqli->error) {
trigger_error($mysqli->error); trigger_error($mysqli->error);
@ -164,9 +171,9 @@ class MapManager implements CallbackListener {
* @return bool * @return bool
*/ */
private function updateMapTimestamp($uid) { private function updateMapTimestamp($uid) {
$mysqli = $this->maniaControl->database->mysqli; $mysqli = $this->maniaControl->database->mysqli;
$mapQuery = "UPDATE `" . self::TABLE_MAPS . "` SET mxid = 0, changed = NOW() WHERE 'uid' = ?"; $mapQuery = "UPDATE `" . self::TABLE_MAPS . "` SET mxid = 0, changed = NOW() WHERE 'uid' = ?";
$mapStatement = $mysqli->prepare($mapQuery); $mapStatement = $mysqli->prepare($mapQuery);
if ($mysqli->error) { if ($mysqli->error) {
trigger_error($mysqli->error); trigger_error($mysqli->error);
@ -187,20 +194,22 @@ class MapManager implements CallbackListener {
* Updates a Map from Mania Exchange * Updates a Map from Mania Exchange
* *
* @param Player $admin * @param Player $admin
* @param $mxId * @param $mxId
* @param $uid * @param $uid
*/ */
public function updateMap(Player $admin, $uid) { public function updateMap(Player $admin, $uid) {
$this->updateMapTimestamp($uid); $this->updateMapTimestamp($uid);
if (!isset($uid)) { if (!isset($uid)) {
trigger_error("Error while updating Map, unkown UID: " . $uid); trigger_error("Error while updating Map, unkown UID: " . $uid);
$this->maniaControl->chat->sendError("Error while updating Map.", $admin->login); $this->maniaControl->chat->sendError("Error while updating Map.", $admin->login);
return; return;
} }
$map = $this->maps[$uid]; $map = $this->maps[$uid];
/** @var Map $map */ /**
* @var Map $map
*/
$mxId = $map->mx->id; $mxId = $map->mx->id;
$this->removeMap($admin, $uid, true, false); $this->removeMap($admin, $uid, true, false);
$this->addMapFromMx($mxId, $admin->login, true); $this->addMapFromMx($mxId, $admin->login, true);
@ -210,27 +219,27 @@ class MapManager implements CallbackListener {
* Remove a Map * Remove a Map
* *
* @param \ManiaControl\Players\Player $admin * @param \ManiaControl\Players\Player $admin
* @param string $uid * @param string $uid
* @param bool $eraseFile * @param bool $eraseFile
* @param bool $message * @param bool $message
*/ */
public function removeMap(Player $admin, $uid, $eraseFile = false, $message = true) { public function removeMap(Player $admin, $uid, $eraseFile = false, $message = true) {
$map = $this->maps[$uid]; $map = $this->maps[$uid];
//Unset the Map everywhere // Unset the Map everywhere
$this->mapQueue->removeFromMapQueue($admin, $map->uid); $this->mapQueue->removeFromMapQueue($admin, $map->uid);
if ($map->mx) { if ($map->mx) {
$this->mxManager->unsetMap($map->mx->id); $this->mxManager->unsetMap($map->mx->id);
} }
// Remove map // Remove map
$this->maniaControl->client->removeMap($map->fileName); $this->maniaControl->client->removeMap($map->fileName);
if ($eraseFile) { if ($eraseFile) {
// Check if ManiaControl can even write to the maps dir // Check if ManiaControl can even write to the maps dir
$mapDir = $this->maniaControl->client->getMapsDirectory(); $mapDir = $this->maniaControl->client->getMapsDirectory();
// Delete map file // Delete map file
if (!@unlink($mapDir . $map->fileName)) { if (!@unlink($mapDir . $map->fileName)) {
trigger_error("Couldn't remove Map '{$mapDir}{$map->fileName}'."); trigger_error("Couldn't remove Map '{$mapDir}{$map->fileName}'.");
@ -238,14 +247,14 @@ class MapManager implements CallbackListener {
return; return;
} }
} }
//Show Message // Show Message
if ($message) { if ($message) {
$message = '$<' . $admin->nickname . '$> removed $<' . $map->name . '$>!'; $message = '$<' . $admin->nickname . '$> removed $<' . $map->name . '$>!';
$this->maniaControl->chat->sendSuccess($message); $this->maniaControl->chat->sendSuccess($message);
$this->maniaControl->log($message, true); $this->maniaControl->log($message, true);
} }
unset($this->maps[$uid]); unset($this->maps[$uid]);
} }
@ -254,31 +263,33 @@ class MapManager implements CallbackListener {
*/ */
public function restructureMapList() { public function restructureMapList() {
$currentIndex = $this->getMapIndex($this->currentMap); $currentIndex = $this->getMapIndex($this->currentMap);
//No RestructureNeeded // No RestructureNeeded
if ($currentIndex < Maplist::MAX_MAPS_PER_PAGE - 1) { if ($currentIndex < Maplist::MAX_MAPS_PER_PAGE - 1) {
return true; return true;
} }
$lowerMapArray = array(); $lowerMapArray = array();
$higherMapArray = array(); $higherMapArray = array();
$i = 0; $i = 0;
foreach($this->maps as $map) { foreach ($this->maps as $map) {
if ($i < $currentIndex) { if ($i < $currentIndex) {
$lowerMapArray[] = $map->fileName; $lowerMapArray[] = $map->fileName;
} else { }
else {
$higherMapArray[] = $map->fileName; $higherMapArray[] = $map->fileName;
} }
$i++; $i++;
} }
$mapArray = array_merge($higherMapArray, $lowerMapArray); $mapArray = array_merge($higherMapArray, $lowerMapArray);
array_shift($mapArray); array_shift($mapArray);
try { try {
$this->maniaControl->client->chooseNextMapList($mapArray); $this->maniaControl->client->chooseNextMapList($mapArray);
} catch(Exception $e) { }
catch (Exception $e) {
trigger_error("Error while restructuring the Maplist. " . $e->getMessage()); trigger_error("Error while restructuring the Maplist. " . $e->getMessage());
return false; return false;
} }
@ -294,30 +305,33 @@ class MapManager implements CallbackListener {
public function shuffleMapList($admin = null) { public function shuffleMapList($admin = null) {
$shuffledMaps = $this->maps; $shuffledMaps = $this->maps;
shuffle($shuffledMaps); shuffle($shuffledMaps);
$mapArray = array(); $mapArray = array();
foreach($shuffledMaps as $map) { foreach ($shuffledMaps as $map) {
/** @var Map $map */ /**
* @var Map $map
*/
$mapArray[] = $map->fileName; $mapArray[] = $map->fileName;
} }
try { try {
$this->maniaControl->client->chooseNextMapList($mapArray); $this->maniaControl->client->chooseNextMapList($mapArray);
} catch(Exception $e) { }
catch (Exception $e) {
trigger_error("Couldn't shuffle mapList. " . $e->getMessage()); trigger_error("Couldn't shuffle mapList. " . $e->getMessage());
return false; return false;
} }
$this->fetchCurrentMap(); $this->fetchCurrentMap();
if ($admin != null) { if ($admin != null) {
$message = '$<' . $admin->nickname . '$> shuffled the Maplist!'; $message = '$<' . $admin->nickname . '$> shuffled the Maplist!';
$this->maniaControl->chat->sendSuccess($message); $this->maniaControl->chat->sendSuccess($message);
$this->maniaControl->log($message, true); $this->maniaControl->log($message, true);
} }
//Restructure if needed // Restructure if needed
$this->restructureMapList(); $this->restructureMapList();
return true; return true;
} }
@ -331,15 +345,15 @@ class MapManager implements CallbackListener {
public function initializeMap($rpcMap) { public function initializeMap($rpcMap) {
$map = new Map($rpcMap); $map = new Map($rpcMap);
$this->saveMap($map); $this->saveMap($map);
$mapsDirectory = $this->maniaControl->server->getMapsDirectory(); $mapsDirectory = $this->maniaControl->server->getMapsDirectory();
if (is_readable($mapsDirectory . $map->fileName)) { if (is_readable($mapsDirectory . $map->fileName)) {
$mapFetcher = new \GBXChallMapFetcher(true); $mapFetcher = new \GBXChallMapFetcher(true);
$mapFetcher->processFile($mapsDirectory . $map->fileName); $mapFetcher->processFile($mapsDirectory . $map->fileName);
$map->authorNick = FORMATTER::stripDirtyCodes($mapFetcher->authorNick); $map->authorNick = FORMATTER::stripDirtyCodes($mapFetcher->authorNick);
$map->authorEInfo = $mapFetcher->authorEInfo; $map->authorEInfo = $mapFetcher->authorEInfo;
$map->authorZone = $mapFetcher->authorZone; $map->authorZone = $mapFetcher->authorZone;
$map->comment = $mapFetcher->comment; $map->comment = $mapFetcher->comment;
} }
return $map; return $map;
} }
@ -348,33 +362,36 @@ class MapManager implements CallbackListener {
* Updates the full Map list, needed on Init, addMap and on ShuffleMaps * Updates the full Map list, needed on Init, addMap and on ShuffleMaps
*/ */
private function updateFullMapList() { private function updateFullMapList() {
$maps = $this->maniaControl->client->getMapList(100, 0); $maps = $this->maniaControl->client->getMapList(100, 0);
$tempList = array(); $tempList = array();
foreach($maps as $rpcMap) { foreach ($maps as $rpcMap) {
if (array_key_exists($rpcMap->uId, $this->maps)) { if (array_key_exists($rpcMap->uId, $this->maps)) {
// Map already exists, only update index // Map already exists, only update index
$tempList[$rpcMap->uId] = $this->maps[$rpcMap->uId]; $tempList[$rpcMap->uId] = $this->maps[$rpcMap->uId];
} else { // Insert Map Object }
$map = $this->initializeMap($rpcMap); else { // Insert Map Object
$map = $this->initializeMap($rpcMap);
$tempList[$map->uid] = $map; $tempList[$map->uid] = $map;
} }
} }
// restore Sorted Maplist // restore Sorted Maplist
$this->maps = $tempList; $this->maps = $tempList;
// Trigger own callback // Trigger own callback
$this->maniaControl->callbackManager->triggerCallback(self::CB_MAPS_UPDATED); $this->maniaControl->callbackManager->triggerCallback(self::CB_MAPS_UPDATED);
//Write MapList // Write MapList
if ($this->maniaControl->settingManager->getSetting($this, self::SETTING_AUTOSAVE_MAPLIST)) { if ($this->maniaControl->settingManager->getSetting($this, self::SETTING_AUTOSAVE_MAPLIST)) {
try { try {
$this->maniaControl->client->saveMatchSettings($this->maniaControl->settingManager->getSetting($this, self::SETTING_MAPLIST_FILE)); $this->maniaControl->client->saveMatchSettings($this->maniaControl->settingManager->getSetting($this, self::SETTING_MAPLIST_FILE));
} catch(Exception $e) { }
catch (Exception $e) {
if ($e->getMessage() == 'Unable to write the playlist file.') { if ($e->getMessage() == 'Unable to write the playlist file.') {
$this->maniaControl->log("Unable to write the playlist file, please checkout your MX-Folders File permissions!"); $this->maniaControl->log("Unable to write the playlist file, please checkout your MX-Folders File permissions!");
} else { }
else {
throw $e; throw $e;
} }
} }
@ -388,15 +405,15 @@ class MapManager implements CallbackListener {
*/ */
private function fetchCurrentMap() { private function fetchCurrentMap() {
$rpcMap = $this->maniaControl->client->getCurrentMapInfo(); $rpcMap = $this->maniaControl->client->getCurrentMapInfo();
if (array_key_exists($rpcMap->uId, $this->maps)) { if (array_key_exists($rpcMap->uId, $this->maps)) {
$this->currentMap = $this->maps[$rpcMap->uId]; $this->currentMap = $this->maps[$rpcMap->uId];
$this->currentMap->nbCheckpoints = $rpcMap->nbCheckpoints; $this->currentMap->nbCheckpoints = $rpcMap->nbCheckpoints;
$this->currentMap->nbLaps = $rpcMap->nbLaps; $this->currentMap->nbLaps = $rpcMap->nbLaps;
return $this->currentMap; return $this->currentMap;
} }
$this->currentMap = $this->initializeMap($rpcMap); $this->currentMap = $this->initializeMap($rpcMap);
$this->maps[$this->currentMap->uid] = $this->currentMap; $this->maps[$this->currentMap->uid] = $this->currentMap;
return $this->currentMap; return $this->currentMap;
} }
@ -407,11 +424,11 @@ class MapManager implements CallbackListener {
public function handleOnInit() { public function handleOnInit() {
$this->updateFullMapList(); $this->updateFullMapList();
$this->fetchCurrentMap(); $this->fetchCurrentMap();
//Fetch Mx Infos // Fetch Mx Infos
$this->mxManager->fetchManiaExchangeMapInformations(); $this->mxManager->fetchManiaExchangeMapInformations();
//Restructure Maplist // Restructure Maplist
$this->restructureMapList(); $this->restructureMapList();
} }
@ -451,7 +468,7 @@ class MapManager implements CallbackListener {
} }
$this->mapBegan = true; $this->mapBegan = true;
$this->mapEnded = false; $this->mapEnded = false;
if (!isset($callback[1][0]["UId"])) { if (!isset($callback[1][0]["UId"])) {
// TODO: why can this even happen? // TODO: why can this even happen?
$this->maniaControl->errorHandler->triggerDebugNotice('map uid not set! ' . print_r($callback, true)); $this->maniaControl->errorHandler->triggerDebugNotice('map uid not set! ' . print_r($callback, true));
@ -461,23 +478,24 @@ class MapManager implements CallbackListener {
// Map already exists, only update index // Map already exists, only update index
$this->currentMap = $this->maps[$callback[1][0]["UId"]]; $this->currentMap = $this->maps[$callback[1][0]["UId"]];
if (!$this->currentMap->nbCheckpoints || !$this->currentMap->nbLaps) { if (!$this->currentMap->nbCheckpoints || !$this->currentMap->nbLaps) {
$rpcMap = $this->maniaControl->client->getCurrentMapInfo(); $rpcMap = $this->maniaControl->client->getCurrentMapInfo();
$this->currentMap->nbLaps = $rpcMap->nbLaps; $this->currentMap->nbLaps = $rpcMap->nbLaps;
$this->currentMap->nbCheckpoints = $rpcMap->nbCheckpoints; $this->currentMap->nbCheckpoints = $rpcMap->nbCheckpoints;
} }
} else { }
$rpcMap = \Maniaplanet\DedicatedServer\Structures\Map::fromArray($callback[1][0]); else {
$rpcMap = \Maniaplanet\DedicatedServer\Structures\Map::fromArray($callback[1][0]);
$this->currentMap = $this->initializeMap($rpcMap); $this->currentMap = $this->initializeMap($rpcMap);
// TODO: can this ever happen? // TODO: can this ever happen?
$this->maniaControl->errorHandler->triggerDebugNotice("new map wasn't fetched yet! " . $callback[1][0]["UId"]); $this->maniaControl->errorHandler->triggerDebugNotice("new map wasn't fetched yet! " . $callback[1][0]["UId"]);
} }
// Restructure MapList if id is over 15 // Restructure MapList if id is over 15
$this->restructureMapList(); $this->restructureMapList();
// Update the mx of the map (for update checks, etc.) // Update the mx of the map (for update checks, etc.)
$this->mxManager->fetchManiaExchangeMapInformations($this->currentMap); $this->mxManager->fetchManiaExchangeMapInformations($this->currentMap);
// Trigger own BeginMap callback // Trigger own BeginMap callback
$this->maniaControl->callbackManager->triggerCallback(self::CB_BEGINMAP, $this->currentMap); $this->maniaControl->callbackManager->triggerCallback(self::CB_BEGINMAP, $this->currentMap);
} }
@ -502,7 +520,7 @@ class MapManager implements CallbackListener {
} }
$this->mapEnded = true; $this->mapEnded = true;
$this->mapBegan = false; $this->mapBegan = false;
// Trigger own EndMap callback // Trigger own EndMap callback
$this->maniaControl->callbackManager->triggerCallback(self::CB_ENDMAP, $this->currentMap); $this->maniaControl->callbackManager->triggerCallback(self::CB_ENDMAP, $this->currentMap);
} }
@ -518,7 +536,7 @@ class MapManager implements CallbackListener {
} }
$this->mapEnded = true; $this->mapEnded = true;
$this->mapBegan = false; $this->mapBegan = false;
// Trigger own EndMap callback // Trigger own EndMap callback
$this->maniaControl->callbackManager->triggerCallback(self::CB_ENDMAP, $this->currentMap); $this->maniaControl->callbackManager->triggerCallback(self::CB_ENDMAP, $this->currentMap);
} }
@ -556,86 +574,88 @@ class MapManager implements CallbackListener {
/** /**
* Adds a Map from Mania Exchange * Adds a Map from Mania Exchange
* *
* @param $mapId * @param $mapId
* @param $login * @param $login
* @param bool $update * @param bool $update
*/ */
public function addMapFromMx($mapId, $login, $update = false) { public function addMapFromMx($mapId, $login, $update = false) {
if (is_numeric($mapId)) { if (is_numeric($mapId)) {
// Check if map exists // Check if map exists
$this->maniaControl->mapManager->mxManager->getMapInfo($mapId, function (MXMapInfo $mapInfo) use (&$login, &$update) { $this->maniaControl->mapManager->mxManager->getMapInfo($mapId,
if (!$mapInfo || !isset($mapInfo->uploaded)) { function (MXMapInfo $mapInfo) use(&$login, &$update) {
// Invalid id if (!$mapInfo || !isset($mapInfo->uploaded)) {
$this->maniaControl->chat->sendError('Invalid MX-Id!', $login); // Invalid id
return; $this->maniaControl->chat->sendError('Invalid MX-Id!', $login);
} return;
}
//TODO hardcoded whiel beta, later take just $mapInfo->url again
$url = 'http://' . $mapInfo->prefix . '.mania-exchange.com/' . $mapInfo->dir . '/download/' . $mapInfo->id; // TODO hardcoded during closed beta, later take just $mapInfo->url again
if($this->maniaControl->settingManager->getSetting($this->mxManager, ManiaExchangeManager::SETTING_MP3_BETA_TESTING)){ $url = 'http://' . $mapInfo->prefix . '.mania-exchange.com/' . $mapInfo->dir . '/download/' . $mapInfo->id;
$url .= '?key=t42kEMjzH7xpAjBFHAvEkC7rqAlw'; if ($this->maniaControl->settingManager->getSetting($this->mxManager, ManiaExchangeManager::SETTING_MP3_BETA_TESTING)) {
} $url .= '?key=t42kEMjzH7xpAjBFHAvEkC7rqAlw';
}
//Download the file
$this->maniaControl->fileReader->loadFile($url, function ($file, $error) use (&$login, &$mapInfo, &$update) { // Download the file
if (!$file) { $this->maniaControl->fileReader->loadFile($url,
// Download error function ($file, $error) use(&$login, &$mapInfo, &$update) {
$this->maniaControl->chat->sendError('Download failed!', $login); if (!$file) {
return; // Download error
} $this->maniaControl->chat->sendError('Download failed!', $login);
$this->processMapFile($file, $mapInfo, $login, $update); return;
}); }
}); $this->processMapFile($file, $mapInfo, $login, $update);
});
});
} }
} }
/** /**
* Process the MapFile * Process the MapFile
* *
* @param $file * @param $file
* @param MXMapInfo $mapInfo * @param MXMapInfo $mapInfo
* @param $login * @param $login
* @param $update * @param $update
*/ */
private function processMapFile($file, MXMapInfo $mapInfo, $login, $update) { private function processMapFile($file, MXMapInfo $mapInfo, $login, $update) {
$mapDir = $this->maniaControl->client->getMapsDirectory(); // Check if map is already on the server
//Check if map is already on the server
if ($this->getMapByUid($mapInfo->uid) != null) { if ($this->getMapByUid($mapInfo->uid) != null) {
// Download error // Download error
$this->maniaControl->chat->sendError('Map is already on the server!', $login); $this->maniaControl->chat->sendError('Map is already on the server!', $login);
return; return;
} }
// Save map // Save map
$fileName = $mapInfo->id . '_' . $mapInfo->name . '.Map.Gbx'; $fileName = $mapInfo->id . '_' . $mapInfo->name . '.Map.Gbx';
$fileName = FileUtil::getClearedFileName($fileName); $fileName = FileUtil::getClearedFileName($fileName);
$downloadDirectory = $this->maniaControl->settingManager->getSetting($this, 'MapDownloadDirectory', 'MX'); $downloadFolderName = $this->maniaControl->settingManager->getSetting($this, 'MapDownloadDirectory', 'MX');
$relativeMapFileName = $downloadFolderName . '/' . $fileName;
$mapFileName = $downloadDirectory . '/' . $fileName; $mapDir = $this->maniaControl->client->getMapsDirectory();
$downloadDirectory = $mapDir . '/' . $downloadFolderName . '/';
//Check if it can get locally Written $fullMapFileName = $downloadDirectory . $fileName;
// Check if it can get written locally
if (is_dir($mapDir)) { if (is_dir($mapDir)) {
// Create download directory if necessary // Create download directory if necessary
if (!is_dir($mapDir . $downloadDirectory) && !mkdir($mapDir . $downloadDirectory)) { if (!is_dir($downloadDirectory) && !mkdir($downloadDirectory)) {
trigger_error("ManiaControl doesn't have to rights to save maps in '{$mapDir}{$downloadDirectory}'."); trigger_error("ManiaControl doesn't have to rights to save maps in '{$downloadDirectory}'.");
$this->maniaControl->chat->sendError("ManiaControl doesn't have the rights to save maps.", $login); $this->maniaControl->chat->sendError("ManiaControl doesn't have the rights to save maps.", $login);
return; return;
} }
$mapDir .= $downloadDirectory . '/'; if (!file_put_contents($fullMapFileName, $file)) {
if (!file_put_contents($mapDir . $fileName, $file)) {
// Save error // Save error
$this->maniaControl->chat->sendError('Saving map failed!', $login); $this->maniaControl->chat->sendError('Saving map failed!', $login);
return; return;
} }
//Write via Write File Method }
} else { else {
// Write map via write file method
try { try {
$this->maniaControl->client->writeFileFromString($mapFileName, $file); $this->maniaControl->client->writeFileFromString($relativeMapFileName, $file);
} catch(InvalidArgumentException $e) { }
catch (InvalidArgumentException $e) {
if ($e->getMessage() == 'data are too big') { if ($e->getMessage() == 'data are too big') {
$this->maniaControl->chat->sendError("Map is too big for a remote save.", $login); $this->maniaControl->chat->sendError("Map is too big for a remote save.", $login);
return; return;
@ -643,38 +663,42 @@ class MapManager implements CallbackListener {
throw $e; throw $e;
} }
} }
// Check for valid map // Check for valid map
try { try {
$this->maniaControl->client->checkMapForCurrentServerParams($mapFileName); $this->maniaControl->client->checkMapForCurrentServerParams($relativeMapFileName);
} catch(Exception $e) { }
trigger_error("Couldn't check if map is valid ('{$mapFileName}'). " . $e->getMessage()); catch (Exception $e) {
trigger_error("Couldn't check if map is valid ('{$relativeMapFileName}'). " . $e->getMessage());
$this->maniaControl->chat->sendError('Wrong MapType or not validated!', $login); $this->maniaControl->chat->sendError('Wrong MapType or not validated!', $login);
return; return;
} }
// Add map to map list // Add map to map list
$this->maniaControl->client->insertMap($mapFileName); $this->maniaControl->client->insertMap($relativeMapFileName);
$this->updateFullMapList(); $this->updateFullMapList();
//Update Mx MapInfo // Update Mx MapInfo
$this->maniaControl->mapManager->mxManager->updateMapObjectsWithManiaExchangeIds(array($mapInfo)); $this->maniaControl->mapManager->mxManager->updateMapObjectsWithManiaExchangeIds(array($mapInfo));
//Update last updated time // Update last updated time
$map = $this->maps[$mapInfo->uid]; $map = $this->maps[$mapInfo->uid];
/** @var Map $map */ /**
* @var Map $map
*/
$map->lastUpdate = time(); $map->lastUpdate = time();
$player = $this->maniaControl->playerManager->getPlayer($login); $player = $this->maniaControl->playerManager->getPlayer($login);
if (!$update) { if (!$update) {
//Message // Message
$message = '$<' . $player->nickname . '$> added $<' . $mapInfo->name . '$>!'; $message = '$<' . $player->nickname . '$> added $<' . $mapInfo->name . '$>!';
$this->maniaControl->chat->sendSuccess($message); $this->maniaControl->chat->sendSuccess($message);
$this->maniaControl->log($message, true); $this->maniaControl->log($message, true);
// Queue requested Map // Queue requested Map
$this->maniaControl->mapManager->mapQueue->addMapToMapQueue($login, $mapInfo->uid); $this->maniaControl->mapManager->mapQueue->addMapToMapQueue($login, $mapInfo->uid);
} else { }
else {
$message = '$<' . $player->nickname . '$> updated $<' . $mapInfo->name . '$>!'; $message = '$<' . $player->nickname . '$> updated $<' . $mapInfo->name . '$>!';
$this->maniaControl->chat->sendSuccess($message); $this->maniaControl->chat->sendSuccess($message);
$this->maniaControl->log($message, true); $this->maniaControl->log($message, true);