removed 'application' folder to have everything in the root directory

This commit is contained in:
Steffen Schröder
2014-09-29 18:20:09 +02:00
parent 1569fd5488
commit 9642433363
284 changed files with 4 additions and 50 deletions

View File

@ -0,0 +1,392 @@
<?php
namespace ManiaControl\Maps;
use FML\Controls\Frame;
use FML\Controls\Label;
use FML\Controls\Labels\Label_Text;
use FML\Controls\Quads\Quad_BgsPlayerCard;
use FML\Controls\Quads\Quad_Icons64x64_1;
use FML\Controls\Quads\Quad_UIConstruction_Buttons;
use FML\Controls\Quads\Quad_UIConstructionBullet_Buttons;
use FML\ManiaLink;
use FML\Script\Features\Paging;
use ManiaControl\Logger;
use ManiaControl\ManiaControl;
use ManiaControl\Manialinks\ManialinkManager;
use ManiaControl\Manialinks\ManialinkPageAnswerListener;
use ManiaControl\Players\Player;
use Maniaplanet\DedicatedServer\Xmlrpc\AlreadyInListException;
use Maniaplanet\DedicatedServer\Xmlrpc\FileException;
use Maniaplanet\DedicatedServer\Xmlrpc\InvalidMapException;
/**
* Maps Directory Browser
*
* @author ManiaControl Team <mail@maniacontrol.com>
* @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/
class DirectoryBrowser implements ManialinkPageAnswerListener {
/*
* Constants
*/
const ACTION_SHOW = 'MapsDirBrowser.Show';
const ACTION_NAVIGATE_UP = 'MapsDirBrowser.NavigateUp';
const ACTION_NAVIGATE_ROOT = 'MapsDirBrowser.NavigateRoot';
const ACTION_OPEN_FOLDER = 'MapsDirBrowser.OpenFolder.';
const ACTION_INSPECT_FILE = 'MapsDirBrowser.InspectFile.';
const ACTION_ADD_FILE = 'MapsDirBrowser.AddFile.';
const ACTION_ERASE_FILE = 'MapsDirBrowser.EraseFile.';
const WIDGET_NAME = 'MapsDirBrowser.Widget';
const CACHE_FOLDER_PATH = 'FolderPath';
/*
* Private properties
*/
/** @var ManiaControl $maniaControl */
private $maniaControl = null;
/**
* Construct a new directory browser instance
*
* @param ManiaControl $maniaControl
*/
public function __construct(ManiaControl $maniaControl) {
$this->maniaControl = $maniaControl;
// ManiaLink Actions
$this->maniaControl->getManialinkManager()->registerManialinkPageAnswerListener(self::ACTION_SHOW, $this, 'handleActionShow');
$this->maniaControl->getManialinkManager()->registerManialinkPageAnswerListener(self::ACTION_NAVIGATE_UP, $this, 'handleNavigateUp');
$this->maniaControl->getManialinkManager()->registerManialinkPageAnswerListener(self::ACTION_NAVIGATE_ROOT, $this, 'handleNavigateRoot');
$this->maniaControl->getManialinkManager()->registerManialinkPageAnswerRegexListener($this->buildActionRegex(self::ACTION_OPEN_FOLDER), $this, 'handleOpenFolder');
$this->maniaControl->getManialinkManager()->registerManialinkPageAnswerRegexListener($this->buildActionRegex(self::ACTION_INSPECT_FILE), $this, 'handleInspectFile');
$this->maniaControl->getManialinkManager()->registerManialinkPageAnswerRegexListener($this->buildActionRegex(self::ACTION_ADD_FILE), $this, 'handleAddFile');
$this->maniaControl->getManialinkManager()->registerManialinkPageAnswerRegexListener($this->buildActionRegex(self::ACTION_ERASE_FILE), $this, 'handleEraseFile');
}
/**
* Build the regex to register for the given action
*
* @param string $actionName
* @return string
*/
private function buildActionRegex($actionName) {
return '/' . $actionName . '*/';
}
/**
* Handle 'Show' action
*
* @param array $actionCallback
* @param Player $player
*/
public function handleActionShow(array $actionCallback, Player $player) {
$this->showManiaLink($player);
}
/**
* Build and show the Browser ManiaLink to the given Player
*
* @param Player $player
* @param mixed $nextFolder
*/
public function showManiaLink(Player $player, $nextFolder = null) {
$oldFolderPath = $player->getCache($this, self::CACHE_FOLDER_PATH);
$isInMapsFolder = false;
if (!$oldFolderPath) {
$oldFolderPath = $this->maniaControl->getServer()->getDirectory()->getMapsFolder();
$isInMapsFolder = true;
}
$folderPath = $oldFolderPath;
if (is_string($nextFolder)) {
$newFolderPath = realpath($oldFolderPath . $nextFolder);
if ($newFolderPath) {
$folderPath = $newFolderPath . DIRECTORY_SEPARATOR;
$folderName = basename($newFolderPath);
switch ($folderName) {
case 'Maps':
$mapsDir = dirname($this->maniaControl->getServer()->getDirectory()->getMapsFolder());
$folderDir = dirname($folderPath);
$isInMapsFolder = ($mapsDir === $folderDir);
break;
case 'UserData':
$dataDir = dirname($this->maniaControl->getServer()->getDirectory()->getGameDataFolder());
$folderDir = dirname($folderPath);
if ($dataDir === $folderDir) {
// Prevent navigation out of maps directory
return;
}
break;
}
}
}
$player->setCache($this, self::CACHE_FOLDER_PATH, $folderPath);
$maniaLink = new ManiaLink(ManialinkManager::MAIN_MLID);
$script = $maniaLink->getScript();
$paging = new Paging();
$script->addFeature($paging);
$frame = $this->maniaControl->getManialinkManager()->getStyleManager()->getDefaultListFrame($script, $paging);
$maniaLink->add($frame);
$width = $this->maniaControl->getManialinkManager()->getStyleManager()->getListWidgetsWidth();
$height = $this->maniaControl->getManialinkManager()->getStyleManager()->getListWidgetsHeight();
$index = 0;
$posY = $height / 2 - 10;
$pageFrame = null;
$navigateRootQuad = new Quad_Icons64x64_1();
$frame->add($navigateRootQuad);
$navigateRootQuad->setPosition($width * -0.47, $height * 0.45)->setSize(4, 4)->setSubStyle($navigateRootQuad::SUBSTYLE_ToolRoot);
$navigateUpQuad = new Quad_Icons64x64_1();
$frame->add($navigateUpQuad);
$navigateUpQuad->setPosition($width * -0.44, $height * 0.45)->setSize(4, 4)->setSubStyle($navigateUpQuad::SUBSTYLE_ToolUp);
if (!$isInMapsFolder) {
$navigateRootQuad->setAction(self::ACTION_NAVIGATE_ROOT);
$navigateUpQuad->setAction(self::ACTION_NAVIGATE_UP);
}
$directoryLabel = new Label_Text();
$frame->add($directoryLabel);
$dataFolder = $this->maniaControl->getServer()->getDirectory()->getGameDataFolder();
$directoryText = substr($folderPath, strlen($dataFolder));
$directoryLabel->setPosition($width * -0.41, $height * 0.45)->setSize($width * 0.85, 4)->setHAlign($directoryLabel::LEFT)->setText($directoryText)->setTextSize(2);
$tooltipLabel = new Label();
$frame->add($tooltipLabel);
$tooltipLabel->setPosition($width * -0.48, $height * -0.44)->setSize($width * 0.8, 5)->setHAlign($tooltipLabel::LEFT)->setTextSize(1)->setText('tooltip');
$mapFiles = $this->scanMapFiles($folderPath);
if (is_array($mapFiles)) {
if (empty($mapFiles)) {
$emptyLabel = new Label();
$frame->add($emptyLabel);
$emptyLabel->setY(20)->setTextColor('aaa')->setText('No files found.')->setTranslate(true);
} else {
$canAddMaps = $this->maniaControl->getAuthenticationManager()->checkPermission($player, MapManager::SETTING_PERMISSION_ADD_MAP);
$canEraseMaps = $this->maniaControl->getAuthenticationManager()->checkPermission($player, MapManager::SETTING_PERMISSION_ERASE_MAP);
foreach ($mapFiles as $filePath => $fileName) {
$shortFilePath = substr($filePath, strlen($folderPath));
if ($index % 15 === 0) {
// New Page
$pageFrame = new Frame();
$frame->add($pageFrame);
$posY = $height / 2 - 10;
$paging->addPage($pageFrame);
}
// Map Frame
$mapFrame = new Frame();
$pageFrame->add($mapFrame);
$mapFrame->setY($posY);
if ($index % 2 === 0) {
// Striped background line
$lineQuad = new Quad_BgsPlayerCard();
$mapFrame->add($lineQuad);
$lineQuad->setZ(-1)->setSize($width, 4)->setSubStyle($lineQuad::SUBSTYLE_BgPlayerCardBig);
}
// File name Label
$nameLabel = new Label_Text();
$mapFrame->add($nameLabel);
$nameLabel->setX($width * -0.48)->setSize($width * 0.79, 4)->setHAlign($nameLabel::LEFT)->setStyle($nameLabel::STYLE_TextCardRaceRank)->setTextSize(1)->setText($fileName);
if (is_dir($filePath)) {
// Folder
$nameLabel->setAction(self::ACTION_OPEN_FOLDER . substr($shortFilePath, 0, -1))->addTooltipLabelFeature($tooltipLabel, 'Open folder ' . $fileName);
} else {
// File
$nameLabel->setAction(self::ACTION_INSPECT_FILE . $fileName)->addTooltipLabelFeature($tooltipLabel, 'Inspect file ' . $fileName);
if ($canAddMaps) {
// 'Add' button
$addButton = new Quad_UIConstructionBullet_Buttons();
$mapFrame->add($addButton);
$addButton->setX($width * 0.42)->setSize(4, 4)->setSubStyle($addButton::SUBSTYLE_NewBullet)->setAction(self::ACTION_ADD_FILE . $fileName)->addTooltipLabelFeature($tooltipLabel, 'Add map ' . $fileName);
}
if ($canEraseMaps) {
// 'Erase' button
$eraseButton = new Quad_UIConstruction_Buttons();
$mapFrame->add($eraseButton);
$eraseButton->setX($width * 0.46)->setSize(4, 4)->setSubStyle($eraseButton::SUBSTYLE_Erase)->setAction(self::ACTION_ERASE_FILE . $fileName)->addTooltipLabelFeature($tooltipLabel, 'Erase file ' . $fileName);
}
}
$posY -= 4;
$index++;
}
}
} else {
$errorLabel = new Label();
$frame->add($errorLabel);
$errorLabel->setY(20)->setTextColor('f30')->setText('No access to the directory.')->setTranslate(true);
}
$this->maniaControl->getManialinkManager()->displayWidget($maniaLink, $player, self::WIDGET_NAME);
}
/**
* Scan the given directory for Map files
*
* @param string $directory
* @return array|bool
*/
protected function scanMapFiles($directory) {
if (!is_readable($directory) || !is_dir($directory)) {
return false;
}
$mapFiles = array();
$dirFiles = scandir($directory);
foreach ($dirFiles as $fileName) {
if (substr($fileName, 0, 1) === '.') {
continue;
}
$fullFileName = $directory . $fileName;
if (!is_readable($fullFileName)) {
continue;
}
if (is_dir($fullFileName)) {
$mapFiles[$fullFileName . DIRECTORY_SEPARATOR] = $fileName . DIRECTORY_SEPARATOR;
continue;
} else {
if ($this->isMapFileName($fileName)) {
$mapFiles[$fullFileName] = $fileName;
}
}
}
return $mapFiles;
}
/**
* Check if the given file name represents a Map file
*
* @param string $fileName
* @return bool
*/
protected function isMapFileName($fileName) {
$mapFileNameEnding = '.map.gbx';
$fileNameEnding = strtolower(substr($fileName, -strlen($mapFileNameEnding)));
return ($fileNameEnding === $mapFileNameEnding);
}
/**
* Handle 'NavigateRoot' action
*
* @param array $actionCallback
* @param Player $player
*/
public function handleNavigateRoot(array $actionCallback, Player $player) {
$player->destroyCache($this, self::CACHE_FOLDER_PATH);
$this->showManiaLink($player);
}
/**
* Handle 'NavigateUp' action
*
* @param array $actionCallback
* @param Player $player
*/
public function handleNavigateUp(array $actionCallback, Player $player) {
$this->showManiaLink($player, '..');
}
/**
* Handle 'OpenFolder' page action
*
* @param array $actionCallback
* @param Player $player
*/
public function handleOpenFolder(array $actionCallback, Player $player) {
$actionName = $actionCallback[1][2];
$folderName = substr($actionName, strlen(self::ACTION_OPEN_FOLDER));
$this->showManiaLink($player, $folderName);
}
/**
* Handle 'InspectFile' page action
*
* @param array $actionCallback
* @param Player $player
*/
public function handleInspectFile(array $actionCallback, Player $player) {
$actionName = $actionCallback[1][2];
$fileName = substr($actionName, strlen(self::ACTION_INSPECT_FILE));
// TODO: show inspect file view
var_dump($fileName);
}
/**
* Handle 'AddFile' page action
*
* @param array $actionCallback
* @param Player $player
*/
public function handleAddFile(array $actionCallback, Player $player) {
$actionName = $actionCallback[1][2];
$fileName = substr($actionName, strlen(self::ACTION_ADD_FILE));
$folderPath = $player->getCache($this, self::CACHE_FOLDER_PATH);
$filePath = $folderPath . $fileName;
$mapsFolder = $this->maniaControl->getServer()->getDirectory()->getMapsFolder();
$relativeFilePath = substr($filePath, strlen($mapsFolder));
// Check for valid map
try {
$this->maniaControl->getClient()->checkMapForCurrentServerParams($relativeFilePath);
} catch (InvalidMapException $exception) {
$this->maniaControl->getChat()->sendException($exception, $player);
return;
} catch (FileException $exception) {
$this->maniaControl->getChat()->sendException($exception, $player);
return;
}
// Add map to map list
try {
$this->maniaControl->getClient()->insertMap($relativeFilePath);
} catch (AlreadyInListException $exception) {
$this->maniaControl->getChat()->sendException($exception, $player);
return;
}
$map = $this->maniaControl->getMapManager()->fetchMapByFileName($relativeFilePath);
if (!$map) {
$this->maniaControl->getChat()->sendError('Error occurred.', $player);
return;
}
// Message
$message = $player->getEscapedNickname() . ' added ' . $map->getEscapedName() . '!';
$this->maniaControl->getChat()->sendSuccess($message);
Logger::logInfo($message, true);
// Queue requested Map
$this->maniaControl->getMapManager()->getMapQueue()->addMapToMapQueue($player, $map);
}
/**
* Handle 'EraseFile' page action
*
* @param array $actionCallback
* @param Player $player
*/
public function handleEraseFile(array $actionCallback, Player $player) {
$actionName = $actionCallback[1][2];
$fileName = substr($actionName, strlen(self::ACTION_ERASE_FILE));
$folderPath = $player->getCache($this, self::CACHE_FOLDER_PATH);
$filePath = $folderPath . $fileName;
if (@unlink($filePath)) {
$this->maniaControl->getChat()->sendSuccess("Erased {$fileName}!");
$this->showManiaLink($player);
} else {
$this->maniaControl->getChat()->sendError("Couldn't erase {$fileName}!");
}
}
}

113
core/Maps/Map.php Normal file
View File

@ -0,0 +1,113 @@
<?php
namespace ManiaControl\Maps;
use ManiaControl\ManiaExchange\MXMapInfo;
use ManiaControl\Utils\Formatter;
/**
* ManiaControl Map Model Class
*
* @author ManiaControl Team <mail@maniacontrol.com>
* @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/
class Map {
/*
* Public properties
*/
public $index = -1;
public $name = 'undefined';
public $rawName = null;
public $uid = null;
public $fileName = null;
public $environment = null;
public $authorTime = -1;
public $goldTime = -1;
public $copperPrice = -1;
public $mapType = null;
public $mapStyle = null;
public $nbCheckpoints = -1;
public $nbLaps = -1;
/** @var MXMapInfo $mx */
public $mx = null;
public $authorLogin = null;
public $authorNick = null;
public $authorZone = null;
public $authorEInfo = null;
public $comment = null;
public $titleUid = null;
public $startTime = -1;
public $lastUpdate = 0;
public $karma = null;
/**
* Construct a new map instance from xmlrpc data
*
* @param \Maniaplanet\DedicatedServer\Structures\Map $mpMap
*/
public function __construct($mpMap = null) {
$this->startTime = time();
if (!$mpMap) {
return;
}
$this->name = Formatter::stripDirtyCodes($mpMap->name);
$this->rawName = $mpMap->name;
$this->uid = $mpMap->uId;
$this->fileName = $mpMap->fileName;
$this->authorLogin = $mpMap->author;
$this->environment = $mpMap->environnement;
$this->authorTime = $mpMap->authorTime;
$this->goldTime = $mpMap->goldTime;
$this->copperPrice = $mpMap->copperPrice;
$this->mapType = $mpMap->mapType;
$this->mapStyle = $mpMap->mapStyle;
$this->nbCheckpoints = $mpMap->nbCheckpoints;
$this->nbLaps = $mpMap->nbLaps;
$this->authorNick = $this->authorLogin;
}
/**
* Get the escaped map name
*
* @return string
*/
public function getEscapedName() {
return Formatter::escapeText($this->name);
}
/**
* Get the game type of the map
*
* @return string
*/
public function getGame() {
switch ($this->environment) {
case 'Storm':
return 'sm';
case 'Canyon':
case 'Stadium':
case 'Valley':
return 'tm';
}
return null;
}
/**
* Check whether a map update is available
*
* @return bool
*/
public function updateAvailable() {
return ($this->mx && ($this->lastUpdate < strtotime($this->mx->updated) || $this->uid !== $this->mx->uid));
}
/**
* Var_Dump the Map
*/
public function dump() {
var_dump(json_decode(json_encode($this)));
}
}

47
core/Maps/MapActions.php Normal file
View File

@ -0,0 +1,47 @@
<?php
namespace ManiaControl\Maps;
use ManiaControl\ManiaControl;
use Maniaplanet\DedicatedServer\Xmlrpc\ChangeInProgressException;
/**
* ManiaControl Map Actions Class
*
* @author ManiaControl Team <mail@maniacontrol.com>
* @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/
class MapActions {
/*
* Private properties
*/
/** @var ManiaControl $maniaControl */
private $maniaControl = null;
/**
* Construct a map actions instance
*
* @param ManiaControl $maniaControl
*/
public function __construct(ManiaControl $maniaControl) {
$this->maniaControl = $maniaControl;
}
/**
* Skip the current Map
*/
public function skipMap() {
// Force an EndMap on the MapQueue to set the next Map
$this->maniaControl->getMapManager()->getMapQueue()->endMap(null);
// Ignore EndMap on MapQueue
$this->maniaControl->getMapManager()->getMapQueue()->dontQueueNextMapChange();
// Switch The Map
try {
$this->maniaControl->getClient()->nextMap();
} catch (ChangeInProgressException $e) {
}
}
}

511
core/Maps/MapCommands.php Normal file
View File

@ -0,0 +1,511 @@
<?php
namespace ManiaControl\Maps;
use FML\Controls\Quad;
use FML\Controls\Quads\Quad_Icons64x64_1;
use FML\Controls\Quads\Quad_UIConstruction_Buttons;
use ManiaControl\Admin\AuthenticationManager;
use ManiaControl\Callbacks\CallbackListener;
use ManiaControl\Callbacks\CallbackManager;
use ManiaControl\Commands\CommandListener;
use ManiaControl\Logger;
use ManiaControl\ManiaControl;
use ManiaControl\Manialinks\IconManager;
use ManiaControl\Manialinks\ManialinkPageAnswerListener;
use ManiaControl\Players\Player;
use Maniaplanet\DedicatedServer\Xmlrpc\ChangeInProgressException;
use Maniaplanet\DedicatedServer\Xmlrpc\FaultException;
/**
* Class offering Commands to manage Maps
*
* @author ManiaControl Team <mail@maniacontrol.com>
* @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/
class MapCommands implements CommandListener, ManialinkPageAnswerListener, CallbackListener {
/*
* Constants
*/
const ACTION_OPEN_MAPLIST = 'MapCommands.OpenMapList';
const ACTION_OPEN_XLIST = 'MapCommands.OpenMXList';
const ACTION_RESTART_MAP = 'MapCommands.RestartMap';
const ACTION_SKIP_MAP = 'MapCommands.NextMap';
const ACTION_SHOW_AUTHOR = 'MapList.ShowAuthorList.';
/*
* Private properties
*/
/** @var ManiaControl $maniaControl */
private $maniaControl = null;
/**
* Construct a new map commands instance
*
* @param ManiaControl $maniaControl
*/
public function __construct(ManiaControl $maniaControl) {
$this->maniaControl = $maniaControl;
$this->initActionsMenuButtons();
// Admin commands
$this->maniaControl->getCommandManager()->registerCommandListener(array('nextmap', 'next', 'skip'), $this, 'command_NextMap', true, 'Skips to the next map.');
$this->maniaControl->getCommandManager()->registerCommandListener(array('restartmap', 'resmap', 'res'), $this, 'command_RestartMap', true, 'Restarts the current map.');
$this->maniaControl->getCommandManager()->registerCommandListener(array('replaymap', 'replay'), $this, 'command_ReplayMap', true, 'Replays the current map (after the end of the map).');
$this->maniaControl->getCommandManager()->registerCommandListener(array('addmap', 'add'), $this, 'command_AddMap', true, 'Adds map from ManiaExchange.');
$this->maniaControl->getCommandManager()->registerCommandListener(array('removemap', 'removethis'), $this, 'command_RemoveMap', true, 'Removes the current map.');
$this->maniaControl->getCommandManager()->registerCommandListener(array('erasemap', 'erasethis'), $this, 'command_EraseMap', true, 'Erases the current map.');
$this->maniaControl->getCommandManager()->registerCommandListener(array('shufflemaps', 'shuffle'), $this, 'command_ShuffleMaps', true, 'Shuffles the maplist.');
$this->maniaControl->getCommandManager()->registerCommandListener(array('writemaplist', 'wml'), $this, 'command_WriteMapList', true, 'Writes the current maplist to a file.');
$this->maniaControl->getCommandManager()->registerCommandListener(array('readmaplist', 'rml'), $this, 'command_ReadMapList', true, 'Loads a maplist into the server.');
// Player commands
$this->maniaControl->getCommandManager()->registerCommandListener('nextmap', $this, 'command_showNextMap', false, 'Shows which map is next.');
$this->maniaControl->getCommandManager()->registerCommandListener(array('maps', 'list'), $this, 'command_List', false, 'Shows the current maplist (or variations).');
$this->maniaControl->getCommandManager()->registerCommandListener(array('xmaps', 'xlist'), $this, 'command_xList', false, 'Shows maps from ManiaExchange.');
// Callbacks
$this->maniaControl->getCallbackManager()->registerCallbackListener(CallbackManager::CB_MP_PLAYERMANIALINKPAGEANSWER, $this, 'handleManialinkPageAnswer');
$this->maniaControl->getManialinkManager()->registerManialinkPageAnswerListener(self::ACTION_OPEN_XLIST, $this, 'command_xList');
$this->maniaControl->getManialinkManager()->registerManialinkPageAnswerListener(self::ACTION_OPEN_MAPLIST, $this, 'command_List');
$this->maniaControl->getManialinkManager()->registerManialinkPageAnswerListener(self::ACTION_RESTART_MAP, $this, 'command_RestartMap');
$this->maniaControl->getManialinkManager()->registerManialinkPageAnswerListener(self::ACTION_SKIP_MAP, $this, 'command_NextMap');
}
/**
* Add all Actions Menu Buttons
*/
private function initActionsMenuButtons() {
// Menu Open xList
$itemQuad = new Quad();
$itemQuad->setImage($this->maniaControl->getManialinkManager()->getIconManager()->getIcon(IconManager::MX_ICON));
$itemQuad->setImageFocus($this->maniaControl->getManialinkManager()->getIconManager()->getIcon(IconManager::MX_ICON_MOVER));
$itemQuad->setAction(self::ACTION_OPEN_XLIST);
$this->maniaControl->getActionsMenu()->addPlayerMenuItem($itemQuad, 5, 'Open MX List');
// Menu Open List
$itemQuad = new Quad_Icons64x64_1();
$itemQuad->setSubStyle($itemQuad::SUBSTYLE_ToolRoot);
$itemQuad->setAction(self::ACTION_OPEN_MAPLIST);
$this->maniaControl->getActionsMenu()->addPlayerMenuItem($itemQuad, 10, 'Open MapList');
// Menu RestartMap
$itemQuad = new Quad_UIConstruction_Buttons();
$itemQuad->setSubStyle($itemQuad::SUBSTYLE_Reload);
$itemQuad->setAction(self::ACTION_RESTART_MAP);
$this->maniaControl->getActionsMenu()->addAdminMenuItem($itemQuad, 10, 'Restart Map');
// Menu NextMap
$itemQuad = new Quad_Icons64x64_1();
$itemQuad->setSubStyle($itemQuad::SUBSTYLE_ArrowFastNext);
$itemQuad->setAction(self::ACTION_SKIP_MAP);
$this->maniaControl->getActionsMenu()->addAdminMenuItem($itemQuad, 20, 'Skip Map');
}
/**
* Show which map is the next
*
* @param array $chatCallback
* @param Player $player
*/
public function command_ShowNextMap(array $chatCallback, Player $player) {
$nextQueued = $this->maniaControl->getMapManager()->getMapQueue()->getNextQueuedMap();
if ($nextQueued) {
/** @var Player $requester */
$requester = $nextQueued[0];
/** @var Map $map */
$map = $nextQueued[1];
$this->maniaControl->getChat()->sendInformation("Next Map is $<{$map->name}$> from $<{$map->authorNick}$> requested by $<{$requester->nickname}$>.", $player);
} else {
$mapIndex = $this->maniaControl->getClient()->getNextMapIndex();
$maps = $this->maniaControl->getMapManager()->getMaps();
$map = $maps[$mapIndex];
$this->maniaControl->getChat()->sendInformation("Next Map is $<{$map->name}$> from $<{$map->authorNick}$>.", $player);
}
}
/**
* Handle //removemap command
*
* @param array $chatCallback
* @param Player $player
*/
public function command_RemoveMap(array $chatCallback, Player $player) {
if (!$this->maniaControl->getAuthenticationManager()->checkPermission($player, MapManager::SETTING_PERMISSION_REMOVE_MAP)
) {
$this->maniaControl->getAuthenticationManager()->sendNotAllowed($player);
return;
}
// Get map
$map = $this->maniaControl->getMapManager()->getCurrentMap();
if (!$map) {
$this->maniaControl->getChat()->sendError("Couldn't remove map.", $player);
return;
}
// Remove map
$this->maniaControl->getMapManager()->removeMap($player, $map->uid);
}
/**
* Handle //erasemap command
*
* @param array $chatCallback
* @param Player $player
*/
public function command_EraseMap(array $chatCallback, Player $player) {
if (!$this->maniaControl->getAuthenticationManager()->checkPermission($player, MapManager::SETTING_PERMISSION_ERASE_MAP)
) {
$this->maniaControl->getAuthenticationManager()->sendNotAllowed($player);
return;
}
// Get map
$map = $this->maniaControl->getMapManager()->getCurrentMap();
if (!$map) {
$this->maniaControl->getChat()->sendError("Couldn't erase map.", $player);
return;
}
// Erase map
$this->maniaControl->getMapManager()->removeMap($player, $map->uid, true);
}
/**
* Handle shufflemaps command
*
* @param array $chatCallback
* @param \ManiaControl\Players\Player $player
*/
public function command_ShuffleMaps(array $chatCallback, Player $player) {
if (!$this->maniaControl->getAuthenticationManager()->checkPermission($player, MapManager::SETTING_PERMISSION_SHUFFLE_MAPS)
) {
$this->maniaControl->getAuthenticationManager()->sendNotAllowed($player);
return;
}
// Shuffles the maps
$this->maniaControl->getMapManager()->shuffleMapList($player);
}
/**
* Handle addmap command
*
* @param array $chatCallback
* @param \ManiaControl\Players\Player $player
*/
public function command_AddMap(array $chatCallback, Player $player) {
if (!$this->maniaControl->getAuthenticationManager()->checkPermission($player, MapManager::SETTING_PERMISSION_ADD_MAP)
) {
$this->maniaControl->getAuthenticationManager()->sendNotAllowed($player);
return;
}
$params = explode(' ', $chatCallback[1][2], 2);
if (count($params) < 2) {
$this->maniaControl->getChat()->sendUsageInfo('Usage example: //addmap 1234', $player);
return;
}
// add Map from Mania Exchange
$this->maniaControl->getMapManager()->addMapFromMx($params[1], $player->login);
}
/**
* Handle /nextmap Command
*
* @param array $chat
* @param \ManiaControl\Players\Player $player
*/
public function command_NextMap(array $chat, Player $player) {
if (!$this->maniaControl->getAuthenticationManager()->checkPermission($player, MapManager::SETTING_PERMISSION_SKIP_MAP)
) {
$this->maniaControl->getAuthenticationManager()->sendNotAllowed($player);
return;
}
$this->maniaControl->getMapManager()->getMapActions()->skipMap();
$message = $player->getEscapedNickname() . ' skipped the current Map!';
$this->maniaControl->getChat()->sendSuccess($message);
Logger::logInfo($message, true);
}
/**
* Handle restartmap command
*
* @param array $chat
* @param \ManiaControl\Players\Player $player
*/
public function command_RestartMap(array $chat, Player $player) {
if (!$this->maniaControl->getAuthenticationManager()->checkPermission($player, MapManager::SETTING_PERMISSION_RESTART_MAP)
) {
$this->maniaControl->getAuthenticationManager()->sendNotAllowed($player);
return;
}
$message = $player->getEscapedNickname() . ' restarted the current Map!';
$this->maniaControl->getChat()->sendSuccess($message);
Logger::logInfo($message, true);
try {
$this->maniaControl->getClient()->restartMap();
} catch (ChangeInProgressException $e) {
}
}
////$this->maniaControl->mapManager->mapQueue->addFirstMapToMapQueue($this->currentVote->voter, $this->maniaControl->mapManager->getCurrentMap());
/**
* Handle replaymap command
*
* @param array $chat
* @param \ManiaControl\Players\Player $player
*/
public function command_ReplayMap(array $chat, Player $player) {
if (!$this->maniaControl->getAuthenticationManager()->checkPermission($player, MapManager::SETTING_PERMISSION_RESTART_MAP)
) {
$this->maniaControl->getAuthenticationManager()->sendNotAllowed($player);
return;
}
$message = $player->getEscapedNickname() . ' replays the current Map!';
$this->maniaControl->getChat()->sendSuccess($message);
Logger::logInfo($message, true);
$this->maniaControl->getMapManager()->getMapQueue()->addFirstMapToMapQueue($player, $this->maniaControl->getMapManager()->getCurrentMap());
}
/**
* Handle writemaplist command
*
* @param array $chat
* @param \ManiaControl\Players\Player $player
*/
public function command_WriteMapList(array $chat, Player $player) {
if (!$this->maniaControl->getAuthenticationManager()->checkRight($player, AuthenticationManager::AUTH_LEVEL_SUPERADMIN)
) {
$this->maniaControl->getAuthenticationManager()->sendNotAllowed($player);
return;
}
$chatCommand = explode(' ', $chat[1][2]);
if (isset($chatCommand[1])) {
if (strstr($chatCommand[1], '.txt')) {
$maplist = $chatCommand[1];
} else {
$maplist = $chatCommand[1] . '.txt';
}
} else {
$maplist = 'maplist.txt';
}
$maplist = 'MatchSettings' . DIRECTORY_SEPARATOR . $maplist;
try {
$this->maniaControl->getClient()->saveMatchSettings($maplist);
$message = 'Maplist $<$fff' . $maplist . '$> written.';
$this->maniaControl->getChat()->sendSuccess($message, $player);
Logger::logInfo($message, true);
} catch (FaultException $e) {
$this->maniaControl->getChat()->sendError('Cannot write maplist $<$fff' . $maplist . '$>!', $player);
}
}
/**
* Handle readmaplist command
*
* @param array $chat
* @param \ManiaControl\Players\Player $player
*/
public function command_ReadMapList(array $chat, Player $player) {
if (!$this->maniaControl->getAuthenticationManager()->checkRight($player, AuthenticationManager::AUTH_LEVEL_SUPERADMIN)
) {
$this->maniaControl->getAuthenticationManager()->sendNotAllowed($player);
return;
}
$chatCommand = explode(' ', $chat[1][2]);
if (isset($chatCommand[1])) {
if (strstr($chatCommand[1], '.txt')) {
$maplist = $chatCommand[1];
} else {
$maplist = $chatCommand[1] . '.txt';
}
} else {
$maplist = 'maplist.txt';
}
$maplist = 'MatchSettings' . DIRECTORY_SEPARATOR . $maplist;
try {
$this->maniaControl->getClient()->loadMatchSettings($maplist);
$message = 'Maplist $<$fff' . $maplist . '$> loaded.';
$this->maniaControl->getMapManager()->restructureMapList();
$this->maniaControl->getChat()->sendSuccess($message, $player);
Logger::logInfo($message, true);
} catch (FaultException $e) {
$this->maniaControl->getChat()->sendError('Cannot load maplist $<$fff' . $maplist . '$>!', $player);
}
}
/**
* Handle ManialinkPageAnswer Callback
*
* @param array $callback
*/
public function handleManialinkPageAnswer(array $callback) {
$actionId = $callback[1][2];
$login = $callback[1][1];
$player = $this->maniaControl->getPlayerManager()->getPlayer($login);
if (strstr($actionId, self::ACTION_SHOW_AUTHOR)) {
$login = str_replace(self::ACTION_SHOW_AUTHOR, '', $actionId);
$this->maniaControl->getMapManager()->getMapList()->playerCloseWidget($player);
$this->showMapListAuthor($login, $player);
}
}
/**
* Show the Player a List of Maps from the given Author
*
* @param string $author
* @param Player $player
*/
private function showMapListAuthor($author, Player $player) {
$maps = $this->maniaControl->getMapManager()->getMaps();
$mapList = array();
/** @var Map $map */
foreach ($maps as $map) {
if ($map->authorLogin == $author) {
array_push($mapList, $map);
}
}
if (empty($mapList)) {
$this->maniaControl->getChat()->sendError('There are no maps to show!', $player->login);
return;
}
$this->maniaControl->getMapManager()->getMapList()->showMapList($player, $mapList);
}
/**
* Handle /maps command
*
* @param array $chatCallback
* @param Player $player
*/
public function command_List(array $chatCallback, Player $player) {
$chatCommands = explode(' ', $chatCallback[1][2]);
$this->maniaControl->getMapManager()->getMapList()->playerCloseWidget($player);
if (isset($chatCommands[1])) {
$listParam = strtolower($chatCommands[1]);
switch ($listParam) {
case 'best':
$this->showMapListKarma(true, $player);
break;
case 'worst':
$this->showMapListKarma(false, $player);
break;
case 'newest':
$this->showMapListDate(true, $player);
break;
case 'oldest':
$this->showMapListDate(false, $player);
break;
case 'author':
if (isset($chatCommands[2])) {
$this->showMaplistAuthor($chatCommands[2], $player);
} else {
$this->maniaControl->getChat()->sendError('Missing Author Login!', $player);
}
break;
default:
$this->maniaControl->getMapManager()->getMapList()->showMapList($player);
break;
}
} else {
$this->maniaControl->getMapManager()->getMapList()->showMapList($player);
}
}
/**
* Show a Karma based MapList
*
* @param bool $best
* @param Player $player
*/
private function showMapListKarma($best, Player $player) {
/** @var \MCTeam\KarmaPlugin $karmaPlugin */
$karmaPlugin = $this->maniaControl->getPluginManager()->getPlugin(MapList::DEFAULT_KARMA_PLUGIN);
if ($karmaPlugin) {
$maps = $this->maniaControl->getMapManager()->getMaps();
$mapList = array();
foreach ($maps as $map) {
if ($map instanceof Map) {
if ($this->maniaControl->getSettingManager()->getSettingValue($karmaPlugin, $karmaPlugin::SETTING_NEWKARMA) === true
) {
$karma = $karmaPlugin->getMapKarma($map);
$map->karma = round($karma * 100.);
} else {
$votes = $karmaPlugin->getMapVotes($map);
$min = 0;
$plus = 0;
foreach ($votes as $vote) {
if (isset($vote->vote)) {
if ($vote->vote !== 0.5) {
if ($vote->vote < 0.5) {
$min = $min + $vote->count;
} else {
$plus = $plus + $vote->count;
}
}
}
}
$map->karma = $plus - $min;
}
$mapList[] = $map;
}
}
usort($mapList, function (Map $mapA, Map $mapB) {
return ($mapA->karma - $mapB->karma);
});
if ($best) {
$mapList = array_reverse($mapList);
}
$this->maniaControl->getMapManager()->getMapList()->showMapList($player, $mapList);
} else {
$this->maniaControl->getChat()->sendError('KarmaPlugin is not enabled!', $player->login);
}
}
/**
* Show a Date based MapList
*
* @param bool $newest
* @param Player $player
*/
private function showMapListDate($newest, Player $player) {
$maps = $this->maniaControl->getMapManager()->getMaps();
usort($maps, function (Map $mapA, Map $mapB) {
return ($mapA->index - $mapB->index);
});
if ($newest) {
$maps = array_reverse($maps);
}
$this->maniaControl->getMapManager()->getMapList()->showMapList($player, $maps);
}
/**
* Handle ManiaExchange list command
*
* @param array $chatCallback
* @param Player $player
*/
public function command_xList(array $chatCallback, Player $player) {
$this->maniaControl->getMapManager()->getMXList()->showList($chatCallback, $player);
}
}

724
core/Maps/MapList.php Normal file
View File

@ -0,0 +1,724 @@
<?php
namespace ManiaControl\Maps;
use FML\Controls\Frame;
use FML\Controls\Gauge;
use FML\Controls\Label;
use FML\Controls\Labels\Label_Button;
use FML\Controls\Labels\Label_Text;
use FML\Controls\Quad;
use FML\Controls\Quads\Quad_BgsPlayerCard;
use FML\Controls\Quads\Quad_Icons64x64_1;
use FML\Controls\Quads\Quad_UIConstruction_Buttons;
use FML\ManiaLink;
use FML\Script\Features\Paging;
use ManiaControl\Callbacks\CallbackListener;
use ManiaControl\Callbacks\CallbackManager;
use ManiaControl\Callbacks\Callbacks;
use ManiaControl\Logger;
use ManiaControl\ManiaControl;
use ManiaControl\Manialinks\IconManager;
use ManiaControl\Manialinks\ManialinkManager;
use ManiaControl\Manialinks\ManialinkPageAnswerListener;
use ManiaControl\Players\Player;
use ManiaControl\Utils\ColorUtil;
use ManiaControl\Utils\Formatter;
use Maniaplanet\DedicatedServer\Xmlrpc\ChangeInProgressException;
use Maniaplanet\DedicatedServer\Xmlrpc\FileException;
use Maniaplanet\DedicatedServer\Xmlrpc\NextMapException;
use Maniaplanet\DedicatedServer\Xmlrpc\NotInListException;
use MCTeam\CustomVotesPlugin;
use MCTeam\KarmaPlugin;
/**
* MapList Widget Class
*
* @author ManiaControl Team <mail@maniacontrol.com>
* @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/
class MapList implements ManialinkPageAnswerListener, CallbackListener {
/*
* Constants
*/
const ACTION_UPDATE_MAP = 'MapList.UpdateMap';
const ACTION_REMOVE_MAP = 'MapList.RemoveMap';
const ACTION_SWITCH_MAP = 'MapList.SwitchMap';
const ACTION_START_SWITCH_VOTE = 'MapList.StartMapSwitchVote';
const ACTION_QUEUED_MAP = 'MapList.QueueMap';
const ACTION_UNQUEUE_MAP = 'MapList.UnQueueMap';
const ACTION_CHECK_UPDATE = 'MapList.CheckUpdate';
const ACTION_CLEAR_MAPQUEUE = 'MapList.ClearMapQueue';
const ACTION_PAGING_CHUNKS = 'MapList.PagingChunk.';
const MAX_MAPS_PER_PAGE = 15;
const MAX_PAGES_PER_CHUNK = 2;
const DEFAULT_KARMA_PLUGIN = 'MCTeam\KarmaPlugin';
const DEFAULT_CUSTOM_VOTE_PLUGIN = 'MCTeam\CustomVotesPlugin';
const CACHE_CURRENT_PAGE = 'CurrentPage';
const WIDGET_NAME = 'MapList';
/*
* Private properties
*/
/** @var ManiaControl $maniaControl */
private $maniaControl = null;
/**
* Construct a new map list instance
*
* @param ManiaControl $maniaControl
*/
public function __construct(ManiaControl $maniaControl) {
$this->maniaControl = $maniaControl;
// Callbacks
$this->maniaControl->getCallbackManager()->registerCallbackListener(ManialinkManager::CB_MAIN_WINDOW_CLOSED, $this, 'closeWidget');
$this->maniaControl->getCallbackManager()->registerCallbackListener(ManialinkManager::CB_MAIN_WINDOW_OPENED, $this, 'handleWidgetOpened');
$this->maniaControl->getCallbackManager()->registerCallbackListener(CallbackManager::CB_MP_PLAYERMANIALINKPAGEANSWER, $this, 'handleManialinkPageAnswer');
$this->maniaControl->getCallbackManager()->registerCallbackListener(MapQueue::CB_MAPQUEUE_CHANGED, $this, 'updateWidget');
$this->maniaControl->getCallbackManager()->registerCallbackListener(MapManager::CB_MAPS_UPDATED, $this, 'updateWidget');
$this->maniaControl->getCallbackManager()->registerCallbackListener(MapManager::CB_KARMA_UPDATED, $this, 'updateWidget');
$this->maniaControl->getCallbackManager()->registerCallbackListener(Callbacks::BEGINMAP, $this, 'updateWidget');
$this->maniaControl->getManialinkManager()->registerManialinkPageAnswerListener(self::ACTION_CHECK_UPDATE, $this, 'checkUpdates');
$this->maniaControl->getManialinkManager()->registerManialinkPageAnswerListener(self::ACTION_CLEAR_MAPQUEUE, $this, 'clearMapQueue');
}
/**
* Clear the Map Queue
*
* @param array $chatCallback
* @param Player $player
*/
public function clearMapQueue(array $chatCallback, Player $player) {
// Clears the Map Queue
$this->maniaControl->getMapManager()->getMapQueue()->clearMapQueue($player);
}
/**
* Check for Map Updates
*
* @param array $chatCallback
* @param Player $player
*/
public function checkUpdates(array $chatCallback, Player $player) {
// Update Mx Infos
$this->maniaControl->getMapManager()->getMXManager()->fetchManiaExchangeMapInformation();
// Reshow the Maplist
$this->showMapList($player);
}
/**
* Display a MapList on the Screen
*
* @param Player $player
* @param Map[] $mapList
* @param int $pageIndex
*/
public function showMapList(Player $player, $mapList = null, $pageIndex = -1) {
$width = $this->maniaControl->getManialinkManager()->getStyleManager()->getListWidgetsWidth();
$height = $this->maniaControl->getManialinkManager()->getStyleManager()->getListWidgetsHeight();
if ($pageIndex < 0) {
$pageIndex = (int)$player->getCache($this, self::CACHE_CURRENT_PAGE);
}
$player->setCache($this, self::CACHE_CURRENT_PAGE, $pageIndex);
$queueBuffer = $this->maniaControl->getMapManager()->getMapQueue()->getQueueBuffer();
$chunkIndex = $this->getChunkIndexFromPageNumber($pageIndex);
$mapsBeginIndex = $this->getChunkMapsBeginIndex($chunkIndex);
// Get Maps
if (!is_array($mapList)) {
$mapList = $this->maniaControl->getMapManager()->getMaps();
}
$mapList = array_slice($mapList, $mapsBeginIndex, self::MAX_PAGES_PER_CHUNK * self::MAX_MAPS_PER_PAGE);
$totalMapsCount = $this->maniaControl->getMapManager()->getMapsCount();
$pagesCount = ceil($totalMapsCount / self::MAX_MAPS_PER_PAGE);
// Create ManiaLink
$maniaLink = new ManiaLink(ManialinkManager::MAIN_MLID);
$script = $maniaLink->getScript();
$paging = new Paging();
$script->addFeature($paging);
$paging->setCustomMaxPageNumber($pagesCount);
$paging->setChunkActionAppendsPageNumber(true);
$paging->setChunkActions(self::ACTION_PAGING_CHUNKS);
// Main frame
$frame = $this->maniaControl->getManialinkManager()->getStyleManager()->getDefaultListFrame($script, $paging);
$maniaLink->add($frame);
// Admin Buttons
if ($this->maniaControl->getAuthenticationManager()->checkPermission($player, MapQueue::SETTING_PERMISSION_CLEAR_MAPQUEUE)
) {
// Clear Map-Queue
$label = new Label_Button();
$frame->add($label);
$label->setText('Clear Map-Queue');
$label->setTextSize(1);
$label->setPosition($width / 2 - 8, -$height / 2 + 9);
$label->setHAlign($label::RIGHT);
$quad = new Quad_BgsPlayerCard();
$frame->add($quad);
$quad->setPosition($width / 2 - 5, -$height / 2 + 9, 0.01);
$quad->setSubStyle($quad::SUBSTYLE_BgPlayerCardBig);
$quad->setHAlign($quad::RIGHT);
$quad->setSize(29, 4);
$quad->setAction(self::ACTION_CLEAR_MAPQUEUE);
}
if ($this->maniaControl->getAuthenticationManager()->checkPermission($player, MapManager::SETTING_PERMISSION_CHECK_UPDATE)
) {
// Check Update
$label = new Label_Button();
$frame->add($label);
$label->setText('Check MX for Updates');
$label->setTextSize(1);
$label->setPosition($width / 2 - 41, -$height / 2 + 9, 0.01);
$label->setHAlign($label::RIGHT);
$quad = new Quad_BgsPlayerCard();
$frame->add($quad);
$quad->setPosition($width / 2 - 37, -$height / 2 + 9, 0.01);
$quad->setSubStyle($quad::SUBSTYLE_BgPlayerCardBig);
$quad->setHAlign($quad::RIGHT);
$quad->setSize(35, 4);
$quad->setAction(self::ACTION_CHECK_UPDATE);
$mxQuad = new Quad();
$frame->add($mxQuad);
$mxQuad->setSize(3, 3);
$mxQuad->setImage($this->maniaControl->getManialinkManager()->getIconManager()->getIcon(IconManager::MX_ICON_GREEN));
$mxQuad->setImageFocus($this->maniaControl->getManialinkManager()->getIconManager()->getIcon(IconManager::MX_ICON_GREEN_MOVER));
$mxQuad->setPosition($width / 2 - 67, -$height / 2 + 9);
$mxQuad->setZ(0.01);
$mxQuad->setAction(self::ACTION_CHECK_UPDATE);
}
if ($this->maniaControl->getAuthenticationManager()->checkPermission($player, MapManager::SETTING_PERMISSION_ADD_MAP)
) {
// Directory browser
$browserButton = new Label_Button();
$frame->add($browserButton);
$browserButton->setPosition($width / -2 + 20, -$height / 2 + 9, 0.01);
$browserButton->setTextSize(1);
$browserButton->setText('Directory Browser');
$browserQuad = new Quad_BgsPlayerCard();
$frame->add($browserQuad);
$browserQuad->setPosition($width / -2 + 20, -$height / 2 + 9, 0.01);
$browserQuad->setSubStyle($browserQuad::SUBSTYLE_BgPlayerCardBig);
$browserQuad->setSize(35, 4);
$browserQuad->setAction(DirectoryBrowser::ACTION_SHOW);
}
// Headline
$headFrame = new Frame();
$frame->add($headFrame);
$headFrame->setY($height / 2 - 5);
$posX = -$width / 2;
$array = array('Id' => $posX + 5, 'Mx Id' => $posX + 10, 'Map Name' => $posX + 20, 'Author' => $posX + 68, 'Karma' => $posX + 115, 'Actions' => $width / 2 - 16);
$this->maniaControl->getManialinkManager()->labelLine($headFrame, $array);
// Predefine description Label
$descriptionLabel = $this->maniaControl->getManialinkManager()->getStyleManager()->getDefaultDescriptionLabel();
$frame->add($descriptionLabel);
$queuedMaps = $this->maniaControl->getMapManager()->getMapQueue()->getQueuedMapsRanking();
/** @var KarmaPlugin $karmaPlugin */
$karmaPlugin = $this->maniaControl->getPluginManager()->getPlugin(self::DEFAULT_KARMA_PLUGIN);
$pageNumber = 1 + $chunkIndex * self::MAX_PAGES_PER_CHUNK;
$paging->setStartPageNumber($pageIndex + 1);
$index = 0;
$mapListId = 1 + $mapsBeginIndex;
$posY = $height / 2 - 10;
$pageFrame = null;
$currentMap = $this->maniaControl->getMapManager()->getCurrentMap();
$mxIcon = $this->maniaControl->getManialinkManager()->getIconManager()->getIcon(IconManager::MX_ICON);
$mxIconHover = $this->maniaControl->getManialinkManager()->getIconManager()->getIcon(IconManager::MX_ICON_MOVER);
$mxIconGreen = $this->maniaControl->getManialinkManager()->getIconManager()->getIcon(IconManager::MX_ICON_GREEN);
$mxIconGreenHover = $this->maniaControl->getManialinkManager()->getIconManager()->getIcon(IconManager::MX_ICON_GREEN_MOVER);
foreach ($mapList as $map) {
/** @var Map $map */
if ($index % self::MAX_MAPS_PER_PAGE === 0) {
$pageFrame = new Frame();
$frame->add($pageFrame);
$posY = $height / 2 - 10;
$paging->addPage($pageFrame, $pageNumber);
$pageNumber++;
}
// Map Frame
$mapFrame = new Frame();
$pageFrame->add($mapFrame);
$mapFrame->setY($posY);
$mapFrame->setZ(0.1);
if ($mapListId % 2 !== 0) {
$lineQuad = new Quad_BgsPlayerCard();
$mapFrame->add($lineQuad);
$lineQuad->setSize($width, 4);
$lineQuad->setSubStyle($lineQuad::SUBSTYLE_BgPlayerCardBig);
$lineQuad->setZ(0.001);
}
if ($currentMap === $map) {
$currentQuad = new Quad_Icons64x64_1();
$mapFrame->add($currentQuad);
$currentQuad->setX($posX + 3.5);
$currentQuad->setZ(0.2);
$currentQuad->setSize(4, 4);
$currentQuad->setSubStyle($currentQuad::SUBSTYLE_ArrowBlue);
}
$mxId = '-';
if (isset($map->mx->id)) {
$mxId = $map->mx->id;
$mxQuad = new Quad();
$mapFrame->add($mxQuad);
$mxQuad->setSize(3, 3);
$mxQuad->setImage($mxIcon);
$mxQuad->setImageFocus($mxIconHover);
$mxQuad->setX($posX + 65);
$mxQuad->setUrl($map->mx->pageurl);
$mxQuad->setZ(0.01);
$description = 'View ' . $map->getEscapedName() . ' on Mania-Exchange';
$mxQuad->addTooltipLabelFeature($descriptionLabel, $description);
if ($map->updateAvailable()) {
$mxQuad = new Quad();
$mapFrame->add($mxQuad);
$mxQuad->setSize(3, 3);
$mxQuad->setImage($mxIconGreen);
$mxQuad->setImageFocus($mxIconGreenHover);
$mxQuad->setX($posX + 62);
$mxQuad->setUrl($map->mx->pageurl);
$mxQuad->setZ(0.01);
$description = 'Update for ' . $map->getEscapedName() . ' available on Mania-Exchange!';
$mxQuad->addTooltipLabelFeature($descriptionLabel, $description);
// Update Button
if ($this->maniaControl->getAuthenticationManager()->checkPermission($player, MapManager::SETTING_PERMISSION_ADD_MAP)
) {
$mxQuad->setAction(self::ACTION_UPDATE_MAP . '.' . $map->uid);
}
}
}
// Display Maps
$array = array($mapListId => $posX + 5, $mxId => $posX + 10, Formatter::stripDirtyCodes($map->name) => $posX + 20, $map->authorNick => $posX + 68);
$labels = $this->maniaControl->getManialinkManager()->labelLine($mapFrame, $array);
if (isset($labels[3])) {
/** @var Label $label */
$label = $labels[3];
$description = 'Click to checkout all maps by $<' . $map->authorLogin . '$>!';
$label->setAction(MapCommands::ACTION_SHOW_AUTHOR . $map->authorLogin);
$label->addTooltipLabelFeature($descriptionLabel, $description);
}
// TODO action detailed map info including mx info
// Map-Queue-Map-Label
if (isset($queuedMaps[$map->uid])) {
$label = new Label_Text();
$mapFrame->add($label);
$label->setX($width / 2 - 13);
$label->setZ(0.2);
$label->setTextSize(1.5);
$label->setText($queuedMaps[$map->uid]);
$label->setTextColor('fff');
// Checks if the Player who opened the Widget has queued the map
$queuer = $this->maniaControl->getMapManager()->getMapQueue()->getQueuer($map->uid);
if ($queuer && $queuer->login == $player->login) {
$description = 'Remove ' . $map->getEscapedName() . ' from the Map Queue';
$label->addTooltipLabelFeature($descriptionLabel, $description);
$label->setAction(self::ACTION_UNQUEUE_MAP . '.' . $map->uid);
} else {
$description = $map->getEscapedName() . ' is on Map-Queue Position: ' . $queuedMaps[$map->uid];
$label->addTooltipLabelFeature($descriptionLabel, $description);
}
} else {
// Map-Queue-Map-Button
$queueLabel = new Label_Button();
$mapFrame->add($queueLabel);
$queueLabel->setX($width / 2 - 13);
$queueLabel->setZ(0.2);
$queueLabel->setSize(3, 3);
$queueLabel->setText('+');
if (in_array($map->uid, $queueBuffer)) {
if ($this->maniaControl->getAuthenticationManager()->checkPermission($player, MapQueue::SETTING_PERMISSION_CLEAR_MAPQUEUE)
) {
$queueLabel->setAction(self::ACTION_QUEUED_MAP . '.' . $map->uid);
}
$queueLabel->setTextColor('f00');
$description = $map->getEscapedName() . ' has recently been played!';
$queueLabel->addTooltipLabelFeature($descriptionLabel, $description);
} else {
$queueLabel->setTextColor('09f');
$queueLabel->setAction(self::ACTION_QUEUED_MAP . '.' . $map->uid);
$description = 'Add ' . $map->getEscapedName() . ' to the Map Queue';
$queueLabel->addTooltipLabelFeature($descriptionLabel, $description);
}
}
if ($this->maniaControl->getAuthenticationManager()->checkPermission($player, MapManager::SETTING_PERMISSION_REMOVE_MAP)
) {
// remove map button
$removeButton = new Label_Button();
$mapFrame->add($removeButton);
$removeButton->setX($width / 2 - 5);
$removeButton->setZ(0.2);
$removeButton->setSize(3, 3);
$removeButton->setTextSize(1);
$removeButton->setText('x');
$removeButton->setTextColor('a00');
$confirmFrame = $this->buildConfirmFrame($maniaLink, $posY, $map->uid, true);
$removeButton->addToggleFeature($confirmFrame);
$description = 'Remove Map: ' . $map->getEscapedName();
$removeButton->addTooltipLabelFeature($descriptionLabel, $description);
}
if ($this->maniaControl->getAuthenticationManager()->checkPermission($player, MapManager::SETTING_PERMISSION_ADD_MAP)
) {
// Switch to button
$switchLabel = new Label_Button();
$mapFrame->add($switchLabel);
$switchLabel->setX($width / 2 - 9);
$switchLabel->setZ(0.2);
$switchLabel->setSize(3, 3);
$switchLabel->setTextSize(2);
$switchLabel->setText('»');
$switchLabel->setTextColor('0f0');
$confirmFrame = $this->buildConfirmFrame($maniaLink, $posY, $map->uid);
$switchLabel->addToggleFeature($confirmFrame);
$description = 'Switch Directly to Map: ' . $map->getEscapedName();
$switchLabel->addTooltipLabelFeature($descriptionLabel, $description);
}
if ($this->maniaControl->getPluginManager()->isPluginActive(self::DEFAULT_CUSTOM_VOTE_PLUGIN)
) {
if ($this->maniaControl->getAuthenticationManager()->checkPermission($player, MapManager::SETTING_PERMISSION_ADD_MAP)
) {
// Switch Map Voting for Admins
$switchQuad = new Quad_UIConstruction_Buttons();
$mapFrame->add($switchQuad);
$switchQuad->setX($width / 2 - 17);
$switchQuad->setZ(0.2);
$switchQuad->setSubStyle($switchQuad::SUBSTYLE_Validate_Step2);
$switchQuad->setSize(3.8, 3.8);
$switchQuad->setAction(self::ACTION_START_SWITCH_VOTE . '.' . $map->uid);
$description = 'Start Map-Switch Vote: $<' . $map->name . '$>';
$switchQuad->addTooltipLabelFeature($descriptionLabel, $description);
} else {
// Switch Map Voting for Player
$switchLabel = new Label_Button();
$mapFrame->add($switchLabel);
$switchLabel->setX($width / 2 - 7);
$switchLabel->setZ(0.2);
$switchLabel->setSize(3, 3);
$switchLabel->setTextSize(2);
$switchLabel->setText('»');
$switchLabel->setTextColor('0f0');
$switchLabel->setAction(self::ACTION_START_SWITCH_VOTE . '.' . $map->uid);
$description = 'Start Map-Switch Vote: ' . $map->getEscapedName();
$switchLabel->addTooltipLabelFeature($descriptionLabel, $description);
}
}
// Display Karma bar
if ($karmaPlugin) {
$karma = $karmaPlugin->getMapKarma($map);
$votes = $karmaPlugin->getMapVotes($map);
if (is_numeric($karma)) {
if ($this->maniaControl->getSettingManager()->getSettingValue($karmaPlugin, $karmaPlugin::SETTING_NEWKARMA)
) {
$karmaText = ' ' . round($karma * 100.) . '% (' . $votes['count'] . ')';
} else {
$min = 0;
$plus = 0;
foreach ($votes as $vote) {
if (isset($vote->vote)) {
if ($vote->vote !== 0.5) {
if ($vote->vote < 0.5) {
$min = $min + $vote->count;
} else {
$plus = $plus + $vote->count;
}
}
}
}
$endKarma = $plus - $min;
$karmaText = ' ' . $endKarma . ' (' . $votes['count'] . 'x / ' . round($karma * 100.) . '%)';
}
$karmaGauge = new Gauge();
$mapFrame->add($karmaGauge);
$karmaGauge->setZ(2);
$karmaGauge->setX($posX + 120);
$karmaGauge->setSize(20, 9);
$karmaGauge->setDrawBg(false);
$karma = floatval($karma);
$karmaGauge->setRatio($karma + 0.15 - $karma * 0.15);
$karmaColor = ColorUtil::floatToStatusColor($karma);
$karmaGauge->setColor($karmaColor . '9');
$karmaLabel = new Label();
$mapFrame->add($karmaLabel);
$karmaLabel->setZ(2);
$karmaLabel->setX($posX + 120);
$karmaLabel->setSize(20 * 0.9, 5);
$karmaLabel->setTextSize(0.9);
$karmaLabel->setTextColor('000');
$karmaLabel->setText($karmaText);
}
}
$posY -= 4;
$mapListId++;
$index++;
}
$this->maniaControl->getManialinkManager()->displayWidget($maniaLink, $player, self::WIDGET_NAME);
}
/**
* Get the Chunk Index with the given Page Index
*
* @param int $pageIndex
* @return int
*/
private function getChunkIndexFromPageNumber($pageIndex) {
$mapsCount = $this->maniaControl->getMapManager()->getMapsCount();
$pagesCount = ceil($mapsCount / self::MAX_MAPS_PER_PAGE);
if ($pageIndex > $pagesCount - 1) {
$pageIndex = $pagesCount - 1;
}
return floor($pageIndex / self::MAX_PAGES_PER_CHUNK);
}
/**
* Calculate the First Map Index to show for the given Chunk
*
* @param int $chunkIndex
* @return int
*/
private function getChunkMapsBeginIndex($chunkIndex) {
return $chunkIndex * self::MAX_PAGES_PER_CHUNK * self::MAX_MAPS_PER_PAGE;
}
/**
* Builds the confirmation frame
*
* @param ManiaLink $maniaLink
* @param float $posY
* @param bool $mapUid
* @param bool $remove
* @return Frame
*/
public function buildConfirmFrame(Manialink $maniaLink, $posY, $mapUid, $remove = false) {
// TODO: get rid of the confirm frame to decrease xml size & network usage
// SUGGESTION: just send them as own manialink again on clicking?
$width = $this->maniaControl->getManialinkManager()->getStyleManager()->getListWidgetsWidth();
$quadStyle = $this->maniaControl->getManialinkManager()->getStyleManager()->getDefaultMainWindowStyle();
$quadSubstyle = $this->maniaControl->getManialinkManager()->getStyleManager()->getDefaultMainWindowSubStyle();
$confirmFrame = new Frame();
$maniaLink->add($confirmFrame);
$confirmFrame->setPosition($width / 2 + 6, $posY);
$confirmFrame->setVisible(false);
$quad = new Quad();
$confirmFrame->add($quad);
$quad->setStyles($quadStyle, $quadSubstyle);
$quad->setSize(12, 4);
$quad = new Quad_BgsPlayerCard();
$confirmFrame->add($quad);
$quad->setSubStyle($quad::SUBSTYLE_BgCardSystem);
$quad->setSize(11, 3.5);
$label = new Label_Button();
$confirmFrame->add($label);
$label->setText('Sure?');
$label->setTextSize(1);
$label->setScale(0.90);
$label->setX(-1.3);
$buttLabel = new Label_Button();
$confirmFrame->add($buttLabel);
$buttLabel->setPosition(3.2, 0.4, 0.2);
$buttLabel->setSize(3, 3);
if ($remove) {
$buttLabel->setTextSize(1);
$buttLabel->setTextColor('a00');
$buttLabel->setText('x');
$quad->setAction(self::ACTION_REMOVE_MAP . '.' . $mapUid);
} else {
$buttLabel->setTextSize(2);
$buttLabel->setTextColor('0f0');
$buttLabel->setText('»');
$quad->setAction(self::ACTION_SWITCH_MAP . '.' . $mapUid);
}
return $confirmFrame;
}
/**
* Unset the player if he opened another Main Widget
*
* @param Player $player
* @param string $openedWidget
*/
public function handleWidgetOpened(Player $player, $openedWidget) {
// unset when another main widget got opened
if ($openedWidget !== self::WIDGET_NAME) {
$player->destroyCache($this, self::CACHE_CURRENT_PAGE);
}
}
/**
* Close the widget
*
* @param Player $player
*/
public function closeWidget(Player $player) {
// TODO: resolve duplicate with 'playerCloseWidget'
$player->destroyCache($this, self::CACHE_CURRENT_PAGE);
}
/**
* Handle ManialinkPageAnswer Callback
*
* @param array $callback
*/
public function handleManialinkPageAnswer(array $callback) {
$actionId = $callback[1][2];
$actionArray = explode('.', $actionId);
if (count($actionArray) <= 2) {
return;
}
$action = $actionArray[0] . '.' . $actionArray[1];
$login = $callback[1][1];
$player = $this->maniaControl->getPlayerManager()->getPlayer($login);
$mapUid = $actionArray[2];
switch ($action) {
case self::ACTION_UPDATE_MAP:
$this->maniaControl->getMapManager()->updateMap($player, $mapUid);
$this->showMapList($player);
break;
case self::ACTION_REMOVE_MAP:
try {
$this->maniaControl->getMapManager()->removeMap($player, $mapUid);
} catch (FileException $e) {
$this->maniaControl->getChat()->sendException($e, $player);
}
break;
case self::ACTION_SWITCH_MAP:
// Don't queue on Map-Change
$this->maniaControl->getMapManager()->getMapQueue()->dontQueueNextMapChange();
try {
$this->maniaControl->getClient()->jumpToMapIdent($mapUid);
} catch (NextMapException $exception) {
$this->maniaControl->getChat()->sendError('Error on Jumping to Map Ident: ' . $exception->getMessage(), $player);
break;
} catch (NotInListException $exception) {
// TODO: "Map not found." -> how is that possible?
$this->maniaControl->getChat()->sendError('Error on Jumping to Map Ident: ' . $exception->getMessage(), $player);
break;
}
$map = $this->maniaControl->getMapManager()->getMapByUid($mapUid);
$message = $player->getEscapedNickname() . ' skipped to Map $z' . $map->getEscapedName() . '!';
$this->maniaControl->getChat()->sendSuccess($message);
Logger::logInfo($message, true);
$this->playerCloseWidget($player);
break;
case self::ACTION_START_SWITCH_VOTE:
/** @var CustomVotesPlugin $votesPlugin */
$votesPlugin = $this->maniaControl->getPluginManager()->getPlugin(self::DEFAULT_CUSTOM_VOTE_PLUGIN);
$map = $this->maniaControl->getMapManager()->getMapByUid($mapUid);
$message = $player->getEscapedNickname() . '$s started a vote to switch to ' . $map->getEscapedName() . '!';
$votesPlugin->defineVote('switchmap', 'Goto ' . $map->name, true, $message)->setStopCallback(Callbacks::ENDMAP);
$votesPlugin->startVote($player, 'switchmap', function ($result) use (&$votesPlugin, &$map) {
$votesPlugin->undefineVote('switchmap');
//Don't queue on Map-Change
$this->maniaControl->getMapManager()->getMapQueue()->dontQueueNextMapChange();
try {
$this->maniaControl->getClient()->JumpToMapIdent($map->uid);
} catch (NextMapException $exception) {
return;
} catch (NotInListException $exception) {
return;
} catch (ChangeInProgressException $exception) {
// TODO: delay skip if change is in progress
return;
}
$this->maniaControl->getChat()->sendInformation('$sVote Successful -> Map switched!');
});
break;
case self::ACTION_QUEUED_MAP:
$this->maniaControl->getMapManager()->getMapQueue()->addMapToMapQueue($callback[1][1], $mapUid);
$this->showMapList($player);
break;
case self::ACTION_UNQUEUE_MAP:
$this->maniaControl->getMapManager()->getMapQueue()->removeFromMapQueue($player, $mapUid);
$this->showMapList($player);
break;
default:
if (substr($actionId, 0, strlen(self::ACTION_PAGING_CHUNKS)) === self::ACTION_PAGING_CHUNKS) {
// Paging chunks
$neededPage = (int)substr($actionId, strlen(self::ACTION_PAGING_CHUNKS));
$this->showMapList($player, null, $neededPage - 1);
}
break;
}
}
/**
* Close the widget for
*
* @param Player $player
*/
public function playerCloseWidget(Player $player) {
$player->destroyCache($this, self::CACHE_CURRENT_PAGE);
$this->maniaControl->getManialinkManager()->closeWidget($player);
}
/**
* Reopen the widget on Map Begin, MapListChanged, etc.
*/
public function updateWidget() {
$players = $this->maniaControl->getPlayerManager()->getPlayers();
foreach ($players as $player) {
$currentPage = $player->getCache($this, self::CACHE_CURRENT_PAGE);
if ($currentPage !== null) {
$this->showMapList($player, null, $currentPage);
}
}
}
}

869
core/Maps/MapManager.php Normal file
View File

@ -0,0 +1,869 @@
<?php
namespace ManiaControl\Maps;
use ManiaControl\Admin\AuthenticationManager;
use ManiaControl\Callbacks\CallbackListener;
use ManiaControl\Callbacks\CallbackManager;
use ManiaControl\Callbacks\Callbacks;
use ManiaControl\Files\FileUtil;
use ManiaControl\Logger;
use ManiaControl\ManiaControl;
use ManiaControl\ManiaExchange\ManiaExchangeList;
use ManiaControl\ManiaExchange\ManiaExchangeManager;
use ManiaControl\ManiaExchange\MXMapInfo;
use ManiaControl\Players\Player;
use ManiaControl\Utils\Formatter;
use Maniaplanet\DedicatedServer\InvalidArgumentException;
use Maniaplanet\DedicatedServer\Xmlrpc\AlreadyInListException;
use Maniaplanet\DedicatedServer\Xmlrpc\Exception;
use Maniaplanet\DedicatedServer\Xmlrpc\FileException;
use Maniaplanet\DedicatedServer\Xmlrpc\IndexOutOfBoundException;
use Maniaplanet\DedicatedServer\Xmlrpc\InvalidMapException;
use Maniaplanet\DedicatedServer\Xmlrpc\NotInListException;
use Maniaplanet\DedicatedServer\Xmlrpc\UnavailableFeatureException;
/**
* ManiaControl Map Manager Class
*
* @author ManiaControl Team <mail@maniacontrol.com>
* @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/
class MapManager implements CallbackListener {
/*
* Constants
*/
const TABLE_MAPS = 'mc_maps';
const CB_MAPS_UPDATED = 'MapManager.MapsUpdated';
const CB_KARMA_UPDATED = 'MapManager.KarmaUpdated';
const SETTING_PERMISSION_ADD_MAP = 'Add Maps';
const SETTING_PERMISSION_REMOVE_MAP = 'Remove Maps';
const SETTING_PERMISSION_ERASE_MAP = 'Erase Maps';
const SETTING_PERMISSION_SHUFFLE_MAPS = 'Shuffle Maps';
const SETTING_PERMISSION_CHECK_UPDATE = 'Check Map Update';
const SETTING_PERMISSION_SKIP_MAP = 'Skip Map';
const SETTING_PERMISSION_RESTART_MAP = 'Restart Map';
const SETTING_AUTOSAVE_MAPLIST = 'Autosave Maplist file';
const SETTING_MAPLIST_FILE = 'File to write Maplist in';
const SETTING_WRITE_OWN_MAPLIST_FILE = 'Write a own Maplist File for every Server called serverlogin.txt';
/*
* Public properties
*/
/** @var MapQueue $mapQueue */
/** @deprecated see getMapQueue() */
public $mapQueue = null;
/** @var MapCommands $mapCommands */
/** @deprecated see getMapCommands() */
public $mapCommands = null;
/** @var MapActions $mapActions */
/** @deprecated see getMapActions() */
public $mapActions = null;
/** @var MapList $mapList */
/** @deprecated see getMapList() */
public $mapList = null;
/** @var DirectoryBrowser $directoryBrowser */
/** @deprecated see getDirectoryBrowser() */
public $directoryBrowser = null;
/** @var ManiaExchangeList $mxList */
/** @deprecated see getMXList() */
public $mxList = null;
/** @var ManiaExchangeManager $mxManager */
/** @deprecated see getMXManager() */
public $mxManager = null;
/*
* Private properties
*/
/** @var ManiaControl $maniaControl */
private $maniaControl = null;
/** @var Map[] $maps */
private $maps = array();
/** @var Map $currentMap */
private $currentMap = null;
private $mapEnded = false;
private $mapBegan = false;
/**
* Construct a new map manager instance
*
* @param ManiaControl $maniaControl
*/
public function __construct(ManiaControl $maniaControl) {
$this->maniaControl = $maniaControl;
$this->initTables();
// Children
$this->mxManager = new ManiaExchangeManager($this->maniaControl);
$this->mapList = new MapList($this->maniaControl);
$this->directoryBrowser = new DirectoryBrowser($this->maniaControl);
$this->mxList = new ManiaExchangeList($this->maniaControl);
$this->mapCommands = new MapCommands($maniaControl);
$this->mapQueue = new MapQueue($this->maniaControl);
$this->mapActions = new MapActions($maniaControl);
// Callbacks
$this->maniaControl->getCallbackManager()->registerCallbackListener(Callbacks::ONINIT, $this, 'handleOnInit');
$this->maniaControl->getCallbackManager()->registerCallbackListener(Callbacks::AFTERINIT, $this, 'handleAfterInit');
$this->maniaControl->getCallbackManager()->registerCallbackListener(CallbackManager::CB_MP_MAPLISTMODIFIED, $this, 'mapsModified');
// Permissions
$this->maniaControl->getAuthenticationManager()->definePermissionLevel(self::SETTING_PERMISSION_ADD_MAP, AuthenticationManager::AUTH_LEVEL_ADMIN);
$this->maniaControl->getAuthenticationManager()->definePermissionLevel(self::SETTING_PERMISSION_REMOVE_MAP, AuthenticationManager::AUTH_LEVEL_ADMIN);
$this->maniaControl->getAuthenticationManager()->definePermissionLevel(self::SETTING_PERMISSION_ERASE_MAP, AuthenticationManager::AUTH_LEVEL_SUPERADMIN);
$this->maniaControl->getAuthenticationManager()->definePermissionLevel(self::SETTING_PERMISSION_SHUFFLE_MAPS, AuthenticationManager::AUTH_LEVEL_ADMIN);
$this->maniaControl->getAuthenticationManager()->definePermissionLevel(self::SETTING_PERMISSION_CHECK_UPDATE, AuthenticationManager::AUTH_LEVEL_MODERATOR);
$this->maniaControl->getAuthenticationManager()->definePermissionLevel(self::SETTING_PERMISSION_SKIP_MAP, AuthenticationManager::AUTH_LEVEL_MODERATOR);
$this->maniaControl->getAuthenticationManager()->definePermissionLevel(self::SETTING_PERMISSION_RESTART_MAP, AuthenticationManager::AUTH_LEVEL_MODERATOR);
// Settings
$this->maniaControl->getSettingManager()->initSetting($this, self::SETTING_AUTOSAVE_MAPLIST, true);
$this->maniaControl->getSettingManager()->initSetting($this, self::SETTING_MAPLIST_FILE, "MatchSettings/tracklist.txt");
$this->maniaControl->getSettingManager()->initSetting($this, self::SETTING_WRITE_OWN_MAPLIST_FILE, false);
}
/**
* Initialize necessary database tables
*
* @return bool
*/
private function initTables() {
$mysqli = $this->maniaControl->getDatabase()->getMysqli();
$query = "CREATE TABLE IF NOT EXISTS `" . self::TABLE_MAPS . "` (
`index` int(11) NOT NULL AUTO_INCREMENT,
`mxid` int(11),
`uid` varchar(50) NOT NULL,
`name` varchar(150) NOT NULL,
`authorLogin` varchar(100) NOT NULL,
`fileName` varchar(100) NOT NULL,
`environment` varchar(50) NOT NULL,
`mapType` varchar(50) NOT NULL,
`changed` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`index`),
UNIQUE KEY `uid` (`uid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Map Data' AUTO_INCREMENT=1;";
$result = $mysqli->query($query);
if ($mysqli->error) {
trigger_error($mysqli->error, E_USER_ERROR);
return false;
}
return $result;
}
/**
* Return the map commands
*
* @return MapCommands
*/
public function getMapCommands() {
return $this->mapCommands;
}
/**
* Return the map actions
*
* @return MapActions
*/
public function getMapActions() {
return $this->mapActions;
}
/**
* Return the map list
*
* @return MapList
*/
public function getMapList() {
return $this->mapList;
}
/**
* Return the directory browser
*
* @return DirectoryBrowser
*/
public function getDirectoryBrowser() {
return $this->directoryBrowser;
}
/**
* Return the mx list
*
* @return ManiaExchangeList
*/
public function getMXList() {
return $this->mxList;
}
/**
* Update a Map from Mania Exchange
*
* @param Player $admin
* @param string $uid
*/
public function updateMap(Player $admin, $uid) {
$this->updateMapTimestamp($uid);
if (!isset($uid) || !isset($this->maps[$uid])) {
$this->maniaControl->getChat()->sendError("Error updating Map: Unknown UID '{$uid}'!", $admin);
return;
}
/** @var Map $map */
$map = $this->maps[$uid];
$mxId = $map->mx->id;
$this->removeMap($admin, $uid, true, false);
$this->addMapFromMx($mxId, $admin->login, true);
}
/**
* Update the Timestamp of a Map
*
* @param string $uid
* @return bool
*/
private function updateMapTimestamp($uid) {
$mysqli = $this->maniaControl->getDatabase()->getMysqli();
$mapQuery = "UPDATE `" . self::TABLE_MAPS . "` SET
mxid = 0,
changed = NOW()
WHERE 'uid' = ?";
$mapStatement = $mysqli->prepare($mapQuery);
if ($mysqli->error) {
trigger_error($mysqli->error);
return false;
}
$mapStatement->bind_param('s', $uid);
$mapStatement->execute();
if ($mapStatement->error) {
trigger_error($mapStatement->error);
$mapStatement->close();
return false;
}
$mapStatement->close();
return true;
}
/**
* Remove a Map
*
* @param Player $admin
* @param string $uid
* @param bool $eraseFile
* @param bool $message
*/
public function removeMap(Player $admin, $uid, $eraseFile = false, $message = true) {
if (!isset($this->maps[$uid])) {
$this->maniaControl->getChat()->sendError('Map does not exist!', $admin);
return;
}
/** @var Map $map */
$map = $this->maps[$uid];
// Unset the Map everywhere
$this->getMapQueue()->removeFromMapQueue($admin, $map->uid);
if ($map->mx) {
$this->getMXManager()->unsetMap($map->mx->id);
}
// Remove map
try {
$this->maniaControl->getClient()->removeMap($map->fileName);
} catch (NotInListException $e) {
} catch (FileException $e) {
}
unset($this->maps[$uid]);
if ($eraseFile) {
// Check if ManiaControl can even write to the maps dir
$mapDir = $this->maniaControl->getClient()->getMapsDirectory();
if ($this->maniaControl->getServer()->checkAccess($mapDir)
) {
// Delete map file
if (!@unlink($mapDir . $map->fileName)) {
$this->maniaControl->getChat()->sendError("Couldn't erase the map file.", $admin);
$eraseFile = false;
}
} else {
$this->maniaControl->getChat()->sendError("Couldn't erase the map file (no access).", $admin);
$eraseFile = false;
}
}
// Show Message
if ($message) {
$action = ($eraseFile ? 'erased' : 'removed');
$message = $admin->getEscapedNickname() . ' ' . $action . ' ' . $map->getEscapedName() . '!';
$this->maniaControl->getChat()->sendSuccess($message);
Logger::logInfo($message, true);
}
}
/**
* Return the map queue
*
* @return MapQueue
*/
public function getMapQueue() {
return $this->mapQueue;
}
/**
* Return the mx manager
*
* @return ManiaExchangeManager
*/
public function getMXManager() {
return $this->mxManager;
}
/**
* Adds a Map from Mania Exchange
*
* @param int $mapId
* @param string $login
* @param bool $update
*/
public function addMapFromMx($mapId, $login, $update = false) {
if (is_numeric($mapId)) {
// Check if map exists
$this->maniaControl->getMapManager()->getMXManager()->fetchMapInfo($mapId, function (MXMapInfo $mapInfo = null) use (
&$login, &$update
) {
if (!$mapInfo || !isset($mapInfo->uploaded)) {
// Invalid id
$this->maniaControl->getChat()->sendError('Invalid MX-Id!', $login);
return;
}
// Download the file
$this->maniaControl->getFileReader()->loadFile($mapInfo->downloadurl, function ($file, $error) use (
&$login, &$mapInfo, &$update
) {
if (!$file || $error) {
// Download error
$this->maniaControl->getChat()->sendError("Download failed: '{$error}'!", $login);
return;
}
$this->processMapFile($file, $mapInfo, $login, $update);
});
});
}
}
/**
* Process the MapFile
*
* @param string $file
* @param MXMapInfo $mapInfo
* @param string $login
* @param bool $update
* @throws InvalidArgumentException
*/
private function processMapFile($file, MXMapInfo $mapInfo, $login, $update) {
// Check if map is already on the server
if ($this->getMapByUid($mapInfo->uid)) {
$this->maniaControl->getChat()->sendError('Map is already on the server!', $login);
return;
}
// Save map
$fileName = $mapInfo->id . '_' . $mapInfo->name . '.Map.Gbx';
$fileName = FileUtil::getClearedFileName($fileName);
$downloadFolderName = $this->maniaControl->getSettingManager()->getSettingValue($this, 'MapDownloadDirectory', 'MX');
$relativeMapFileName = $downloadFolderName . DIRECTORY_SEPARATOR . $fileName;
$mapDir = $this->maniaControl->getServer()->getDirectory()->getMapsFolder();
$downloadDirectory = $mapDir . $downloadFolderName . DIRECTORY_SEPARATOR;
$fullMapFileName = $downloadDirectory . $fileName;
// Check if it can get written locally
if ($this->maniaControl->getServer()->checkAccess($mapDir)) {
// Create download directory if necessary
if (!is_dir($downloadDirectory) && !mkdir($downloadDirectory) || !is_writable($downloadDirectory)) {
$this->maniaControl->getChat()->sendError("ManiaControl doesn't have to rights to save maps in '{$downloadDirectory}'.", $login);
return;
}
if (!file_put_contents($fullMapFileName, $file)) {
// Save error
$this->maniaControl->getChat()->sendError('Saving map failed!', $login);
return;
}
} else {
// Write map via write file method
try {
$this->maniaControl->getClient()->writeFile($relativeMapFileName, $file);
} catch (InvalidArgumentException $e) {
if ($e->getMessage() === 'data are too big') {
$this->maniaControl->getChat()->sendError("Map is too big for a remote save.", $login);
return;
}
throw $e;
}
}
// Check for valid map
try {
$this->maniaControl->getClient()->checkMapForCurrentServerParams($relativeMapFileName);
} catch (InvalidMapException $exception) {
$this->maniaControl->getChat()->sendException($exception, $login);
return;
} catch (FileException $exception) {
$this->maniaControl->getChat()->sendException($exception, $login);
return;
}
// Add map to map list
try {
$this->maniaControl->getClient()->insertMap($relativeMapFileName);
} catch (AlreadyInListException $exception) {
$this->maniaControl->getChat()->sendException($exception, $login);
return;
}
$this->updateFullMapList();
// Update Mx MapInfo
$this->maniaControl->getMapManager()->getMXManager()->updateMapObjectsWithManiaExchangeIds(array($mapInfo));
// Update last updated time
$map = $this->getMapByUid($mapInfo->uid);
if (!$map) {
// TODO: improve this - error reports about not existing maps
$this->maniaControl->getErrorHandler()->triggerDebugNotice('Map not in List after Insert!');
$this->maniaControl->getChat()->sendError('Server Error!', $login);
return;
}
$map->lastUpdate = time();
$player = $this->maniaControl->getPlayerManager()->getPlayer($login);
if (!$update) {
// Message
$message = $player->getEscapedNickname() . ' added $<' . $mapInfo->name . '$>!';
$this->maniaControl->getChat()->sendSuccess($message);
Logger::logInfo($message, true);
// Queue requested Map
$this->maniaControl->getMapManager()->getMapQueue()->addMapToMapQueue($login, $mapInfo->uid);
} else {
$message = $player->getEscapedNickname() . ' updated $<' . $mapInfo->name . '$>!';
$this->maniaControl->getChat()->sendSuccess($message);
Logger::logInfo($message, true);
}
}
/**
* Get Map by UID
*
* @param string $uid
* @return Map
*/
public function getMapByUid($uid) {
if (isset($this->maps[$uid])) {
return $this->maps[$uid];
}
return null;
}
/**
* Updates the full Map list, needed on Init, addMap and on ShuffleMaps
*/
private function updateFullMapList() {
$tempList = array();
try {
$offset = 0;
while ($this->maniaControl->getClient()) {
$maps = $this->maniaControl->getClient()->getMapList(150, $offset);
foreach ($maps as $rpcMap) {
if (array_key_exists($rpcMap->uId, $this->maps)) {
// Map already exists, only update index
$tempList[$rpcMap->uId] = $this->maps[$rpcMap->uId];
} else {
// Insert Map Object
$map = $this->initializeMap($rpcMap);
$tempList[$map->uid] = $map;
}
}
$offset += 150;
}
} catch (IndexOutOfBoundException $e) {
}
// restore Sorted MapList
$this->maps = $tempList;
// Trigger own callback
$this->maniaControl->getCallbackManager()->triggerCallback(self::CB_MAPS_UPDATED);
// Write MapList
if ($this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_AUTOSAVE_MAPLIST)
) {
if ($this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_WRITE_OWN_MAPLIST_FILE)
) {
$serverLogin = $this->maniaControl->getServer()->login;
$matchSettingsFileName = "MatchSettings/{$serverLogin}.txt";
} else {
$matchSettingsFileName = $this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_MAPLIST_FILE);
}
try {
$this->maniaControl->getClient()->saveMatchSettings($matchSettingsFileName);
} catch (FileException $e) {
Logger::logError("Unable to write the playlist file, please checkout your MX-Folders File permissions!");
}
}
}
/**
* Initializes a Map
*
* @param mixed $rpcMap
* @return Map
*/
public function initializeMap($rpcMap) {
$map = new Map($rpcMap);
$this->saveMap($map);
return $map;
}
/**
* Save a Map in the Database
*
* @param Map $map
* @return bool
*/
private function saveMap(Map &$map) {
//TODO saveMaps for whole maplist at once (usage of prepared statements)
$mysqli = $this->maniaControl->getDatabase()->getMysqli();
$mapQuery = "INSERT INTO `" . self::TABLE_MAPS . "` (
`uid`,
`name`,
`authorLogin`,
`fileName`,
`environment`,
`mapType`
) VALUES (
?, ?, ?, ?, ?, ?
) ON DUPLICATE KEY UPDATE
`index` = LAST_INSERT_ID(`index`),
`fileName` = VALUES(`fileName`),
`environment` = VALUES(`environment`),
`mapType` = VALUES(`mapType`);";
$mapStatement = $mysqli->prepare($mapQuery);
if ($mysqli->error) {
trigger_error($mysqli->error);
return false;
}
$mapStatement->bind_param('ssssss', $map->uid, $map->rawName, $map->authorLogin, $map->fileName, $map->environment, $map->mapType);
$mapStatement->execute();
if ($mapStatement->error) {
trigger_error($mapStatement->error);
$mapStatement->close();
return false;
}
$map->index = $mapStatement->insert_id;
$mapStatement->close();
return true;
}
/**
* Get's a Map by it's Mania-Exchange Id
*
* @param int $mxId
* @return Map
*/
public function getMapByMxId($mxId) {
foreach ($this->maps as $map) {
if ($map->mx && $map->mx->id == $mxId) {
return $map;
}
}
return null;
}
/**
* Shuffles the MapList
*
* @param Player $admin
* @return bool
*/
public function shuffleMapList($admin = null) {
$shuffledMaps = $this->maps;
shuffle($shuffledMaps);
$mapArray = array();
foreach ($shuffledMaps as $map) {
/** @var Map $map */
$mapArray[] = $map->fileName;
}
try {
$this->maniaControl->getClient()->chooseNextMapList($mapArray);
} catch (Exception $e) {
//TODO temp added 19.04.2014
$this->maniaControl->getErrorHandler()->triggerDebugNotice("Exception line 331 MapManager" . $e->getMessage());
trigger_error("Couldn't shuffle mapList. " . $e->getMessage());
return false;
}
$this->fetchCurrentMap();
if ($admin) {
$message = $admin->getEscapedNickname() . ' shuffled the Maplist!';
$this->maniaControl->getChat()->sendSuccess($message);
Logger::logInfo($message, true);
}
// Restructure if needed
$this->restructureMapList();
return true;
}
/**
* Freshly fetch current Map
*
* @return Map
*/
private function fetchCurrentMap() {
try {
$rpcMap = $this->maniaControl->getClient()->getCurrentMapInfo();
} catch (UnavailableFeatureException $exception) {
return null;
}
if (array_key_exists($rpcMap->uId, $this->maps)) {
$this->currentMap = $this->maps[$rpcMap->uId];
$this->currentMap->nbCheckpoints = $rpcMap->nbCheckpoints;
$this->currentMap->nbLaps = $rpcMap->nbLaps;
return $this->currentMap;
}
$this->currentMap = $this->initializeMap($rpcMap);
$this->maps[$this->currentMap->uid] = $this->currentMap;
return $this->currentMap;
}
/**
* Restructures the Maplist
*/
public function restructureMapList() {
$currentIndex = $this->getMapIndex($this->getCurrentMap());
// No RestructureNeeded
if ($currentIndex < Maplist::MAX_MAPS_PER_PAGE - 1) {
return true;
}
$lowerMapArray = array();
$higherMapArray = array();
$index = 0;
foreach ($this->maps as $map) {
if ($index < $currentIndex) {
$lowerMapArray[] = $map->fileName;
} else {
$higherMapArray[] = $map->fileName;
}
$index++;
}
$mapArray = array_merge($higherMapArray, $lowerMapArray);
array_shift($mapArray);
try {
$this->maniaControl->getClient()->chooseNextMapList($mapArray);
} catch (Exception $e) {
trigger_error("Error restructuring the Maplist. " . $e->getMessage());
return false;
}
return true;
}
/**
* Returns the MapIndex of a given map
*
* @param Map $map
* @return int
*/
public function getMapIndex(Map $map) {
$maps = $this->getMaps();
return array_search($map, $maps);
}
/**
* Get all Maps
*
* @param int $offset
* @param int $length
* @return Map[]
*/
public function getMaps($offset = null, $length = null) {
if ($offset === null) {
return array_values($this->maps);
}
if ($length === null) {
return array_slice($this->maps, $offset);
}
return array_slice($this->maps, $offset, $length);
}
/**
* Get Current Map
*
* @return Map
*/
public function getCurrentMap() {
if (!$this->currentMap) {
return $this->fetchCurrentMap();
}
return $this->currentMap;
}
/**
* Handle OnInit callback
*/
public function handleOnInit() {
$this->updateFullMapList();
$this->fetchCurrentMap();
// Restructure Maplist
$this->restructureMapList();
}
/**
* Handle AfterInit callback
*/
public function handleAfterInit() {
// Fetch MX infos
$this->getMXManager()->fetchManiaExchangeMapInformation();
}
/**
* Handle Script BeginMap callback
*
* @param string $mapUid
* @param string $restart
*/
public function handleScriptBeginMap($mapUid, $restart) {
$this->beginMap($mapUid, Formatter::parseBoolean($restart));
}
/**
* Manage the Begin of a Map
*
* @param string $uid
* @param bool $restart
*/
private function beginMap($uid, $restart = false) {
//If a restart occurred, first call the endMap to set variables back
if ($restart) {
$this->endMap();
}
if ($this->mapBegan) {
return;
}
$this->mapBegan = true;
$this->mapEnded = false;
if (array_key_exists($uid, $this->maps)) {
// Map already exists, only update index
$this->currentMap = $this->maps[$uid];
if (!$this->currentMap->nbCheckpoints || !$this->currentMap->nbLaps) {
$rpcMap = $this->maniaControl->getClient()->getCurrentMapInfo();
$this->currentMap->nbLaps = $rpcMap->nbLaps;
$this->currentMap->nbCheckpoints = $rpcMap->nbCheckpoints;
}
}
// Restructure MapList if id is over 15
$this->restructureMapList();
// Update the mx of the map (for update checks, etc.)
$this->getMXManager()->fetchManiaExchangeMapInformation($this->currentMap);
// Trigger own BeginMap callback
$this->maniaControl->getCallbackManager()->triggerCallback(Callbacks::BEGINMAP, $this->currentMap);
}
/**
* Manage the End of a Map
*/
private function endMap() {
if ($this->mapEnded) {
return;
}
$this->mapEnded = true;
$this->mapBegan = false;
// Trigger own EndMap callback
$this->maniaControl->getCallbackManager()->triggerCallback(Callbacks::ENDMAP, $this->currentMap);
}
/**
* Fetch a map by its file path
*
* @param string $relativeFileName
* @return Map
*/
public function fetchMapByFileName($relativeFileName) {
$mapInfo = $this->maniaControl->getClient()->getMapInfo($relativeFileName);
if (!$mapInfo) {
return null;
}
return $this->initializeMap($mapInfo);
}
/**
* Handle BeginMap callback
*
* @param array $callback
*/
public function handleBeginMap(array $callback) {
$this->beginMap($callback[1][0]["UId"]);
}
/**
* Handle Script EndMap Callback
*/
public function handleScriptEndMap() {
$this->endMap();
}
/**
* Handle EndMap Callback
*
* @param array $callback
*/
public function handleEndMap(array $callback) {
$this->endMap();
}
/**
* Handle Maps Modified Callback
*
* @param array $callback
*/
public function mapsModified(array $callback) {
$this->updateFullMapList();
}
/**
* Get the Number of Maps
*
* @return int
*/
public function getMapsCount() {
return count($this->maps);
}
}

491
core/Maps/MapQueue.php Normal file
View File

@ -0,0 +1,491 @@
<?php
namespace ManiaControl\Maps;
use ManiaControl\Admin\AuthenticationManager;
use ManiaControl\Callbacks\CallbackListener;
use ManiaControl\Callbacks\Callbacks;
use ManiaControl\Commands\CommandListener;
use ManiaControl\Logger;
use ManiaControl\ManiaControl;
use ManiaControl\Players\Player;
use ManiaControl\Utils\Formatter;
use Maniaplanet\DedicatedServer\Xmlrpc\NextMapException;
use Maniaplanet\DedicatedServer\Xmlrpc\NotInListException;
/**
* ManiaControl Map Queue Class
*
* @author ManiaControl Team <mail@maniacontrol.com>
* @copyright 2014 ManiaControl Team
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/
class MapQueue implements CallbackListener, CommandListener {
/*
* Constants
*/
const CB_MAPQUEUE_CHANGED = 'MapQueue.MapQueueBoxChanged';
const SETTING_SKIP_MAP_ON_LEAVE = 'Skip Map when the requester leaves';
const SETTING_SKIP_MAPQUEUE_ADMIN = 'Skip Map when admin leaves';
const SETTING_MAPLIMIT_PLAYER = 'Maximum maps per player in the Map-Queue (-1 = unlimited)';
const SETTING_MAPLIMIT_ADMIN = 'Maximum maps per admin (Admin+) in the Map-Queue (-1 = unlimited)';
const SETTING_BUFFERSIZE = 'Size of the Map-Queue buffer (recently played maps)';
const SETTING_PERMISSION_CLEAR_MAPQUEUE = 'Clear MapQueue';
const SETTING_PERMISSION_QUEUE_BUFFER = 'Queue maps in buffer';
const ADMIN_COMMAND_CLEAR_MAPQUEUE = 'clearmapqueue';
const ADMIN_COMMAND_CLEAR_JUKEBOX = 'clearjukebox';
/*
* Private properties
*/
/** @var ManiaControl $maniaControl */
private $maniaControl = null;
private $queuedMaps = array();
private $nextMap = null;
private $buffer = array();
private $nextNoQueue = false;
/**
* Construct a new map queue instance
*
* @param ManiaControl $maniaControl
*/
public function __construct(ManiaControl $maniaControl) {
$this->maniaControl = $maniaControl;
// Callbacks
$this->maniaControl->getCallbackManager()->registerCallbackListener(Callbacks::ENDMAP, $this, 'endMap');
$this->maniaControl->getCallbackManager()->registerCallbackListener(Callbacks::BEGINMAP, $this, 'beginMap');
$this->maniaControl->getCallbackManager()->registerCallbackListener(Callbacks::AFTERINIT, $this, 'handleAfterInit');
// Settings
$this->maniaControl->getSettingManager()->initSetting($this, self::SETTING_SKIP_MAP_ON_LEAVE, true);
$this->maniaControl->getSettingManager()->initSetting($this, self::SETTING_SKIP_MAPQUEUE_ADMIN, false);
$this->maniaControl->getSettingManager()->initSetting($this, self::SETTING_MAPLIMIT_PLAYER, 1);
$this->maniaControl->getSettingManager()->initSetting($this, self::SETTING_MAPLIMIT_ADMIN, -1);
$this->maniaControl->getSettingManager()->initSetting($this, self::SETTING_BUFFERSIZE, 10);
// Permissions
$this->maniaControl->getAuthenticationManager()->definePermissionLevel(self::SETTING_PERMISSION_CLEAR_MAPQUEUE, AuthenticationManager::AUTH_LEVEL_MODERATOR);
$this->maniaControl->getAuthenticationManager()->definePermissionLevel(self::SETTING_PERMISSION_QUEUE_BUFFER, AuthenticationManager::AUTH_LEVEL_ADMIN);
// Admin Commands
$this->maniaControl->getCommandManager()->registerCommandListener(self::ADMIN_COMMAND_CLEAR_JUKEBOX, $this, 'command_ClearMapQueue', true, 'Clears the Map-Queue.');
$this->maniaControl->getCommandManager()->registerCommandListener(self::ADMIN_COMMAND_CLEAR_MAPQUEUE, $this, 'command_ClearMapQueue', true, 'Clears the Map-Queue.');
$this->maniaControl->getCommandManager()->registerCommandListener(array('jb', 'jukebox', 'mapqueue'), $this, 'command_MapQueue', false, 'Shows current maps in Map-Queue.');
}
/**
* Don't queue on the next MapChange
*/
public function dontQueueNextMapChange() {
$this->nextNoQueue = true;
}
/**
* Add current map to buffer on startup
*/
public function handleAfterInit() {
$currentMap = $this->maniaControl->getMapManager()->getCurrentMap();
$this->buffer[] = $currentMap->uid;
}
/**
* Clear the map-queue via admin command clear map queue
*
* @param array $chatCallback
* @param Player $admin
*/
public function command_ClearMapQueue(array $chatCallback, Player $admin) {
$this->clearMapQueue($admin);
}
/**
* Clear the Map Queue
*
* @param Player $admin |null
*/
public function clearMapQueue(Player $admin = null) {
if ($admin && !$this->maniaControl->getAuthenticationManager()->checkPermission($admin, self::SETTING_PERMISSION_CLEAR_MAPQUEUE)
) {
$this->maniaControl->getAuthenticationManager()->sendNotAllowed($admin);
return;
}
if ($admin && empty($this->queuedMaps)) {
$this->maniaControl->getChat()->sendError('$fa0There are no maps in the jukebox!', $admin->login);
return;
}
//Destroy map - queue list
$this->queuedMaps = array();
if ($admin) {
$title = $this->maniaControl->getAuthenticationManager()->getAuthLevelName($admin->authLevel);
$message = '$fa0' . $title . ' $<$fff' . $admin->nickname . '$> cleared the Map-Queue!';
$this->maniaControl->getChat()->sendInformation($message);
Logger::logInfo($message, true);
}
// Trigger callback
$this->maniaControl->getCallbackManager()->triggerCallback(self::CB_MAPQUEUE_CHANGED, array('clear'));
}
/**
* Handle the mapqueue/jukebox command
*
* @param array $chatCallback
* @param Player $player
*/
public function command_MapQueue(array $chatCallback, Player $player) {
$chatCommands = explode(' ', $chatCallback[1][2]);
if (isset($chatCommands[1])) {
$listParam = strtolower($chatCommands[1]);
switch ($listParam) {
case 'list':
$this->showMapQueue($player);
break;
case 'display':
$this->showMapQueueManialink($player);
break;
case 'clear':
$this->clearMapQueue($player);
break;
default:
$this->showMapQueue($player);
break;
}
} else {
$this->showMapQueue($player);
}
}
/**
* Show current mapqueue in the chat
*
* @param Player $player
*/
public function showMapQueue(Player $player) {
if (empty($this->queuedMaps)) {
$this->maniaControl->getChat()->sendError('$fa0There are no maps in the jukebox!', $player->login);
return;
}
$message = '$fa0Upcoming maps in the Map-Queue:';
$index = 1;
foreach ($this->queuedMaps as $queuedMap) {
$message .= ' $<$fff' . $index . '$>. [$<$fff' . Formatter::stripCodes($queuedMap[1]->name) . '$>]';
$index++;
}
$this->maniaControl->getChat()->sendInformation($message, $player);
}
/**
* Show current mapqueue in a manialink
*
* @param Player $player
*/
public function showMapQueueManialink(Player $player) {
if (empty($this->queuedMaps)) {
$this->maniaControl->getChat()->sendError('There are no Maps in the Jukebox!', $player);
return;
}
$maps = array();
foreach ($this->queuedMaps as $queuedMap) {
array_push($maps, $queuedMap[1]);
}
$this->maniaControl->getMapManager()->getMapList()->showMapList($player, $maps);
}
/**
* Return the current queue buffer
*
* @return string[]
*/
public function getQueueBuffer() {
return $this->buffer;
}
/**
* Add map as first map in queue (for /replay)
*
* @param Player $player
* @param Map $map
*/
public function addFirstMapToMapQueue(Player $player, Map $map) {
if ($map) {
if (array_key_exists($map->uid, $this->queuedMaps)) {
unset($this->queuedMaps[$map->uid]);
}
array_unshift($this->queuedMaps, array($player, $map, true));
}
}
/**
* Adds a Map to the Map-Queue from Plugins or whatever
*
* @param $uid
* @return bool
*/
public function serverAddMapToMapQueue($uid) {
$map = $this->maniaControl->getMapManager()->getMapByUid($uid);
if (!$map) {
return false;
}
$this->queuedMaps[$uid] = array(null, $map);
$this->maniaControl->getChat()->sendInformation('$fa0$<$fff' . $map->name . '$> has been added to the Map-Queue by the Server.');
// Trigger callback
$this->maniaControl->getCallbackManager()->triggerCallback(self::CB_MAPQUEUE_CHANGED, array('add', $this->queuedMaps[$uid]));
return true;
}
/**
* Add a Map to the map-queue
*
* @param string $login
* @param string $uid
*/
public function addMapToMapQueue($login, $uid) {
$player = $this->maniaControl->getPlayerManager()->getPlayer($login);
if (!$player) {
return;
}
// Check if the Player is muted
if ($player->isMuted()) {
$this->maniaControl->getChat()->sendError('Muted Players are not allowed to queue a map.', $player);
return;
}
//Check if player is allowed to add (another) map
$isModerator = $this->maniaControl->getAuthenticationManager()->checkRight($player, AuthenticationManager::AUTH_LEVEL_MODERATOR);
$mapsForPlayer = 0;
foreach ($this->queuedMaps as $queuedMap) {
if ($queuedMap[0]->login == $login) {
$mapsForPlayer++;
}
}
if ($isModerator) {
$maxAdmin = $this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_MAPLIMIT_ADMIN);
if ($maxAdmin >= 0 && $mapsForPlayer >= $maxAdmin) {
$this->maniaControl->getChat()->sendError('You already have $<$fff' . $maxAdmin . '$> map(s) in the Map-Queue!', $login);
return;
}
} else {
$maxPlayer = $this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_MAPLIMIT_PLAYER);
if ($maxPlayer >= 0 && $mapsForPlayer >= $maxPlayer) {
$this->maniaControl->getChat()->sendError('You already have $<$fff' . $maxPlayer . '$> map(s) in the Map-Queue!', $login);
return;
}
}
// Check if the map is already juked
$map = null;
if ($uid instanceof Map) {
$map = $uid;
$uid = $map->uid;
}
if (array_key_exists($uid, $this->queuedMaps)) {
$this->maniaControl->getChat()->sendError('That map is already in the Map-Queue!', $login);
return;
}
//TODO recently maps not able to add to queue-amps setting, and management
// Check if map is in the buffer
if (in_array($uid, $this->buffer)) {
$this->maniaControl->getChat()->sendError('That map has recently been played!', $login);
if (!$this->maniaControl->getAuthenticationManager()->checkPermission($player, self::SETTING_PERMISSION_CLEAR_MAPQUEUE)
) {
return;
}
}
if (!$map) {
$map = $this->maniaControl->getMapManager()->getMapByUid($uid);
}
$this->queuedMaps[$uid] = array($player, $map);
$this->maniaControl->getChat()->sendInformation('$fa0$<$fff' . $map->name . '$> has been added to the Map-Queue by $<$fff' . $player->nickname . '$>.');
// Trigger callback
$this->maniaControl->getCallbackManager()->triggerCallback(self::CB_MAPQUEUE_CHANGED, array('add', $this->queuedMaps[$uid]));
}
/**
* Remove a Map from the Map queue
*
* @param Player $player
* @param string $uid
*/
public function removeFromMapQueue(Player $player, $uid) {
if (!isset($this->queuedMaps[$uid])) {
return;
}
/** @var Map $map */
$map = $this->queuedMaps[$uid][1];
unset($this->queuedMaps[$uid]);
$this->maniaControl->getChat()->sendInformation('$fa0$<$fff' . $map->name . '$> is removed from the Map-Queue by $<$fff' . $player->nickname . '$>.');
// Trigger callback
$this->maniaControl->getCallbackManager()->triggerCallback(self::CB_MAPQUEUE_CHANGED, array('remove', $map));
}
/**
* Called on endmap
*
* @param Map $map
*/
public function endMap(Map $map = null) {
//Don't queue next map (for example on skip to map)
if ($this->nextNoQueue) {
$this->nextNoQueue = false;
return;
}
$this->nextMap = null;
if ($this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_SKIP_MAP_ON_LEAVE)
) {
// Skip Map if requester has left
foreach ($this->queuedMaps as $queuedMap) {
$player = $queuedMap[0];
// Check if map is added via replay vote/command
if (isset($queuedMap[2]) && $queuedMap[2] === true) {
break;
}
// Player found, so play this map (or if it got juked by the server)
if ($player == null || $this->maniaControl->getPlayerManager()->getPlayer($player->login)) {
break;
}
if (!$this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_SKIP_MAPQUEUE_ADMIN)) {
//Check if the queuer is a admin
if ($player->authLevel > 0) {
break;
}
}
// Trigger callback
$this->maniaControl->getCallbackManager()->triggerCallback(self::CB_MAPQUEUE_CHANGED, array('skip', $queuedMap[0]));
// Player not found, so remove the map from the mapqueue
array_shift($this->queuedMaps);
$this->maniaControl->getChat()->sendInformation('$fa0$<$fff' . $queuedMap[0]->name . '$> is skipped because $<' . $player->nickname . '$> left the game!');
}
}
$this->nextMap = array_shift($this->queuedMaps);
//Check if Map Queue is empty
if (!$this->nextMap || !isset($this->nextMap[1])) {
return;
}
$map = $this->nextMap[1];
//Message only if it's juked by a player (not by the server)
if ($this->nextMap[0]) {
/** @var Map $map */
$this->maniaControl->getChat()->sendInformation('$fa0Next map will be $<$fff' . $map->name . '$> as requested by $<' . $this->nextMap[0]->nickname . '$>.');
}
try {
$this->maniaControl->getClient()->setNextMapIdent($map->uid);
} catch (NextMapException $e) {
} catch (NotInListException $e) {
}
}
/**
* Called on begin map
*
* @param Map $map
*/
public function beginMap(Map $map) {
if (in_array($map->uid, $this->buffer)) {
return;
}
if (count($this->buffer) >= $this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_BUFFERSIZE)
) {
array_shift($this->buffer);
}
$this->buffer[] = $map->uid;
}
/**
* Return the next Map if the next map is a queuedmap or null if it's not
*
* @return Map
*/
public function getNextMap() {
return $this->nextMap;
}
/**
* Return the first Queued Map
*
* @return array(Player $player, Map $map)
*/
public function getNextQueuedMap() {
foreach ($this->queuedMaps as $queuedMap) {
//return the first Queued Map
return $queuedMap;
}
return null;
}
/**
* Return a list with the indexes of the queued maps
*
* @return array
*/
public function getQueuedMapsRanking() {
$index = 1;
$queuedMaps = array();
foreach ($this->queuedMaps as $queuedMap) {
$map = $queuedMap[1];
$queuedMaps[$map->uid] = $index;
$index++;
}
return $queuedMaps;
}
/**
* Return the Queuer of a Map
*
* @param string $uid
* @return mixed
*/
public function getQueuer($uid) {
return $this->queuedMaps[$uid][0];
}
/**
* Dummy Function for testing
*/
public function printAllMaps() {
foreach ($this->queuedMaps as $map) {
$map = $map[1];
var_dump($map->name);
}
}
}